diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 743475ed9..c22bd437b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -230,7 +230,10 @@ jobs: shell: bash run: | rustc -vV | sed -n 's/^release: /rustc /p' - cat target/release/deps/weavepy-*.order-note 2>/dev/null || echo "no order note" + # (Cargo 1.100 links the binary under build///out/, + # earlier cargos under deps/.) + notes=$(find target/release/deps target/release/build -name 'weavepy*.order-note' 2>/dev/null || true) + if [ -n "$notes" ]; then cat $notes; else echo "no order note"; fi - name: Build merge-base weavepy (A/B reference) if: github.event_name == 'pull_request' # A separate worktree + target dir so the two builds never @@ -284,6 +287,23 @@ jobs: name: cold-jit-diagnostic-${{ matrix.os }} path: target/performance/cold-jit-ci/${{ github.run_id }}-${{ github.run_attempt }}/ if-no-files-found: warn + # Where a flagged fixture's time went: each tier setting's kernel + # time and, on macOS, instructions and cycles, for both binaries + # (see tools/bench_gate_counts.py). Equal counts with unequal times + # are the runner or the code's layout; unequal counts name a tier. + - name: Count instructions for the fixtures a failed gate flagged + if: failure() && matrix.os != 'windows-latest' && github.event_name == 'pull_request' && steps.bench_gate.outcome == 'failure' + timeout-minutes: 10 + shell: bash + run: | + python tools/bench_gate_counts.py \ + --base "$BASE_WEAVEPY" --new target/release/weavepy \ + --report bench-report.md | tee bench-gate-counts.md + { + echo "## Flagged fixtures by tier setting" + echo + cat bench-gate-counts.md + } >> "$GITHUB_STEP_SUMMARY" - name: Append bench report to job summary if: always() shell: bash diff --git a/Cargo.lock b/Cargo.lock index ab9978921..4107114ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2559,6 +2559,7 @@ dependencies = [ "parking_lot", "pkcs8", "regex", + "ring", "rusqlite", "rust_decimal", "rustls", diff --git a/Cargo.toml b/Cargo.toml index 17724cc82..d0c77b050 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -138,6 +138,8 @@ memchr = "2.8" libc = "0.2" libmimalloc-sys = { version = "0.1.49", default-features = false } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +# rustls's crypto provider; `hashlib` takes its SHA-256, SHA-384 and SHA-512. +ring = { version = "0.17", default-features = false } rustls-pki-types = "1.7" # PKCS#8 "ENCRYPTED PRIVATE KEY" (PBES2) decryption for password-protected # keys in SSLContext.load_cert_chain. diff --git a/README.md b/README.md index b5b538bd3..8217d4b68 100644 --- a/README.md +++ b/README.md @@ -20,9 +20,9 @@ are how it measures progress. | --- | --- | --- | | CPython test suite | 464 of 468 `Lib/test` entries pass | November 2, 2026, on macOS | | Real packages | 48 of 48 install and pass a behavior check | September 2026, on macOS and Linux; kept in CI | -| Warm speed | 0.85 times CPython's time | November 13, 2026, over 33 workloads | -| Peak memory | 1.14 times CPython's resident set, 1.22 times its footprint | November 13, 2026, over 33 workloads | -| Everyday library code | 1.44 times CPython's time | November 13, 2026, over 54 short loops | +| Warm speed | 0.84 times CPython's time | November 15, 2026, over 33 workloads | +| Peak memory | 1.13 times CPython's resident set | November 15, 2026, over 33 workloads | +| Everyday library code | 1.23 times CPython's time | November 15, 2026, over 54 short loops | The sections below explain what these numbers cover and where they fall short. @@ -128,15 +128,19 @@ small fraction of CPython's instructions, while `zip`, `Enum` lookups, dict copies and calls through `*args` still take one and a half to two and a half times as many. The [progress note](docs/PERFORMANCE-PROGRESS.md) lists them. -Ordinary library-heavy code is where WeavePy is behind. A battery of 54 -everyday operations (`tools/pybench/everyday.py`: file and directory work, -text, data formats, classes, threads, common modules) runs at 1.44 times -CPython's time on average (1.79 before the work that followed its first run). -WeavePy is ahead on 12 of the 54 and past twice CPython's time on 14, with -thread queues, `inspect` and `typing`, `weakref`, class-protocol code, and -`enum` with `dataclasses` between 3 and 4 times. File and stream I/O, which was -far slower still (a line read took a system call per byte), is now level with -CPython or ahead of it. The rest is the current work. +Ordinary library-heavy code was where WeavePy was furthest behind, and is now +about level. A battery of 54 everyday operations (`tools/pybench/everyday.py`: +file and directory work, text, data formats, classes, threads, common modules) +runs at 0.97 times CPython's time on average, measured on November 19, 2026, at +`c69d14ad` (1.79 when the battery was first run, 1.26 four days earlier). +WeavePy is ahead on 28 of the 54 and past one and a half times CPython's time +on 5: `threading_queue_ops` (2.2), `argparse_ops` (1.9), `inspect_typing_ops` +(1.7), `email_html_ops` (1.6) and `exceptions_ops` (1.5). Those are short runs +of standard-library code that end before the JIT has warmed up, and threads: +starting one costs three times what it does in CPython. File and stream I/O, +which was far slower still (a line read took a system call per byte), is now +level with CPython or ahead of it, as are `datetime`, `re` and `json`. The rest +is the current work. Code that the JIT compiles fully can run far faster. The numeric loops in the [bench gate fixtures](docs/PERFORMANCE-CPYTHON-PARITY.md) took 5% to 8% of @@ -164,6 +168,12 @@ measurements and the work behind them. code pages a program is done with once its imports are over; a plain release build does that only in processes that run for more than a tenth of a second. +- **Threads.** Starting and joining a thread takes about twice CPython's + time, and so does handing items to freshly started workers through a + `queue.Queue`. On Windows a second thread, even an idle one, still turns + reference counts atomic and cell borrows locked, which costs object-heavy + code 12% to 30%; elsewhere both stay plain under the GIL and an idle thread + costs nothing measurable. - **Imports and warm-up.** Importing large parts of the standard library costs about 1.4 times CPython's instructions; a faster start-up hides most of it in short scripts. Cold time is a little under CPython's overall, but some diff --git a/crates/weavepy-bench/src/runner.rs b/crates/weavepy-bench/src/runner.rs index 631e41caf..43a65cecc 100644 --- a/crates/weavepy-bench/src/runner.rs +++ b/crates/weavepy-bench/src/runner.rs @@ -160,12 +160,21 @@ fn runset(samples: &[Sample]) -> RunSet { } /// Time a single fixture under the PR binary *and* a merge-base -/// binary, interleaving the legs sample by sample (PR, base, CPython, -/// PR, base, CPython, …) so slow drift on a shared runner — thermal -/// ramp, a neighbor tenant spinning up — lands on both legs equally -/// and cancels in the PR/base ratio. This is what makes the A/B gate -/// immune to the machine skew that a committed-baseline comparison -/// spends its whole envelope absorbing. +/// binary, interleaving the legs round by round so slow drift on a +/// shared runner — thermal ramp, a neighbor tenant spinning up — lands +/// on both legs equally and cancels in the PR/base ratio. This is what +/// makes the A/B gate immune to the machine skew that a +/// committed-baseline comparison spends its whole envelope absorbing. +/// +/// Within a round the two binaries run in a balanced order (PR, base, +/// base, PR, then CPython; the next round base, PR, PR, base), two +/// samples each. A fixed PR, base, CPython order put every PR sample +/// right after another program's run and every base sample right after +/// a near-identical one's, so whatever a leg inherits from the process +/// before it (shared cache and page-cache state, the frozen code +/// cache's files) favored the base: a PR that changed no code could +/// fail the gate. Balanced, each binary follows the other program, the +/// other binary and itself equally often. /// /// A base-leg failure is not an error: a fixture added by the PR /// under test may exercise syntax the merge-base binary cannot run @@ -183,24 +192,27 @@ pub fn run_one_ab( } else { opts.samples }; - let mut pr_samples = Vec::with_capacity(opts.samples as usize); - let mut base_samples = Vec::with_capacity(opts.samples as usize); + let mut pr_samples = Vec::with_capacity(2 * opts.samples as usize); + let mut base_samples = Vec::with_capacity(2 * opts.samples as usize); let mut py_samples = Vec::with_capacity(opts.samples as usize); let mut base_ok = true; for i in 0..runs { let keep = !opts.warmup || i > 0; - let pr = time_subprocess(weavepy.as_os_str(), fix, &[])?; - if keep { - pr_samples.push(pr); - } - if base_ok { - match time_subprocess(base.as_os_str(), fix, &[]) { - Ok(b) => { - if keep { - base_samples.push(b); + for is_pr in ab_order(i) { + if is_pr { + let pr = time_subprocess(weavepy.as_os_str(), fix, &[])?; + if keep { + pr_samples.push(pr); + } + } else if base_ok { + match time_subprocess(base.as_os_str(), fix, &[]) { + Ok(b) => { + if keep { + base_samples.push(b); + } } + Err(_) => base_ok = false, } - Err(_) => base_ok = false, } } if let Some(py) = python { @@ -222,6 +234,14 @@ pub fn run_one_ab( .with_base(base_set)) } +/// The order of round `round`'s four A/B legs (`true` the PR binary's): +/// PR, base, base, PR on even rounds and its mirror on odd ones (see +/// [`run_one_ab`]). +fn ab_order(round: u32) -> [bool; 4] { + let pr_first = round.is_multiple_of(2); + [pr_first, !pr_first, !pr_first, pr_first] +} + /// Run all known fixtures A/B (see [`run_one_ab`]) and return one /// [`Row`] per fixture. pub fn run_suite_ab(opts: &RunOpts, base: &Path) -> io::Result> { @@ -854,7 +874,26 @@ fn demangle_rust(sym: &str) -> String { #[cfg(test)] mod tests { - use super::{demangle_rust, median, parse_bench_ns, parse_sample_output, ScalingRow}; + use super::{ab_order, demangle_rust, median, parse_bench_ns, parse_sample_output, ScalingRow}; + + /// Over any two consecutive rounds each binary runs four times, and + /// each is once the leg right after the CPython leg (a round's first) + /// and once the leg right before it (its last). + #[test] + fn ab_order_is_balanced() { + for start in 0..4u32 { + let rounds = [ab_order(start), ab_order(start + 1)]; + let pr = rounds.iter().flatten().filter(|&&is_pr| is_pr).count(); + assert_eq!(pr, 4); + assert_ne!(rounds[0][0], rounds[1][0]); + assert_ne!(rounds[0][3], rounds[1][3]); + for r in rounds { + assert_eq!(r[0], r[3]); + assert_eq!(r[1], r[2]); + assert_ne!(r[0], r[1]); + } + } + } #[test] fn demangles_legacy_rust_symbols() { diff --git a/crates/weavepy-capi/src/abstract_.rs b/crates/weavepy-capi/src/abstract_.rs index 746a94450..d83113e6f 100644 --- a/crates/weavepy-capi/src/abstract_.rs +++ b/crates/weavepy-capi/src/abstract_.rs @@ -3652,11 +3652,17 @@ pub unsafe extern "C" fn PySequence_Check(o: *mut PyObject) -> c_int { // raise "Could not convert object to sequence". A foreign sequence // that really has `sq_item` (numpy's `_array_converter`) returns 1 // at the C-slot check above and never reaches here. - if matches!( - inst.cls().lookup("__getitem__"), - Some(Object::Function(_) | Object::BoundMethod(_)) - ) { - return 1; + match inst.cls().lookup("__getitem__") { + Some(Object::Function(_) | Object::BoundMethod(_)) => return 1, + // A class written in Python whose `__getitem__` is served + // natively and that declares itself a sequence + // (`Py_TPFLAGS_SEQUENCE`: `array.array`, whose C type in + // CPython has `sq_item`): Pillow's `putdata(array(...))` + // asks exactly this. + Some(Object::Builtin(_)) if inst.cls().collection_flags() & (1 << 5) != 0 => { + return 1 + } + _ => {} } } } diff --git a/crates/weavepy-capi/src/buffer.rs b/crates/weavepy-capi/src/buffer.rs index 97f1f07aa..a84fb9541 100644 --- a/crates/weavepy-capi/src/buffer.rs +++ b/crates/weavepy-capi/src/buffer.rs @@ -515,7 +515,7 @@ fn describe_native_export(obj: &Object) -> Result { let base_ptr = memoryview_backing_ptr(&mv.buffer); let ptr = unsafe { base_ptr.add(start) }; let itemsize = mv.itemsize.get().max(1); - let format = mv.format.borrow().clone().into_bytes(); + let format = mv.format.borrow().as_bytes().to_vec(); // Element shape/stride: honour an explicit shape, else derive a // 1-D `[len / itemsize]` C-contiguous layout. This is what keeps // a typed view's `itemsize`/`format` self-consistent with the diff --git a/crates/weavepy-capi/src/force_link_table.rs b/crates/weavepy-capi/src/force_link_table.rs index f12bfc88d..a86680b5f 100644 --- a/crates/weavepy-capi/src/force_link_table.rs +++ b/crates/weavepy-capi/src/force_link_table.rs @@ -1351,6 +1351,23 @@ static FORCE_LINK: &[FnPtr] = &[ addr!(strings::PyByteArray_Resize), addr!(strings::PyUnicode_DecodeASCII), addr!(strings::PyUnicode_DecodeLatin1), + addr!(strings::PyUnicode_DecodeUTF16), + addr!(strings::PyUnicode_DecodeUTF16Stateful), + addr!(strings::PyUnicode_DecodeUTF32), + addr!(strings::PyUnicode_DecodeUTF32Stateful), + addr!(strings::PyUnicode_DecodeUTF7), + addr!(strings::PyUnicode_DecodeUTF7Stateful), + addr!(strings::PyUnicode_DecodeUnicodeEscape), + addr!(strings::PyUnicode_DecodeRawUnicodeEscape), + addr!(strings::PyUnicode_AsUTF16String), + addr!(strings::PyUnicode_AsUTF32String), + addr!(strings::PyUnicode_AsUnicodeEscapeString), + addr!(strings::PyUnicode_AsRawUnicodeEscapeString), + addr!(strings::PyUnicode_GetDefaultEncoding), + addr!(strings::PyUnicode_AsWideChar), + addr!(strings::PyUnicode_AsWideCharString), + addr!(strings::PyUnicode_FSConverter), + addr!(strings::PyUnicode_FSDecoder), addr!(strings::PyUnicode_DecodeFSDefault), addr!(strings::PyUnicode_DecodeFSDefaultAndSize), addr!(strings::PyUnicode_EncodeFSDefault), diff --git a/crates/weavepy-capi/src/lifecycle.rs b/crates/weavepy-capi/src/lifecycle.rs index 0bce5cebe..46afc89d6 100644 --- a/crates/weavepy-capi/src/lifecycle.rs +++ b/crates/weavepy-capi/src/lifecycle.rs @@ -224,6 +224,7 @@ pub unsafe extern "C" fn PyEval_SaveThread() -> *mut PyThreadState { // represent the token as the count of guards we just // popped, encoded into the pointer. Anything non-null // restores; null means "we weren't holding the GIL". + weavepy_vm::gil::before_gil_release(); let popped = pop_gil_guard(); if popped.is_some() { // Encode "1 guard popped" as a dangling sentinel; the @@ -256,5 +257,6 @@ pub unsafe extern "C" fn PyEval_AcquireThread(_state: *mut PyThreadState) { #[no_mangle] pub unsafe extern "C" fn PyEval_ReleaseThread(_state: *mut PyThreadState) { // Paired with `PyEval_AcquireThread`. + weavepy_vm::gil::before_gil_release(); let _ = pop_gil_guard(); } diff --git a/crates/weavepy-capi/src/memoryview.rs b/crates/weavepy-capi/src/memoryview.rs index 547e6f487..fbad668eb 100644 --- a/crates/weavepy-capi/src/memoryview.rs +++ b/crates/weavepy-capi/src/memoryview.rs @@ -336,7 +336,7 @@ pub unsafe extern "C" fn PyMemoryView_FromObjectAndFlags( len: Cell::new(view_len), readonly: Cell::new(readonly), released: Cell::new(false), - format: RefCell::new(format), + format: RefCell::new(format.into()), itemsize: Cell::new(view_itemsize), shape: RefCell::new(shape), strides: RefCell::new(strides), @@ -497,7 +497,7 @@ pub unsafe extern "C" fn PyMemoryView_FromBuffer(view: *const Py_buffer) -> *mut len: Cell::new(len), readonly: Cell::new(readonly), released: Cell::new(false), - format: RefCell::new(format), + format: RefCell::new(format.into()), itemsize: Cell::new(itemsize), shape: RefCell::new(shape), strides: RefCell::new(strides), @@ -590,7 +590,7 @@ pub unsafe extern "C" fn PyMemoryView_GetContiguous( MemoryViewBuffer::Bytes(out.into()), total * itemsize, true, - mv.format.borrow().clone(), + mv.format.borrow().to_string(), itemsize, ); if ndim >= 1 { @@ -648,7 +648,7 @@ pub unsafe extern "C" fn PyMemoryView_GET_BUFFER(mv: *mut PyObject) -> *mut Py_b (p, Some(buf_box)) } }; - let format = view.format.borrow().clone() + "\0"; + let format = view.format.borrow().to_string() + "\0"; let format_storage: Box<[u8]> = format.into_bytes().into_boxed_slice(); let itemsize = view.itemsize.get().max(1); diff --git a/crates/weavepy-capi/src/strings.rs b/crates/weavepy-capi/src/strings.rs index b028d5495..3b1184787 100644 --- a/crates/weavepy-capi/src/strings.rs +++ b/crates/weavepy-capi/src/strings.rs @@ -723,6 +723,406 @@ pub unsafe extern "C" fn PyUnicode_DecodeLatin1( crate::object::into_owned(Object::from_str(out)) } +/// `(s, size)` as a byte slice (`None`: a NULL pointer with a nonzero +/// size, which CPython would read through). +unsafe fn raw_bytes<'a>(s: *const c_char, size: PySsizeT) -> Option<&'a [u8]> { + if s.is_null() { + return (size == 0).then_some(&[][..]); + } + Some(unsafe { std::slice::from_raw_parts(s as *const u8, size.max(0) as usize) }) +} + +/// An engine decode's result as an owned `str` (or NULL with the error +/// pending). +fn decoded_or_null(r: Result) -> *mut PyObject { + match r { + Ok(o) => crate::object::into_owned(o), + Err(e) => { + crate::errors::set_pending_from_runtime(e); + ptr::null_mut() + } + } +} + +type UtfDecode = + fn(&[u8], &str, i32, bool) -> Result<(Object, usize, i32), weavepy_vm::error::RuntimeError>; + +/// The UTF-16/UTF-32 decoders' shared protocol: `*byteorder` (NULL means +/// 0) picks the order, 0 sniffing a BOM, and gets the order in effect at +/// the end; with `consumed` NULL the input must end on a whole unit. +unsafe fn decode_utf_wide( + decode: UtfDecode, + s: *const c_char, + size: PySsizeT, + errors: *const c_char, + byteorder: *mut c_int, + consumed: *mut PySsizeT, +) -> *mut PyObject { + let Some(data) = (unsafe { raw_bytes(s, size) }) else { + crate::errors::set_type_error("NULL data with a nonzero size"); + return ptr::null_mut(); + }; + let err = unsafe { cstr_or(errors, "strict") }; + let bo = if byteorder.is_null() { + 0 + } else { + unsafe { *byteorder } + }; + let r = decode(data, &err, bo, consumed.is_null()).map(|(text, used, bo)| { + if !byteorder.is_null() { + unsafe { *byteorder = bo }; + } + if !consumed.is_null() { + unsafe { *consumed = used as PySsizeT }; + } + text + }); + decoded_or_null(r) +} + +/// `PyUnicode_DecodeUTF16(s, size, errors, byteorder)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_DecodeUTF16( + s: *const c_char, + size: PySsizeT, + errors: *const c_char, + byteorder: *mut c_int, +) -> *mut PyObject { + use weavepy_vm::stdlib::codecs_engine::utf16_decode; + unsafe { decode_utf_wide(utf16_decode, s, size, errors, byteorder, ptr::null_mut()) } +} + +/// `PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, consumed)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_DecodeUTF16Stateful( + s: *const c_char, + size: PySsizeT, + errors: *const c_char, + byteorder: *mut c_int, + consumed: *mut PySsizeT, +) -> *mut PyObject { + use weavepy_vm::stdlib::codecs_engine::utf16_decode; + unsafe { decode_utf_wide(utf16_decode, s, size, errors, byteorder, consumed) } +} + +/// `PyUnicode_DecodeUTF32(s, size, errors, byteorder)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_DecodeUTF32( + s: *const c_char, + size: PySsizeT, + errors: *const c_char, + byteorder: *mut c_int, +) -> *mut PyObject { + use weavepy_vm::stdlib::codecs_engine::utf32_decode; + unsafe { decode_utf_wide(utf32_decode, s, size, errors, byteorder, ptr::null_mut()) } +} + +/// `PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, consumed)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_DecodeUTF32Stateful( + s: *const c_char, + size: PySsizeT, + errors: *const c_char, + byteorder: *mut c_int, + consumed: *mut PySsizeT, +) -> *mut PyObject { + use weavepy_vm::stdlib::codecs_engine::utf32_decode; + unsafe { decode_utf_wide(utf32_decode, s, size, errors, byteorder, consumed) } +} + +/// `PyUnicode_DecodeUTF7Stateful(s, size, errors, consumed)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_DecodeUTF7Stateful( + s: *const c_char, + size: PySsizeT, + errors: *const c_char, + consumed: *mut PySsizeT, +) -> *mut PyObject { + let Some(data) = (unsafe { raw_bytes(s, size) }) else { + crate::errors::set_type_error("NULL data with a nonzero size"); + return ptr::null_mut(); + }; + let err = unsafe { cstr_or(errors, "strict") }; + let r = weavepy_vm::stdlib::codecs_engine::utf7_decode(data, &err, consumed.is_null()).map( + |(text, used)| { + if !consumed.is_null() { + unsafe { *consumed = used as PySsizeT }; + } + text + }, + ); + decoded_or_null(r) +} + +/// `PyUnicode_DecodeUTF7(s, size, errors)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_DecodeUTF7( + s: *const c_char, + size: PySsizeT, + errors: *const c_char, +) -> *mut PyObject { + unsafe { PyUnicode_DecodeUTF7Stateful(s, size, errors, ptr::null_mut()) } +} + +/// `PyUnicode_DecodeUnicodeEscape(s, size, errors)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_DecodeUnicodeEscape( + s: *const c_char, + size: PySsizeT, + errors: *const c_char, +) -> *mut PyObject { + let Some(data) = (unsafe { raw_bytes(s, size) }) else { + crate::errors::set_type_error("NULL data with a nonzero size"); + return ptr::null_mut(); + }; + let err = unsafe { cstr_or(errors, "strict") }; + decode_capi(data, "unicode_escape", &err) +} + +/// `PyUnicode_DecodeRawUnicodeEscape(s, size, errors)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_DecodeRawUnicodeEscape( + s: *const c_char, + size: PySsizeT, + errors: *const c_char, +) -> *mut PyObject { + let Some(data) = (unsafe { raw_bytes(s, size) }) else { + crate::errors::set_type_error("NULL data with a nonzero size"); + return ptr::null_mut(); + }; + let err = unsafe { cstr_or(errors, "strict") }; + decode_capi(data, "raw_unicode_escape", &err) +} + +/// `PyUnicode_AsUTF16String(unicode)`: with a BOM, in native order. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_AsUTF16String(o: *mut PyObject) -> *mut PyObject { + unsafe { PyUnicode_AsEncodedString(o, c"utf-16".as_ptr(), ptr::null()) } +} + +/// `PyUnicode_AsUTF32String(unicode)`: with a BOM, in native order. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_AsUTF32String(o: *mut PyObject) -> *mut PyObject { + unsafe { PyUnicode_AsEncodedString(o, c"utf-32".as_ptr(), ptr::null()) } +} + +/// `PyUnicode_AsUnicodeEscapeString(unicode)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_AsUnicodeEscapeString(o: *mut PyObject) -> *mut PyObject { + unsafe { PyUnicode_AsEncodedString(o, c"unicode_escape".as_ptr(), ptr::null()) } +} + +/// `PyUnicode_AsRawUnicodeEscapeString(unicode)`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_AsRawUnicodeEscapeString(o: *mut PyObject) -> *mut PyObject { + unsafe { PyUnicode_AsEncodedString(o, c"raw_unicode_escape".as_ptr(), ptr::null()) } +} + +/// `PyUnicode_GetDefaultEncoding()`. +#[no_mangle] +pub extern "C" fn PyUnicode_GetDefaultEncoding() -> *const c_char { + c"utf-8".as_ptr() +} + +/// The code points of the `str` at `o` as `wchar_t` units (UTF-16 where +/// `wchar_t` is 16 bits), or NULL-and-`TypeError` for anything else. +unsafe fn wide_units(o: *mut PyObject) -> Option> { + if o.is_null() { + crate::errors::set_type_error("bad argument to internal function"); + return None; + } + let obj = unsafe { crate::object::clone_object_value(o) }; + let Some(cps) = weavepy_vm::stdlib::codecs_engine::str_codepoints(&obj) else { + crate::errors::set_type_error("expected str"); + return None; + }; + let mut out: Vec = Vec::with_capacity(cps.len() + 1); + if std::mem::size_of::() == 2 { + for cp in cps { + if cp >= 0x10000 { + let v = cp - 0x10000; + out.push((0xD800 + (v >> 10)) as libc::wchar_t); + out.push((0xDC00 + (v & 0x3FF)) as libc::wchar_t); + } else { + out.push(cp as libc::wchar_t); + } + } + } else { + out.extend(cps.into_iter().map(|cp| cp as libc::wchar_t)); + } + Some(out) +} + +/// `PyUnicode_AsWideChar(unicode, w, size)`: copies at most `size` units +/// (a terminating NUL only if it fits) and returns how many it copied, or +/// with `w` NULL, the size the whole string needs, NUL included. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_AsWideChar( + o: *mut PyObject, + w: *mut libc::wchar_t, + size: PySsizeT, +) -> PySsizeT { + let Some(units) = (unsafe { wide_units(o) }) else { + return -1; + }; + if w.is_null() { + return units.len() as PySsizeT + 1; + } + let size = size.max(0) as usize; + let n = units.len().min(size); + unsafe { + ptr::copy_nonoverlapping(units.as_ptr(), w, n); + if n < size { + *w.add(n) = 0; + } + } + n as PySsizeT +} + +/// `PyUnicode_AsWideCharString(unicode, size)`: a NUL-terminated copy +/// from `PyMem_Malloc`, its length (NUL excluded) stored through `size`; +/// with `size` NULL an embedded NUL is a `ValueError`. +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_AsWideCharString( + o: *mut PyObject, + size: *mut PySsizeT, +) -> *mut libc::wchar_t { + let Some(mut units) = (unsafe { wide_units(o) }) else { + return ptr::null_mut(); + }; + if size.is_null() && units.contains(&0) { + crate::errors::set_value_error("embedded null character"); + return ptr::null_mut(); + } + let len = units.len(); + units.push(0); + let bytes = units.len() * std::mem::size_of::(); + let buf = unsafe { crate::memory::PyMem_Malloc(bytes) } as *mut libc::wchar_t; + if buf.is_null() { + unsafe { crate::errors::PyErr_NoMemory() }; + return ptr::null_mut(); + } + unsafe { ptr::copy_nonoverlapping(units.as_ptr(), buf, units.len()) }; + if !size.is_null() { + unsafe { *size = len as PySsizeT }; + } + buf +} + +/// What a `PyArg_Parse` converter returns to ask for a cleanup call. +const PY_CLEANUP_SUPPORTED: c_int = 0x20000; + +/// The shared shape of `PyUnicode_FSConverter`/`PyUnicode_FSDecoder`: +/// NULL `arg` releases `*addr`; otherwise `os.fspath(arg)` is turned into +/// the wanted type by `convert` and stored in `*addr`. +unsafe fn fs_convert( + arg: *mut PyObject, + addr: *mut std::ffi::c_void, + convert: impl FnOnce(Object) -> Result, +) -> c_int { + let slot = addr as *mut *mut PyObject; + if arg.is_null() { + unsafe { + crate::object::Py_DecRef(*slot); + *slot = ptr::null_mut(); + } + return 1; + } + let path = unsafe { crate::wave4::PyOS_FSPath(arg) }; + if path.is_null() { + return 0; + } + let value = unsafe { crate::object::clone_object_value(path) }; + unsafe { crate::object::Py_DecRef(path) }; + match convert(value) { + Ok(out) => { + unsafe { *slot = crate::object::into_owned(out) }; + PY_CLEANUP_SUPPORTED + } + Err(()) => 0, + } +} + +/// `PyUnicode_FSConverter(arg, addr)`: a path as `bytes` (str paths are +/// encoded with the filesystem encoding). +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_FSConverter( + arg: *mut PyObject, + addr: *mut std::ffi::c_void, +) -> c_int { + unsafe { + fs_convert(arg, addr, |value| { + let bytes = match &value { + Object::Bytes(b) => b.to_vec(), + Object::Str(_) | Object::WStr(_) => { + match weavepy_vm::stdlib::codecs_mod::encode_obj( + &value, + "utf-8", + "surrogateescape", + ) { + Ok(b) => b, + Err(e) => { + crate::errors::set_pending_from_runtime(e); + return Err(()); + } + } + } + _ => { + crate::errors::set_type_error("expected str, bytes or os.PathLike object"); + return Err(()); + } + }; + if bytes.contains(&0) { + crate::errors::set_value_error("embedded null byte"); + return Err(()); + } + Ok(Object::Bytes(bytes.into())) + }) + } +} + +/// `PyUnicode_FSDecoder(arg, addr)`: a path as `str` (bytes paths are +/// decoded with the filesystem encoding). +#[no_mangle] +pub unsafe extern "C" fn PyUnicode_FSDecoder( + arg: *mut PyObject, + addr: *mut std::ffi::c_void, +) -> c_int { + unsafe { + fs_convert(arg, addr, |value| { + let text = match &value { + Object::Str(_) | Object::WStr(_) => value, + Object::Bytes(b) => { + match weavepy_vm::stdlib::codecs_mod::decode_bytes_obj( + b, + "utf-8", + "surrogateescape", + ) { + Ok(t) => t, + Err(e) => { + crate::errors::set_pending_from_runtime(e); + return Err(()); + } + } + } + _ => { + crate::errors::set_type_error("expected str, bytes or os.PathLike object"); + return Err(()); + } + }; + let has_nul = match weavepy_vm::stdlib::codecs_engine::str_codepoints(&text) { + Some(cps) => cps.contains(&0), + None => false, + }; + if has_nul { + crate::errors::set_value_error("embedded null character"); + return Err(()); + } + Ok(text) + }) + } +} + /// `PyUnicode_FromEncodedObject(obj, encoding, errors)` — accept /// a bytes object or buffer-protocol exporter and decode it. #[no_mangle] diff --git a/crates/weavepy-capi/tests/capi_sequence_check.rs b/crates/weavepy-capi/tests/capi_sequence_check.rs new file mode 100644 index 000000000..19d545ce0 --- /dev/null +++ b/crates/weavepy-capi/tests/capi_sequence_check.rs @@ -0,0 +1,99 @@ +//! `PySequence_Check` and the sequence calls on an `array.array`. +//! +//! The `array` class is written in Python with its item methods served +//! natively. To C code it is what CPython's C type is: a sequence, with a +//! size, items, and an iterator (Pillow's `putdata(array(...))` asks +//! `PySequence_Check` first and refuses anything else). +use std::ffi::CString; +use weavepy_capi::abstract_::{ + PyIter_Next, PyObject_GetIter, PySequence_Check, PySequence_GetItem, PySequence_Size, +}; +use weavepy_capi::errors::PyErr_Occurred; +use weavepy_capi::lifecycle::{Py_FinalizeEx, Py_Initialize}; + +use weavepy_capi::module::{PyImport_AddModule, PyModule_GetDict}; +use weavepy_capi::numbers::PyLong_AsLong; +use weavepy_capi::object::{PyObject, Py_DecRef}; +use weavepy_capi::pythonrun::{PyRun_SimpleString, PyRun_String, Py_eval_input}; + +fn run(source: &str) { + let source = CString::new(source).unwrap(); + assert_eq!(unsafe { PyRun_SimpleString(source.as_ptr()) }, 0); +} + +unsafe fn eval(source: &str, globals: *mut PyObject) -> *mut PyObject { + let source = CString::new(source).unwrap(); + let value = unsafe { PyRun_String(source.as_ptr(), Py_eval_input, globals, globals) }; + assert!(!value.is_null(), "C API evaluation failed"); + value +} + +#[test] +fn an_array_is_a_sequence_to_c_code() { + // Keep initialization and finalization in one test, as for embedding. + unsafe { Py_Initialize() }; + run("import array\n\ + ints = array.array('i', [10, 20, 30])\n\ + floats = array.array('f', [0.0]) * 100\n\ + class Sub(array.array):\n pass\n\ + sub = Sub('B', b'abc')\n\ + class Items:\n def __getitem__(self, i):\n return i\n\ + items = Items()\n"); + unsafe { + let name = CString::new("__main__").unwrap(); + let module = PyImport_AddModule(name.as_ptr()); + assert!(!module.is_null()); + let globals = PyModule_GetDict(module); + assert!(!globals.is_null()); + for (source, want) in [ + ("ints", 1), + ("floats", 1), + ("sub", 1), + ("items", 1), + ("[1, 2]", 1), + ("(1, 2)", 1), + ("'text'", 1), + ("b'bytes'", 1), + ("range(3)", 1), + ("{1: 2}", 0), + ("{1, 2}", 0), + ("5", 0), + ("None", 0), + ] { + let value = eval(source, globals); + assert_eq!(PySequence_Check(value), want, "PySequence_Check({source})"); + Py_DecRef(value); + } + let ints = eval("ints", globals); + assert_eq!(PySequence_Size(ints), 3); + for (i, want) in [10, 20, 30].into_iter().enumerate() { + let item = PySequence_GetItem(ints, i as isize); + assert!(!item.is_null()); + assert_eq!(PyLong_AsLong(item), want); + Py_DecRef(item); + } + let last = PySequence_GetItem(ints, -1); + assert!(!last.is_null()); + assert_eq!(PyLong_AsLong(last), 30); + Py_DecRef(last); + let it = PyObject_GetIter(ints); + assert!(!it.is_null()); + let mut total = 0; + loop { + let item = PyIter_Next(it); + if item.is_null() { + break; + } + total += PyLong_AsLong(item); + Py_DecRef(item); + } + assert!(PyErr_Occurred().is_null()); + assert_eq!(total, 60); + Py_DecRef(it); + Py_DecRef(ints); + let floats = eval("floats", globals); + assert_eq!(PySequence_Size(floats), 100); + Py_DecRef(floats); + assert_eq!(Py_FinalizeEx(), 0); + } +} diff --git a/crates/weavepy-cli/src/alloc.rs b/crates/weavepy-cli/src/alloc.rs index ce8d1884a..bf0df3ca4 100644 --- a/crates/weavepy-cli/src/alloc.rs +++ b/crates/weavepy-cli/src/alloc.rs @@ -39,32 +39,35 @@ pub(crate) struct Mimalloc; unsafe impl GlobalAlloc for Mimalloc { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + #[cfg(target_vendor = "apple")] + if layout.size() > large::MIN { + // SAFETY: the caller's contract. + return unsafe { large::alloc(layout, false) }; + } // SAFETY: plain FFI allocation calls. - let p: *mut u8 = unsafe { - if plain(layout.size(), layout.align()) { - mi_malloc(layout.size()).cast() - } else { - mi_malloc_aligned(layout.size(), layout.align()).cast() - } - }; - p + unsafe { mi_alloc(layout) } } #[inline] unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - // SAFETY: as in `alloc`. - let p: *mut u8 = unsafe { - if plain(layout.size(), layout.align()) { - mi_zalloc(layout.size()).cast() - } else { - mi_zalloc_aligned(layout.size(), layout.align()).cast() - } - }; - p + #[cfg(target_vendor = "apple")] + if layout.size() > large::MIN { + // SAFETY: the caller's contract. + return unsafe { large::alloc(layout, true) }; + } + // SAFETY: plain FFI allocation calls. + unsafe { mi_alloc_zeroed(layout) } } #[inline] - unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + #[cfg(target_vendor = "apple")] + if layout.size() > large::MIN { + // SAFETY: the caller's contract. + return unsafe { large::free(ptr) }; + } + #[cfg(not(target_vendor = "apple"))] + let _ = layout; // SAFETY: `ptr` came from this allocator (the caller's contract). unsafe { mi_free(ptr.cast::()) } } @@ -83,8 +86,215 @@ unsafe impl GlobalAlloc for Mimalloc { } } +/// A block for `layout` from mimalloc's plain or aligned entry point. +/// +/// # Safety +/// +/// As [`GlobalAlloc::alloc`]'s. +#[inline(always)] +unsafe fn mi_alloc(layout: Layout) -> *mut u8 { + // SAFETY: plain FFI allocation calls. + unsafe { + if plain(layout.size(), layout.align()) { + mi_malloc(layout.size()).cast() + } else { + mi_malloc_aligned(layout.size(), layout.align()).cast() + } + } +} + +/// [`mi_alloc`], zeroed. +/// +/// # Safety +/// +/// As [`GlobalAlloc::alloc_zeroed`]'s. +#[inline(always)] +unsafe fn mi_alloc_zeroed(layout: Layout) -> *mut u8 { + // SAFETY: as in `mi_alloc`. + unsafe { + if plain(layout.size(), layout.align()) { + mi_zalloc(layout.size()).cast() + } else { + mi_zalloc_aligned(layout.size(), layout.align()).cast() + } + } +} + +/// Freed blocks too large for mimalloc's arenas, kept a while for reuse. +/// +/// mimalloc maps a block over [`ARENA_MAX_OBJECT_KIB`] from the OS and +/// unmaps it when it's freed, so a program that builds and drops such a +/// buffer over and over (`b"x" * 4_000_000`, a whole-file read, `[0] * +/// 1_000_000`) faulted every page of it in again each time: five to eight +/// times CPython's time, whose allocator keeps freed large blocks for +/// reuse as this does. A few blocks stay, each taken by an allocation of +/// about its size, and [`trim`] frees any idle past the purge delay, so +/// a block nothing reuses leaves the resident set soon after. +#[cfg(target_vendor = "apple")] +mod large { + use super::{mi_free, mi_usable_size}; + use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, Ordering}; + + /// Blocks above this many bytes are mapped from the OS. + pub(super) const MIN: usize = super::ARENA_MAX_OBJECT_KIB as usize * 1024; + /// The largest block kept, and the most kept in all. + const MAX: usize = 32 << 20; + const TOTAL: usize = 64 << 20; + const SLOTS: usize = 4; + + struct Cache { + /// (block, usable size, when it was kept in microseconds). + slots: [(usize, usize, u64); SLOTS], + } + + static LOCK: AtomicBool = AtomicBool::new(false); + static mut CACHE: Cache = Cache { + slots: [(0, 0, 0); SLOTS], + }; + + /// The cache under its spin lock (held for a few instructions). + fn with(f: impl FnOnce(&mut Cache) -> R) -> R { + while LOCK + .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed) + .is_err() + { + std::hint::spin_loop(); + } + // SAFETY: the lock gives exclusive access. + let r = f(unsafe { &mut *std::ptr::addr_of_mut!(CACHE) }); + LOCK.store(false, Ordering::Release); + r + } + + /// Microseconds on a monotonic clock that doesn't allocate. + fn now() -> u64 { + let mut ts = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: a plain clock read into a local. + unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &raw mut ts) }; + ts.tv_sec as u64 * 1_000_000 + ts.tv_nsec as u64 / 1000 + } + + /// [`super::Mimalloc`]'s allocation of more than [`MIN`] bytes: a kept + /// block of about the size (zeroed if asked), else mimalloc's. Out of + /// line, so the small allocations' path stays a compare and a jump. + /// + /// # Safety + /// + /// As [`std::alloc::GlobalAlloc::alloc`]'s. + #[cold] + #[inline(never)] + pub(super) unsafe fn alloc(layout: std::alloc::Layout, zeroed: bool) -> *mut u8 { + if layout.align() <= super::MAX_ALIGN { + if let Some(p) = take(layout.size()) { + if zeroed { + // (Zeroing resident pages costs a fraction of faulting + // in fresh ones.) + // SAFETY: the block holds at least `layout.size()` bytes. + unsafe { std::ptr::write_bytes(p, 0, layout.size()) }; + } + return p; + } + } + // SAFETY: the caller's contract. + unsafe { + if zeroed { + super::mi_alloc_zeroed(layout) + } else { + super::mi_alloc(layout) + } + } + } + + /// [`super::Mimalloc`]'s release of a block of more than [`MIN`] bytes: + /// kept if there's room, else freed. + /// + /// # Safety + /// + /// `ptr` is a live block of this allocator. + #[cold] + #[inline(never)] + pub(super) unsafe fn free(ptr: *mut u8) { + if !keep(ptr) { + // SAFETY: the caller's contract. + unsafe { mi_free(ptr.cast::()) }; + } + } + + /// A kept block of at least `size` bytes, and not much more. + fn take(size: usize) -> Option<*mut u8> { + if size > MAX { + return None; + } + with(|c| { + let i = c.slots.iter().position(|&(p, usable, _)| { + p != 0 && usable >= size && usable - size <= size / 4 + })?; + let p = c.slots[i].0; + c.slots[i] = (0, 0, 0); + Some(p as *mut u8) + }) + } + + /// Keep the freed block `ptr` if there's room: `false` to free it. + fn keep(ptr: *mut u8) -> bool { + // SAFETY: `ptr` is a live mimalloc block being freed. + let usable = unsafe { mi_usable_size(ptr.cast::().cast_const()) }; + if usable > MAX { + return false; + } + let at = now(); + with(|c| { + let held: usize = c.slots.iter().map(|s| s.1).sum(); + match c.slots.iter().position(|&(p, _, _)| p == 0) { + Some(i) if held + usable <= TOTAL => { + c.slots[i] = (ptr as usize, usable, at); + true + } + _ => false, + } + }) + } + + /// Free the kept blocks idle for longer than `idle_micros`. + pub(super) fn trim(idle_micros: u64) { + let at = now(); + let mut old = [0usize; SLOTS]; + with(|c| { + for (slot, out) in c.slots.iter_mut().zip(old.iter_mut()) { + if slot.0 != 0 && at.saturating_sub(slot.2) > idle_micros { + *out = slot.0; + *slot = (0, 0, 0); + } + } + }); + for p in old.into_iter().filter(|&p| p != 0) { + // SAFETY: a block this cache owned. + unsafe { mi_free(p as *mut c_void) }; + } + } +} + +/// Free the large blocks kept for reuse that have sat idle past the purge +/// delay (see [`large`]): from the runtime's memory ticks. +pub(crate) fn trim_large_blocks() { + #[cfg(target_vendor = "apple")] + large::trim( + if PURGE_DELAY_OURS.load(std::sync::atomic::Ordering::Relaxed) { + PURGE_DELAY_MS as u64 * 1000 + } else { + LARGE_PURGE_DELAY_MS as u64 * 1000 + }, + ); +} + extern "C" { fn mi_option_set(option: c_int, value: c_long); + #[cfg(target_vendor = "apple")] + fn mi_usable_size(p: *const c_void) -> usize; fn mi_collect(force: bool); #[cfg(unix)] #[allow(clippy::too_many_arguments)] diff --git a/crates/weavepy-cli/src/lib.rs b/crates/weavepy-cli/src/lib.rs index e4c59bdea..3ff9db727 100644 --- a/crates/weavepy-cli/src/lib.rs +++ b/crates/weavepy-cli/src/lib.rs @@ -2154,6 +2154,10 @@ fn run_source_with_options(source: &str, opts: &RunOptions) -> Result<()> { let repl = repl::Repl::new(interpreter, true, opts.flags.ignore_environment)?; return repl.run_inspect(); } + // (The GIL, through the handling of the run's result: an exception + // it returns is an object, read and released below beside whatever + // threads the program left running.) + let _gil = weavepy::vm::gil::hold_gil(); match weavepy::run_source_with_options(source, &opts) { Ok(()) => Ok(()), Err(err) => { diff --git a/crates/weavepy-cli/src/memory.rs b/crates/weavepy-cli/src/memory.rs index e7e0923a5..98fb4bf11 100644 --- a/crates/weavepy-cli/src/memory.rs +++ b/crates/weavepy-cli/src/memory.rs @@ -7,7 +7,9 @@ //! //! - releases the code pages it no longer runs (see [`crate::text_trim`]); //! - keeps freed heap resident longer once it's large (see -//! [`crate::alloc::note_resident`]). +//! [`crate::alloc::note_resident`]); +//! - frees the large blocks kept for reuse that have sat idle (see +//! [`crate::alloc::trim_large_blocks`]). use std::sync::atomic::{AtomicU64, Ordering}; @@ -37,6 +39,7 @@ pub(crate) extern "C" fn tick() { return; } NEXT_LOOK.store(now + LOOK_EVERY_MICROS, Ordering::Relaxed); + crate::alloc::trim_large_blocks(); if let Some(resident) = crate::text_trim::resident() { crate::alloc::note_resident(resident.all); crate::text_trim::grown(resident, now, weavepy_vm::import_activity()); diff --git a/crates/weavepy-cli/weavepy.order b/crates/weavepy-cli/weavepy.order index ececc9322..612683fd5 100644 --- a/crates/weavepy-cli/weavepy.order +++ b/crates/weavepy-cli/weavepy.order @@ -144,7 +144,6 @@ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc3vec3VecNtCs9D __RINvMs6_NtCseIGkHRfguhS_9hashbrown3rawINtB6_8RawTableTNtNtCsdq5mISKDh0s_5alloc6string6StringuEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_uNtNtNtCs6KxzipSu1yP_3std4hash6random11RandomStateE0ECs9p2CpBq5ts3_10weavepy_vm __RNvMs6_NtCsdq5mISKDh0s_5alloc2rcINtB5_2RcNtCs9DEk322Hfll_16weavepy_compiler9LineIndexE9drop_slowBF_ __RNvMs6_NtCsdq5mISKDh0s_5alloc2rcINtB5_2RceE9drop_slowCs9DEk322Hfll_16weavepy_compiler -__RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtCsllk7SLrseIa_14weavepy_parser3ast4StmtEECscifjXFcM73a_16weavepy_compiler __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCsllk7SLrseIa_14weavepy_parser3ast8StmtKindECscifjXFcM73a_16weavepy_compiler __RNvCs9p2CpBq5ts3_10weavepy_vm18argv_str_to_object __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtCsllk7SLrseIa_14weavepy_parser3ast3ArgEECscifjXFcM73a_16weavepy_compiler @@ -191,7 +190,6 @@ __RNvMsd_NtCs9p2CpBq5ts3_10weavepy_vm5typesNtB5_10TypeObject13set_metaclass __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc5boxed3BoxNtNtCsllk7SLrseIa_14weavepy_parser3ast4ExprEECscifjXFcM73a_16weavepy_compiler __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtCsllk7SLrseIa_14weavepy_parser3ast9TypeParamEECscifjXFcM73a_16weavepy_compiler __RNvXs1i_NtCs2NHf1dqD6Ob_4core3fmtReNtB6_7Display3fmtB8_ -__RNvCscifjXFcM73a_16weavepy_compiler23class_body_reads_dunder __RNvXs3_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11InterpreterNtNtCs2NHf1dqD6Ob_4core7default7Default7default __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins16default_builtins __RNvNtCs9p2CpBq5ts3_10weavepy_vm6object19py_hash_bytes_slice @@ -200,7 +198,6 @@ __RNCINvMs0_NtNtCs6KxzipSu1yP_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtB __RNvXsE_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB5_7DictKeyNtNtCs2NHf1dqD6Ob_4core3cmp9PartialEq2eq __RNvMs1r_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_6Object7is_same __RNvNtCs9p2CpBq5ts3_10weavepy_vm6object11py_str_hash -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object9BuiltinFnE9drop_slowBK_ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCs9p2CpBq5ts3_10weavepy_vm6object9BuiltinFnEBF_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm6object13py_hash_value __RINvYNtNtNtCs6KxzipSu1yP_3std4hash6random11RandomStateNtNtCs2NHf1dqD6Ob_4core4hash11BuildHasher8hash_oneRjECscifjXFcM73a_16weavepy_compiler @@ -261,9 +258,7 @@ __RNvNvNtCs9p2CpBq5ts3_10weavepy_vm13builtin_types20install_type_dunders9mk_gets __RNvNvNtCs9p2CpBq5ts3_10weavepy_vm13builtin_types22install_module_methods7builtin __RNvMs1v_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_6Object9new_tuple __RINvMNtCs9p2CpBq5ts3_10weavepy_vm13tuple_storageNtB3_12TupleStorage10from_arrayKj0_EB5_ -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcINtNtCs9p2CpBq5ts3_10weavepy_vm4sync7GilCellINtNtB7_3vec3VecNtNtBL_6object6ObjectEEE9drop_slowBL_ __RNvMs1v_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_6Object8new_dict -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcINtNtCs9p2CpBq5ts3_10weavepy_vm4sync7GilCellNtNtBL_6object8DictDataEE9drop_slowBL_ __RNvMs1v_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_6Object7new_set __RINvMs1v_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB7_6Object9new_bytesINtNtCsdq5mISKDh0s_5alloc3vec3VechEEB9_ __RNCINvMs0_NtNtCs6KxzipSu1yP_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9p2CpBq5ts3_10weavepy_vm12shared_value7ThinArcINtB1J_12SliceStoragehEEE10initializeNCINvB1a_11get_or_initNCINvMs1v_NtB1L_6objectNtB3E_6Object9new_bytesINtNtCsdq5mISKDh0s_5alloc3vec3VechEE0E0zE0E0B1L_ @@ -290,9 +285,7 @@ __RINvMs1v_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB7_6Object18new_frozenset_fromIN __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object12FrozenSetObjE9drop_slowBK_ __RNvMs6_NtCs9p2CpBq5ts3_10weavepy_vm5tier2NtB5_8JitState12get_compiled __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object13MethodWrapperE9drop_slowBK_ -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcINtNtCs9p2CpBq5ts3_10weavepy_vm4sync7GilCellNtNtBL_6object10PyIteratorEE9drop_slowBL_ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCs9p2CpBq5ts3_10weavepy_vm6object10PyIteratorEBF_ -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm13tuple_storage12TupleStorageE9drop_slowBK_ __RINvYNtNtNtCs6KxzipSu1yP_3std4hash6random11RandomStateNtNtCs2NHf1dqD6Ob_4core4hash11BuildHasher8hash_oneRTjNtNtCsdq5mISKDh0s_5alloc6string6StringEECseUjftuVGxe6_12weavepy_capi __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins8class_of __RNvXs_NtNtNtCs2NHf1dqD6Ob_4core5array4iter10iter_innerAINtNtNtBa_3mem12maybe_uninit11MaybeUninitTNtNtCs9p2CpBq5ts3_10weavepy_vm6object7DictKeyNtB1z_6ObjectEEj1_NtB4_11PartialDrop12partial_dropB1B_ @@ -383,7 +376,6 @@ __RINvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9method_kwNvB2_14memoryview_hexEB4_ __RINvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9method_kwNvB2_18memoryview_tobytesEB4_ __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object10PyPropertyE9drop_slowBK_ __RINvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9method_kwNvB2_16property_init_kwEB4_ -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object5RangeE9drop_slowBK_ __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object7PySliceE9drop_slowBK_ __RINvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9method_kwNvB2_17staticmethod_callEB4_ __RINvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9method_kwNvB2_13str_format_kwEB4_ @@ -443,7 +435,6 @@ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter25run_until_yield_or_return __RNvCs9IcUwEW2Om8_7stacker15remaining_stack __RINvMs0_NtNtNtNtCs6KxzipSu1yP_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCs2NHf1dqD6Ob_4core4cell4CellINtNtB1j_6option6OptionjEEzE16get_or_init_slowNvNvCs9IcUwEW2Om8_7stacker11STACK_LIMIT27___rust_std_internal_init_fnEB2A_ __RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecNtCs9DEk322Hfll_16weavepy_compiler15CompWalrusScopeE8grow_oneBO_ -__RNvMs1_NtCscifjXFcM73a_16weavepy_compiler9flowgraphNtB5_3Cfg11jump_thread __RNvNtCs9p2CpBq5ts3_10weavepy_vm10ext_loader24current_extension_loader __RNvNtCseUjftuVGxe6_12weavepy_capi6loader17vm_load_extension __RINvMs6_NtCseIGkHRfguhS_9hashbrown3rawINtB6_8RawTableTNtNtNtCs6KxzipSu1yP_3std3ffi6os_str8OsStringuEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_uNtNtNtBW_4hash6random11RandomStateE0ECs9p2CpBq5ts3_10weavepy_vm @@ -524,8 +515,6 @@ __RNvCs9p2CpBq5ts3_10weavepy_vm21code_pure_leaf_decide __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter18call_from_bytecode __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter9core_call __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter15call_c_profiled -__RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins10str_result -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object11BoundMethodE9drop_slowBK_ __RNvMs1r_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_6Object9make_iter __RNvMsf_NtCs9p2CpBq5ts3_10weavepy_vm4syncINtB5_7GilCellNtNtB7_6object10PyIteratorE6borrowB7_ __RNvMs1p_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_10PyIterator18next_value_checked @@ -541,14 +530,12 @@ __RNvNtCs9p2CpBq5ts3_10weavepy_vm13vm_singletons24current_worker_thread_id __RINvMNtNtCs6KxzipSu1yP_3std4sync9once_lockINtB3_8OnceLockINtNtCsl3bTtyQSXML_8lock_api5mutex5MutexNtNtCsfqmARTQr4sq_11parking_lot9raw_mutex8RawMutexINtNtNtNtB7_11collections4hash3map7HashMapyyEEE10initializeNCINvB2_11get_or_initNCNvNtCs9p2CpBq5ts3_10weavepy_vm13vm_singletons10worker_map0E0zEB3J_ __RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecNtNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib16faulthandler_mod16RegisteredThreadE8grow_oneBS_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm6object23collect_small_int_range -__RNvYNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins5b_lenINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ __RNvNtCsgxfhAVHT8pU_10weavepy_vm8builtins18new_str_split_list __RNvMst_NtCs9p2CpBq5ts3_10weavepy_vm12shared_valueNtB5_9SharedStr6concat __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter17type_call_default __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter11instantiate __RNvCs9p2CpBq5ts3_10weavepy_vm20object_needs_vm_iter __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter16collect_iterable -__RNvXs0_NtNtCsdq5mISKDh0s_5alloc3vec11spec_extendINtB7_3VecNtNtCs9p2CpBq5ts3_10weavepy_vm6object6ObjectEINtB5_10SpecExtendBU_INtNtB7_9into_iter8IntoIterBU_EE11spec_extendBY_ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter14leaf_fused_len __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter17leaf_builtin_call __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9str_arity @@ -562,7 +549,6 @@ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter15flush_lean_cold __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter15push_lean_shell __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter17retire_lean_frame __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter24specialized_store_subscr -__RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins15ensure_dict_key __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins15ensure_hashable __RNvNtCs9p2CpBq5ts3_10weavepy_vm13vm_singletons23current_interpreter_ptr __RNvNtCs9p2CpBq5ts3_10weavepy_vm6object19dict_mutation_event @@ -579,23 +565,19 @@ __RNvYNCNCNvXs3_Cs9p2CpBq5ts3_10weavepy_vmNtBc_11InterpreterNtNtCs2NHf1dqD6Ob_4c __RNvYNCNCNvXs3_Cs9p2CpBq5ts3_10weavepy_vmNtBc_11InterpreterNtNtCs2NHf1dqD6Ob_4core7default7Default7defaults0_0s_0INtNtNtBY_3ops8function6FnOnceTRNtNtBc_6object6ObjectEE9call_onceBc_ __RNvCs9p2CpBq5ts3_10weavepy_vm17py_frame_traverse __RNvXsm_NtCs9p2CpBq5ts3_10weavepy_vm5typesNtB5_10PyInstanceNtNtNtCs2NHf1dqD6Ob_4core3ops4drop4Drop4drop -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcINtNtCs9p2CpBq5ts3_10weavepy_vm4sync7GilCellNtNtBL_6object6ObjectEE9drop_slowBL_ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter16pop_jump_if_step __RNvMs1r_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_6Object9is_truthy __RNvYNCNCNvXs3_Cs9p2CpBq5ts3_10weavepy_vmNtBc_11InterpreterNtNtCs2NHf1dqD6Ob_4core7default7Default7defaults0_0s0_0INtNtNtBY_3ops8function6FnOnceTRNtNtBc_6object6ObjectEE9call_onceBc_ __RNvCs9p2CpBq5ts3_10weavepy_vm21py_traceback_traverse -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm5types10PyInstanceE9drop_slowBK_ __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object11PyTracebackE9drop_slowBK_ __RNvXse_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB5_11PyTracebackNtNtNtCs2NHf1dqD6Ob_4core3ops4drop4Drop4drop __RNvMs3_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB5_7PyFrame14refresh_locals __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object7PyFrameE9drop_slowBK_ -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object10FrameShellE9drop_slowBK_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm6object16is_function_slot __RNvNtCs9p2CpBq5ts3_10weavepy_vm10specialize29attempt_specialize_store_attr __RNvCs9p2CpBq5ts3_10weavepy_vm16metaclass_method __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins5b_dir __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins14str_startswith -__RNvNtCs9p2CpBq5ts3_10weavepy_vm5tier213try_enter_osr __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter13contains_full __RINvMNtNtCs6KxzipSu1yP_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvCs9p2CpBq5ts3_10weavepy_vm5tsdbg0E0zEB1w_ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter13sort_with_key @@ -642,7 +624,6 @@ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter18inline_gen_deliver __RINvMs2_NtNtCs6KxzipSu1yP_3std6thread5localINtB6_8LocalKeyNtNtCsgxfhAVHT8pU_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_20with_key_eq_deferredINtNtCs2NHf1dqD6Ob_4core6result6ResultINtNtB2u_6option6OptionbENtNtBY_5error12RuntimeErrorENCNvMs4_BY_NtBY_11Interpreter17leaf_builtin_calls2_0E0TB2p_bEEBY_ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter22specialized_store_attr __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter15do_getattr_call -__RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins11dict_lookup __RNvNtCs9p2CpBq5ts3_10weavepy_vm6object12module_class __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter23module_spec_file_origin __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter17ensure_os_environ @@ -652,7 +633,6 @@ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter24alloc_plain_instance_obj __RNvNtCs9p2CpBq5ts3_10weavepy_vm10specialize22type_has_attr_override __RNvMsd_NtCs9p2CpBq5ts3_10weavepy_vm5typesNtB5_10TypeObject18setattr_is_default __RNvMsd_NtCs9p2CpBq5ts3_10weavepy_vm5typesNtB5_10TypeObject21validate_python_bases -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object10PyFunctionE9drop_slowBK_ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter22specialized_compare_op __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15weave_frame_mod9frame_arg __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter18maybe_donate_tuple @@ -664,7 +644,6 @@ __RNvNtCs9p2CpBq5ts3_10weavepy_vm14descr_registry24is_native_descr_accessor __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter15reentrant_py_eq __RNvMs1r_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_6Object15type_name_owned __RNvNvNtCs9p2CpBq5ts3_10weavepy_vm12type_surface24install_type_dict_extras12type_prepare -__RNvCs9p2CpBq5ts3_10weavepy_vm20mangle_class_private __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter24finalize_class_namespace __RINvMs0_NtNtNtNtCs6KxzipSu1yP_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCs2NHf1dqD6Ob_4core4cell7RefCellINtNtNtNtBe_11collections4hash3map7HashMapjNtNtCs9p2CpBq5ts3_10weavepy_vm6object6ObjectEEuE16get_or_init_slowNvNvNtB2A_8builtins15DOCSTRING_CACHE27___rust_std_internal_init_fnEB2A_ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter15do_hasattr_call @@ -732,7 +711,6 @@ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter27dynamic_type_call_with_me __RNCNvMs4_CsgxfhAVHT8pU_10weavepy_vmNtB7_11Interpreter24finalize_class_namespaces_0B7_ __RNvYNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins10dict_itemsINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ __RNvCs9p2CpBq5ts3_10weavepy_vm16is_generic_alias -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object10PyDictViewE9drop_slowBK_ __RNvMs1r_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_6Object9type_name __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter8core_new __RNvMsl_NtCs9p2CpBq5ts3_10weavepy_vm5typesNtB5_10PyInstance12new_deferred @@ -744,7 +722,6 @@ __RNvCs9p2CpBq5ts3_10weavepy_vm23collect_type_parameters __RNvCs9p2CpBq5ts3_10weavepy_vm15is_typevar_like __RNvYNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins11b_bytearrayINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins14b_bytearray_kw -__RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins15bytes_construct __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9dict_keys __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins11dict_values __RNvCs9p2CpBq5ts3_10weavepy_vm9bignum_op @@ -755,8 +732,6 @@ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter17frame_locals_view __RNvYNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins8b_objectINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins8b_object __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter11call_object -__RNvYNvNvNtCs9p2CpBq5ts3_10weavepy_vm13builtin_types22install_object_dunders14object_setattrINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -__RNvNvNtCs9p2CpBq5ts3_10weavepy_vm13builtin_types22install_object_dunders14object_setattr __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15weave_frame_mod7is_comp __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15weave_frame_mod15is_module_scope __RNvXse_NtNtCsdq5mISKDh0s_5alloc3vec9into_iterINtB5_8IntoIterTNtNtCsgxfhAVHT8pU_10weavepy_vm6object6ObjectBX_EENtNtNtCs2NHf1dqD6Ob_4core3ops4drop4Drop4dropB11_ @@ -803,7 +778,6 @@ __RNvCs9p2CpBq5ts3_10weavepy_vm22apply_slice_assignment __RNvCs9p2CpBq5ts3_10weavepy_vm17slice_bound_index __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter20leaf_instance_dunder __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter25default_getattribute_slow -__RNvNtCs9p2CpBq5ts3_10weavepy_vm13builtin_types26make_exception_with_object __RNvMs1r_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB6_6Object4repr __RNvNtCs9p2CpBq5ts3_10weavepy_vm6object16bytes_repr_inner __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter24build_exception_instance @@ -844,7 +818,6 @@ __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter29leaf_resolve_instance_att __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtCs9p2CpBq5ts3_10weavepy_vm8LeafAttrEBD_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins8str_find __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib2os21stat_result_from_meta -__RNvYNvNvNtCs9p2CpBq5ts3_10weavepy_vm13builtin_types22install_object_dunders11object_initINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ __RNvMsk_NtCs9p2CpBq5ts3_10weavepy_vm5typesNtB5_11SlotStorage8index_of __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter19run_py_exact_nofree __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter14load_attr_type @@ -872,15 +845,11 @@ __RNvMNtCsjh7C7x83D1_16cranelift_entity3mapINtB2_12SecondaryMapNtNtNtCsjptKdgsvU __RNvMs3_NtCsjh7C7x83D1_16cranelift_entity4listINtB5_10EntityListNtNtNtCsjptKdgsvUHx_17cranelift_codegen2ir8entities5ValueE4pushB15_ __RNvMs3_NtCsjh7C7x83D1_16cranelift_entity4listINtB5_10EntityListNtNtNtCsjptKdgsvUHx_17cranelift_codegen2ir8entities5ValueE4growB15_ __RNvMNtNtCsbDk7wfpOkh5_17cranelift_codegen2ir12instructionsNtB2_9BlockCall5block -__RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecINtNtCs2NHf1dqD6Ob_4core6option6OptionNtNtCslXHHUCZmUMI_14weavepy_parser3ast4ExprEE8grow_oneB1s_ __RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecINtNtCs2NHf1dqD6Ob_4core6option6OptionmEE8grow_oneCscifjXFcM73a_16weavepy_compiler __RINvMs1_NtCseIGkHRfguhS_9hashbrown3mapINtB6_7HashMapNtNtCsdq5mISKDh0s_5alloc6string6StringuNtNtNtCs6KxzipSu1yP_3std4hash6random11RandomStateE6removeBO_ECsgxfhAVHT8pU_10weavepy_vm __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtCsllk7SLrseIa_14weavepy_parser3ast13ComprehensionEECscifjXFcM73a_16weavepy_compiler -__RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCsllk7SLrseIa_14weavepy_parser3ast13ComprehensionECscifjXFcM73a_16weavepy_compiler __RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVeccE8grow_oneCs86VDVqQvmSJ_13weavepy_lexer __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCsllk7SLrseIa_14weavepy_parser3ast7KeywordECscifjXFcM73a_16weavepy_compiler -__RNvNtCscifjXFcM73a_16weavepy_compiler7ast_opt10eval_binop -__RNvNtCscifjXFcM73a_16weavepy_compiler7ast_opt10str_points __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueTNtCscifjXFcM73a_16weavepy_compiler8ConstantBC_BC_EEBE_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm11stdlib_tree18write_install_json __RNCNvNtCsgxfhAVHT8pU_10weavepy_vm11stdlib_tree18write_install_json0B5_ @@ -978,7 +947,6 @@ __RNvMNtCs4hkhsQnToZM_16cranelift_entity3mapINtB2_12SecondaryMapNtNtCsxQU3dQfy2Z __RNvMNtCsjh7C7x83D1_16cranelift_entity3mapINtB2_12SecondaryMapNtNtCsg5x2jOlcZiN_16cranelift_module6module6FuncIdINtNtCs2NHf1dqD6Ob_4core6option6OptionNtNtCsi4RZ8CCGiUR_13cranelift_jit13compiled_blob12CompiledBlobEE20resize_for_index_mutB2r_ __RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecTjjNtNtCsxQU3dQfy2Z_16cranelift_module6module6FuncIdEE8grow_oneCsfzv165as8SU_13cranelift_jit __RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecNtNtCsxQU3dQfy2Z_16cranelift_module6module6FuncIdE8grow_oneCsfzv165as8SU_13cranelift_jit -__RNvXsb_NtCsdq5mISKDh0s_5alloc3vecINtB5_3VecNtNtCs4AKF9fflq5R_11weavepy_jit2ir9StrMethodENtNtCs2NHf1dqD6Ob_4core5clone5Clone5cloneBJ_ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCs4AKF9fflq5R_11weavepy_jit2ir12AttrSiteMetaEBF_ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCslVgqr2fq4Oj_11weavepy_jit7analyze9PathArenaEBF_ __RNCINvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9method_kwNvB4_12int_to_bytesEs_0B6_ @@ -990,9 +958,6 @@ __RINvMs2_NtNtCs6KxzipSu1yP_3std6thread5localINtB6_8LocalKeyINtNtCs2NHf1dqD6Ob_4 __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter25push_pending_caller_shell __RNvNtCs9p2CpBq5ts3_10weavepy_vm13leaf_builtins4push __RINvMs6_NtCseIGkHRfguhS_9hashbrown3rawINtB6_8RawTableTjNtNtCs4AKF9fflq5R_11weavepy_jit7analyze7PairSrcEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_NtNtNtCs6KxzipSu1yP_3std4hash6random11RandomStateE0EBV_ -__RNvYNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9str_titleINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -__RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins9str_title -__RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecNtNtCs4AKF9fflq5R_11weavepy_jit2ir11GlobalGuardE8grow_oneBQ_ __RNvMNtCs4hkhsQnToZM_16cranelift_entity3mapINtB2_12SecondaryMapNtNtNtCsbDk7wfpOkh5_17cranelift_codegen2ir8entities5ValueNtB10_5BlockE20resize_for_index_mutB14_ __RNvMNtCsjh7C7x83D1_16cranelift_entity3mapINtB2_12SecondaryMapNtNtNtCsjptKdgsvUHx_17cranelift_codegen2ir8entities5ValueNtBZ_5BlockE20resize_for_index_mutB13_ __RNvMNtCsjh7C7x83D1_16cranelift_entity3mapINtB2_12SecondaryMapNtNtNtCsjptKdgsvUHx_17cranelift_codegen2ir8entities5ValuehE20resize_for_index_mutB13_ @@ -1001,29 +966,20 @@ __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15datetime_native13plain_drop_ok __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter12do_bool_call __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter14class_ns_store __RNvNtNtCsgxfhAVHT8pU_10weavepy_vm6stdlib15datetime_native14instance_fixed -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15datetime_native6dt_sub -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15datetime_native6td_mul __RNvYNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins12dict_setitemINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins12dict_setitem __RINvYNtNtCsd2t6IBsyVzy_18cranelift_frontend8frontend15FuncInstBuilderNtNtNtCsbDk7wfpOkh5_17cranelift_codegen2ir7builder11InstBuilder4jumpRINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtB19_12instructions8BlockArgEECs9p2CpBq5ts3_10weavepy_vm -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15datetime_native13format_offset -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15datetime_native16dt_fromisoformat __RNvCs9p2CpBq5ts3_10weavepy_vm14intersect_sets -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15datetime_native9parse_hms -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib15datetime_native8date_sub __RNvMsc_Csf2xUKSCCMOo_8smallvecINtB5_8SmallVecANtNtCsbJykKlzQLBk_9regalloc25index5Blockj10_E21reserve_one_uncheckedCsbDk7wfpOkh5_17cranelift_codegen __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtCs9p2CpBq5ts3_10weavepy_vm5tier211MethodEntryEEB1c_ __RNvMsc_Csf2xUKSCCMOo_8smallvecINtB5_8SmallVecANtNtCsbJykKlzQLBk_9regalloc25index5Blockj10_E8try_growCsbDk7wfpOkh5_17cranelift_codegen __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCsahm1S0TGo59_14target_lexicon6triple6TripleECsbDk7wfpOkh5_17cranelift_codegen -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib18collections_native13deque_getitem __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib18collections_native10deque_bool __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtNtCsfzv165as8SU_13cranelift_jit6memory6system6MemoryEBH_ __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib18collections_native20deque_iterator_index __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins16coerce_index_i64 __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm6object14SlotDescriptorE9drop_slowBK_ -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib18collections_native16deque_appendleft __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtCs9p2CpBq5ts3_10weavepy_vm5types10TypeObjectE9drop_slowBK_ -__RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtNtCsdq5mISKDh0s_5alloc3vec6splice6SpliceINtNtNtNtB4_4iter7sources8repeat_n7RepeatNNtNtCs9p2CpBq5ts3_10weavepy_vm6object6ObjectEEEB24_ __RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecNtNtCsbDk7wfpOkh5_17cranelift_codegen13loop_analysis8LoopDataE8grow_oneBQ_ __RINvXs_NtCsbDk7wfpOkh5_17cranelift_codegen7ctxhashNtB5_7NullCtxINtB5_7CtxHashTNtNtNtB7_2ir5types4TypeNtNtB1i_12instructions15InstructionDataEE8ctx_hashNtCse8Yum7N1ehu_10rustc_hash8FxHasherEB7_ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCsjptKdgsvUHx_17cranelift_codegen9flowgraph16ControlFlowGraphEBF_ @@ -1031,71 +987,44 @@ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCsjptKdgsvUHx_17cranelift_codegen14 __RNvMsc_Csf2xUKSCCMOo_8smallvecINtB5_8SmallVecATmNtNtNtCsbDk7wfpOkh5_17cranelift_codegen3isa6unwind10UnwindInstEj8_E21reserve_one_uncheckedBQ_ __RNvYNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib13itertools_mod10count_coreINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ __RNvMsA_NtCs9p2CpBq5ts3_10weavepy_vm4syncNtB5_8RealLock11try_acquire -__RINvMs6_NtCseIGkHRfguhS_9hashbrown3rawINtB6_8RawTableTyINtNtCsdq5mISKDh0s_5alloc4sync3ArcNtNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib11thread_real17ThreadHandleStateEEE14reserve_rehashNCINvNtB8_3map11make_hasheryBR_NtNtNtCs6KxzipSu1yP_3std4hash6random11RandomStateE0EB1v_ -__RNvNtCs9p2CpBq5ts3_10weavepy_vm5tier214wpjit_list_len __RINvMs6_NtCseIGkHRfguhS_9hashbrown3rawINtB6_8RawTableTmINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtBW_6string6StringEEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_NtNtNtCs6KxzipSu1yP_3std4hash6random11RandomStateE0ECs4AKF9fflq5R_11weavepy_jit __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtCs9p2CpBq5ts3_10weavepy_vm5tier29AttrGuardEEB1c_ __RNvMsc_Csf2xUKSCCMOo_8smallvecINtB5_8SmallVecANtCsbJykKlzQLBk_9regalloc210Allocationj4_E21reserve_one_uncheckedBK_ __RNCINvMs16_NtCs9p2CpBq5ts3_10weavepy_vm6objectNtB9_9BuiltinFn11with_kwargsNvNtNtBb_6stdlib11thread_real21start_joinable_threadEs_0Bb_ -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib11thread_real19spawn_python_worker -__RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecTNtNtB7_6string6StringNtNtCs9p2CpBq5ts3_10weavepy_vm6object6ObjectEE8grow_oneB1c_ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtCs9p2CpBq5ts3_10weavepy_vm3gil8GilGuardEEB1c_ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCs9p2CpBq5ts3_10weavepy_vm3gil8GilGuardEBF_ -__RNvMsA_NtCs9p2CpBq5ts3_10weavepy_vm4syncNtB5_8RealLock15acquire_timeout -__RNvMs_NtCsfqmARTQr4sq_11parking_lot7condvarNtB4_7Condvar19wait_until_internal __RNvMs_NtCswHAcCYaqJh_11parking_lot7condvarNtB4_7Condvar19wait_until_internal __RINvMs0_NtNtNtNtCs6KxzipSu1yP_3std3sys12thread_local6native4lazyINtB6_7StorageNtNtCs8TNC6SO7etN_16parking_lot_core11parking_lot10ThreadDatauE16get_or_init_slowNvNvNvB1g_16with_thread_data11THREAD_DATA27___rust_std_internal_init_fnECsfqmARTQr4sq_11parking_lot __RINvMs0_NtNtNtNtCs6KxzipSu1yP_3std3sys12thread_local6native4lazyINtB6_7StorageNtNtCsdCPRsQxKMa_16parking_lot_core11parking_lot10ThreadDatauE16get_or_init_slowNvNvNvB1g_16with_thread_data11THREAD_DATA27___rust_std_internal_init_fnECswHAcCYaqJh_11parking_lot __RNvMs1_NtCs8TNC6SO7etN_16parking_lot_core11parking_lotNtB5_10ThreadData3new -__RNvMs1_NtCsdCPRsQxKMa_16parking_lot_core11parking_lotNtB5_10ThreadData3new __RNvMNtCs8TNC6SO7etN_16parking_lot_core11parking_lotNtB2_9HashTable3new -__RNvMNtCsdCPRsQxKMa_16parking_lot_core11parking_lotNtB2_9HashTable3new __RINvMs2_NtNtCs6KxzipSu1yP_3std6thread5localINtB6_8LocalKeyNtNtCs9p2CpBq5ts3_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCs2NHf1dqD6Ob_4core6option6OptionNtBW_6ObjectENCNvMs4_BY_NtBY_11Interpreter11instantiates_0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ -__RNSNvYNCINvNtNtCs6KxzipSu1yP_3std6thread9lifecycle15spawn_uncheckedNCNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib11thread_real19spawn_python_workers1_0uEs_0INtNtNtCs2NHf1dqD6Ob_4core3ops8function6FnOnceuE9call_once6vtableB1b_ -__RINvNtNtCs6KxzipSu1yP_3std3sys9backtrace28___rust_begin_short_backtraceNCNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib11thread_real19spawn_python_workers1_0uEB1f_ -__RINvMs6_NtCseIGkHRfguhS_9hashbrown3rawINtB6_8RawTableTyyEE14reserve_rehashNCINvNtB8_3map11make_hasheryyNtNtNtCs6KxzipSu1yP_3std4hash6random11RandomStateE0ECs9p2CpBq5ts3_10weavepy_vm -__RNvNtCs9p2CpBq5ts3_10weavepy_vm13vm_singletons26install_seed_builtin_types __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueTmINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtBI_6string6StringEB1a_EECs9p2CpBq5ts3_10weavepy_vm __RNvMsf_NtCs9p2CpBq5ts3_10weavepy_vm4syncINtB5_7GilCellNtNtB7_16weakref_registry13RegistryInnerE17try_borrow_lockedB7_ -__RNvMs_NtCsfqmARTQr4sq_11parking_lot7condvarNtB4_7Condvar15notify_one_slow __RNvMs_NtCswHAcCYaqJh_11parking_lot7condvarNtB4_7Condvar15notify_one_slow __RNvNtCs8TNC6SO7etN_16parking_lot_core11parking_lot16lock_bucket_pair -__RNvNtCsdCPRsQxKMa_16parking_lot_core11parking_lot16lock_bucket_pair -__RNvMs1_NtCsfqmARTQr4sq_11parking_lot9raw_mutexNtB5_8RawMutex9lock_slow __RNvMs1_NtCswHAcCYaqJh_11parking_lot9raw_mutexNtB5_8RawMutex9lock_slow -__RNvXNtNtCs2NHf1dqD6Ob_4core4iter8adaptersINtB2_12GenericShuntINtNtB2_3map3MapINtNtNtB6_5slice4iter4IterReENCNvMs_NtNtCsgxfhAVHT8pU_10weavepy_vm6stdlib12pickle_accelNtB1N_20ModuleFunctionsGuard3new0EINtNtB6_6option6OptionNtNtB6_7convert10InfallibleEENtNtNtB4_6traits8iterator8Iterator4nextB1R_ __RNCNvNtCs9p2CpBq5ts3_10weavepy_vm5tier215method_ret_infos6_0B5_ -__RNvMsf_NtCs9p2CpBq5ts3_10weavepy_vm4syncINtB5_7GilCellAjj3_E21try_borrow_mut_lockedB7_ -__RNvMsf_NtCs9p2CpBq5ts3_10weavepy_vm4syncINtB5_7GilCellAjj3_E17try_borrow_lockedB7_ -__RNvYNvNvNtCs9p2CpBq5ts3_10weavepy_vm13builtin_types22install_object_dunders14object_delattrINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -__RNvNtCs9p2CpBq5ts3_10weavepy_vm5tier215wpjit_bytes_get -__RNvNvNtCs9p2CpBq5ts3_10weavepy_vm13builtin_types22install_object_dunders14object_delattr __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter24generic_delattr_instance __RNvMsf_NtCs9p2CpBq5ts3_10weavepy_vm4syncINtB5_7GilCellNtNtB7_16weakref_registry13RegistryInnerE21try_borrow_mut_lockedB7_ __RNvCs9p2CpBq5ts3_10weavepy_vm16fallback_globals __RNvNtCs9p2CpBq5ts3_10weavepy_vm5tier217wpjit_list_repeat __RNvNtCs9p2CpBq5ts3_10weavepy_vm5tier217enter_scalar_leaf -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcINtNtCsl3bTtyQSXML_8lock_api5mutex5MutexNtNtCsfqmARTQr4sq_11parking_lot9raw_mutex8RawMutexINtNtCs2NHf1dqD6Ob_4core6option6OptionIBx_NtNtCs9p2CpBq5ts3_10weavepy_vm15thread_registry11ThreadEntryEEEE9drop_slowB2S_ __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcINtNtCs6dvEX9a1rCm_8lock_api5mutex5MutexNtNtCswHAcCYaqJh_11parking_lot9raw_mutex8RawMutexINtNtCs2NHf1dqD6Ob_4core6option6OptionIBx_NtNtCsgxfhAVHT8pU_10weavepy_vm15thread_registry11ThreadEntryEEEE9drop_slowB2R_ __RNvYNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins5b_ordINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins5b_ord -__RNvNtCs9p2CpBq5ts3_10weavepy_vm6object13int_from_i128 -__RNCNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib11thread_real25make_thread_handle_objects_0B7_ -__RNvMs0_NtNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder10save_items __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib12pickle_accel6encode15InstanceContextEEB15_ __RNvMs1_NtCsdq5mISKDh0s_5alloc3vecINtB5_3VechE6resizeCs9p2CpBq5ts3_10weavepy_vm __RNvYNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins5b_chrINtNtNtCs2NHf1dqD6Ob_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins5b_chr __RNvMs1_NtCsfqmARTQr4sq_11parking_lot9raw_mutexNtB5_8RawMutex11unlock_slow __RNvMs1_NtCswHAcCYaqJh_11parking_lot9raw_mutexNtB5_8RawMutex11unlock_slow -__RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib11thread_real20join_wait_collecting __RINvNtNtNtNtCs6KxzipSu1yP_3std3sys12thread_local6native4lazy7destroyNtNtCs8TNC6SO7etN_16parking_lot_core11parking_lot10ThreadDataECsfqmARTQr4sq_11parking_lot __RINvNtNtNtNtCs6KxzipSu1yP_3std3sys12thread_local6native4lazy7destroyNtNtCsdCPRsQxKMa_16parking_lot_core11parking_lot10ThreadDataECswHAcCYaqJh_11parking_lot __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib7sre_mod11sre_compile __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib7sre_mod8sre_exec __RNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib7sre_mod14subject_to_vec __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueINtNtCsdq5mISKDh0s_5alloc5boxed3BoxNtNtCs9p2CpBq5ts3_10weavepy_vm5tier27CallCtxEEB1e_ -__RNvNtNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib12pickle_accel7classes14is_member_slot __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib12pickle_accel6encode9ClassPlanE9drop_slowBO_ __RNvNtNtCslSKxsPn8Dnr_10num_bigint7biguint11subtraction4sub2 __RNvXNtNtCslSKxsPn8Dnr_10num_bigint7biguint11subtractionNtB4_7BigUintINtNtNtCs2NHf1dqD6Ob_4core3ops5arith3SubRBR_E3sub @@ -1103,12 +1032,9 @@ __RINvNtNtNtCs2NHf1dqD6Ob_4core5slice4sort8unstable7ipnsortTjjNtNtCsxQU3dQfy2Z_1 __RINvNtNtNtCs2NHf1dqD6Ob_4core5slice4sort8unstable7ipnsortTjjNtNtCsg5x2jOlcZiN_16cranelift_module6module6FuncIdENCINvMB6_SBT_20sort_unstable_by_keyjNCNvMs0_NtCsi4RZ8CCGiUR_13cranelift_jit7backendNtB2t_9JITModule20finalize_definitionss0_0E0EB2v_ __RNvCs9p2CpBq5ts3_10weavepy_vm8unary_op __RNvMsf_NtCs9p2CpBq5ts3_10weavepy_vm4syncINtB5_7GilCellNtNtB7_6object10PyIteratorE17try_borrow_lockedB7_ -__RNvMs1_NtNtCs6KxzipSu1yP_3std6thread9lifecycleINtB5_9JoinInneruE4joinCs9p2CpBq5ts3_10weavepy_vm -__RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcINtNtNtCs6KxzipSu1yP_3std6thread9lifecycle6PacketuEE9drop_slowCs9p2CpBq5ts3_10weavepy_vm __RNvNtCs9p2CpBq5ts3_10weavepy_vm8builtins7b_float __RNvMs4_Cs9p2CpBq5ts3_10weavepy_vmNtB5_11Interpreter8op_truth __RNvCs9p2CpBq5ts3_10weavepy_vm18long_overflows_f64 -__RNvXs_NtCsbLzj8cKgNSH_4zmij7privatedNtB4_6Sealed20write_to_zmij_buffer __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcNtNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib10json_accel10EncoderCfgE9drop_slowBM_ __RNvMsn_NtCsdq5mISKDh0s_5alloc4syncINtB5_3ArcINtNtB7_3vec3VecmEE9drop_slowCs9p2CpBq5ts3_10weavepy_vm __RNvNtCs9p2CpBq5ts3_10weavepy_vm9proc_init23restore_initial_std_fds @@ -1136,7 +1062,6 @@ __RNCINvMs0_NtNtCs6KxzipSu1yP_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtB __RNvMs0_NtCs67nvpeQgtOq_13weavepy_lexer5tokenNtB5_7Keyword10from_ident __RNvMs5_NtCsdq5mISKDh0s_5alloc7raw_vecNtB5_11RawVecInner11finish_growCs67nvpeQgtOq_13weavepy_lexer __RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecmE8grow_oneCs67nvpeQgtOq_13weavepy_lexer -__RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib13codecs_engine6EncCtxEBH_ __RNvMs5_NtCsdq5mISKDh0s_5alloc7raw_vecNtB5_11RawVecInner11finish_growCslXHHUCZmUMI_14weavepy_parser __RNvMs5_NtCsdq5mISKDh0s_5alloc7raw_vecNtB5_11RawVecInner11finish_growCs9DEk322Hfll_16weavepy_compiler __RINvNvMs2_NtCsdq5mISKDh0s_5alloc7raw_vecINtB8_11RawVecInnerpE7reserve21do_reserve_and_handleNtNtBa_5alloc6GlobalECs9DEk322Hfll_16weavepy_compiler @@ -1261,7 +1186,6 @@ __RINvNtCs2NHf1dqD6Ob_4core3ptr9drop_glueNtNtCsjptKdgsvUHx_17cranelift_codegen13 __RNvMs4_NtCsdq5mISKDh0s_5alloc7raw_vecINtB5_6RawVecINtNtB7_3vec3VecyEE8grow_oneCs9p2CpBq5ts3_10weavepy_vm __RNvMs0_NtCs9p2CpBq5ts3_10weavepy_vm15thread_registryNtB5_14ThreadRegistry8register __RINvNtNtCs6KxzipSu1yP_3std3sys9backtrace28___rust_begin_short_backtraceNCNCNCINvNtNtB6_6thread9lifecycle15spawn_uncheckedNCNvNtNtCs9p2CpBq5ts3_10weavepy_vm6stdlib11thread_real19spawn_python_workers1_0uEs_000uEB23_ -__RNCNvNtCs4AKF9fflq5R_11weavepy_jit7analyze15analyze_for_rets5_0B5_ __RNvNtCs9p2CpBq5ts3_10weavepy_vm13vm_singletons24install_worker_thread_id __RNvMsf_NtCs9p2CpBq5ts3_10weavepy_vm4syncINtB5_7GilCellINtNtCsdq5mISKDh0s_5alloc3vec3VecONtB7_11InterpreterEE21try_borrow_mut_lockedB7_ __RNvMsf_NtCs9p2CpBq5ts3_10weavepy_vm4syncINtB5_7GilCellINtNtCsdq5mISKDh0s_5alloc3vec3VecNtNtB7_13vm_singletons13ThreadHandlesEE21try_borrow_mut_lockedB7_ @@ -1824,14 +1748,12 @@ mi_bbitmap_try_find_and_clear mi_bchunk_try_find_and_clear8 mi_bbitmap_init mi_bitmap_clearN -mi_bitmap_chunkmap_try_clear.isra.0 mi_bbitmap_unsafe_setN mi_bitmap_popcountN mi_bbitmap_try_find_and_clearNX mi_bitmap_clear mi_bchunk_xsetNC mi_bbitmap_setN -mi_bbitmap_chunkmap_try_clear.isra.0 mi_bitmap_init mi_bchunk_try_find_and_clearNX mi_bbitmap_try_clearNC @@ -2001,7 +1923,6 @@ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCsaWnZMC9MjUX_10weavepy_vm16Interprete _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5lUuJoaUEBp_16weavepy_compiler8ColTableEBD_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5lUuJoaUEBp_16weavepy_compiler10RareFieldsEBD_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterTINtBG_3VechENtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectEEEB1G_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsaWnZMC9MjUX_10weavepy_vm14descr_registry9DescrMetaEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs7DszM8lEsNG_10serde_json3map3MapNtNtCs1C1lLj4PWSY_5alloc6string6StringNtNtBG_5value5ValueEECsaWnZMC9MjUX_10weavepy_vm _RINvNtCsevLNFiNqfJP_4core3mem4dropINtNtB4_6option6OptionINtNtCsaWnZMC9MjUX_10weavepy_vm2rc2RcINtNtBX_4sync7GilCellNtNtBX_6object8DictDataEEEEBX_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsaWnZMC9MjUX_10weavepy_vm6object8DepartedEBF_ @@ -2530,7 +2451,6 @@ _RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsaWnZMC9MjUX_10weavepy_vm6objec _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsaWnZMC9MjUX_10weavepy_vm7dictmap6BucketENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsaWnZMC9MjUX_10weavepy_vm7dictmap6BucketuEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBK_ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtB7_6string6StringENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCs5Hy3mROkL0v_11weavepy_cli -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ _RNvMNtCs1C1lLj4PWSY_5alloc3vecINtB2_3VecNtCs5lUuJoaUEBp_16weavepy_compiler10ExcHandlerE13with_capacityBE_ _RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectE8truncateBI_ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtCs5lUuJoaUEBp_16weavepy_compiler8ConstantENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCsaWnZMC9MjUX_10weavepy_vm @@ -2540,7 +2460,6 @@ _RNvXNtNtNtCsgHYyB3hU8Ec_3std6thread6thread18thread_name_stringNtB2_16ThreadName _RINvMNtCsaWnZMC9MjUX_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtB5_6object6ObjectEEB5_ _RINvMNtCsaWnZMC9MjUX_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1t_3ops5range5RangejENCNCNvMs4_B5_NtB5_11Interpreter17fill_extended_raw00EEB5_ _RINvMNtCsaWnZMC9MjUX_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterQINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtB5_6object6ObjectEEB5_ -_RINvMNtCsaWnZMC9MjUX_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtNtB1t_5slice4iter4IterNtNtB5_6object6ObjectEEEB5_ _RNvXs0_NtNtCsevLNFiNqfJP_4core5array5drainQINtB5_5DrainReNCINvMNtNtB9_3ops9try_traitINtBZ_17NeverShortCircuitNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectE10wrap_mut_1BR_NCNvXs3_B1N_NtB1N_11InterpreterNtNtB9_7default7Default7defaults_0E0EINtNtB11_8function5FnMutTjEE8call_mutB1N_ _mi_allocator_init mi_process_attach @@ -2726,7 +2645,6 @@ _RNvXs6_NtNtCsevLNFiNqfJP_4core3fmt3numjNtB7_8LowerHex3fmt _RNvXNtNtNtCsevLNFiNqfJP_4core3fmt3num3imphNtB6_7Display3fmt _RNvXs9_NtNtNtCsevLNFiNqfJP_4core3fmt3num3implNtB9_7Display3fmt _RNvXse_NtNtNtCsevLNFiNqfJP_4core3fmt3num3impxNtB9_7Display3fmt -_RNvXs8_NtNtNtCsevLNFiNqfJP_4core3fmt3num3impmNtB9_7Display3fmt _RNvXs2_NtCs1C1lLj4PWSY_5alloc3streNtNtB7_6borrow7ToOwned8to_owned _RNvMs3_NtCs1C1lLj4PWSY_5alloc3stre12to_lowercase _RNvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib13codecs_engine11utf8_decode @@ -2754,7 +2672,6 @@ _RNvMsf_NtCsaWnZMC9MjUX_10weavepy_vm4syncINtB5_7GilCellxE10borrow_mutB7_ _RNvMsK_NtCsaWnZMC9MjUX_10weavepy_vm4syncNtB5_7GilLock12try_lock_for _RNvNtCsaWnZMC9MjUX_10weavepy_vm4sync14note_vm_thread _RNvMsf_NtCsaWnZMC9MjUX_10weavepy_vm4syncINtB5_7GilCellNtNtB7_6object6ObjectE6borrowB7_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCsaWnZMC9MjUX_10weavepy_vm4sync3RefNtNtBG_6object10PyIteratorEEBG_ _RNvMs2_NtCsaWnZMC9MjUX_10weavepy_vm8gc_traceNtB5_8Registry10forget_key _RNvMs4_NtCsaWnZMC9MjUX_10weavepy_vm8gc_traceNtB5_7GcState19sweep_deferred_from.llvm.11043968194109836189 _RNCNvMs4_NtCsaWnZMC9MjUX_10weavepy_vm8gc_traceNtB7_7GcState18collect_generation0B9_ @@ -3034,14 +2951,10 @@ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCsaWnZMC9MjUX_10weavepy_vm6ob _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtCsaWnZMC9MjUX_10weavepy_vm10MethodSlotE8and_thenPNtNtBL_6object10PyFunctionNCINvMs4_BL_NtBL_11Interpreter9leaf_coreKb0_Esq_0EBL_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtBG_6string6StringjEEECsaWnZMC9MjUX_10weavepy_vm _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters5chain5ChainINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectEINtNtBG_3map3MapIB1e_TNtNtB1k_6string6StringB21_EENCNvMs4_B25_NtB25_11Interpreter20core_builtin_kw_lane0EEEB25_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters9enumerate9EnumerateINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainNtCs5lUuJoaUEBp_16weavepy_compiler8ConstantEEEB24_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTINtNtCsaWnZMC9MjUX_10weavepy_vm2rc2RcNtNtB13_6object10PyFunctionEIBZ_NtCs5lUuJoaUEBp_16weavepy_compiler10CodeObjectEEEEB13_.llvm.17678331130600083860 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCskibSv91bgl1_9hashbrown3raw8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEEECs5lUuJoaUEBp_16weavepy_compiler -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCsgHYyB3hU8Ec_3std4sync9once_lock8OnceLockINtNtB4_6option6OptionINtNtCsaWnZMC9MjUX_10weavepy_vm12shared_value7ThinArcINtB1N_12SliceStorageNtNtB1P_6object7DictKeyEEEEEB1P_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4ExprEEECs5lUuJoaUEBp_16weavepy_compiler _RINvMs_Csbg2BJAIJWf_7weavepyNtB5_10RunOptions15with_extra_pathINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsgHYyB3hU8Ec_3std4path7PathBufEB1v_ECs5Hy3mROkL0v_11weavepy_cli _RNvMsz_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_8IntoItercNtNtB7_7set_val9SetValZSTE10dying_nextCsaWnZMC9MjUX_10weavepy_vm -_RNvNvNtCsaWnZMC9MjUX_10weavepy_vm13builtin_types30install_mutable_container_init9list_init _RNvMs1k_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB6_6PyFile10read_bytes _RNvMs1k_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB6_6PyFile8readable _RNvMs1k_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB6_6PyFile14read_bytes_opt @@ -3053,7 +2966,6 @@ _RNvMs1k_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB6_6PyFile12close_report _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjuEE14reserve_rehashNCINvNtB8_3map11make_hasherjuNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECslMglkRgF9CW_11weavepy_jit _RINvNtCsaWnZMC9MjUX_10weavepy_vm3gil18allow_threads_thenINtNtCsevLNFiNqfJP_4core6result6ResultNtNtCsgHYyB3hU8Ec_3std2fs4FileNtNtNtBX_2io5error5ErrorENCNvNtB4_8builtins6b_opens_0EB4_ _RNvNtCs5lUuJoaUEBp_16weavepy_compiler12cpython_code13cache_entries -_RNvYNvNvNtCsaWnZMC9MjUX_10weavepy_vm13builtin_types30install_mutable_container_init9list_initINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter22instance_call_function _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter12do_exec_call _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter12load_special @@ -3085,7 +2997,6 @@ _RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4h _RNvXsu_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3setINtB5_4IterjENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4nextCslMglkRgF9CW_11weavepy_jit _RINvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib10json_accel11with_interpNCNvB2_17json_make_encoders2_0TbbbEEB6_ _RINvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib10json_accel11with_interpNCNvB2_12encoder_calls_0NtNtB6_6object6ObjectEB6_ -_RNvMs3_NtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter6finish _RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6copied6CopiedINtNtNtBc_5slice4iter4IterjEENtNtNtBa_6traits8iterator8Iterator7collectINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetjEECslMglkRgF9CW_11weavepy_jit _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtCs5lUuJoaUEBp_16weavepy_compiler8ConstantENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBH_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjmNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCslMglkRgF9CW_11weavepy_jit @@ -3169,37 +3080,14 @@ _RNvMs2_NtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib11marshal_modNtB5_4Scan4unit _RNvMNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib11marshal_modNtB2_13MarshalWriter17write_code_fields _RNvXs_NvMs_NtNtCs1C1lLj4PWSY_5alloc3ffi5c_strNtB9_7CString3newRShNtB4_11SpecNewImpl13spec_new_impl _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4ExprEENtNtBK_5clone5Clone5cloneCs5lUuJoaUEBp_16weavepy_compiler -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast9TypeParamENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCs5lUuJoaUEBp_16weavepy_compiler -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs5lUuJoaUEBp_16weavepy_compiler6fxhash8FxHasherEE6removeBO_EB2i_ _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEE12remove_entryNCINvNtB8_3map14equivalent_keyBQ_BQ_uE0ECs5lUuJoaUEBp_16weavepy_compiler -_RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4StmtNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalECs5lUuJoaUEBp_16weavepy_compiler.llvm.5760298518589479789 -_RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCs4mGAQSAXlfR_14weavepy_parser3ast3ArgNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalECs5lUuJoaUEBp_16weavepy_compiler.llvm.5760298518589479789 -_RNvXsM_NtCs4mGAQSAXlfR_14weavepy_parser3astNtB5_9ArgumentsNtNtCsevLNFiNqfJP_4core5clone5Clone5clone -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5lUuJoaUEBp_16weavepy_compiler12LazyClassCtxEBD_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmTmNtNtCslMglkRgF9CW_11weavepy_jit5value7JitTypeENtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBU_ _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmTmNtNtCslMglkRgF9CW_11weavepy_jit5value7JitTypeEEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EBX_ _RINvMs2_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB6_7HashMapmTmNtNtCslMglkRgF9CW_11weavepy_jit5value7JitTypeEE3getmEB1b_ _RINvMs2_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB6_7HashMapjTmmmEE3getjECslMglkRgF9CW_11weavepy_jit _RINvMsi_NtCskibSv91bgl1_9hashbrown3rawINtB6_12RawIterRangeTmuEE9fold_implNCINvXsG_NtB8_3mapINtB1i_4ItermuENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4folduNCINvXsU_B1i_INtB1i_4KeysmuEB1G_4folduNCINvXsB_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3setINtB3s_12IntersectionmNtNtNtB3y_4hash6random11RandomStateEB1G_4folduNCINvNtNtB1M_8adapters6copied9copy_foldmuNCINvNtB5p_3map8map_foldmBU_uNCINvXs8_NtB8_3setINtB6z_7HashSetmB4y_EINtNtB1K_7collect6ExtendmE6extendINtB5n_6CopiedB4c_EE0NCINvNvB1G_8for_each4callBU_NCINvXs1i_B1i_INtB1i_7HashMapmuB4y_EIB74_BU_E6extendINtB62_3MapB7A_B6q_EE0E0E0E0E0E0E0uECslMglkRgF9CW_11weavepy_jit _RINvMs2_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB6_7HashMapjNtNtCslMglkRgF9CW_11weavepy_jit7analyze7PairSrcE3getjEB19_ -_RNvMs_NtCs5lUuJoaUEBp_16weavepy_compiler8validateNtB4_9Validator19visit_comprehension -_RNvNtCs5lUuJoaUEBp_16weavepy_compiler8validate20collect_name_targets -_RNvMs_NtCs5lUuJoaUEBp_16weavepy_compiler8validateNtB4_9Validator13record_walrus -_RNvNtCs5lUuJoaUEBp_16weavepy_compiler8validate22collect_walrus_targets -_RNvMs0_NtCs5lUuJoaUEBp_16weavepy_compiler9flowgraphNtB5_3Cfg15make_load_const _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler21compile_comprehension -_RNvCs5lUuJoaUEBp_16weavepy_compiler24expr_contains_async_comp -_RNvCs5lUuJoaUEBp_16weavepy_compiler19expr_contains_await -_RNvCs5lUuJoaUEBp_16weavepy_compiler17compile_comp_body -_RNvCs5lUuJoaUEBp_16weavepy_compiler20comp_clause_is_async -_RNvCs5lUuJoaUEBp_16weavepy_compiler18collect_comp_reads -_RNvNvCs5lUuJoaUEBp_16weavepy_compiler25reject_walrus_in_iterable4scan -_RNvCs5lUuJoaUEBp_16weavepy_compiler19stamp_comp_elt_span -_RNvCs5lUuJoaUEBp_16weavepy_compiler22check_comp_walrus_nest -_RNvNvCs5lUuJoaUEBp_16weavepy_compiler22check_comp_walrus_nest5visit -_RNvNvCs5lUuJoaUEBp_16weavepy_compiler27collect_comp_scope_walruses5visit -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast13ComprehensionE8grow_oneBQ_ -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser14parse_comp_for _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSNtNtCs4mGAQSAXlfR_14weavepy_parser3ast13ComprehensionECs5lUuJoaUEBp_16weavepy_compiler.llvm.5039911182826057357 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtCs5lUuJoaUEBp_16weavepy_compiler15CompWalrusScopeEEB1a_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmmNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCslMglkRgF9CW_11weavepy_jit @@ -3214,33 +3102,19 @@ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections _RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjuNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE12contains_keyjECslMglkRgF9CW_11weavepy_jit _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell4CellTyyEEE4withNCNvMNtNtBa_4hash6randomNtB1I_11RandomState3new0B21_ECslMglkRgF9CW_11weavepy_jit _RNvYNCNKNvNvMNtNtCsgHYyB3hU8Ec_3std4hash6randomNtBb_11RandomState3new4KEYS0s_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1l_6option6OptionQIB20_INtNtB1l_4cell4CellTyyEEEEEE9call_onceCslMglkRgF9CW_11weavepy_jit -_RNCNvMs_NtCs5lUuJoaUEBp_16weavepy_compiler8validateNtB6_9Validator10visit_stmt0B8_ _RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters5chainINtB5_5ChainINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterNtNtCs1C1lLj4PWSY_5alloc6string6StringEINtB13_10DifferenceB1S_INtNtBb_4hash18BuildHasherDefaultNtNtCs5lUuJoaUEBp_16weavepy_compiler6fxhash8FxHasherEEENtNtNtB9_6traits8iterator8Iterator4folduNCINvNtB7_3map8map_foldRB1S_B1S_uNvYB1S_NtNtBb_5clone5Clone5cloneNCIB4Z_B1S_TB1S_uEuNCINvXs8_NtCskibSv91bgl1_9hashbrown3setINtB6r_7HashSetB1S_B2S_EINtNtB4m_7collect6ExtendB1S_E6extendINtNtB7_6cloned6ClonedINtB13_5UnionB1S_B2S_EEE0NCINvNvB4i_8for_each4callB6a_NCINvXs1i_NtB6t_3mapINtB9h_7HashMapB1S_uB2S_EIB7k_B6a_E6extendINtB51_3MapB7T_B6i_EE0E0E0E0EB3t_ -_RNvMNtCs5lUuJoaUEBp_16weavepy_compiler6mangleNtB2_7Mangler4name -_RNvMNtCs5lUuJoaUEBp_16weavepy_compiler6mangleNtB2_7Mangler4stmt.llvm.7097748234550460502 -_RNvMNtCs5lUuJoaUEBp_16weavepy_compiler6mangleNtB2_7Mangler4expr -_RNvNtCs5lUuJoaUEBp_16weavepy_compiler6mangle17mangle_class_body _RINvMsi_NtCskibSv91bgl1_9hashbrown3rawINtB6_12RawIterRangeTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEE9fold_implNCINvXsG_NtB8_3mapINtB1T_4IterBV_uENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4folduNCINvXsU_B1T_INtB1T_4KeysBV_uEB2j_4folduNCINvXsF_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3setINtB47_10DifferenceBV_INtNtB2r_4hash18BuildHasherDefaultNtNtCs5lUuJoaUEBp_16weavepy_compiler6fxhash8FxHasherEEB2j_4folduNCINvNtNtB2p_8adapters3map8map_foldRBV_BV_uNvYBV_NtNtB2r_5clone5Clone5cloneNCIB6Q_BV_BU_uNCINvXs8_NtB8_3setINtB8n_7HashSetBV_B5d_EINtNtB2n_7collect6ExtendBV_E6extendINtNtB6U_6cloned6ClonedINtB47_5UnionBV_B5d_EEE0NCINvNvB2j_8for_each4callBU_NCINvXs1i_B1T_INtB1T_7HashMapBV_uB5d_EIB8U_BU_E6extendINtB6S_3MapB9s_B8e_EE0E0E0E0E0E0E0uEB5P_ _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEE12remove_entryNCINvNtB8_3map14equivalent_keyeBQ_uE0ECs5lUuJoaUEBp_16weavepy_compiler _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecTjjEEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1v_3ops5range5RangejENCNvMs1_NtCs5lUuJoaUEBp_16weavepy_compiler9flowgraphNtB2L_3Cfg26insert_prefix_instructions0EE9from_iterB2N_ -_RNvCs5lUuJoaUEBp_16weavepy_compiler24collect_self_attr_stores _RNvXs1i_NtCsevLNFiNqfJP_4core3fmtReNtB6_7Display3fmtCs5lUuJoaUEBp_16weavepy_compiler _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler18cell_or_free_index _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler28compile_deferred_annotations _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler17compile_class_def -_RNvCs5lUuJoaUEBp_16weavepy_compiler20stmt_needs_classdict _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler16build_class_body _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler19compile_class_value -_RNCNvCs5lUuJoaUEBp_16weavepy_compiler32class_body_defs_claim_class_cell0B3_ -_RNvNvCs5lUuJoaUEBp_16weavepy_compiler23class_body_reads_dunder10stmt_reads -_RNvNvCs5lUuJoaUEBp_16weavepy_compiler24collect_self_attr_stores6target _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler21note_identifier_const -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast7KeywordE8grow_oneBQ_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collectINtB6_3VecNtCs5lUuJoaUEBp_16weavepy_compiler8ConstantEINtNtB6_14spec_from_iter12SpecFromIterBY_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB6_9into_iter8IntoIterNtNtB8_6string6StringENcNtBY_3Str0EE9from_iterB10_ _RNvMNtCs1C1lLj4PWSY_5alloc5sliceSNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4Stmt6to_vecCs5lUuJoaUEBp_16weavepy_compiler -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser15parse_class_def -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5lUuJoaUEBp_16weavepy_compiler6mangle7ManglerEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast7KeywordEECs5lUuJoaUEBp_16weavepy_compiler _RNvXs2_NtNtCsgHYyB3hU8Ec_3std4hash6randomNtB5_13DefaultHasherNtNtCsevLNFiNqfJP_4core4hash6Hasher5write.llvm.10899224388223826234 _RNvMs4_NtNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3map5entryINtB5_11VacantEntrymNtNtB9_7set_val9SetValZSTE12insert_entryCslMglkRgF9CW_11weavepy_jit _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjTmmENtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCslMglkRgF9CW_11weavepy_jit @@ -3249,23 +3123,15 @@ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters3map3MapINtNtN _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterNtCs5lUuJoaUEBp_16weavepy_compiler8ConstantENvCsaWnZMC9MjUX_10weavepy_vm18constant_to_objectENtNtB35_6object6ObjectEB35_ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTNtNtB7_6string6StringNtCs5lUuJoaUEBp_16weavepy_compiler7CompSymEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneB13_ _RNvNtCs5lUuJoaUEBp_16weavepy_compiler6mangle13demangle_name -_RNvMNtCs5lUuJoaUEBp_16weavepy_compiler6mangleNtB2_7Mangler9arguments _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtCs5lUuJoaUEBp_16weavepy_compiler8ConstantEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB28_5slice4iter4IterNtNtCs4mGAQSAXlfR_14weavepy_parser3ast5AliasENCNvMsK_BW_NtBW_8Compiler19compile_import_from0EE9from_iterBW_ _RINvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_14compile_assign0EB6_ _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler27collect_nested_comp_symbols -_RNvCs5lUuJoaUEBp_16weavepy_compiler29collect_comp_scope_inner_free -_RNvCs5lUuJoaUEBp_16weavepy_compiler12comp_inlines _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler14comp_own_cells _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler29collect_global_walrus_shallow _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler12comp_symbols -_RNvCs5lUuJoaUEBp_16weavepy_compiler20expr_yields_in_scope -_RNvCs5lUuJoaUEBp_16weavepy_compiler28collect_target_names_ordered _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler13closure_index -_RNvCs5lUuJoaUEBp_16weavepy_compiler25expr_contains_typeparamfn _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler21collect_names_shallow -_RNvCs5lUuJoaUEBp_16weavepy_compiler31collect_inlined_comp_inner_free _RNvYINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterTNtNtB9_6string6StringNtCs5lUuJoaUEBp_16weavepy_compiler7CompSymEENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator3nthB1e_ -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser17parse_import_from _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtBG_6string6StringNtCs5lUuJoaUEBp_16weavepy_compiler7CompSymEEEB1w_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters3rev3RevINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterTNtNtB1g_6string6StringINtNtB4_6option6OptionNtCs5lUuJoaUEBp_16weavepy_compiler7BindingEEEEEB2I_ _RNvMsf_CsaWnZMC9MjUX_10weavepy_vmNtB5_8SumState7entered @@ -3278,8 +3144,6 @@ _RINvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB6_8Compiler15needed_in_innerNCNvB2_2 _RNCNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB7_8Compiler27collect_nested_comp_symbols0B7_ _RNCNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB7_8Compiler29collect_global_walrus_shallows_0B7_ _RNCNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB7_8Compiler21collect_names_shallow0B7_ -_RNvMNtCslNdsVBa5Sgt_13weavepy_lexer7scannerNtB2_7Scanner19note_invalid_escape -_RNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt18eval_unaryop_const _RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetmEEE11extend_withCslMglkRgF9CW_11weavepy_jit _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetmEENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalECslMglkRgF9CW_11weavepy_jit _RINvMs0_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmuNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6retainNCINvMs_NtB8_3setINtB1T_7HashSetmBQ_E6retainNCNvNtCslMglkRgF9CW_11weavepy_jit7analyze22entry_unassigned_reads0E0EB2z_ @@ -3288,12 +3152,9 @@ _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmINtNtCs1C1lLj4PWSY_5allo _RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjjNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE12contains_keyjECslMglkRgF9CW_11weavepy_jit _RINvMs2_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB6_7HashMapmNtNtCslMglkRgF9CW_11weavepy_jit5value7JitTypeE3getmEB19_ _RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultdNtNtNtB5_3num11float_parse15ParseFloatErrorE7map_errNtNtCs1C1lLj4PWSY_5alloc6string6StringNCNvNtCs4mGAQSAXlfR_14weavepy_parser6parser12parse_numbers1_0EB2h_ -_RINvNvNtCs5lUuJoaUEBp_16weavepy_compiler6intern13constant_hash4hashNtNtNtCsgHYyB3hU8Ec_3std4hash6random13DefaultHasherEB6_ -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapymNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCs5lUuJoaUEBp_16weavepy_compiler _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecmEINtB2_12SpecFromItermINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtNtB1q_3str4iter5CharsNCNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt10str_points0EE9from_iterB2A_ _RNvXsf_NtNtCsevLNFiNqfJP_4core5slice3cmpReNtB5_13SliceContains14slice_containsCs4mGAQSAXlfR_14weavepy_parser _RINvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_18compile_expr_inners3_0EB6_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4StmtEEB1c_ _RNvMs4_NtCsaWnZMC9MjUX_10weavepy_vm8gc_traceNtB5_7GcState14is_tracked_obj _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter16load_from_source _RNvMsf_CsaWnZMC9MjUX_10weavepy_vmNtB5_8SumState3add @@ -3307,11 +3168,8 @@ _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler14compile_delete _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler20compile_ex_call_args _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler23compile_slice_two_parts _RNvCs5lUuJoaUEBp_16weavepy_compiler19clone_finally_frame -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser11parse_while -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser16parse_else_block _RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser24skip_trivia_and_newlines _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4ExprEBF_ -_RNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt6int_of _RNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt16eval_binop_const _RINvMs6_NtCs1PctigBqNUG_9hashbrown3rawINtB6_8RawTableTNtNtCsh6LdJn3jKWc_9regalloc25index5BlockuEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_uINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtCsdwcRXB9VvRM_10rustc_hash8FxHasherEE0ECs6NsaeEkylgU_17cranelift_codegen _RINvMs6_NtCs1PctigBqNUG_9hashbrown3rawINtB6_8RawTableTNtCsh6LdJn3jKWc_9regalloc210AllocationBQ_EE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BQ_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtCsdwcRXB9VvRM_10rustc_hash8FxHasherEE0ECs6NsaeEkylgU_17cranelift_codegen @@ -3850,7 +3708,6 @@ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4mGAQSAXlfR_14weavepy_parser3a _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast5AliasENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCs5lUuJoaUEBp_16weavepy_compiler _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter16set_from_vm_iter _RINvMNtCs5lUuJoaUEBp_16weavepy_compiler6internNtB3_11InternIndex4findNtNtB5_4name4NameNCNvB2_11intern_names_0NCB1o_s0_0EB5_ -_RNvNtCs5lUuJoaUEBp_16weavepy_compiler6intern9name_hash _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftTmmENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB1m_11sort_by_keymNCNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB2p_8Compiler25push_body_exc_entries_idss0_0E0EB2p_ _RNvNtCs5lUuJoaUEBp_16weavepy_compiler6mangle12mangle_ident _RNvMsL_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB5_8DictData20track_deferred_owner @@ -3858,12 +3715,9 @@ _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler22compile_ex_call_kwargs _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler15emit_super_attr _RINvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_15emit_super_attr0EB6_ _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler19except_unbind_stmts -_RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCs4mGAQSAXlfR_14weavepy_parser3ast13ComprehensionNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalECs5lUuJoaUEBp_16weavepy_compiler.llvm.5760298518589479789 _RNvMsf_NtCsaWnZMC9MjUX_10weavepy_vm4syncINtB5_7GilCellNtNtB7_7dictmap6SetMapE10try_borrowB7_.llvm.11043968194109836189 -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser9parse_del _RINvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB3_6Parser20as_target_diagnosticNCNvB2_9parse_try0NCB1g_s_0EB5_ _RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser12parse_assert -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser11parse_yield _RINvMsl0_NtCs8nxjnOh64fR_23cranelift_assembler_x644instNtB7_7jne_d326encodeNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x644inst8external11AsmCodeSinkEB1l_ _RINvMsP_NtCs8nxjnOh64fR_23cranelift_assembler_x644instINtB6_11addq_mi_sxbNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x644inst8external18CraneliftRegistersE6encodeNtB1b_11AsmCodeSinkEB1j_ _RINvMsJG_NtCs8nxjnOh64fR_23cranelift_assembler_x644instINtB7_11subq_mi_sxbNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x644inst8external18CraneliftRegistersE6encodeNtB1c_11AsmCodeSinkEB1k_ @@ -3890,7 +3744,6 @@ _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter21normalize_hash_result _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter13classdict_get _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter16templatelib_attr _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterNtNtCs5lUuJoaUEBp_16weavepy_compiler4name4NameENCNvMsK_B1r_NtB1r_8Compiler6finishs_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2K_8for_each4callmNCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB3X_3VecmE14extend_trustedBN_E0E0EB1r_ -_RNvNtCs5lUuJoaUEBp_16weavepy_compiler8validate21check_annotation_expr _RINvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_18compile_stmt_inners_0EB6_ _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler21emit_annotate_closure _RNvXsw_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_9WireMarksNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq @@ -3898,19 +3751,12 @@ _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler23emit_with_except_finish _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler23annotation_child_prefix _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler12compile_with _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler13make_lazy_ctx -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8WithItemE8grow_oneBQ_ _RNvMs0_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8ConstantE32forget_allocation_drop_remainingCs5lUuJoaUEBp_16weavepy_compiler -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser10parse_with -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser15parse_with_item _RINvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB3_6Parser20as_target_diagnosticNCNvB2_27import_as_target_diagnostic0NCB1g_s_0EB5_ _RNvNtCs4mGAQSAXlfR_14weavepy_parser6parser19join_str_into_parts _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectE10ok_or_elseNtNtBM_5error12RuntimeErrorNCNvMs4_BM_NtBM_11Interpreter4stepsE_0EBM_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4ExprEEB1t_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8ConstantEECs5lUuJoaUEBp_16weavepy_compiler -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8WithItemEECs5lUuJoaUEBp_16weavepy_compiler -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8ExprKindEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast3ArgEEB1c_ -_RNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt9int_const _RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable7ipnsortNtNtNtCsh6LdJn3jKWc_9regalloc23ion15data_structures12InsertedMoveNCINvMB6_SBT_20sort_unstable_by_keyyNCNvMNtBX_5movesINtBV_3EnvINtNtNtCs6NsaeEkylgU_17cranelift_codegen8machinst5vcode5VCodeNtNtNtNtNtNtB33_3isa3x645lower4isle14generated_code5MInstEE22resolve_inserted_moves0E0EB33_ _RINvMNtCs8nxjnOh64fR_23cranelift_assembler_x643vexNtB3_9VexPrefix6encodeNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x644inst8external11AsmCodeSinkEB1i_ _RNvXsc_NtNtCsevLNFiNqfJP_4core5slice5indexTINtNtNtB9_3ops5range5BoundjEBF_EINtB5_10SliceIndexSNtNtNtCsh6LdJn3jKWc_9regalloc23ion15data_structures18LiveRangeListEntryE5indexCs6NsaeEkylgU_17cranelift_codegen @@ -3936,13 +3782,10 @@ _RNvMsc_Cs7l6ndySnbnD_8smallvecINtB5_8SmallVecAmj10_E21reserve_one_uncheckedCs6N _RNvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib11marshal_mod16startup_interned _RNvXsK_NtCslNdsVBa5Sgt_13weavepy_lexer5tokenNtB5_5TokenNtNtCsevLNFiNqfJP_4core5clone5Clone5clone _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB28_8Compiler6finishs0_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB35_8for_each4callmNCINvMsk_NtB1r_3vecINtB4i_3VecmE14extend_trustedBN_E0E0EB28_ -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtCs5lUuJoaUEBp_16weavepy_compiler12LazyClassCtxE9drop_slowBF_ _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler15emit_send_dance _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5lUuJoaUEBp_16weavepy_compiler8validate9DirectiveE8grow_oneBQ_ -_RNvYNCNvMNtCslNdsVBa5Sgt_13weavepy_lexer7scannerNtB7_7Scanner11scan_number0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceThEE9call_onceB9_ _RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser12parse_global _RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser15parse_name_list -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8ConstantEBF_.llvm.10202912905620990601 _RINvMs6_NtCs1PctigBqNUG_9hashbrown3rawINtB6_8RawTableTNtNvMNtNtCsh6LdJn3jKWc_9regalloc23ion5movesINtNtBX_15data_structures3EnvpE34apply_allocations_and_insert_moves19BlockparamSourceKeyNtBZ_10AllocationEE6insertNCINvNtB8_3map11make_hasherBQ_B2X_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtCsdwcRXB9VvRM_10rustc_hash8FxHasherEE0ECs6NsaeEkylgU_17cranelift_codegen _RNvMs4_NtCsjr56wCXnemN_18cranelift_frontend8frontendNtB5_15FunctionBuilder15switch_to_block _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x645lower4isle14generated_code10CondResultEBN_ @@ -4039,10 +3882,8 @@ _RNvMs4_NtNtCs6NsaeEkylgU_17cranelift_codegen8machinst5lowerINtB5_5LowerNtNtNtNt _RNvMs3_NtNtCs6NsaeEkylgU_17cranelift_codegen8machinst5lowerINtB5_5LowerNtNtNtNtNtNtB9_3isa3x645lower4isle14generated_code5MInstE28get_value_as_source_or_constB9_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftNtNtNtCsh6LdJn3jKWc_9regalloc23ion15data_structures12InsertedMoveNCINvMB8_SB1m_20sort_unstable_by_keyyNCNvMNtB1q_5movesINtB1o_3EnvINtNtNtCs6NsaeEkylgU_17cranelift_codegen8machinst5vcode5VCodeNtNtNtNtNtNtB3z_3isa3x645lower4isle14generated_code5MInstEE22resolve_inserted_moves0E0EB3z_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftTNtNtNtCsh6LdJn3jKWc_9regalloc23ion15data_structures11PosWithPrioNtB1t_4EditENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB1m_11sort_by_keyyNCNvMsp_B1p_NtB1p_5Edits4sort0E0ECs6NsaeEkylgU_17cranelift_codegen -_RNvXs0_NtCs5lUuJoaUEBp_16weavepy_compiler6fxhashINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetNtNtCs1C1lLj4PWSY_5alloc6string6StringINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtB5_8FxHasherEENtB5_7NameSet8add_name _RINvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB6_8Compiler21compile_annotate_codeNCNvB2_28compile_deferred_annotationss0_0EB6_ _RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtCs5lUuJoaUEBp_16weavepy_compiler18DeferredAnnotationE4pushBH_ -_RNvMs_NtCs5lUuJoaUEBp_16weavepy_compiler8validateNtB4_9Validator16visit_annotation _RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultNtCs5lUuJoaUEBp_16weavepy_compiler10CodeObjectNtBK_12CompileErrorE7map_errNtNtCsaWnZMC9MjUX_10weavepy_vm5error12RuntimeErrorNCNvMs4_B1Y_NtB1Y_11Interpreter12do_exec_calls2_0EB1Y_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyANtNtCsaWnZMC9MjUX_10weavepy_vm12shared_value9SharedStrj4_E4withNCINvNtNtBZ_6stdlib13functools_mod19with_partial_fieldsINtNtCsevLNFiNqfJP_4core6option6OptionNtNtBZ_6object6ObjectENCINvB21_17with_partial_callB3r_NCNvMs4_BZ_NtBZ_11Interpreter17core_partial_calls_0E0E0IB2Q_B2P_EEBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyANtNtCsaWnZMC9MjUX_10weavepy_vm12shared_value9SharedStrj4_E4withNCINvNtNtBZ_6stdlib13functools_mod19with_partial_fieldsINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_6object10PyFunctionEENCINvB21_17with_partial_callB3r_NCNvMs4_BZ_NtBZ_11Interpreter17core_partial_calls0_0E0E0IB2Q_B2P_EEBZ_ @@ -4055,7 +3896,6 @@ _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter24function_annotation_dict _RINvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB6_11Interpreter18lean_bind_keywordsINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtB6_7dictmap4IterNCNCNvB2_17core_partial_calls0_00EEB6_ _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter12do_next_call _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter36parse_source_emitting_warnings_flags -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtCs5lUuJoaUEBp_16weavepy_compiler18DeferredAnnotationE8grow_oneBO_ _RNvMNtCs4mGAQSAXlfR_14weavepy_parser5errorNtB2_10ParseError14syntax_message _RNvXsB_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_9LineTableNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler17compile_subkwargs @@ -4141,27 +3981,20 @@ _RNvMs_NtCsaWnZMC9MjUX_10weavepy_vm7timsortINtB4_10MergeStateNtNtB6_6object6Obje _RINvNtCsaWnZMC9MjUX_10weavepy_vm7timsort4sortNtNtB4_6object6ObjectNtNtB4_5error12RuntimeErrorNCINvMs4_B4_NtB4_11Interpreter10sort_keyedBH_NCNvB1y_13sort_with_keys_0Es2_0EB4_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjNtNtCslMglkRgF9CW_11weavepy_jit7analyze7PairSrcNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBS_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set8IntoIterNtNtCs1C1lLj4PWSY_5alloc6string6StringEECs5lUuJoaUEBp_16weavepy_compiler -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser16parse_assign_rhs -_RNvMNtCs5lUuJoaUEBp_16weavepy_compiler8validateNtB2_5Scope13directive_for _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter21percent_mod_left_slot _RINvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib12warnings_mod10with_stateuNCNCNvB2_5builds_0s_0EB6_ _RINvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib12warnings_mod10with_stateNtNtB6_6object6ObjectNCNCNvB2_5builds_0s0_0EB6_ _RINvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib12warnings_mod10with_statebNCNCNvB2_5builds_00EB6_ _RNvXs2_NtNtCsevLNFiNqfJP_4core5slice3cmpNtCs5lUuJoaUEBp_16weavepy_compiler10ExcHandlerINtB5_14SlicePartialEqBC_E17equal_same_lengthBE_ -_RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters6clonedINtB4_6ClonedINtNtB6_6filter6FilterINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvCs5lUuJoaUEBp_16weavepy_compiler28class_body_propagating_reads0EENtNtNtB8_6traits8iterator8Iterator4nextB2W_ -_RNCNvNtCs5lUuJoaUEBp_16weavepy_compiler8validate21check_annotation_exprs_0B5_ _RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters5chainINtB5_5ChainINtNtB7_6filter6FilterINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvCs5lUuJoaUEBp_16weavepy_compiler23collect_inner_free_impl0EB1m_ENtNtNtB9_6traits8iterator8Iterator4folduNCINvNtB7_3map8map_foldRB2e_B2e_uNvYB2e_NtNtBb_5clone5Clone5cloneNCIB4E_B2e_TB2e_uEuNCINvXs8_NtCskibSv91bgl1_9hashbrown3setINtB66_7HashSetB2e_INtNtBb_4hash18BuildHasherDefaultNtNtB2V_6fxhash8FxHasherEEINtNtB41_7collect6ExtendB2e_E6extendINtNtB7_6cloned6ClonedBO_EE0NCINvNvB3X_8for_each4callB5P_NCINvXs1i_NtB68_3mapINtB9v_7HashMapB2e_uB6T_EIB7R_B5P_E6extendINtB4G_3MapB8q_B5X_EE0E0E0E0EB2V_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB4_3VecNtNtB6_6string6StringEINtB2_10SpecExtendBR_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1D_6filter6FilterINtNtNtB1H_5slice4iter4IterTBR_NtCs5lUuJoaUEBp_16weavepy_compiler7CompSymEENCNvMsK_B3g_NtB3g_8Compiler29compile_inlined_comprehensions1_0ENCB3Y_s2_0EE11spec_extendB3g_ _RINvMsi_NtCskibSv91bgl1_9hashbrown3rawINtB6_12RawIterRangeTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEE9fold_implNCINvXsG_NtB8_3mapINtB1T_4IterBV_uENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4folduNCINvXsU_B1T_INtB1T_4KeysBV_uEB2j_4folduNCINvNtNtB2p_8adapters6filter11filter_foldRBV_uNCNvCs5lUuJoaUEBp_16weavepy_compiler23collect_inner_free_impl0QNCINvNtB45_3map8map_foldB4E_BV_uNvYBV_NtNtB2r_5clone5Clone5cloneNCIB5N_BV_BU_uNCINvXs8_NtB8_3setINtB79_7HashSetBV_INtNtB2r_4hash18BuildHasherDefaultNtNtB4N_6fxhash8FxHasherEEINtNtB2n_7collect6ExtendBV_E6extendINtNtB45_6cloned6ClonedINtNtB45_5chain5ChainINtB43_6FilterINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterBV_EB4J_EBa3_EEE0NCINvNvB2j_8for_each4callBU_NCINvXs1i_B1T_INtB1T_7HashMapBV_uB7A_EIB8z_BU_E6extendINtB5P_3MapB97_B70_EE0E0E0E0E0E0E0uEB4N_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4StmtEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB28_5slice4iter4IterTNtNtB6_6string6StringRNtBW_4ExprEENCNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB3V_8Compiler28compile_function_annotations0EE9from_iterB3V_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtB6_6string6StringEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB1I_6filter6FilterINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterBU_ENCNvCs5lUuJoaUEBp_16weavepy_compiler28class_body_propagating_reads0EEE9from_iterB3U_ _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler29emit_genexp_call_optimization -_RNvCs5lUuJoaUEBp_16weavepy_compiler28class_body_propagating_reads _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler21emit_annotation_value _RNvXsp_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8ColTableNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq _RINvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB6_8Compiler21compile_annotate_codeNCNvB2_28compile_function_annotationss_0EB6_ -_RNCNvNvCs5lUuJoaUEBp_16weavepy_compiler24class_level_reads_dunder6nested0B5_ -_RNvNtCs4mGAQSAXlfR_14weavepy_parser6parser17skip_field_string _RNvMs5_NtCsjr56wCXnemN_18cranelift_frontend8frontendNtB5_15FunctionBuilder18append_block_param _RNvMs5_NtCsjr56wCXnemN_18cranelift_frontend8frontendNtB5_15FunctionBuilder12block_params _RNvMs4_NtCsjr56wCXnemN_18cranelift_frontend8frontendNtB5_15FunctionBuilder12create_block @@ -4357,11 +4190,8 @@ _RINvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB6_11Interpreter14core_fast_leafNCNvB2_19co _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectE3mapBJ_NvBN_9clone_hotEBN_ _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter14core_push_init _RNvXse_NtNtCs1w4Ic9Wfcv9_10num_bigint7biguint5powerNtB7_7BigUintINtNtCscluLgnrMnoD_10num_traits3pow3PowyE3pow -_RNvXsa_NtNtCs1w4Ic9Wfcv9_10num_bigint7biguint14multiplicationNtB7_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops5arith9MulAssignRBX_E10mul_assign -_RNvXsa_NtNtCs1w4Ic9Wfcv9_10num_bigint6bigint5powerNtB7_6BigIntINtNtCscluLgnrMnoD_10num_traits3pow3PowyE3pow _RNvMs_NtCs5lUuJoaUEBp_16weavepy_compiler8validateNtB4_9Validator13visit_pattern _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler20patma_emit_fail_pops -_RNvCs5lUuJoaUEBp_16weavepy_compiler27collect_class_visible_reads _RNvCs5lUuJoaUEBp_16weavepy_compiler21validate_case_pattern _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler15compile_pattern _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler18emit_next_location @@ -4419,7 +4249,6 @@ _RNvMs10_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree4nodeINtB6_16BalancingCont _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter19core_leaf_site_call _RNvCsaWnZMC9MjUX_10weavepy_vm14method_site_py _RNvMsM_CsaWnZMC9MjUX_10weavepy_vmNtB5_10MethodSlot8get_held -_RNvCsaWnZMC9MjUX_10weavepy_vm16method_site_leaf.llvm.11081471256077229350 _RINvNtNtCs6NsaeEkylgU_17cranelift_codegen4opts14generated_code20constructor_iconst_uNtB4_11IsleContextEB6_ _RINvNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x645lower4isle14generated_code19constructor_x64_subINtNtNtBc_8machinst4isle11IsleContextNtB2_5MInstNtB8_10X64BackendEEBc_ _RINvNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x645lower4isle14generated_code23constructor_x64_sub_rawINtNtNtBc_8machinst4isle11IsleContextNtB2_5MInstNtB8_10X64BackendEEBc_ @@ -4454,9 +4283,7 @@ _RNvMs4_NtCsaWnZMC9MjUX_10weavepy_vm8gc_traceNtB5_7GcState18complete_finalizer _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterINtNtB1f_6option6OptionNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectEENCNvMs4_B2M_NtB2M_11Interpreter18function_type_call0EB2I_EB2M_ _RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters7flatten7FlattenINtNtNtBc_5slice4iter4IterINtNtBc_6option6OptionNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4ExprEEENtNtNtBa_6traits8iterator8Iterator8for_eachQNCNvCs5lUuJoaUEBp_16weavepy_compiler25expr_contains_typeparamfn0EB3h_ _RNvMsu_CsaWnZMC9MjUX_10weavepy_vmNtB5_8CallSlot8poly_hit -_RNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt8make_str _RINvXs4_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB6_8IntoItermENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4folduNCINvNtNtB15_8adapters3map8map_foldmcuNCNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt8make_strs_0NCINvNvBZ_8for_each4callcNCINvXsd_NtBa_6stringNtB46_6StringINtNtB13_7collect6ExtendcE6extendINtB25_3MapBI_B2C_EE0E0E0EB2I_ -_RNvMNtCs1C1lLj4PWSY_5alloc5sliceSm6repeatCs5lUuJoaUEBp_16weavepy_compiler _RNvNtNtCs1w4Ic9Wfcv9_10num_bigint7biguint7convert20from_radix_digits_be _RNvNtNtCs1w4Ic9Wfcv9_10num_bigint7biguint7convert11to_radix_le _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter16dict_of_keywords @@ -4472,7 +4299,6 @@ _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler16patma_store_name _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast7PatternE8grow_oneBQ_ _RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCs4mGAQSAXlfR_14weavepy_parser3ast9MatchCaseNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalECs5lUuJoaUEBp_16weavepy_compiler.llvm.5760298518589479789 _RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser18parse_name_pattern -_RNvNtCs4mGAQSAXlfR_14weavepy_parser6parser13expr_children _RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser20finish_class_pattern _RNvXss_NtCs4mGAQSAXlfR_14weavepy_parser3astNtB5_7PatternNtNtCsevLNFiNqfJP_4core5clone5Clone5clone _RNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt24fold_const_match_pattern @@ -4499,7 +4325,6 @@ _RINvMsh_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB6_16MemoryViewBuffer9with_readINt _RNvMsi_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB5_12PyMemoryView10shape_dims _RNvMs9_NtCsaWnZMC9MjUX_10weavepy_vm9frame_jitNtB5_5Lower10shared_dec _RNvMs1_NtCsaWnZMC9MjUX_10weavepy_vm9frame_jitNtB5_6Native3ran -_RNCINvNtCsaWnZMC9MjUX_10weavepy_vm9frame_jit11direct_doneKb0_Es_0B6_ _RNvMs9_NtCsaWnZMC9MjUX_10weavepy_vm9frame_jitNtB5_5Lower7compare _RNvMs6_NtCsaWnZMC9MjUX_10weavepy_vm9frame_jitNtB5_10DirectSite7promote _RNvMs9_NtCsaWnZMC9MjUX_10weavepy_vm9frame_jitNtB5_5Lower10local_addr @@ -4526,11 +4351,8 @@ _RINvNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x645lower4isle14generated_c _RINvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib15datetime_native14construct_withNCNvB2_15construct_names0EB6_ _RINvYNtNtCsjr56wCXnemN_18cranelift_frontend8frontend15FuncInstBuilderNtNtNtCs6NsaeEkylgU_17cranelift_codegen2ir7builder11InstBuilder4jumpRANtNtB19_12instructions8BlockArgj3_ECsaWnZMC9MjUX_10weavepy_vm _RINvYNtNtCsjr56wCXnemN_18cranelift_frontend8frontend15FuncInstBuilderNtNtNtCs6NsaeEkylgU_17cranelift_codegen2ir7builder11InstBuilder4brifRANtNtB19_12instructions8BlockArgj0_RSB2d_ECsaWnZMC9MjUX_10weavepy_vm -mi_bitmap_try_find_and_claim _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCsaWnZMC9MjUX_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCNvMs4_B28_NtB28_11Interpreter14leaf_init_eval0E0zEB28_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSINtNtCsaWnZMC9MjUX_10weavepy_vm12shared_value7ThinArcINtBF_12SliceStorageNtNtBH_6object7DictKeyEEEBH_ -mi_arena_try_claim_abandoned -mi_arena_page_at_slice _RINvMske_NtCs8nxjnOh64fR_23cranelift_assembler_x644instNtB7_7jae_d326encodeNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x644inst8external11AsmCodeSinkEB1l_ _RINvMsaH_NtCs8nxjnOh64fR_23cranelift_assembler_x644instINtB7_9cmovlq_rmNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x644inst8external18CraneliftRegistersE6encodeNtB19_11AsmCodeSinkEB1h_ _RNvXNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x645lower4isleINtNtNtBa_8machinst4isle11IsleContextNtNtB2_14generated_code5MInstNtB6_10X64BackendENtB1D_7Context17x64_cmovlq_rm_raw @@ -4555,7 +4377,6 @@ _RNvXs4_NtCsevLNFiNqfJP_4core6optionINtB5_6OptionNtNtCsaWnZMC9MjUX_10weavepy_vm6 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCsaWnZMC9MjUX_10weavepy_vm8ChainRecEECsbg2BJAIJWf_7weavepy _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler19compile_await_dance _RNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB5_8Compiler18compile_async_with -_RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser16parse_async_stmt _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCsaWnZMC9MjUX_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionbENCNCNvMs4_BY_NtBY_11Interpreter17leaf_builtin_calls4_00E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ _RINvNtCsaWnZMC9MjUX_10weavepy_vm6object20with_key_eq_deferredINtNtCsevLNFiNqfJP_4core6result6ResultINtNtB12_6option6OptionbENtNtB4_5error12RuntimeErrorENCNvMs4_B4_NtB4_11Interpreter17leaf_builtin_calls4_0EB4_ _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter15collapse_commit @@ -4570,7 +4391,6 @@ _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter17resolve_field_str _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter13chain_recycle _RNvMs1k_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB6_6PyFile8getvalue _RNvMs1k_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB6_6PyFile11set_newline -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtCsevLNFiNqfJP_4core6option6OptionTNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectINtNtB7_3vec3VecB1p_EIB28_TNtNtB7_6string6StringB1p_EEEEE8grow_oneB1t_ _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter12format_value _RNCNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt10eval_binop0B5_ _RINvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt12eval_numericNCNvB2_10eval_binop0NCBY_s_0NvB2_5c_subEB4_ @@ -4630,7 +4450,6 @@ _RNvNvCs5lUuJoaUEBp_16weavepy_compiler25body_reads_super_or_class18strip_class_b _RNvYNvNvNtCsaWnZMC9MjUX_10weavepy_vm13builtin_types22install_object_dunders11object_hashINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvYNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins11b_frozensetINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast9TypeParamE8grow_oneBQ_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecRNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4ExprE8grow_oneBR_ _RINvXs5_NtCs1C1lLj4PWSY_5alloc6stringNtB6_6StringINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorcE9from_iterINtNtNtBS_8adapters3map3MapINtNtNtBU_5slice4iter4ItermENCNvNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB30_8Compiler20compile_template_str12cps_to_consts_0EEB30_ _RNvMNtCs4mGAQSAXlfR_14weavepy_parser6parserNtB2_6Parser21parse_type_alias_stmt _RNvNtCs4mGAQSAXlfR_14weavepy_parser6parser21check_type_param_expr @@ -4758,7 +4577,6 @@ _RNvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib7ast_mod5parse _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtB8_6filter6FilterNtNtNtBc_3str4iter5CharsNCNvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib2io16encoding_key_for0ENvMNtNtBc_4char7methodsc12to_lowercaseENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvMsg_NtB8_7flattenINtB4b_13FlattenCompatppE9iter_fold7flattenNtB2O_11ToLowercaseuNCINvNvXsi_B4b_B4o_B3m_4fold7flattenB55_uNCINvNvB3m_8for_each4callcNCINvXsd_NtCs1C1lLj4PWSY_5alloc6stringNtB6D_6StringINtNtB3q_7collect6ExtendcE6extendINtB4b_7FlatMapBX_B55_B2J_EE0E0E0E0EB1P_ _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins6b_open _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins16bytes_startswith -_RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins13file_readline _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins10file_close _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins13bridge_str_of _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins11code_method @@ -4767,7 +4585,6 @@ _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins13open_path_arg _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins13file_seekable _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins9b_open_kw _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins25bytes_match_prefix_suffix -_RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins9file_seek _RNCINvNtCsaWnZMC9MjUX_10weavepy_vm8builtins9method_kwNvB4_15bytes_decode_kwEs_0B6_ _RNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins10set_update _RNvXNtCs1C1lLj4PWSY_5alloc6borrowNtNtB4_6string6StringNtB2_7ToOwned8to_ownedCsaWnZMC9MjUX_10weavepy_vm @@ -4813,7 +4630,6 @@ _RNvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib2io8tw_close _RNvYNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins16bytes_startswithINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins9b_open_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1y_EEE4callB6_ _RNvYNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins10set_updateINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins9file_seekINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins15bytes_decode_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1F_EEE4callB6_ _RNvYNvNtCsaWnZMC9MjUX_10weavepy_vm8builtins13file_readlineINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib2io7tw_initINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1z_EEE4callB8_ @@ -4827,13 +4643,10 @@ _RINvMs_NtCsb7iyowqPMyM_6anyhow4kindNtB5_5Adhoc3newReECs5Hy3mROkL0v_11weavepy_cl _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockTbNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectEE10initializeNCINvB1a_11get_or_initNCNvNtB1M_8builtins17code_co_positionss2_0E0zE0E0B1M_.llvm.15267372747089667077 _RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCsaWnZMC9MjUX_10weavepy_vm6object6ObjectENtNtNtNtBb_4iter6traits8iterator8Iterator4findNCNvNtNtBU_6stdlib9ast_build5build0EBU_ _RNvYNCNKNvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib10codecs_mod14IO_TEXT_EXEMPT0s_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1m_6option6OptionQIB21_INtNtB1m_4cell4CellbEEEEE9call_onceBc_.llvm.15267372747089667077 -_RNvNvCs5lUuJoaUEBp_16weavepy_compiler24class_nested_scope_reads11expr_nested -_RNvNvCs5lUuJoaUEBp_16weavepy_compiler24class_nested_scope_reads12stmts_nested _RINvNtCsaWnZMC9MjUX_10weavepy_vm6object16write_float_reprNtNtCs1C1lLj4PWSY_5alloc6string6StringEB4_ _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter19reduce_ex_proto_arg _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter21object_default_reduce _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter16object_reduce_ex -_RNvNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib4time8zone_str _RNvMs3_NtCsaWnZMC9MjUX_10weavepy_vm6objectNtB5_7PyFrame14current_lineno _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter20reentrant_py_eq_bool _RNCNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB7_11Interpreter21percent_mod_left_slot0B7_ @@ -4909,7 +4722,6 @@ _RNvMs_NtCsaWnZMC9MjUX_10weavepy_vm7timsortINtB4_10MergeStateTNtNtB6_6object6Obj _RNvMs_NtCsaWnZMC9MjUX_10weavepy_vm7timsortINtB4_10MergeStateTNtNtB6_6object6ObjectBX_ENCINvMs4_B6_NtB6_11Interpreter10sort_keyedBW_NCNvB1r_13sort_with_keys0_0Es_0E8merge_atB6_ _RINvMsy4_NtCs8nxjnOh64fR_23cranelift_assembler_x644instINtB7_6negq_mNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x644inst8external18CraneliftRegistersE6encodeNtB16_11AsmCodeSinkEB1e_ _RINvMswC_NtCs8nxjnOh64fR_23cranelift_assembler_x644instINtB7_13imulq_rmi_sxlNtNtNtNtNtCs6NsaeEkylgU_17cranelift_codegen3isa3x644inst8external18CraneliftRegistersE6encodeNtB1e_11AsmCodeSinkEB1m_ -_RNvMNtNtCsaWnZMC9MjUX_10weavepy_vm6stdlib15datetime_nativeNtB2_11PackedSlots11free_values _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter21core_native_method_kw _RINvYNtNtCsjr56wCXnemN_18cranelift_frontend8frontend15FuncInstBuilderNtNtNtCs6NsaeEkylgU_17cranelift_codegen2ir7builder11InstBuilder8f64constdECslMglkRgF9CW_11weavepy_jit _RNvXsk_NtCsevLNFiNqfJP_4core3fmtcNtB5_7Display3fmt @@ -4945,7 +4757,6 @@ _RNCNvMsK_Cs5lUuJoaUEBp_16weavepy_compilerNtB7_8Compiler21compile_comprehension0 _RNvMs_NtCsaWnZMC9MjUX_10weavepy_vm7timsortINtB4_10MergeStateNtNtB6_6object6ObjectNCINvMs4_B6_NtB6_11Interpreter10sort_keyedBW_NCNvB1m_13sort_with_keys_0Es0_0E8merge_atB6_ _RINvNtCsaWnZMC9MjUX_10weavepy_vm7timsort4sortNtNtB4_6object6ObjectNtNtB4_5error12RuntimeErrorNCINvMs4_B4_NtB4_11Interpreter10sort_keyedBH_NCNvB1y_13sort_with_keys_0Es0_0EB4_ _RNvXs1_NtCs1w4Ic9Wfcv9_10num_bigint6bigintNtB5_6BigIntNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq -_RINvNtNtNtNtCsevLNFiNqfJP_4core3num3imp7dec2flt6lemire13compute_floatdEBa_ _RNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt8float_of _RNvNtCs5lUuJoaUEBp_16weavepy_compiler7ast_opt10int_to_f64 _RNvMs4_CsaWnZMC9MjUX_10weavepy_vmNtB5_11Interpreter15default_delattr @@ -5211,8 +5022,6 @@ _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter16unpack_meta_call _RINvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB6_11Interpreter16lean_init_extendINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtNtB1f_5slice4iter4IterNtNtB6_6object6ObjectEEEB6_ _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter16finish_genexp_at _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter12core_setitem -_RNvMs2_Cs8wxea0EYzJz_10weavepy_vmNtB5_5Frame7exc_mut -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter12quiet_unwind _RINvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB6_11Interpreter12prepend_pathNtNtCsgHYyB3hU8Ec_3std4path7PathBufECs8PNjY2wQFqL_7weavepy _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter20emit_escape_warnings _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter16current_sys_attr @@ -5283,9 +5092,6 @@ _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter14gen_drain_next.llvm.866921 _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter15gen_step_native _RNCNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB7_11Interpreter19generator_send_leans0_0B7_ _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter15core_gen_return -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter14sync_exc_attrs -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter13inline_finish -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter19binary_subscr_basic.llvm.8669210988209730996 _RNvCs8wxea0EYzJz_10weavepy_vm16convert_in_place _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter21core_pure_global_call _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter13run_module_as @@ -5318,8 +5124,6 @@ _RNvCs8wxea0EYzJz_10weavepy_vm18meta_check_is_type _RNvCs8wxea0EYzJz_10weavepy_vm16checks_like_type _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter15leaf_class_attr _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter17core_value_method -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter24instantiate_raised_class -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter12core_reraise _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter24instance_dunder_function.llvm.8669210988209730996 _RNvCs8wxea0EYzJz_10weavepy_vm22format_simple_in_place _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter21flush_pending_callers @@ -5349,9 +5153,6 @@ _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter26load_attr_instance_default _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter19generator_send_fold.llvm.8669210988209730996 _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter18core_laid_out_attr _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter15core_local_attr -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter23attach_implicit_context -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter14inline_deliver -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter22instance_native_dunder _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter21leaf_class_data_descr _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter23run_shutdown_finalizers _RNvXs6_Cs8wxea0EYzJz_10weavepy_vmNtB5_11InterpreterNtNtCsevLNFiNqfJP_4core7default7Default7default @@ -5395,7 +5196,6 @@ _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter23alloc_lean_instance_obj _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter12lean_payload.llvm.8669210988209730996 _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter10retire_gen _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter12store_subscr -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter28break_implicit_context_cycle.llvm.8669210988209730996 _RNvCs8wxea0EYzJz_10weavepy_vm15build_string_at _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter11import_path _RNvMs2_Cs8wxea0EYzJz_10weavepy_vmNtB5_5Frame3pop @@ -5426,7 +5226,6 @@ _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter14core_str_binop _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter14try_inline_gen _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter20core_class_fn_method _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter29leaf_resolve_instance_attr_ix -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter24build_exception_instance _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter13contains_full _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter20call_dunder_function _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter22leaf_attr_resolve_site @@ -5502,8 +5301,6 @@ _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter10core_slice _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter24specialized_store_subscr _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter15core_gen_resume _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter18inline_gen_deliver -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter19normalize_exception -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter23leaf_instance_subscript _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter30register_source_with_linecache _RNvXsd_Cs8wxea0EYzJz_10weavepy_vmNtB5_9InlineActNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop _RNvXsm_Cs8wxea0EYzJz_10weavepy_vmNtB5_9LeanFrameNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop @@ -5667,11 +5464,9 @@ _RINvMsd_NtCs8wxea0EYzJz_10weavepy_vm5typesNtB6_10TypeObject12memo_verdictNCNvMs _RNvMsk_NtCs8wxea0EYzJz_10weavepy_vm5typesNtB5_11SlotStorage4iter _RNvMsl_NtCs8wxea0EYzJz_10weavepy_vm5typesNtB5_10PyInstance11dict_shared _RNvMsi_NtCs8wxea0EYzJz_10weavepy_vm5typesNtB5_11SlotStorage21values_for_layout_mut -_RNvNtCs8wxea0EYzJz_10weavepy_vm6object15leaf_tuple_item _RNvNtCs8wxea0EYzJz_10weavepy_vm6object9siphash13 _RNvMs1t_NtCs8wxea0EYzJz_10weavepy_vm6objectNtB6_7SipMemo8allocate _RNvNtCs8wxea0EYzJz_10weavepy_vm6object13set_hash_seed -_RNvNtCs8wxea0EYzJz_10weavepy_vm6object21type_hash_is_identity _RNvXs1_NtNtNtCsevLNFiNqfJP_4core3ops8function5implsQNCNvNtCsePCACruCPSX_15weavepy_codegen8liveness7analyzes8_0INtB7_5FnMutTNtNtBU_2ir5ValueEE8call_mutBU_ _RNvXs1_NtNtNtCsevLNFiNqfJP_4core3ops8function5implsQNCNvMsV_CskKPjDLDyyy_16weavepy_compilerNtBW_8Compiler25push_body_exc_entries_ids0INtB7_5FnMutTRRTmmmEEE8call_mutBW_ _RNvNvNtCs8wxea0EYzJz_10weavepy_vm13builtin_types22install_module_methods7dict_of @@ -5685,7 +5480,6 @@ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmNtNtCskKPjDLDyyy_16weavepy_ _RINvXs1i_NtCskibSv91bgl1_9hashbrown3mapINtB7_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCskKPjDLDyyy_16weavepy_compiler6fxhash8FxHasherEEINtNtNtNtB1x_4iter6traits7collect6ExtendTBP_uEE6extendINtNtNtB3d_8adapters3map3MapINtNtNtBT_3vec9into_iter8IntoIterBP_ENCINvXs8_NtB9_3setINtB5a_7HashSetBP_B1s_EIB37_BP_E6extendB4q_E0EEB2j_ _RNCNvNtCsePCACruCPSX_15weavepy_codegen8liveness7analyzes0_0B5_.llvm.4591017390144106049 _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collectINtB6_3VecTNtNtCsePCACruCPSX_15weavepy_codegen2ir5ValuehbEEINtNtB6_14spec_from_iter12SpecFromIterBY_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB6_9into_iter8IntoIterBZ_ENCNvMNtB13_7codegenINtB3O_3GenNtNtB13_3x643X64E5block0EE9from_iterB13_ -_RINvNtCs8wxea0EYzJz_10weavepy_vm10specialize21specialize_call_kw_byINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1c_5slice4iter4IterNtNtB4_6object6ObjectENCNvB2_32attempt_specialize_call_kw_namess_0EEB4_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort31small_sort_general_with_scratchNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1s_NtNtBa_3cmp10PartialOrd2ltECskKPjDLDyyy_16weavepy_compiler _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort18small_sort_generalNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1f_NtNtBa_3cmp10PartialOrd2ltECskKPjDLDyyy_16weavepy_compiler _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1m_NtNtBa_3cmp10PartialOrd2ltECskKPjDLDyyy_16weavepy_compiler @@ -5710,7 +5504,6 @@ _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTymEE12remove_entryNCINvNt _RNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objects22compile_cached_builtin _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB6_6object6ObjectNtNtB6_5error12RuntimeErrorENCNvB2_12pattern_exec0EB6_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objects11with_interpNtNtB6_6object6ObjectNCNvB2_14parse_template0EB6_ -_RNvMsf_NtCs8wxea0EYzJz_10weavepy_vm4syncINtB5_7GilCellNtNtB7_6object10PyIteratorE10try_borrowB7_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs8wxea0EYzJz_10weavepy_vm6object8HashAlgoE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEBX_ _RNvMs_NtCskKPjDLDyyy_16weavepy_compiler8validateNtB4_9Validator13mark_assigned _RNvMs_NtCskKPjDLDyyy_16weavepy_compiler8validateNtB4_9Validator12visit_target @@ -5721,7 +5514,6 @@ _RNvMs_NtCskKPjDLDyyy_16weavepy_compiler8validateNtB4_9Validator22push_type_para _RNvMs_NtCskKPjDLDyyy_16weavepy_compiler8validateNtB4_9Validator10visit_body _RNvMsn_NtCs1w4Ic9Wfcv9_10num_bigint6bigintNtB5_6BigInt20from_signed_bytes_le _RINvMNtCsePCACruCPSX_15weavepy_codegen7codegenINtB3_3GenNtNtB5_3x643X64E4opndNCNvB2_4insts_0EB5_ -_RNCNvMNtCsePCACruCPSX_15weavepy_codegen7codegenINtB4_3GenNtNtB6_3x643X64E9next_uses0B6_ _RNvNtCskKPjDLDyyy_16weavepy_compiler11native_code6encode _RNvMs_NtCskKPjDLDyyy_16weavepy_compiler11native_codeNtB4_6Writer8constant _RNvMs_NtCskKPjDLDyyy_16weavepy_compiler11native_codeNtB4_6Writer4code @@ -5819,10 +5611,8 @@ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable9quicksort9quicksortNtNtCs1C _RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRNtNtCs1C1lLj4PWSY_5alloc6string6StringECskKPjDLDyyy_16weavepy_compiler _RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneReECskKPjDLDyyy_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8ConstantECskKPjDLDyyy_16weavepy_compiler.llvm.16156458908895297507 -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterINtNtB4_6option6OptionNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectEEEB1P_.llvm.8413732861020376357 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4ExprEEECskKPjDLDyyy_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs8wxea0EYzJz_10weavepy_vm5trace15MonitoringToolsEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs8wxea0EYzJz_10weavepy_vm6object14SlotDescriptorEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCskKPjDLDyyy_16weavepy_compiler12FinallyFrameEBD_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs4YWHfu9gMZS_7memmap24MmapECs8wxea0EYzJz_10weavepy_vm _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCs8wxea0EYzJz_10weavepy_vm11weak_object10WeakObjectEEEB1y_ @@ -5836,12 +5626,10 @@ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcNt _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4mGAQSAXlfR_14weavepy_parser3ast4ExprECskKPjDLDyyy_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters9enumerate9EnumerateINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainNtCskKPjDLDyyy_16weavepy_compiler8ConstantEEEB24_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4mGAQSAXlfR_14weavepy_parser3ast9ArgumentsECskKPjDLDyyy_16weavepy_compiler -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs8wxea0EYzJz_10weavepy_vm7dictmap5TableNtNtBG_6object6ObjectEEBG_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs8wxea0EYzJz_10weavepy_vm6object9DictWatchEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs8wxea0EYzJz_10weavepy_vm5types8SlotDataEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCskibSv91bgl1_9hashbrown3raw8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEEECskKPjDLDyyy_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcNtNtB1u_5types10TypeObjectEEEB1u_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs8wxea0EYzJz_10weavepy_vm6object11FileBackendEBF_.llvm.8413732861020376357 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsePCACruCPSX_15weavepy_codegen2ir13JumpTableDataEECs8wxea0EYzJz_10weavepy_vm.llvm.8413732861020376357 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8ExprKindECskKPjDLDyyy_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4mGAQSAXlfR_14weavepy_parser3ast13ExceptHandlerECskKPjDLDyyy_16weavepy_compiler.llvm.16156458908895297507 @@ -5894,7 +5682,6 @@ _RNvMsQ_Cs8wxea0EYzJz_10weavepy_vmNtB5_10MethodSlot6getter.llvm.8669210988209730 _RINvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB6_11Interpreter16lean_init_extendINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainNtNtB6_6object6ObjectEEB6_ _RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter18is_attribute_error _RINvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB6_11Interpreter10sort_keyedTNtNtB6_6object6ObjectB11_ENCNvB2_13sort_with_keys0_0EB6_ -_RNvNvCs8wxea0EYzJz_10weavepy_vm19code_names_anywhere17constant_mentions _RINvCs8wxea0EYzJz_10weavepy_vm9slice_seqcEB2_ _RNvMs1_NtCskKPjDLDyyy_16weavepy_compiler9flowgraphNtB5_3Cfg20const_loading_instrs _RNvMs1_NtCskKPjDLDyyy_16weavepy_compiler9flowgraphNtB5_3Cfg36is_exit_or_eval_check_without_lineno @@ -6016,7 +5803,6 @@ _RNvMNtCs1C1lLj4PWSY_5alloc3vecINtB2_3VecNtNtCs8wxea0EYzJz_10weavepy_vm5tier23Pi _RNvMs1_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VechE17extend_from_sliceCs8wxea0EYzJz_10weavepy_vm _RNvMNtCs1C1lLj4PWSY_5alloc3vecINtB2_3VecNtNtCs8wxea0EYzJz_10weavepy_vm5tier29AttrGuardE13with_capacityBG_ _RINvNtCs1C1lLj4PWSY_5alloc3vec9from_elemINtB2_3VechEECsePCACruCPSX_15weavepy_codegen -_RINvMsb_NtCs8wxea0EYzJz_10weavepy_vm9inst_dictNtB6_11SplitValues11reserve_forNCNvMs7_B8_NtB8_11Interpreter15core_store_inits2_0EB8_ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCskKPjDLDyyy_16weavepy_compiler8bytecode9BinOpKindE6map_ormNCNvNtBM_12cpython_code14map_to_cpython0EBM_ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRTyINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcNtNtBQ_5types12InstancePlanEEE8and_thenTIBM_NtB1o_10TypeObjectEBL_jENCNvMs7_BQ_NtBQ_11Interpreter10core_new_ns0_0EBQ_ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectE10ok_or_elseNtNtBM_5error12RuntimeErrorNCNvMs7_BM_NtBM_11Interpreter4stepsR_0EBM_ @@ -6049,7 +5835,6 @@ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4c _RNvXs1_NtCsevLNFiNqfJP_4core7convertNtNtCs1C1lLj4PWSY_5alloc6string6StringINtB5_4IntoINtNtBC_4sync3ArceEE4intoCs8wxea0EYzJz_10weavepy_vm _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11thread_real6keeperNtNtB6_4sync9RealRLockEB6_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11thread_real6keeperNtNtB6_4sync8RealLockEB6_ -_RNvNtCsgHYyB3hU8Ec_3std3env11current_dir _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib12weakref_real5b_dynNCNvB2_26make_ref_object_with_classs1_0EB6_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib12weakref_real5b_dynNCNvB2_26make_ref_object_with_classs2_0EB6_ _RINvYINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtBa_6string6StringENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator7collectINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetBR_INtNtB1l_4hash18BuildHasherDefaultNtNtCskKPjDLDyyy_16weavepy_compiler6fxhash8FxHasherEEEB3Q_ @@ -6066,16 +5851,9 @@ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit4UnitEEB1t_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit6inline5PlansEBH_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterTjINtBG_3VecNtNtCs4YL2KM1Jyjv_11weavepy_jit7analyze2SEEEEEB1F_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit10DirectSiteEEEB1u_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit9SuperSiteEEEB1u_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcNtNtB1d_6object9BuiltinFnEEEB1d_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit8TypeSiteEEEB1u_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit8EstimateEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4YL2KM1Jyjv_11weavepy_jit2ir8OsrEntryEEB1c_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3set8BTreeSetjEECs4YL2KM1Jyjv_11weavepy_jit -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNCINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB13_8OnceLockIBC_INtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit6NativeEEE10initializeNCINvB12_11get_or_initNCNvB2z_7publish0E0zE0EEB2B_.llvm.5721293015000088327 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit4UnitEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit6inline10InlineSiteEEEB1w_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcNtCskKPjDLDyyy_16weavepy_compiler10CodeObjectEEEB1d_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit6inline11InlineFrameEEB1e_ _RNvMsz_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_8IntoIterjNtNtB7_7set_val9SetValZSTE10dying_nextCs4YL2KM1Jyjv_11weavepy_jit @@ -6146,9 +5924,7 @@ _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower8ref_call _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower6branch _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower10ref_or_own _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapjThjEINtNtB4_4hash18BuildHasherDefaultNtNtCsePCACruCPSX_15weavepy_codegen6fxhash8FxHasherEEECs4YL2KM1Jyjv_11weavepy_jit -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapmTmNtNtCs4YL2KM1Jyjv_11weavepy_jit5value7JitTypeEINtNtB4_4hash18BuildHasherDefaultNtNtCsePCACruCPSX_15weavepy_codegen6fxhash8FxHasherEEEB1D_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapjNtNtCs4YL2KM1Jyjv_11weavepy_jit7analyze14CompHeaderPlanINtNtB4_4hash18BuildHasherDefaultNtNtCsePCACruCPSX_15weavepy_codegen6fxhash8FxHasherEEEB1B_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterINtNtB4_6option6OptionNtNtCs4YL2KM1Jyjv_11weavepy_jit2ir6TBlockEEEB1P_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCs4YL2KM1Jyjv_11weavepy_jit2ir12IterLoopMetaEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB29_6filter6FilterINtNtNtB2d_5slice4iter4IterNtBW_12ListLoopMetaENCNvNtBY_7analyze12analyze_oncesf_0ENCB42_sg_0EE9from_iterBY_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecmEINtB2_12SpecFromItermINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1m_6filter6FilterINtNtNtB1q_3ops5range5RangejENCNvNtCs4YL2KM1Jyjv_11weavepy_jit7analyze12analyze_oncesm_0ENCB2X_sn_0EE9from_iterB31_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecmEINtB2_12SpecFromItermINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set8IntoItermEE9from_iterCs4YL2KM1Jyjv_11weavepy_jit @@ -6179,11 +5955,9 @@ _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower11load_method _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower16load_method_site _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower15load_attr_plain _RINvYINtNtNtCsevLNFiNqfJP_4core3ops5range5RangejENtNtNtNtBa_4iter6traits8iterator8Iterator3anyNCNvNtCs4YL2KM1Jyjv_11weavepy_jit7analyze12analyze_onces2_0EB1A_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsePCACruCPSX_15weavepy_codegen2ir9ValueDataE8grow_oneBQ_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsePCACruCPSX_15weavepy_codegen2ir13JumpTableDataEECs4YL2KM1Jyjv_11weavepy_jit.llvm.12598832926007596078 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcNtNtB1d_6object10PyFunctionEEEB1d_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCs8wxea0EYzJz_10weavepy_vm5tier212NativeCalleeEEEB1y_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4YL2KM1Jyjv_11weavepy_jit2ir12AttrSiteMetaEECs8wxea0EYzJz_10weavepy_vm _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4YL2KM1Jyjv_11weavepy_jit2ir13MathGuardMetaEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs8wxea0EYzJz_10weavepy_vm5tier29MathGuardEEB1c_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs8wxea0EYzJz_10weavepy_vm5tier212NativeCalleeEEINtB2_12SpecFromIterBU_INtNtNtNtBZ_4iter8adapters3map3MapINtNtNtBZ_5slice4iter4IterNtB1y_11MethodEntryENCNvMs6_B1y_NtB1y_8JitState23method_native_table_for0EE9from_iterB1A_ @@ -6244,7 +6018,6 @@ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellNtNtCs8wxea0EYzJz_1 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs8wxea0EYzJz_10weavepy_vm5tier28SiteArgsEEB1c_ _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower9build_map _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecTjNtNtCs4YL2KM1Jyjv_11weavepy_jit7analyze14CompHeaderPlanEEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map4IterjBW_ENCNvBY_12plan_rewrites5_0EE9from_iterB10_ -_RNvNtCs8wxea0EYzJz_10weavepy_vm5tier219jit_off_for_process _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCskKPjDLDyyy_16weavepy_compiler4name4NameEECs8wxea0EYzJz_10weavepy_vm _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower5is_op _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower8identity @@ -6287,7 +6060,6 @@ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecTmNtNvNtCs8wxea0EYzJz _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCs4YL2KM1Jyjv_11weavepy_jit7analyze2SEEINtB2_12SpecFromIterBU_INtNtB4_5drain5DrainBU_EE9from_iterBY_ _RNvMsa_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_5Lower5unary _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionPNtNtCs8wxea0EYzJz_10weavepy_vm6object10PyFunctionE11is_some_andNCINvMs7_BN_NtBN_11Interpreter9leaf_coreKb0_Esr_0EBN_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRxE6map_orTjjENCNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB14_11Interpreter16core_pure_methods_0EB14_ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtCs8wxea0EYzJz_10weavepy_vm10MethodSlotE8and_thenPNtNtBL_6object10PyFunctionNCINvMs7_BL_NtBL_11Interpreter9leaf_coreKb0_Esq_0EBL_ _RINvMs2_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB6_7HashMapmmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsePCACruCPSX_15weavepy_codegen6fxhash8FxHasherEE3getmECs4YL2KM1Jyjv_11weavepy_jit _RNvYNCNKNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib13functools_mod16LRU_NATIVE_DEPTH0s_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1r_6option6OptionQIB26_INtNtB1r_4cell4CelljEEEEE9call_onceBc_.llvm.8413732861020376357 @@ -6299,7 +6071,6 @@ _RNvMs_NtCsePCACruCPSX_15weavepy_codegen7builderNtB4_15FuncInstBuilder4isub _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionTmTNtNtCs4YL2KM1Jyjv_11weavepy_jit5value7JitTypeBL_EEE3mapINtNtB5_6result6ResultBK_NtNtBP_7analyze10JitVerdictENCNvB25_13step_abstracts2_0EBP_ _RNvMsl_NtCs8wxea0EYzJz_10weavepy_vm5typesNtB5_10PyInstance17laid_out_position _RNvXsK_NtCs1C1lLj4PWSY_5alloc6stringNtB5_6StringINtNtCsevLNFiNqfJP_4core7convert4FromReE4from -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs8wxea0EYzJz_10weavepy_vm8builtins12SetInplaceOpEEB1c_ _RINvNtCsevLNFiNqfJP_4core3mem4dropINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcNtNtBB_6object11PyGeneratorEEBB_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjNtNtCs8wxea0EYzJz_10weavepy_vm8builtins12SetInplaceOpEEEEB1z_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit10LazyGenRecEBF_ @@ -6312,9 +6083,7 @@ _RINvMs2_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB6_7HashMapTNtNtCsePCA _RNvMs1y_NtCs8wxea0EYzJz_10weavepy_vm6objectNtB6_6Object11is_int_like _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6result6ResultuNtNtCs8wxea0EYzJz_10weavepy_vm5error12RuntimeErrorEEB12_.llvm.9203291563379082861 _RINvNtCsevLNFiNqfJP_4core3mem4dropTINtNtCs8wxea0EYzJz_10weavepy_vm4sync6RefMutNtNtBC_6object8DictDataEBx_EEBC_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyANtNtCs8wxea0EYzJz_10weavepy_vm12shared_value9SharedStrj4_E4withNCINvNtNtBZ_6stdlib13functools_mod19with_partial_fieldsINtNtCsevLNFiNqfJP_4core6option6OptionTNtNtBZ_6object6ObjectB3s_EENCNvB21_14partial_inline0E0IB2Q_B2P_EEBZ_ _RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtNtBc_5slice4iter4IterNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectEBR_ENtNtNtBa_6traits8iterator8Iterator3allNCNvMs1s_B1j_B1h_8eq_value0EB1l_ -_RNvNtCs8wxea0EYzJz_10weavepy_vm5tier223try_borrowed_dyn_scalar _RNvMsl_NtCs8wxea0EYzJz_10weavepy_vm5typesNtB5_10PyInstance11try_recycle _RNvXs6_NtCs8wxea0EYzJz_10weavepy_vm9frame_jitNtB5_10DirectSiteNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs8wxea0EYzJz_10weavepy_vm9frame_jit6inline10InlineSiteEBH_ @@ -6343,14 +6112,12 @@ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecmEINtB2_12SpecFromIte _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecINtNtCsevLNFiNqfJP_4core6option6OptionTNtNtCs8wxea0EYzJz_10weavepy_vm6object7DictKeyNtB1z_6ObjectEEEINtB2_12SpecFromIterBU_INtNtNtNtBZ_4iter8adapters3map3MapNtNtB1B_7dictmap8IntoIterNcNtBU_4Some0EE9from_iterB1B_ _RNvMNtCsevLNFiNqfJP_4core5sliceSj4swapCs8wxea0EYzJz_10weavepy_vm _RNvMNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib13functools_mod9lru_stateNtB2_5Links7indices -_RNvNtCslNdsVBa5Sgt_13weavepy_lexer7scanner8tokenize _RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters5chainINtB5_5ChainIBP_IBP_INtNtBb_6option8IntoIterTRNtNtCs8wxea0EYzJz_10weavepy_vm6object7DictKeyRNtB1A_6ObjectEEINtNtB7_3map3MapINtNtB7_7flatten7FlattenIB19_RINtNtCs1C1lLj4PWSY_5alloc3vec3VecTB1y_B2i_EEEENCNvMsk_NtB1C_5typesNtB49_11SlotStorage4iters_0EEINtB2Q_7FlatMapIB19_RINtNtB3m_5boxed3BoxNtB1A_8DictDataEENtNtB1C_7dictmap4IterNCB43_s0_0EEIB4P_IB19_TRINtNtB1C_12shared_value7ThinArcINtB6v_12SliceStorageB1y_EERSB2i_EEINtNtB7_3zip3ZipINtNtNtBb_5slice4iter4IterB1y_EIB7N_B2i_EENCB43_s1_0EENtNtNtB9_6traits8iterator8Iterator8try_folduNCINvNtB7_6filter15filter_try_foldB1w_uINtNtNtBb_3ops12control_flow11ControlFlowuENCB43_s2_0NCINvNvB8E_3any5checkB1w_NCNvB1C_25exception_holds_nonatomics_0E0E0B9Z_EB1C_ _RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectE6appendBI_ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionPNtNtCs8wxea0EYzJz_10weavepy_vm6object10PyFunctionE11is_some_andNCINvMs7_BN_NtBN_11Interpreter17core_local_methodKb0_Es0_0EBN_ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectE10ok_or_elseNtNtBM_5error12RuntimeErrorNCNvMs7_BM_NtBM_11Interpreter4stepsE_0EBM_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyANtNtCs8wxea0EYzJz_10weavepy_vm12shared_value9SharedStrj4_E4withNCINvNtNtBZ_6stdlib13functools_mod19with_partial_fieldsINtNtCsevLNFiNqfJP_4core6option6OptionTINtNtBZ_2rc2RcNtNtBZ_6object9BuiltinFnEjEENCINvB21_17with_partial_callB3r_NCNvMs7_BZ_NtBZ_11Interpreter20core_partial_builtins_0E0E0IB2Q_B2P_EEBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyANtNtCs8wxea0EYzJz_10weavepy_vm12shared_value9SharedStrj4_E4withNCINvNtNtBZ_6stdlib13functools_mod19with_partial_fieldsINtNtCsevLNFiNqfJP_4core6option6OptionNtNtBZ_6object6ObjectENCINvB21_17with_partial_callB3r_NCNvMs7_BZ_NtBZ_11Interpreter17core_partial_calls_0E0E0IB2Q_B2P_EEBZ_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyANtNtCs8wxea0EYzJz_10weavepy_vm12shared_value9SharedStrj4_E4withNCINvNtNtBZ_6stdlib13functools_mod19with_partial_fieldsINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_6object10PyFunctionEENCINvB21_17with_partial_callB3r_NCNvMs7_BZ_NtBZ_11Interpreter17core_partial_calls0_0E0E0IB2Q_B2P_EEBZ_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib13functools_mod17with_stolen_cacheINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB6_6object6ObjectENCNCNvB2_8lru_calls_00EB6_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib13functools_mod17with_stolen_cacheuNCNCNvB2_9lru_store00EB6_ _RNvMNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11random_coreNtB2_2Mt13init_by_array.llvm.16543740499146762547 @@ -6392,7 +6159,6 @@ _RNvMsV_CskKPjDLDyyy_16weavepy_compilerNtB5_8Compiler15emit_super_attr _RINvMsV_CskKPjDLDyyy_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_15emit_super_attr0EB6_ _RNvCskKPjDLDyyy_16weavepy_compiler23method_references_class _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8ConstantEECskKPjDLDyyy_16weavepy_compiler -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterINtNtBI_4sync3ArcNtNtCs8wxea0EYzJz_10weavepy_vm15thread_registry11ThreadEntryEEEB1K_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs8wxea0EYzJz_10weavepy_vm6object20ByteArrayExportGuardEBF_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecmEINtB2_12SpecFromItermINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtNtB1q_3str4iter5CharsNCNvNtCskKPjDLDyyy_16weavepy_compiler7ast_opt10str_points0EE9from_iterB2A_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCs4mGAQSAXlfR_14weavepy_parser3ast8ConstantEINtB2_12SpecFromIterBU_INtNtNtCsevLNFiNqfJP_4core4iter8adapters12GenericShuntINtNtB26_3map3MapINtNtNtB2a_5slice4iter4IterNtCskKPjDLDyyy_16weavepy_compiler8ConstantENvNtB3F_9flowgraph15to_ast_constantEINtNtB2a_6option6OptionNtNtB2a_7convert10InfallibleEEE9from_iterB3F_ @@ -6422,7 +6188,6 @@ _RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCskKPjDLDyyy_16weavep _RINvNtCsevLNFiNqfJP_4core3mem4dropINtNtB4_6option6OptionTNtNtCs8wxea0EYzJz_10weavepy_vm6object7DictKeyNtBV_6ObjectEEEBX_ _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs8wxea0EYzJz_10weavepy_vm8gc_trace17DeferredContainerE6retainNCNvMse_BH_NtBH_7GcState19sweep_deferred_froms_0EBJ_ _RNvMNtCs1C1lLj4PWSY_5alloc3vecINtB2_3VechE13with_capacityCs8wxea0EYzJz_10weavepy_vm -_RNvCsdtSMxSA38aw_7___rustc12___rust_alloc _RNvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB2_8OnceLockINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcDNtNtCsevLNFiNqfJP_4core3any3AnyNtNtB1y_6marker4SendNtB21_4SyncEL_EE3setBX_ _RNvMs_NtNtCsePCACruCPSX_15weavepy_codegen2ir9condcodesNtB4_7FloatCC7inverse _RNvNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib4math14freshen_result7freshen @@ -6441,10 +6206,8 @@ _RNvMsk_NtCs8wxea0EYzJz_10weavepy_vm5typesNtB5_11SlotStorage14get_hinted_mut _RNvMs_NtCs8wxea0EYzJz_10weavepy_vm7timsortINtB4_10MergeStateTNtNtB6_6object6ObjectBX_ENCINvMs7_B6_NtB6_11Interpreter10sort_keyedBW_NCNvB1r_13sort_with_keys0_0Es2_0E2ltB6_ _RINvMs0_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapINtNtCs1C1lLj4PWSY_5alloc4sync3ArceEuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCskKPjDLDyyy_16weavepy_compiler4name2FxEE6retainNCINvMs_NtB8_3setINtB3a_7HashSetBO_B1p_E6retainNCNvMs1_B2e_NtB2e_4Pool6intern0E0EB2g_ _RNvMsf_NtCs8wxea0EYzJz_10weavepy_vm4syncINtB5_7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB7_2rc2RcNtNtB7_5types10TypeObjectEEE10try_borrowB7_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTjINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcNtNtBI_5types10PyInstanceEEEBI_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtB6_6string6StringEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB1I_6filter6FilterINtNtNtB1M_5slice4iter4IterBU_ENCNvMsd_NtCs8wxea0EYzJz_10weavepy_vm5typesNtB3x_10TypeObject19member_slots_sorted0EEE9from_iterB3z_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB6_3VecNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectEINtB4_10SpecExtendBT_INtNtCsevLNFiNqfJP_4core6option8IntoIterBT_EE11spec_extendBX_ -_RNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB5_11Interpreter17resolve_field_str _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib10struct_mod8registerNvB2_12b_pack_plainEB6_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib10struct_mod8registerNvB2_13b_value_codesEB6_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib10struct_mod8registerNvB2_13b_unpack_fromEB6_ @@ -6471,7 +6234,6 @@ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCs8wxea0EYzJz_10w _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtB6_6string6StringEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1M_5slice4iter4IterTBU_NtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectEENCNvMs7_B30_NtB30_11Interpreter16bind_python_argss_0EE9from_iterB30_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VechEINtB2_12SpecFromIterhINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtNtB1q_3str4iter5CharsNCNvCs8wxea0EYzJz_10weavepy_vm9binary_ops6_0EE9from_iterB2y_ _RNvCs8wxea0EYzJz_10weavepy_vm18certain_miss_error -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainINtNtCs8wxea0EYzJz_10weavepy_vm7dictmap6BucketuEEEB1n_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11random_core7with_mtdNCNvB2_11random_from0EB6_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objects10with_matchINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB6_6object6ObjectNtNtB6_5error12RuntimeErrorENCNvB2_14match_position0EB6_ _RNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objects7span_of @@ -6561,14 +6323,12 @@ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB6_3VecINtNtB8_5boxed3BoxNtCs _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs8wxea0EYzJz_10weavepy_vm8DelegateEBD_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterINtNtBI_5boxed3BoxNtCs8wxea0EYzJz_10weavepy_vm9InlineActEEEB1J_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters3rev3RevINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainNtCs8wxea0EYzJz_10weavepy_vm8DelegateEEEB1S_ -_RNvMNtCs4YL2KM1Jyjv_11weavepy_jit5lowerNtB2_7Lowerer19emit_attr_get_chain _RNvNtCsePCACruCPSX_15weavepy_codegen4fold6negate _RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecmE17try_reserve_exactCs8wxea0EYzJz_10weavepy_vm _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB25_3rev3RevINtNtNtB29_5slice4iter4IterBU_EEEE9from_iterBY_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11heapq_accel11with_interpNCNvB2_13heappush_impls_0NtNtB6_6object6ObjectEB6_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11heapq_accel11with_interpNCNvB2_12heappop_impl0NtNtB6_6object6ObjectEB6_ _RINvNtCs8wxea0EYzJz_10weavepy_vm6object16write_float_reprNtNtNtB4_6stdlib10json_accel10JsonWriterEB4_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib10json_accel7KeyMemoEBH_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB4_3VecmEINtB2_10SpecExtendmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtNtB1l_3str4iter5CharsNvYmINtNtB1l_7convert4FromcE4fromEE11spec_extendCs8wxea0EYzJz_10weavepy_vm _RNCNvMs7_Cs8wxea0EYzJz_10weavepy_vmNtB7_11Interpreter21percent_mod_left_slot0B7_ _RINvXs11_NtCs1C1lLj4PWSY_5alloc2rcINtB7_2RcSNtNtCs8wxea0EYzJz_10weavepy_vm6object7DictKeyEINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorBG_E9from_iterINtNtNtB1x_8adapters3map3MapINtNtB2J_5chain5ChainINtNtNtB1z_5slice4iter4IterReEB3r_ENCNCNCNvNtNtBK_6stdlib4time16struct_time_keys000EEBK_ @@ -6581,10 +6341,7 @@ _RNvNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib12pickle_accel6encode8identity _RNvMs0_NtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder5enter _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib12pickle_accel6decodeNCNCNvB2_10make_loads0s_0EB6_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainTNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectyEEEB1n_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib12pickle_accel10PlainClassEEB1e_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainTINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcNtNtB1o_5types10TypeObjectEINtBG_3VecNtNtB1o_6object6ObjectEEEEB1o_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcINtNtB1d_4sync7GilCellNtNtB1d_6object8DictDataEEEEB1d_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib12pickle_accel7ScratchEBH_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable9quicksort9quicksortNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB15_NtNtBa_3cmp10PartialOrd2ltECskKPjDLDyyy_16weavepy_compiler _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB6_3VecNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectEINtB4_10SpecExtendBT_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB6_5drain5DrainTBT_yEENCNvMsc_NtNtBX_6stdlib12pickle_accelNtB3k_7Decoder6extend0EE11spec_extendBX_ _RNvYNCNKNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib12pickle_accel13SPARE_SCRATCH00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1l_6option6OptionQIB20_INtNtB1l_4cell4CellIB20_NtB8_7ScratchEEEEEE9call_onceBc_.llvm.17829461671745883609 @@ -6610,7 +6367,6 @@ _RNvYNvNtCs8wxea0EYzJz_10weavepy_vm8builtins18bytes_translate_kwINtNtNtCsevLNFiN _RNvXsl_NtCsgHYyB3hU8Ec_3std4pathNtB5_10ComponentsNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq _RNvNtCs8wxea0EYzJz_10weavepy_vm17frozen_code_cache10result_put _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objects11with_interpNtNtB6_6object6ObjectNCNvB2_7run_subs_0EB6_ -_RNvMs_NtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objectsNtB4_4Sink12finish_plain _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB6_6object6ObjectNtNtB6_5error12RuntimeErrorENCNvB2_15pattern_scanner0EB6_ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6option6OptionINtNtB19_6result6ResultNtNtB6_6object6ObjectNtNtB6_5error12RuntimeErrorEENCNvB2_8sub_fast0EB6_ _RNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib11sre_objects13has_backslash @@ -6626,14 +6382,10 @@ _RINvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib7sre_mod10exec_foundhTjjINtNtCsevLNFiN _RNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib7sre_mod13sre_cache_put _RNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib7sre_mod19sre_unicode_tolower _RNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib7sre_mod19sre_unicode_iscased -_RNvNtCs8wxea0EYzJz_10weavepy_vm7seqiter12any_all_fast -_RNvNtCs8wxea0EYzJz_10weavepy_vm7seqiter8any_fast _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs8wxea0EYzJz_10weavepy_vm17frozen_code_cache10result_put0E0zE0E0B2m_.llvm.5721293015000088327 _RNvMsD_NtCsgHYyB3hU8Ec_3std2fsNtB5_10DirBuilder7__create _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmNtNtNtCs1w4Ic9Wfcv9_10num_bigint7biguint4iter9U32DigitsE9from_iterCs8wxea0EYzJz_10weavepy_vm _RNCINvNtCs8wxea0EYzJz_10weavepy_vm8builtins9method_kwNvB4_18bytes_translate_kwEs_0B6_ -_RNvNtCs8wxea0EYzJz_10weavepy_vm8builtins18dict_fromkeys_leaf -_RNvNtCs8wxea0EYzJz_10weavepy_vm8builtins18bytearray_byte_arg _RINvXs5_NtCs1C1lLj4PWSY_5alloc6stringNtB6_6StringINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorcE9from_iterINtNtNtBS_8adapters10take_while9TakeWhileNtNtNtBU_3str4iter5CharsNCNvNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib14sqlite3_native4stmt10sql_is_dml0EEB3a_ _RNvMs2_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB5_7HashMapxINtNtCs8wxea0EYzJz_10weavepy_vm2rc2RcINtNtB19_4sync7GilCellNtNtNtB19_6stdlib14sqlite3_native9ConnStateEEE6insertB19_ _RNvMNtCsevLNFiNqfJP_4core6resultINtB2_6ResultNtNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib14sqlite3_native6cursor10CursorLockNtNtBP_5error12RuntimeErrorE2okBP_ @@ -6641,7 +6393,6 @@ _RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultNtNtNtCs1C1lLj4PWSY_5alloc3ffi5c_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib14sqlite3_native6cursor11CursorStateEBJ_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib14sqlite3_native9ConnStateEBH_ _RNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib14sqlite3_native6method -_RINvMs0_NtCs8wxea0EYzJz_10weavepy_vm5errorNtB6_11PyException12from_builtinReEB8_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VechEINtB4_18SpecFromIterNestedhINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1F_5slice4iter4IterhENCNvMs_NtB8_5sliceSh18to_ascii_uppercase0EE9from_iterCs8wxea0EYzJz_10weavepy_vm _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectE10ok_or_elseNtNtBM_5error12RuntimeErrorNCNvNtNtNtBM_6stdlib14sqlite3_native6cursor15cur_executemanys_0EBM_ _RINvNtNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib14sqlite3_native4stmt13bind_sequenceNCNvB2_15bind_parameterss_0EB8_ @@ -6651,7 +6402,6 @@ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4c _RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapINtNtNtB6_5slice4iter4IterNtNtCs8wxea0EYzJz_10weavepy_vm6object6ObjectENCNvNtNtB1A_6stdlib4math8math_gcd0EyINtNtB6_6option6OptionNtNtB6_7convert10InfallibleENCINvXsI_B2S_IB2Q_INtNtCs1C1lLj4PWSY_5alloc3vec3VecyEEINtNtNtB4_6traits7collect12FromIteratorIB2Q_yEE9from_iterBQ_E0B3V_EB1A_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs8wxea0EYzJz_10weavepy_vm9PolyCallsEBD_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCs8wxea0EYzJz_10weavepy_vm6object7DictKeyEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtBY_7dictmap4KeysuEEE9from_iterBY_ -_RNvNtNtCs8wxea0EYzJz_10weavepy_vm6stdlib15datetime_native9dt_packed _RNvXs1N_NtNtCs1w4Ic9Wfcv9_10num_bigint7biguint8divisionRNtB8_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops5arith3RemyE3rem _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionPNtNtCs8wxea0EYzJz_10weavepy_vm6object10PyFunctionE6filterNCNvNtBN_9frame_jit13h_load_globals4_0EBN_ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtCs8wxea0EYzJz_10weavepy_vm10MethodSlotE8and_thenPNtNtBL_6object10PyFunctionNCNvNtBL_9frame_jit13h_load_globals3_0EBL_ @@ -6749,10 +6499,7 @@ _RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2R _RNvMs_NtCs5HK7yca7OMW_10weavepy_vm10hot_filterNtB4_11AtomicBloom11may_contain.llvm.9250547820948799359 _RNCNvCs5HK7yca7OMW_10weavepy_vm22set_function_attributes0_0B3_ _RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter14leaf_core_attrs_0B7_ -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter4steps0_0B7_ -_RNCNvCs5HK7yca7OMW_10weavepy_vm19percent_format_withs6_0B3_ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22cached_property_getter -_RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_Esx_0B8_ _RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtB1a_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEEB27_.llvm.4890245414193407415 _RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalEBO_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtCs7usbkSbEEZs_16weavepy_compiler8CodeBodyEEBZ_.llvm.3546700407397947748 @@ -6760,7 +6507,6 @@ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm6object12DepartedBackEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs1C1lLj4PWSY_5alloc6string6StringECs5HK7yca7OMW_10weavepy_vm.llvm.4890245414193407415 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtB1n_4sync7GilCellNtNtB1n_6object8DictDataEEEEEB1n_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object9DictWatchEEB11_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsgHYyB3hU8Ec_3std4path7PathBufEEECs5HK7yca7OMW_10weavepy_vm _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5HK7yca7OMW_10weavepy_vm10MethodSlotEBD_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEBC_BC_EEB12_ @@ -6836,7 +6582,6 @@ _RNvMs0_NtCs7usbkSbEEZs_16weavepy_compiler11native_codeNtB5_6Reader4body _RNvMNtCs7usbkSbEEZs_16weavepy_compiler11native_codeNtB2_6Module3new _RNvNtCs7usbkSbEEZs_16weavepy_compiler11native_code13decode_lazily _RNCNvNtCs5HK7yca7OMW_10weavepy_vm11stdlib_tree19write_build_details0B5_ -_RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState7untrack _RINvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB6_7GcState11young_leaveNtNtB8_5types10PyInstanceEB8_.llvm.15809725932051974371 _RINvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB6_7GcState11young_leaveNtNtB8_6object10PyFunctionEB8_.llvm.15809725932051974371 _RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState22rebuild_tracked_filter @@ -6917,224 +6662,39 @@ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTNtNtCs5HK7yca _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtNtB8_11collections5btree3set8IntoIterNtNtB8_6string6StringEINvMs1y_B15_B13_8from_strB3M_EEE9from_iterB17_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTNtNtB6_6string6StringNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapNtNtB1r_7dictmap4IterNCNvB1r_22set_function_attributes_0EE9from_iterB1r_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB6_9into_iter8IntoIterINtNtB17_2rc2RcNtNtB17_5types10TypeObjectEENcNtB13_4Type0EE9from_iterB17_ -_RNvMs1_NtCs7usbkSbEEZs_16weavepy_compiler9flowgraphNtB5_3Cfg36is_exit_or_eval_check_without_lineno _RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler9flowgraphNtB4_5Block8add_jump -_RNvMs1_NtCs7usbkSbEEZs_16weavepy_compiler9flowgraphNtB5_3Cfg20const_loading_instrs -_RNvMs1_NtCs7usbkSbEEZs_16weavepy_compiler9flowgraphNtB5_3Cfg21scan_block_for_locals -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9file_read -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13property_with -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14wstr_attr_dict _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins8dict_pop -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins22coexist_builtin_dunder -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11dict_insert _RNvNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12vm_intrinsic5build -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins24bytearray_receiver_guard _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18ensure_set_element -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins21mappingproxy_delegate -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins21property_init_members -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins22construct_staticmethod -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins8str_join -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins8dict_get -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11list_append _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10file_enter -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18set_membership_key -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10dict_clear -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12b_int_compat -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins6b_dict -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17dict_insert_exact -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17mappingproxy_args -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16property_payload -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11dict_remove -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16str_isidentifier -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11list_remove -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16mappingproxy_get -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins7set_pop -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17str_replace_exact -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18join_exact_strings -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16parse_float_text -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins27transform_decimal_and_space _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18validate_open_mode _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12b_memoryview _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16sync_frame_spine _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9file_exit -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins20function_get_builtin -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18object_is_callable -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14numeric_dunders2_0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11list_insert -_RNCINvNtCs5HK7yca7OMW_10weavepy_vm8builtins9method_kwNvB4_14str_replace_kwEs_0B6_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16reentrant_interp -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11b_enumerate -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11b_frozenset -_RNCNvNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12vm_intrinsic5build0B7_.llvm.13937324807167308475 -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins20try_coerce_index_i64 -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19int_bit_length_leaf -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins15object_identity -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins23reentrant_load_attr_opt -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17int_to_bytes_leaf -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18mappingproxy_items -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19int_from_bytes_leaf _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16audit_open_event -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18construct_property -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11hash_object -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17dict_setitem_leaf -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13b_set_tp_name.llvm.13937324807167308475 -_RNCINvNtCs5HK7yca7OMW_10weavepy_vm8builtins9method_kwNvB4_13str_format_kwEs_0B6_ _RNvCs5993W3JedWL_14weavepy_parser19parse_with_warnings.llvm.13852504158782296996 -_RNvCs5993W3JedWL_14weavepy_parser21eval_backslash_at_eof.llvm.13852504158782296996 _RNvMs5_NtNtNtCsgHYyB3hU8Ec_3std4sync6poison5mutexINtB5_5MutexINtNtCsevLNFiNqfJP_4core6option6OptionyEE4lockCs5HK7yca7OMW_10weavepy_vm -_RNvMNtNtCsg55y0en7y7K_6chrono6offset3utcNtB2_3Utc3now -_RNvCs89hHMyD40Kn_15weavepy_codegen4dump _RNvMs3_Cs89hHMyD40Kn_15weavepy_codegenNtB5_4Code6placed -mi_bchunk_popcountNC _RNvMs2_NtCsgHYyB3hU8Ec_3std2fsNtB5_4File8metadata -_RNvNvNtCsgHYyB3hU8Ec_3std2fs4read5inner -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15worth_compilings6_0B5_ -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower9exit_with -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower15after_helper_to -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10top_to_mem -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower14check_released -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11global_miss -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit4tags -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11lower_block -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower4goto -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower4push -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower7call_op -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10branch_out -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10store_last -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11load_global -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10copy_value -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower21plain_release_in_line -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15h_for_iter_rest -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12block_starts -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11leave_block -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower9write_tag -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11instruction -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10call_typed -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower3sig -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10store_fast -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7in_loop -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11lower_range -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower5flush -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower7require -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower12operand_site -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower14fill_side_exit -_RNvMs3_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_4Slot11try_compile -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit9native_at.llvm.3361737253219229403 -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11iter_layouts0_0B5_ -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower9load_fast -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower15after_helper_if -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit20maybe_unbound_locals -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower7operand -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10local_addr -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower15store_from_slot -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower4exit -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6define -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit5parts -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8h_global _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit18counted_at_payload -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11materialize -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower9slot_addr -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower9call_site -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower8for_iter -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10h_for_iter _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCsgHYyB3hU8Ec_3std4sync9once_lock8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcDNtNtB4_3any3AnyNtNtB4_6marker4SendNtB2h_4SyncEL_EEEB1t_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6NativeEEE10initializeNCINvB2_11get_or_initNCNvB26_7publish0E0zEB28_ -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser13parse_bit_xor -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser12parse_addsub -_RNvNtCs5993W3JedWL_14weavepy_parser6parser19split_string_prefix -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser24check_string_expr_string -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser26collect_pep695_type_params -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser23take_colon_type_comment -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser11parse_block -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser9parse_try -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser26parse_target_list_no_tuple -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser13parse_ternary -_RNvNtCs5993W3JedWL_14weavepy_parser6parser12strip_quotes -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser17parse_dotted_name -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser3eat -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser10at_keyword -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser18try_arg_annotation -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser8parse_or -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser9parse_and -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser9parse_not -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser18parse_function_def -_RNvNtCs5993W3JedWL_14weavepy_parser6parser12parse_number -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser26take_trailing_type_comment -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser22parse_subscript_single -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser13parse_bit_and -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser12parse_muldiv -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser27take_def_body_type_comments -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser15parse_call_args -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser16consume_stmt_end -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser16parse_dict_value -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser17parse_eval_module.llvm.7425312718194757584 -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser24parse_ternary_or_starred -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser13string_prefix -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser13decode_string -_RNvNtCs5993W3JedWL_14weavepy_parser6parser15decode_str_body -_RNvNtCs5993W3JedWL_14weavepy_parser6parser15cps_to_constant -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser21parse_arguments_inner -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser5check _RNvNtCs5993W3JedWL_14weavepy_parser6parser10parse_eval _RNvNtCs5993W3JedWL_14weavepy_parser6parser21parse_eval_with_flufl -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser22parse_simple_statement -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser11parse_power -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser24check_import_alias_debug _RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser24attach_arg_type_comments -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser19at_expression_start -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser20parse_target_or_star -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser8parse_if -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser12parse_bit_or -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser11parse_shift -_RNvNtCs5993W3JedWL_14weavepy_parser6parser16constant_str_cps -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser5ident -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser6expect -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser15prev_token_span -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser9parse_for -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser17expect_dict_colon -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser18parse_eval_element -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser21parse_expression_list -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser11parse_unary -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser12parse_import -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser12parse_return -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser19find_invalid_target -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser11parse_raise -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser10parse_atom -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser4bump -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser22expect_or_forgot_comma -_RNvNtCs5HK7yca7OMW_10weavepy_vm5error14stop_iteration -_RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm5errorNtB5_11PyException9type_name -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower20inline_settle_fields -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline10callees_at -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline10call_start.llvm.2449273802214287896 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4plan -_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtB8_6string6StringE16extend_desugaredINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set8IntoIterBG_EECs7usbkSbEEZs_16weavepy_compiler -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs5HK7yca7OMW_10weavepy_vm5tier23PinE8push_mutBJ_ _RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecmE16into_boxed_sliceCs5HK7yca7OMW_10weavepy_vm _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtB7_5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14InstMethodSiteEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB11_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline11InlineFrameENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBL_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecIBw_INtNtB7_5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm9InlineActEEE8push_mutB13_ _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakNtNtBL_6object10PyFunctionEINtBJ_2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEjEE6retainNCNvNtNtBL_6stdlib18collections_native19namedtuple_registers_0EBL_ _RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs89hHMyD40Kn_15weavepy_codegen7codegen4SnapEE11extend_withB1l_ -_RNvMs1_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEE6resizeB1l_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtB7_5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit9SuperSiteEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB11_ _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs89hHMyD40Kn_15weavepy_codegen2ir4InstE6retainNCNvNtBJ_8simplify8simplifys2_0EBJ_ -_RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VechE16into_boxed_sliceCs5HK7yca7OMW_10weavepy_vm -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtBK_4sync7GilCellNtNtBK_6object6ObjectEEE8push_mutBK_ _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE5drainINtNtNtCsevLNFiNqfJP_4core3ops5range14RangeInclusivejEEBJ_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtB7_5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8TypeSiteEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB11_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs5993W3JedWL_14weavepy_parser3ast4ExprEE8push_mutB1l_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtCs7usbkSbEEZs_16weavepy_compiler9LoopFrameE8push_mutBH_ _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakNtNtBL_5types10TypeObjectEBG_EE6retainNCNCNvNtNtBL_6stdlib13itertools_mod14register_types00EBL_ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs5993W3JedWL_14weavepy_parser3ast4ExprENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCs7usbkSbEEZs_16weavepy_compiler _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTmNtNtCs89hHMyD40Kn_15weavepy_codegen3x643FixEE6retainNCNvMs1_BJ_NtBJ_3X645relaxs3_0EBL_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtCs7usbkSbEEZs_16weavepy_compiler12FinallyFrameE8push_mutBH_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs7usbkSbEEZs_16weavepy_compiler8validate5ScopeE8push_mutBJ_ _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakNtNtBK_5types10TypeObjectEE6retainNCNvMsd_B1k_B1i_10subclasses0EBK_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBK_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs5993W3JedWL_14weavepy_parser3ast4ExprE8push_mutBJ_ -_RNCNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB7_8Compiler18compile_stmt_inners0_0B7_ -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtB7_6string6StringENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCs7usbkSbEEZs_16weavepy_compiler _RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionTIBw_hEmEEE11extend_withCs89hHMyD40Kn_15weavepy_codegen _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VechENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCscY2bcUAVtje_11weavepy_cli _RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VeclE11extend_withCs5HK7yca7OMW_10weavepy_vm @@ -7142,487 +6702,160 @@ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTjIBw_NtNtNtCs5HK7yca7OMW_10weavepy_ _RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecTmNtCs5HK7yca7OMW_10weavepy_vm8StoreSrcEE16into_boxed_sliceBI_ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VeciENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCs5HK7yca7OMW_10weavepy_vm _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBK_6object9BuiltinFnEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBK_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm11stdlib_tree8contains -_RNvMsb_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB5_11SplitValues4take -_RNvMsh_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB5_8InstDict11materialize -_RINvMsb_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB6_11SplitValues10fill_freshNCNCNvMs7_B8_NtB8_11Interpreter15core_store_inits5_00NCB1e_s_0EB8_ _RINvMsb_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB6_11SplitValues10first_pushNCNvMsi_B6_NtNtB8_5types10PyInstance12split_append0EB8_ _RINvMsb_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB6_11SplitValues11reserve_forNCNvNtB8_5tier215try_native_ctor0EB8_ -_RNvMsb_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB5_11SplitValues5reset _RNvXse_NtNtCsgHYyB3hU8Ec_3std2io5stdioNtB5_6StdoutNtNtNtCsevLNFiNqfJP_4core2io5write5Write9write_fmt _RNvXsi_NtNtCsgHYyB3hU8Ec_3std2io5stdioNtB5_10StdoutLockNtNtNtCsevLNFiNqfJP_4core2io5write5Write9write_all _RNvXsf_NtNtCsgHYyB3hU8Ec_3std2io5stdioRNtB5_6StdoutNtNtNtCsevLNFiNqfJP_4core2io5write5Write9write_fmt -_RINvMNtNtCsevLNFiNqfJP_4core4cell4onceINtB3_8OnceCellINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBU_5types10TypeObjectEE8try_initNCINvB2_11get_or_initNCNCNvNtNtBU_6stdlib4time16struct_time_type00E0zEBU_.llvm.15809725932051974371 -_RINvMNtNtCsevLNFiNqfJP_4core4cell4onceINtB3_8OnceCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecjEE8try_initNCINvB2_11get_or_initNCNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB1Y_6Parser8line_col0E0zEB20_.llvm.4761433731191428751 _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1m_NtNtBa_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort18small_sort_generalNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1f_NtNtBa_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort31small_sort_general_with_scratchNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1s_NtNtBa_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort12sort4_stableNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB19_NtNtBa_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftTmNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB1m_7sort_byNCNvMNtB1s_7codegenINtB2X_3GenNtNtB1s_3x643X64E11choose_pinss0_0E0EB1s_ -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm12type_surface11unwrap_shim14check_receiver -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm12type_surface11unwrap_shim0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm12type_surface15obj_len_builtin -_RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultINtNtCs5HK7yca7OMW_10weavepy_vm4sync3RefNtNtBN_9inst_dict11SplitValuesENtBL_11BorrowErrorE9is_ok_andNCNvBN_21default_lookup_missess0_0EBN_ _RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultINtNtCs5HK7yca7OMW_10weavepy_vm4sync3RefINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBN_6object6ObjectEENtBL_11BorrowErrorE9is_ok_andNCNvMs7_BN_NtBN_11Interpreter17leaf_builtin_calls6_0EBN_ -_RNvMNtCs5HK7yca7OMW_10weavepy_vm11weak_objectNtB2_10WeakObject12strong_count -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod13quick_asserts0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod20simple_first_checked -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtNtCsevLNFiNqfJP_4core4cell4once8OnceCellINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB1T_5types10TypeObjectEEEB1T_.llvm.4890245414193407415 _RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakNtNtB2j_5types10TypeObjectEB2e_EEEEB2j_.llvm.4890245414193407415 -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB1a_6object6ObjectEEEB1a_.llvm.4890245414193407415 _RNvMNtNtCs3QF46a9Pg1X_8indexmap3map5entryINtB2_5EntryNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCs7usbkSbEEZs_16weavepy_compiler7BindingE9or_insertB1t_ -_RNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint7convert22from_bitwise_digits_le -_RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCs5993W3JedWL_14weavepy_parser3ast7KeywordNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalECs7usbkSbEEZs_16weavepy_compiler.llvm.16607524104033215587 _RINvMNtCsevLNFiNqfJP_4core3stre12trim_matchesNCNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter11decimal_i640EBN_ -_RINvMNtCsevLNFiNqfJP_4core3stre18trim_start_matchescECs5HK7yca7OMW_10weavepy_vm -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5993W3JedWL_14weavepy_parser3ast8ConstantECs7usbkSbEEZs_16weavepy_compiler.llvm.16607524104033215587 -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5993W3JedWL_14weavepy_parser3ast13ExceptHandlerECs7usbkSbEEZs_16weavepy_compiler.llvm.16607524104033215587 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBG_6string6StringEECs7usbkSbEEZs_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCsgHYyB3hU8Ec_3std4sync9once_lock8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7abc_mod8AbcStateEEEB23_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueANtNtCs5HK7yca7OMW_10weavepy_vm6object6Objectj3_EBG_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBG_6string6StringEECscY2bcUAVtje_11weavepy_cli _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueAINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEj20_EB12_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm9InlineActEEEB1s_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm17frozen_code_cache7PayloadEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm7timsort10MergeStateTNtNtBG_6object6ObjectB1r_ENCINvMs7_BG_NtBG_11Interpreter10sort_keyedB1q_NCNvB1W_13sort_with_keys0_0E0EEBG_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecIBC_hEEECs5HK7yca7OMW_10weavepy_vm -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs5HK7yca7OMW_10weavepy_vm5tier23PinEEB1c_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel10EncoderCfgEBH_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod13MarshalReaderEBH_.llvm.10335684157103142333 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod7MatcherhEEBI_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5types10TypeObjectEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5types12InstancePlanEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier23PinEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtBG_5trace15MonitoringToolsEEBG_.llvm.16112649145315725652 -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm6object6PyFileEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcNtNtB12_13tuple_storage12TupleStorageEEEB12_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod8CodePlanEEB13_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters5chain5ChainINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtNtBG_3map3MapIB1e_TNtNtB1k_6string6StringB21_EENCNvMs7_B25_NtB25_11Interpreter20core_builtin_kw_lane0EEEB25_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBG_5types10PyInstanceEEBG_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs89hHMyD40Kn_15weavepy_codegen2ir13DataFlowGraphECs5HK7yca7OMW_10weavepy_vm -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5993W3JedWL_14weavepy_parser3ast8ExprKindECs7usbkSbEEZs_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtCs7usbkSbEEZs_16weavepy_compiler12FinallyFrameEEBZ_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm16weakref_registry11WeakRefSlotEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcNtNtBG_13tuple_storage12TupleStorageEEBG_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEEB1y_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5993W3JedWL_14weavepy_parser3ast4StmtECs7usbkSbEEZs_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters4take4TakeINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB25_6object10PyFunctionEbjEEEEB25_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs89hHMyD40Kn_15weavepy_codegen3x643X64EBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB12_6string6StringEEECscY2bcUAVtje_11weavepy_cli _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs5993W3JedWL_14weavepy_parser3ast4StmtEEECs7usbkSbEEZs_16weavepy_compiler -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6result6ResultNtCs5HK7yca7OMW_10weavepy_vm11StepOutcomeNtNtBZ_5error12RuntimeErrorEEBZ_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtCs5HK7yca7OMW_10weavepy_vm8LeafStopEEBZ_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6result6ResultNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectNtNtB11_5error12RuntimeErrorEEB11_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtBG_6object11FileBackendEEBG_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze6RegionEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs89hHMyD40Kn_15weavepy_codegen8liveness8AnalysisEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs89hHMyD40Kn_15weavepy_codegen2ir8FunctionECs5HK7yca7OMW_10weavepy_vm _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5993W3JedWL_14weavepy_parser3ast4ExprECs7usbkSbEEZs_16weavepy_compiler.llvm.16607524104033215587 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm14descr_registry9DescrMetaEEB11_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object20ByteArrayExportGuardEEB11_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB1v_6object10PyFunctionEbEEEB1v_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8EstimateEEB11_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtB12_4sync7GilCellNtNtB12_6object8DictDataEEEEB12_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5HK7yca7OMW_10weavepy_vm10QuietEntryEBD_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5HK7yca7OMW_10weavepy_vm10CoreSwitchEBD_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB12_6object10FrameShellEEEB12_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5HK7yca7OMW_10weavepy_vm11NativeTruthEBD_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs89hHMyD40Kn_15weavepy_codegen4CodeECs5HK7yca7OMW_10weavepy_vm -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5993W3JedWL_14weavepy_parser3ast9ArgumentsECs7usbkSbEEZs_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5types13LeafAttrEntryEBF_.llvm.4890245414193407415 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm7NewInitEEEB1y_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze4PlanEBF_ -_RNvXs3_NtCsevLNFiNqfJP_4core4bstrNtB5_7ByteStrNtNtB7_3fmt7Display3fmt -_RINvXs7_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3setINtB6_7HashSetNtNtCs1C1lLj4PWSY_5alloc6string6StringINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEEINtNtNtNtB1L_4iter6traits7collect12FromIteratorB14_E9from_iterINtNtNtB18_3vec9into_iter8IntoIterB14_EEB2x_ _RNvXs_NtNtNtCsevLNFiNqfJP_4core5array4iter10iter_innerAINtNtNtBa_3mem12maybe_uninit11MaybeUninitNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEj5_NtB4_11PartialDrop12partial_dropB1A_ _RNvXs_NtNtNtCsevLNFiNqfJP_4core5array4iter10iter_innerAINtNtNtBa_3mem12maybe_uninit11MaybeUninitNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEj3_NtB4_11PartialDrop12partial_dropB1A_ -_RINvMNtCs5HK7yca7OMW_10weavepy_vm13tuple_storageNtB3_12TupleStorage10from_arrayKj2_EB5_ _RINvMNtCs5HK7yca7OMW_10weavepy_vm13tuple_storageNtB3_12TupleStorage10from_arrayKj3_EB5_ -_RINvMNtCs5HK7yca7OMW_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterNtNtB5_11frame_slots10StackDrainEB5_ _RINvXsb_NtNtCs1C1lLj4PWSY_5alloc5boxed4iterINtB8_3BoxSNtCs5HK7yca7OMW_10weavepy_vm8AttrPolyEINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorBQ_E9from_iterINtNtNtB1z_8adapters3map3MapINtNtNtB1B_3ops5range5RangejENCNCINvMst_BS_NtBS_16CodeConstObjects11alloc_sitesBQ_FEBQ_E0s0_0EEBS_ _RINvXsb_NtNtCs1C1lLj4PWSY_5alloc5boxed4iterINtB8_3BoxSINtNtNtCsevLNFiNqfJP_4core4sync6atomic6AtomicbEEINtNtNtNtBX_4iter6traits7collect12FromIteratorBQ_E9from_iterINtNtNtB1J_8adapters3map3MapINtNtNtBa_3vec9into_iter8IntoIterbENvMs2_BT_BQ_3newEECs5HK7yca7OMW_10weavepy_vm _RINvXsb_NtNtCs1C1lLj4PWSY_5alloc5boxed4iterINtB8_3BoxSNtCs5HK7yca7OMW_10weavepy_vm9FieldSlotEINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorBQ_E9from_iterINtNtNtB1A_8adapters3map3MapINtNtNtB1C_3ops5range5RangejENCNCINvMst_BS_NtBS_16CodeConstObjects11alloc_sitesBQ_NvMsG_BS_BQ_5emptyE0s0_0EEBS_ _RINvXsb_NtNtCs1C1lLj4PWSY_5alloc5boxed4iterINtB8_3BoxSINtNtNtCsevLNFiNqfJP_4core4sync6atomic6AtomichEEINtNtNtNtBX_4iter6traits7collect12FromIteratorBQ_E9from_iterINtNtNtB1J_8adapters3map3MapINtNtNtBX_5slice4iter4IterbENCNvMsb_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB3C_5Parts6finish0EEB3E_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real1b _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real16ref_subclass_new _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real13construct_ref _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real19remove_dead_weakref -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real14proxy_referent -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real16supports_weakref -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real19find_cached_wrapper -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real5b_dynNCNvB2_26make_ref_object_with_classs0_0EB6_ -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real26make_ref_object_with_classs0_0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real24install_proxy_forwarding _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real27install_callable_proxy_call -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real26make_ref_object_with_class.llvm.15809725932051974371 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real19weakref_native_hash -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real16wrapper_referent.llvm.15809725932051974371 _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real20make_proxy_forwarder -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real13ref_type_call -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17native_store_fast _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22deopt_load_global_slow -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13lookup_method -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18ensure_module_spec -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14leaf_py_setter -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16core_gen_call_ex -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19kw_names_bind_check -_RNvCs5HK7yca7OMW_10weavepy_vm18is_union_initiator -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12do_hash_call _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot13poly_remember -_RNvCs5HK7yca7OMW_10weavepy_vm25detect_yield_from_subiter -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter30winner_aware_dynamic_type_call -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13core_new_user -_RNvNtCs5HK7yca7OMW_10weavepy_vm13leaf_builtins19register_jit_method -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter25exec_eval_compile_options -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter41parse_eval_source_emitting_warnings_flags -_RNvNvCs5HK7yca7OMW_10weavepy_vm32collect_compiler_syntax_warnings10visit_body -_RNvCs5HK7yca7OMW_10weavepy_vm15exception_value -_RNvCs5HK7yca7OMW_10weavepy_vm19split_name_trailers -_RNvCs5HK7yca7OMW_10weavepy_vm16group_int_digits -_RNvCs5HK7yca7OMW_10weavepy_vm9with_sign -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16drain_gc_garbage _RNvCs5HK7yca7OMW_10weavepy_vm18object_to_constant -_RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter18lean_bind_keywordsINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtNtB1h_5slice4iter4IterNtNtB6_6object6ObjectEB1W_EEB6_ -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter16bind_python_argss8_0B7_ _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot16get_held_unbound -_RNvCs5HK7yca7OMW_10weavepy_vm27type_attr_certainly_missing -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15gen_ex_on_frame.llvm.3987546058129701445 -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15core_seq_concat _RNvCs5HK7yca7OMW_10weavepy_vm13code_name_key -_RNvCs5HK7yca7OMW_10weavepy_vm19dict_view_set_elems -_RNvCs5HK7yca7OMW_10weavepy_vm15dict_may_shadow -_RNvCs5HK7yca7OMW_10weavepy_vm21native_scalar_compare.llvm.3987546058129701445 -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter27specialized_unpack_sequence -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17instance_gen_call _RNvCs5HK7yca7OMW_10weavepy_vm13slice_indices -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13core_push_new -_RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter18lean_bind_keywordsINtNtNtNtCsevLNFiNqfJP_4core4iter7sources5empty5EmptyTRNtNtB6_6object6ObjectB20_EEEB6_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15core_store_slot -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18core_iter_collapse -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter26fire_caught_stop_iteration -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15data_descr_kind _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot3set -_RNvCs5HK7yca7OMW_10weavepy_vm18split_format_field -_RNvCs5HK7yca7OMW_10weavepy_vm20format_via_spec_impl.llvm.3987546058129701445 -_RNvCs5HK7yca7OMW_10weavepy_vm19int_precision_apply _RINvCs5HK7yca7OMW_10weavepy_vm9slice_seqhEB2_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17managed_dict_attr -_RNvCs5HK7yca7OMW_10weavepy_vm15meta_entry_fill _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17call_getattr_hook _RNvCs5HK7yca7OMW_10weavepy_vm12adjust_slice -_RNvCs5HK7yca7OMW_10weavepy_vm19code_names_anywhere -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21deopt_load_attr_taken -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter16module_shadowings0_0B7_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17core_call_forward _RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_EsD_0B8_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20leaf_load_super_attr -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter25materialize_class_mapping -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21try_dict_from_mapping -_RNvCs5HK7yca7OMW_10weavepy_vm14class_entry_of.llvm.3987546058129701445 -_RNvCs5HK7yca7OMW_10weavepy_vm17coerce_len_result -_RNvCs5HK7yca7OMW_10weavepy_vm15leaf_issubclass -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15compare_op_step -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter10core_new_ns0_0B7_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22load_method_ic_resolve -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20core_builtin_kw_lane -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter16leaf_load_methods_0B7_ -_RNvCs5HK7yca7OMW_10weavepy_vm15str_format_auto.llvm.3987546058129701445 -_RNvCs5HK7yca7OMW_10weavepy_vm14format_int_hex -_RNvCs5HK7yca7OMW_10weavepy_vm20inst_dict_attr_named _RNvNtCs5HK7yca7OMW_10weavepy_vm13leaf_builtins16register_fast_kw _RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter19leaf_load_type_attrs6_0B7_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21release_call_operands -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20kw_names_bind_cached -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17lean_call_kw_fill -_RNvCs5HK7yca7OMW_10weavepy_vm17make_pep604_union -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter24leaf_builtin_dunder_attr -_RNvCs5HK7yca7OMW_10weavepy_vm16class_dunder_new _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20release_finished_gen -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11do_str_call -_RNvCs5HK7yca7OMW_10weavepy_vm15code_stamp_slot.llvm.3987546058129701445 -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter9iter_next -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15native_truth_of -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22specialized_compare_op -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17try_lean_for_iter -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14lazy_iter_next.llvm.3987546058129701445 -_RNvNvCs5HK7yca7OMW_10weavepy_vm32collect_compiler_syntax_warnings10visit_args _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot16get_inst_builtin _RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_Esw_0B8_ -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter22meta_store_transparent0B7_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21binop_instance_dunder _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot3get -_RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter17core_local_methodKb1_Es0_0B8_ _RNvCs5HK7yca7OMW_10weavepy_vm17bridged_arg_bytes -_RNvCs5HK7yca7OMW_10weavepy_vm25decode_source_bytes_inner.llvm.3987546058129701445 -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter14leaf_type_name0B7_ -_RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter16lean_init_extendNtNtB6_11frame_slots10StackDrainEB6_ _RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter12load_special0B7_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16leaf_contains_eq -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17core_pure_kw_call -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15default_setattr -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16leaf_setter_eval _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot9poly_peek -_RNCNvCs5HK7yca7OMW_10weavepy_vm17make_pep604_union0B3_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17seq_contains_rich -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16rich_compare_obj _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot7peek_fn -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15pull_for_unpack -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19generator_next_fast -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20specialized_for_iter -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15core_new_finish _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16frame_globals_at -_RNvCs5HK7yca7OMW_10weavepy_vm13bind_int_args -_RNvMsA_Cs5HK7yca7OMW_10weavepy_vmNtB5_8AttrPoly6record -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17type_setattr_pair -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12do_exec_call -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter8do_print _RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter8do_prints_0B7_ -_RNvCs5HK7yca7OMW_10weavepy_vm11bind_method -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18core_fill_extended -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter23core_specialize_call_kw -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16type_method_pair -_RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter20kw_names_fill_localsNtNtB6_11frame_slots10FrameStackEB6_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15common_constant -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20park_suspended_boxed -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13class_ns_load -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11delete_attr.llvm.3987546058129701445 -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter25leaf_load_meta_class_attr -_RINvCs5HK7yca7OMW_10weavepy_vm15h_inst_dict_setKm7_EB2_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16leaf_load_method -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15core_store_init -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22deopt_store_attr_taken -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13delete_subscr -_RNvCs5HK7yca7OMW_10weavepy_vm15source_code_get -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16core_pure_method -_RNvCs5HK7yca7OMW_10weavepy_vm19render_format_field -_RNvCs5HK7yca7OMW_10weavepy_vm15apply_alignment _RNvCs5HK7yca7OMW_10weavepy_vm16mv_slice_subview _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12do_repr_call _RNvCs5HK7yca7OMW_10weavepy_vm17call_site_callees -_RNvCs5HK7yca7OMW_10weavepy_vm25translate_source_newlines -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15dict_merge_from -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20call_python_kw_names -_RNvMs2_Cs5HK7yca7OMW_10weavepy_vmNtB5_5Frame12skip_end_for _RNvCs5HK7yca7OMW_10weavepy_vm16store_init_shape -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11core_new_ex -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter9sync_recs -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter10flush_lean -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19leaf_instance_truth -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14lazy_iter_step -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17merge_exec_kwargs -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20native_value_payload -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter9iter_step -_RNvCs5HK7yca7OMW_10weavepy_vm17scan_format_field -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12pop_top_step -_RNvCs5HK7yca7OMW_10weavepy_vm12attr_name_of -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter26kwonly_defaults_cover_slow -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16core_class_store -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12core_call_kw -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14core_gen_yield -_RNvCs5HK7yca7OMW_10weavepy_vm14spec_parent_of -_RNvCs5HK7yca7OMW_10weavepy_vm17is_union_eligible -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14core_dict_next -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18class_ns_store_key -_RNvCs5HK7yca7OMW_10weavepy_vm20percent_render_plain _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot16set_inst_builtin -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19dispatch_compare_op -_RNvCs5HK7yca7OMW_10weavepy_vm8eq_class -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14core_leaf_init -_RNvCs5HK7yca7OMW_10weavepy_vm22instance_native_dunder -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12do_eval_call -_RNvCs5HK7yca7OMW_10weavepy_vm15source_code_put -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter27dynamic_type_call_with_meta0B7_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11do_int_call -_RNvMsA_Cs5HK7yca7OMW_10weavepy_vmNtB5_8AttrPoly5empty -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22instance_call_function _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12load_special -_RNvCs5HK7yca7OMW_10weavepy_vm24percent_args_need_bridge -_RNvCs5HK7yca7OMW_10weavepy_vm26percent_render_plain_value -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19do_dict_update_call -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11core_new_kw _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19plain_store_verdict -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22meta_store_transparent -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20del_type_attr_direct -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter23type_dunder_transparent -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14pooled_scratch -_RNvNvCs5HK7yca7OMW_10weavepy_vm32collect_compiler_syntax_warnings10visit_expr -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20automatic_collection -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20instance_call_native -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15do_min_max_call _RNvMst_Cs5HK7yca7OMW_10weavepy_vmNtB5_16CodeConstObjects17alloc_field_sites -_RNvMs_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13codecs_engineNtB4_6EncCtx3new -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13codecs_engine11utf8_encode -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real6keeperNtNtB8_4sync8RealLockE0B8_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real10rlock_exit -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real4heldNtNtB8_4sync9RealRLockE0B8_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real14lock_method_kw -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real16make_lock_object.llvm.4890245414193407415 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real13allocate_lock -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real1b -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real14module_getattr -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real9get_ident -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real22rlock_try_acquire_leaf -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real4heldNtNtB6_4sync9RealRLockEB6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real16new_rlock_object -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real11lock_method -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real13lock_instance -_RINvMs6_NtCsgN1fMlPi2rB_9hashbrown3rawINtB6_8RawTablejE14reserve_rehashNCINvNtCs3QF46a9Pg1X_8indexmap5inner8get_hashNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCs7usbkSbEEZs_16weavepy_compiler7BindingE0EB2u_ _RINvMs6_NtCsgN1fMlPi2rB_9hashbrown3rawINtB6_8RawTablejE6insertNCINvNtCs3QF46a9Pg1X_8indexmap5inner8get_hashNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCs7usbkSbEEZs_16weavepy_compiler7BindingE0EB2l_ _RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters6copiedINtB5_6CopiedINtNtNtBb_5slice4iter4IterNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5BlockEENtNtNtB9_6traits8iterator8Iterator8try_folduNCINvNvB2c_4find5checkB1s_QNCNvNtB1w_8liveness7analyzes3_0E0INtNtNtBb_3ops12control_flow11ControlFlowB1s_EEB1w_ -_RNvMNtCs4oeOcPWpyDO_13weavepy_lexer7scannerNtB2_7Scanner11scan_string -_RNvMNtCs4oeOcPWpyDO_13weavepy_lexer7scannerNtB2_7Scanner20verify_end_of_number -_RNvNtCs5HK7yca7OMW_10weavepy_vm17frozen_code_cache11result_path _RNvNtCs5HK7yca7OMW_10weavepy_vm17frozen_code_cache10result_get -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable9quicksort9quicksortNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB17_NtNtBa_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler -_RNvMsr_NtCsevLNFiNqfJP_4core3numx27from_ascii_bytes_radix_impl _RINvMsm_NtCsevLNFiNqfJP_4core5arrayARej5_7try_mapINtNtNtB8_3ops9try_trait17NeverShortCircuitNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyENCINvMBO_BL_10wrap_mut_1By_NCNvNvNtB1w_16weakref_registry12WRAPPER_KEYS27___rust_std_internal_init_fn0E0EB1w_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecTmNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueEEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB28_6filter6FilterINtNtB28_9enumerate9EnumerateINtNtNtB2c_5slice4iter4IterBW_EENCNvMNtB10_7codegenINtB4i_3GenNtNtB10_3x643X64E11choose_pins0ENCB4f_s_0EE9from_iterB10_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCs89hHMyD40Kn_15weavepy_codegen3asm5LabelEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2a_3ops5range5RangejENCINvNtBY_7codegen7compileNtNtBY_3x643X64E0EE9from_iterBY_ _RNvMso_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_10PyProperty6reinit -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object17materialize_shell _RNvMs1q_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_10PyIterator18next_value_checked _RNvMs1q_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_10PyIterator9remaining _RNCNvNtCs5HK7yca7OMW_10weavepy_vm6object12read_fd_intr0B5_ -_RNvMso_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_10PyProperty4fdel _RNvMs1s_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6Object8eq_value _RINvNtCs5HK7yca7OMW_10weavepy_vm6object20with_key_eq_deferredINtNtCsevLNFiNqfJP_4core6result6ResultINtNtB12_6option6OptionbENtNtB4_5error12RuntimeErrorENCNvMs7_B4_NtB4_11Interpreter13leaf_contains0EB4_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object16py_hash_long_i64 _RNvNtCs5HK7yca7OMW_10weavepy_vm6object20c_contiguous_strides _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile13take_pushback.llvm.9250547820948799359 _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile10read_bytes _RNvMsj_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_12PyMemoryView14has_suboffsets _RNvMsH_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_9DictWatch3new -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object15dict_watch_bump _RNvMs1q_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_10PyIterator10pure_ready _RNvMs1q_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_10PyIterator9pure_skip _RNvMs1y_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6Object13as_bytes_view -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object16bytes_membership _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile14read_bytes_opt _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile16close_with_flush _RNvMsj_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_12PyMemoryView12stride_bytes _RNvMsj_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_12PyMemoryView8to_bytes -_RNvMso_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_10PyProperty3doc _RNvMs11_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_10PyFunction12name_objects _RNvXs1n_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFileNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object18native_scalar_repr _RNCNvMs1q_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB8_10PyIterator10next_values0_0Ba_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object14eq_is_identity -_RNvMso_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_10PyProperty4fset _RNvMs1y_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6Object12interned_str _RNvMs1q_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_10PyIterator9pure_peek _RNvMsM_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_8DictData16build_key_filter _RNvMsj_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_12PyMemoryView13shallow_clone _RNvMs14_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_11BoundMethod16is_pymethod_type -_RNvMse_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_11PyTraceback5frame _RNvMs1q_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_10PyIterator15dict_iter_guard _RNvMsj_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_12PyMemoryView10shape_dims _RNvMsM_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_8DictData24with_capacity_and_hasher -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object9member_eq _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile12close_report _RNvMsj_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_12PyMemoryView15is_c_contiguous _RNvMs1y_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6Object9from_char -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object21meta_hash_is_identity _RNvMs1s_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6Object8contains _RINvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB7_6PyFile3newNtNtCs1C1lLj4PWSY_5alloc6string6StringBW_EB9_ _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile8readable _RNvNtCs5HK7yca7OMW_10weavepy_vm6object12str_char_len -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object26instance_has_custom_dunder _RNvMNtNtCs3QF46a9Pg1X_8indexmap5inner5entryINtNtNtB6_3map5entry5EntryNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCs7usbkSbEEZs_16weavepy_compiler7BindingE3newB1J_ _RNvXs2_NtNtCsevLNFiNqfJP_4core3str7patterncNtB5_7Pattern15is_contained_in _RINvMs3_NtCs3QF46a9Pg1X_8indexmap3mapINtB6_8IndexMapNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCs7usbkSbEEZs_16weavepy_compiler7BindingINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtB1s_6fxhash8FxHasherEE3getBO_EB1s_ -_RINvMs3_NtCs3QF46a9Pg1X_8indexmap3mapINtB6_8IndexMapNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCs7usbkSbEEZs_16weavepy_compiler7BindingINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtB1s_6fxhash8FxHasherEE3geteEB1s_ -_RINvMs3_NtCs3QF46a9Pg1X_8indexmap3mapINtB6_8IndexMapNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCs7usbkSbEEZs_16weavepy_compiler7BindingINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtB1s_6fxhash8FxHasherEE12get_index_ofBO_EB1s_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict7exports -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict13install_odict _RNvNtCs89hHMyD40Kn_15weavepy_codegen8simplify8simplify _RNvXs5_NtNtCs1C1lLj4PWSY_5alloc3vec5drainINtB5_5DrainNtCs7usbkSbEEZs_16weavepy_compiler8ConstantENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBR_ _RNvMsq_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_11SlotStorage14store_position _RNvMsr_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10PyInstance12class_dunder -_RNvMs5_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_13LeafAttrCache4grow -_RNvMs5_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_13LeafAttrCache9table_mut _RNvMso_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_11SlotStorage21values_for_layout_mut _RNvMsr_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10PyInstance7recycle _RNvMso_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_11SlotStorage6retire _RNvMsr_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10PyInstance11with_native _RNvNtNtCs5HK7yca7OMW_10weavepy_vm5types10type_cache5probe -_RNvMs5_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_13LeafAttrCache4free.llvm.4890245414193407415 _RNvMsq_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_11SlotStorage9get_index -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject14verdict_record _RNvMso_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_11SlotStorage11from_layout _RNvMsq_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_11SlotStorage4iter _RNvMsq_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_11SlotStorage13insert_shared _RNvMsr_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10PyInstance3new -_RNvMse_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_5CBody3set _RNvMsq_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_11SlotStorage13get_index_mut _RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject19class_attr_is_plain -_RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters4skipINtB5_4SkipINtNtNtBb_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEENtNtNtB9_6traits8iterator8Iterator8try_folduNCINvNvB28_3any5checkRB1o_NvB1s_20object_needs_vm_iterE0INtNtNtBb_3ops12control_flow11ControlFlowuEEB1s_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtCs7usbkSbEEZs_16weavepy_compiler10ExcHandlerE8grow_oneBO_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecThcEE8grow_oneCs5993W3JedWL_14weavepy_parser _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTjjEE8grow_oneCs89hHMyD40Kn_15weavepy_codegen _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVeclE8grow_oneCs89hHMyD40Kn_15weavepy_codegen _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs89hHMyD40Kn_15weavepy_codegen2ir8InstDataE8grow_oneBQ_ _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTmbEE8grow_oneCs89hHMyD40Kn_15weavepy_codegen _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs89hHMyD40Kn_15weavepy_codegen2ir11ExtFuncDataE8grow_oneBQ_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecThjEE8grow_oneCs4oeOcPWpyDO_13weavepy_lexer -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtCs7usbkSbEEZs_16weavepy_compiler9LoopFrameE8grow_oneBO_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8SideExitE8grow_oneBQ_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtCs7usbkSbEEZs_16weavepy_compiler12FinallyFrameE8grow_oneBO_ -_RINvNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB8_11RawVecInnerpE7reserve21do_reserve_and_handleNtNtBa_5alloc6GlobalECs5993W3JedWL_14weavepy_parser _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5993W3JedWL_14weavepy_parser3ast4ExprE8grow_oneBQ_ _RNvMs5_NtCs1C1lLj4PWSY_5alloc7raw_vecNtB5_11RawVecInner11finish_growCs89hHMyD40Kn_15weavepy_codegen.llvm.8271801047618170978 _RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE7reserveB7_ -_RINvNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB8_11RawVecInnerpE7reserve21do_reserve_and_handleNtNtBa_5alloc6GlobalECsd5p0HaiaiO6_11weavepy_jit -_RNvMs5_NtCs1C1lLj4PWSY_5alloc7raw_vecNtB5_11RawVecInner11finish_growCsd5p0HaiaiO6_11weavepy_jit.llvm.17333637510844599878 -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5993W3JedWL_14weavepy_parser3ast13ExceptHandlerE8grow_oneBQ_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecReE8grow_oneCs5993W3JedWL_14weavepy_parser _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeE8grow_oneBQ_ _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTmNtNtCs89hHMyD40Kn_15weavepy_codegen3x643FixEE8grow_oneBS_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5993W3JedWL_14weavepy_parser3ast5AliasE8grow_oneBQ_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs7usbkSbEEZs_16weavepy_compiler8validate5ScopeE8grow_oneBQ_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5993W3JedWL_14weavepy_parser3ast5CmpOpE8grow_oneBQ_ -_RINvNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB8_11RawVecInnerpE7reserve21do_reserve_and_handleNtNtBa_5alloc6GlobalECs89hHMyD40Kn_15weavepy_codegen -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5993W3JedWL_14weavepy_parser3ast3ArgE8grow_oneBQ_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtB7_3vec3VecmEE8grow_oneCs7usbkSbEEZs_16weavepy_compiler _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTmmhEE8grow_oneCs5HK7yca7OMW_10weavepy_vm -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTNtNtCs89hHMyD40Kn_15weavepy_codegen3asm5LabelINtNtB7_3vec3VecBN_EEE8grow_oneBR_ -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB4_3X646alu_ri.llvm.11741802452671993001 -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm8br_table -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm5store -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm10alu_imm_ok -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3jcc -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB4_3X645widen.llvm.11741802452671993001 -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm7add_mem -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4fcmp -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4fjcc -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3jmp -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3alu -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm9store_imm -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm6finish -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB4_3X644emit.llvm.11741802452671993001 -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB4_3X647jcc_raw.llvm.11741802452671993001 -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3imm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB4_3X646alu_rr.llvm.11741802452671993001 -_RNvMs1_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X647load_rm.llvm.11741802452671993001 -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3cmp -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4csel -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm8epilogue -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm7bitcast -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm14fcvt_from_sint -_RNvXs1b_NtCs5993W3JedWL_14weavepy_parser3astNtB6_8ConstantNtNtCsevLNFiNqfJP_4core5clone5Clone5clone -_RNvXsZ_NtCs5993W3JedWL_14weavepy_parser3astNtB5_8ExprKindNtNtCsevLNFiNqfJP_4core5clone5Clone5clone.llvm.16607524104033215587 _RNvMNtNtNtNtCsgHYyB3hU8Ec_3std3sys3pal4unix4timeNtB2_8Timespec12sub_timespec.llvm.9621187620753702693 -_RNvNtNtCs2qMPZxtgKFx_10num_bigint6bigint7convert20from_signed_bytes_le -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod15partial_new_fors_0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod8lru_type -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod12partial_call -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod15partial_new_for -_RNCNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod8lru_type00B9_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod11partial_new -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod5build -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBT_ -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjjNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCs5HK7yca7OMW_10weavepy_vm _RINvXs1i_NtCskibSv91bgl1_9hashbrown3mapINtB7_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEEINtNtNtNtB1x_4iter6traits7collect6ExtendTBP_uEE6extendINtNtNtB3e_8adapters3map3MapINtNtNtBT_3vec9into_iter8IntoIterBP_ENCINvXs8_NtB9_3setINtB5b_7HashSetBP_B1s_EIB38_BP_E6extendB4r_E0EEB2j_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir4TypexENtBQ_5ValueINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBS_6fxhash8FxHasherEE6insertBS_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjuNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCs5HK7yca7OMW_10weavepy_vm @@ -7631,59 +6864,24 @@ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapymNtNtNtCsgHYyB3hU8Ec_3std4h _RINvXs1i_NtCskibSv91bgl1_9hashbrown3mapINtB7_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEEINtNtNtNtB1x_4iter6traits7collect6ExtendTBP_uEE6extendINtNtNtB3e_8adapters3map3MapIB40_INtNtNtB1x_5slice4iter4IterTReNtNtCs4oeOcPWpyDO_13weavepy_lexer5token4SpanEENCNvMs_NtB2j_8validateNtB5R_9Validator14visit_functions_0ENCINvXs8_NtB9_3setINtB6P_7HashSetBP_B1s_EIB38_BP_E6extendB4r_E0EEB2j_ _RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapymINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs5HK7yca7OMW_10weavepy_vm8fasthash14ObjectIdHasherEE6removeyEB1H_ _RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjuNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6removejECs5HK7yca7OMW_10weavepy_vm -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEE6insertB1G_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapyjNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCs5HK7yca7OMW_10weavepy_vm _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringmNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCs7usbkSbEEZs_16weavepy_compiler -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertCsd5p0HaiaiO6_11weavepy_jit -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmNtNtCs7usbkSbEEZs_16weavepy_compiler8bytecode6OpCodeINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBS_6fxhash8FxHasherEE6insertBS_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapyjINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs5HK7yca7OMW_10weavepy_vm8fasthash14ObjectIdHasherEE6insertB1G_ -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEE6insertB2h_ _RINvMs0_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6retainNCINvMs_NtB8_3setINtB2J_7HashSetmBQ_E6retainNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze13numeric_slotss_0E0EB3p_ -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertCsd5p0HaiaiO6_11weavepy_jit _RINvMs_CsfhlKP0AX26y_7weavepyNtB5_10RunOptions15with_extra_pathINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsgHYyB3hU8Ec_3std4path7PathBufEB1w_ECscY2bcUAVtje_11weavepy_cli _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib2os9os_fspath -_RNvMNtNtCsg55y0en7y7K_6chrono5naive4dateNtB2_9NaiveDate25from_num_days_from_ce_opt _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtB8_6filter6FilterINtNtB8_9enumerate9EnumerateINtNtNtBc_5slice4iter4IterNtCs7usbkSbEEZs_16weavepy_compiler10ExcHandlerEENCNCNvNtB2d_9flowgraph5builds1_00ENCINvNvNtNtNtBa_6traits8iterator8Iterator10min_by_key3keyTjRB2b_EmNCB2Z_s_0E0EB3C_4foldTmB4q_ENCINvNvB3C_6min_by4foldB4U_INvB3A_7compareB4q_mEE0EB2d_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects19compile_cached_fast -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12make_pattern -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_12pattern_exec0E0B8_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects14compile_cached _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects6layout -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12pattern_code -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects9new_match -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects7install -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects13pattern_match -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12pattern_exec _RNvMNtCs7usbkSbEEZs_16weavepy_compiler6internNtB2_11InternIndex11intern_name _RNvMs4_NtCs5HK7yca7OMW_10weavepy_vm5traceNtB5_15MonitoringTools3new -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod8dumps_kw.llvm.10335684157103142333 -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader8read_int -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader4take -_RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB2_13MarshalWriter10write_body -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod8register -_RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB2_13MarshalWriter11write_value -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod8loads_kw -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader16read_value_inner.llvm.10335684157103142333 -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader8fill_ref _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader9read_code -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader10read_value _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod16tuple_of_strings -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader9read_byte _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader11reserve_ref -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader8note_ref _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod18tuple_to_constants _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod8bytes_of -_RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_modNtB2_13MarshalWriter10into_bytes _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11marshal_mod9string_of _RNvMs4_NtNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3map5entryINtB5_11VacantEntrycNtNtB9_7set_val9SetValZSTE12insert_entryCs5HK7yca7OMW_10weavepy_vm -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10codecs_mod10encode_str -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10codecs_mod5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10codecs_mod10encode_obj -_RNvXsk_NtCs7usbkSbEEZs_16weavepy_compiler4nameNtB5_4NameINtNtCsevLNFiNqfJP_4core7convert4FromNtNtCs1C1lLj4PWSY_5alloc6string6StringE4from _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionTINtB5_3VechEmEENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalECs89hHMyD40Kn_15weavepy_codegen -_RINvXs1_NtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemhNtB6_12SpecFromElem9from_elemNtNtBa_5alloc6GlobalECs5HK7yca7OMW_10weavepy_vm _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtB5_3VechENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalECs89hHMyD40Kn_15weavepy_codegen _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs89hHMyD40Kn_15weavepy_codegen7codegen4SnapENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEB1r_ _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionINtB5_3VecTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValuehbEEENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEB1C_ @@ -7691,135 +6889,44 @@ _RNvXNvNtNtCsevLNFiNqfJP_4core2io5write17default_write_fmtINtB2_7AdapterNtNtNtCs _RINvNtCs5HK7yca7OMW_10weavepy_vm7timsort4sortTNtNtB4_6object6ObjectBI_ENtNtB4_5error12RuntimeErrorNCINvMs7_B4_NtB4_11Interpreter10sort_keyedBH_NCNvB1D_13sort_with_keys0_0Es_0EB4_ _RINvNtCs5HK7yca7OMW_10weavepy_vm7timsort4sortNtNtB4_6object6ObjectNtNtB4_5error12RuntimeErrorNCINvMs7_B4_NtB4_11Interpreter10sort_keyedBH_NCNvB1y_13sort_with_keys_0Es_0EB4_ _RNvXsb_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCs7usbkSbEEZs_16weavepy_compiler -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjuEE14reserve_rehashNCINvNtB8_3map11make_hasherjuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0ECsd5p0HaiaiO6_11weavepy_jit _RINvMsi_NtCskibSv91bgl1_9hashbrown3rawINtB6_12RawIterRangeTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEE9fold_implNCINvXsG_NtB8_3mapINtB1T_4IterBV_uENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4folduNCINvXsU_B1T_INtB1T_4KeysBV_uEB2j_4folduNCINvNtNtB2p_8adapters3map8map_foldRBV_BV_uNvYBV_NtNtB2r_5clone5Clone5cloneNCIB41_BV_BU_uNCINvXs8_NtB8_3setINtB5y_7HashSetBV_INtNtB2r_4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEEINtNtB2n_7collect6ExtendBV_E6extendINtNtB45_6cloned6ClonedINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterBV_EEE0NCINvNvB2j_8for_each4callBU_NCINvXs1i_B1T_INtB1T_7HashMapBV_uB5Z_EIB7q_BU_E6extendINtB43_3MapB7Y_B5p_EE0E0E0E0E0E0uEB6B_ _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmuEE12remove_entryNCINvNtB8_3map14equivalent_keymmuE0ECs7usbkSbEEZs_16weavepy_compiler -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtBV_3vec3VecTThmhEIBR_ShEEEEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_B1r_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs5HK7yca7OMW_10weavepy_vm _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjuEE14reserve_rehashNCINvNtB8_3map11make_hasherjuNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs5HK7yca7OMW_10weavepy_vm -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmNtNtCs7usbkSbEEZs_16weavepy_compiler8bytecode6OpCodeEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBV_6fxhash8FxHasherEE0EBV_ _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjjEE12remove_entryNCINvNtB8_3map14equivalent_keyjjjE0ECs5HK7yca7OMW_10weavepy_vm -_RINvMsa_NtCskibSv91bgl1_9hashbrown3rawNtB6_13RawTableInner13drop_elementsTINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB1f_3vec3VecTThmhEIB1b_ShEEEEECs5HK7yca7OMW_10weavepy_vm.llvm.2221200793792468279 -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmuEE14reserve_rehashNCINvNtB8_3map11make_hashermuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEE0EB2u_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTyINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakNtNtB1t_16weakref_registry11WeakRefSlotEEEE14reserve_rehashNCINvNtB8_3map11make_hasheryBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtB1t_8fasthash14ObjectIdHasherEE0EB1t_ -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEE12contains_keyeEB2i_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringmEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_mNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs7usbkSbEEZs_16weavepy_compiler _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTjTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtBW_4sync4CellyEEjEEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBW_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_uINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEE0EB37_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTyjEE14reserve_rehashNCINvNtB8_3map11make_hasheryjNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs5HK7yca7OMW_10weavepy_vm -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTymEE14reserve_rehashNCINvNtB8_3map11make_hasherymNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs7usbkSbEEZs_16weavepy_compiler -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmuEE14reserve_rehashNCINvNtB8_3map11make_hashermuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0ECsd5p0HaiaiO6_11weavepy_jit -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir4TypexENtBT_5ValueEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_B1A_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBV_6fxhash8FxHasherEE0EBV_ _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCs7usbkSbEEZs_16weavepy_compiler -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14ResolvedGlobalEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0EBV_ _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBW_6string6StringEB1o_EmEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCs5HK7yca7OMW_10weavepy_vm _RINvMsi_NtCskibSv91bgl1_9hashbrown3rawINtB6_12RawIterRangeTyAmj6_EE9fold_implNCINvXsG_NtB8_3mapINtB1m_4IteryBW_ENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4foldmNCINvXsM_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB2W_6ValuesyBW_EB1M_4foldmNCINvNvMsg_NtNtB1S_8adapters7flattenINtB4k_13FlattenCompatppE9iter_fold7flattenRBW_mNCINvNvXsi_B4k_B4J_B1M_4fold7flattenINtNtNtB1U_5slice4iter4ItermEmNCNvMs4_NtCs5HK7yca7OMW_10weavepy_vm5traceNtB6H_15MonitoringTools10union_masks_0E0E0E0E0mEB6J_ -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEE12contains_keyBO_EB2i_ -_RNvNtCs7usbkSbEEZs_16weavepy_compiler11native_code6encode -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler11native_codeNtB4_6Writer4u32s -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler11native_codeNtB4_6Writer4strs -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler11native_codeNtB4_6Writer4code -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler11native_codeNtB4_6Writer4name -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler11native_codeNtB4_6Writer5table -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler11native_codeNtB4_6Writer8constant -_RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_00Bb_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier219resolve_plain_dicts.llvm.10617736694814397161 -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216probe_class_ctor -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier218publish_obj_layout -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier221laid_out_slots_layout -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier222probe_class_ctor_shape -_RNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB7_8JitState12get_compileds_0B9_ -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile00B7_ -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s7_0B7_ -_RNvMs3_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB5_15WeakRefRegistry14collect_strong _RNvMs_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB4_10WeakTarget7is_dead _RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB5_11WeakRefSlot5clear _RNvMs3_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB5_15WeakRefRegistry8register _RNvNtCs5HK7yca7OMW_10weavepy_vm16weakref_registry21fixed_wrapper_storage -_RNvMs3_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB5_15WeakRefRegistry3new -_RNvNtCs5HK7yca7OMW_10weavepy_vm16weakref_registry16id_of_by_variant -_RNvNtCs5HK7yca7OMW_10weavepy_vm16weakref_registry13on_death_slow -_RNvMs3_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB5_15WeakRefRegistry13clear_entries _RNvMNtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB2_10WrapperKey5owned -_RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB5_11WeakRefSlot7upgrade -_RNvNtCs5HK7yca7OMW_10weavepy_vm16weakref_registry18sweep_dead_targets -_RNvNtCs5HK7yca7OMW_10weavepy_vm16weakref_registry15queue_callbacks -_RNvNtCs5HK7yca7OMW_10weavepy_vm16weakref_registry13wrapper_value _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtCs5HK7yca7OMW_10weavepy_vm9SiteTableNtB1J_9FieldSlotEE10initializeNCINvB1a_11get_or_initNCINvMst_B1J_NtB1J_16CodeConstObjects11alloc_sitesB2j_NvMsG_B1J_B2j_5emptyE0E0zE0E0B1J_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtNtBa_6poison5mutex5MutexINtNtNtNtBc_11collections4hash3map7HashMapyjEEE10initializeNCINvB1a_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10signal_mod16pthread_registry0E0zE0E0B3A_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCNvMNtBa_9lazy_lockINtB1a_8LazyLockTINtNtCs5UJUBJEE7PZ_8lock_api5mutex5MutexNtNtCs2zRUMDvV71V_11parking_lot9raw_mutex8RawMutexNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod15ImportLockStateENtNtB2o_7condvar7CondvarEE5force0E0B3e_.llvm.3774527374720384575 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCsd5p0HaiaiO6_11weavepy_jit7runtime9ObjLayoutE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0Cs5HK7yca7OMW_10weavepy_vm.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcINtB1J_12SliceStorageNtNtB1L_6object7DictKeyEEE10initializeNCINvB1a_11get_or_initNCNvNtB1L_16weakref_registry21fixed_wrapper_storage0E0zE0E0B1L_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm9StoreInitEEE10initializeNCINvB1a_11get_or_initNCNvB2T_15code_store_init0E0zE0E0B2T_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace10root_debug0E0zE0E0B2m_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline7enabled0E0zE0E0B2o_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCs89hHMyD40Kn_15weavepy_codegen3mem4near6RegionEE10initializeNCINvB1a_11get_or_initNvB2k_7reserveE0zE0E0B2o_.llvm.13936311991460135361 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtNtBa_6poison5mutex5MutexINtNtNtNtBc_11collections4hash3set7HashSetNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrNtNtB2T_8fasthash13FxBuildHasherEEE10initializeNCINvB1a_11get_or_initNCNvMs1y_NtB2T_6objectNtB4X_6Object12interned_str0E0zE0E0B2T_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockyE10initializeNCINvB1a_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod12compiler_tag0E0zE0E0B2o_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcINtB1J_12SliceStorageNtNtB1L_6object7DictKeyEEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib11thread_real11lock_layout0E0zE0E0B1L_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit5stats6decide0E0zE0E0B2o_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCNvMNtBa_9lazy_lockINtB1a_8LazyLockNtNtCs5HK7yca7OMW_10weavepy_vm16weakref_registry15WeakRefRegistryE5force0E0B1J_.llvm.2449273802214287896 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtNtBa_6poison5mutex5MutexINtNtNtNtBc_11collections4hash3map7HashMapjjEEE10initializeNCINvB1a_11get_or_initNvYB1G_NtNtCsevLNFiNqfJP_4core7default7Default7defaultE0zE0E0Cs5HK7yca7OMW_10weavepy_vm.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockjE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8chunk_ir0E0zE0E0B2m_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6NativeEEE10initializeNCINvB1a_11get_or_initNCNvB2T_7publish0E0zE0E0B2V_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9inst_dict16note_materialize0E0zE0E0B2m_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7enabled0E0zE0E0B2m_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCsd5p0HaiaiO6_11weavepy_jit7runtime9ObjLayoutE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0B1K_.llvm.13143382369088262339 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockTINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs1C1lLj4PWSY_5alloc6string6StringEB1H_EE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13name_admitted0E0zE0E0B3G_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockjE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10chunk_room0E0zE0E0B2m_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB1L_6string6StringEE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11op_disabled0E0zE0E0B3f_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace11stats_debug0E0zE0E0B2m_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9hot_gates9env_flags9jit_trace0E0zE0E0B2o_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockjE10initializeNCINvB1a_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline9max_total0E0zE0E0B2o_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6verify0E0zE0E0B2m_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtBc_4path7PathBufEE10initializeNCINvB1a_11get_or_initNCNvCs89hHMyD40Kn_15weavepy_codegen4dump0E0zE0E0B3g_.llvm.13936311991460135361 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockTxxEE10initializeNCINvB1a_11get_or_initNCNvMs11_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB2s_10PyFunction12name_objects0E0zE0E0B2u_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectB1H_EE10initializeNCINvB1a_11get_or_initNCNvB1L_14code_gen_names0E0zE0E0B1L_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtCs5HK7yca7OMW_10weavepy_vm9SiteTableNtB1J_8AttrPolyEE10initializeNCINvB1a_11get_or_initNCINvMst_B1J_NtB1J_16CodeConstObjects11alloc_sitesB2j_FEB2j_E0E0zE0E0B1J_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs5UJUBJEE7PZ_8lock_api5mutex5MutexNtNtCs2zRUMDvV71V_11parking_lot9raw_mutex8RawMutexINtNtCs1C1lLj4PWSY_5alloc3vec3VecRNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod12CompiledCodeEEE10initializeNCINvB1a_11get_or_initNCNvB3I_8registry0E0zE0E0B3M_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtBc_4time7InstantE10initializeNCINvB1a_11get_or_initNvMB1I_B1G_3nowE0zE0E0Cs5HK7yca7OMW_10weavepy_vm.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs89hHMyD40Kn_15weavepy_codegen7codegen6timing0E0zE0E0B2m_.llvm.13936311991460135361 -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types20install_type_dunders12type_setattr _RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types19install_module_init11module_init -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types25install_import_error_init22import_error_init_impl -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types20install_type_dunders12type_delattr -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types30install_mutable_container_init12self_payload -_RNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types21overrides_dunder_init _RNCNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types16make_default_new0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types10object_new -_RNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types19native_seed_for_new -_RINvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types25make_exception_with_classReEB4_ _RNCNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types14make_owned_news_0B5_ -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types30install_mutable_container_init12dict_init_kw _RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types14make_owned_new11reject_bool _RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types22install_module_methods19module_getattr_miss -_RNvNvMNtCs5HK7yca7OMW_10weavepy_vm13builtin_typesNtB4_12BuiltinTypes5build9proxy_new -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types25install_import_error_inits_0B5_ _RNCNvMNtCs5HK7yca7OMW_10weavepy_vm13builtin_typesNtB4_12BuiltinTypes5builds4_0B6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod13sre_cache_get -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE8do_matchB9_ -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE14do_match_innerB9_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod1b -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod13register_code -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod5build -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod14codeseq_to_vec0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod14codeseq_to_vec _RINvNtCs5HK7yca7OMW_10weavepy_vm3gil18allow_threads_theniNCNCNvNtB4_6object12read_fd_intr00EB4_ _RINvNtCs5HK7yca7OMW_10weavepy_vm3gil18allow_threads_thenINtNtCsevLNFiNqfJP_4core6result6ResultNtNtCsgHYyB3hU8Ec_3std2fs4FileNtNtNtBX_2io5error5ErrorENCNvNtNtB4_6stdlib7io_full7io_open0EB4_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod16imp_exec_builtin _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod15fix_co_filename -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod7builtin -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod18imp_create_builtin _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod15imp_find_frozen _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod19fix_co_filename_rec _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod21fix_constant_filename -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod22imp_extension_suffixes -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod14imp_is_builtin _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod19import_lock_acquire _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod19import_lock_release -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod13imp_is_frozen -_RNvXNtCsevLNFiNqfJP_4core3anyNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects5StateNtB2_3Any7type_idBx_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_3ops5range5RangejENCNvNtCs89hHMyD40Kn_15weavepy_codegen8liveness7analyzes9_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2m_8for_each4callmNCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB3z_3VecmE14extend_trustedBN_E0E0EB1v_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterReENCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects6layout0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2r_8for_each4callNtNtB1y_6object7DictKeyNCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB40_3VecB3u_E14extend_trustedBN_E0E0EB1y_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtB8_9enumerate9EnumerateINtNtNtBc_5slice4iter4IterbEENCNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB20_5Lower5lower0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2W_8for_each4callINtNtBc_6option6OptionNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5BlockENCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB5d_3VecB3Z_E14extend_trustedBN_E0E0EB22_ @@ -7828,7 +6935,6 @@ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtB8_9enumerate _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_3ops5range5RangexENCNvNtCs5HK7yca7OMW_10weavepy_vm5tier221laid_out_slots_layouts2_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2t_8for_each4callTNtNtB1v_6object7DictKeyNtB3z_6ObjectENCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB4h_3VecB3w_E14extend_trustedBN_E0E0EB1v_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_5types10TypeObjectEEEE4withNCNvNtNtBZ_6stdlib11thread_real10rlock_type0B2e_EBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_5types10TypeObjectEEEE4withNCNvNtNtBZ_6stdlib11thread_real9lock_type0B2e_EBZ_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionxENCNvBW_13py_hash_values_0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionbENCNCNvMs7_BY_NtBY_11Interpreter13leaf_contains00E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_5types10TypeObjectEEEE4withNCNvNtNtBZ_6stdlib12weakref_real10proxy_type0B2e_EBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtNtNtBa_11collections4hash3set7HashSetNtNtBZ_12shared_value9SharedStrNtNtBZ_8fasthash13FxBuildHasherEEE4withNCNvNtNtBZ_6stdlib3sys15str_is_interned0bEBZ_ @@ -7846,10 +6952,7 @@ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10w _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBa_11collections4hash3map7HashMapjTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtB2i_4sync4CellyEEjENtNtB2i_8fasthash13FxBuildHasherEEE4withNCNvNtB2i_6object15dict_watch_bump0uEB2i_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB27_5types10PyInstanceEEEE8try_withNCNvMsr_B2F_B2D_7recycles_0uEB27_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNvNtBY_8builtins6b_dicts0_0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNvMs7_BY_NtBY_11Interpreter11instantiate0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell4CellTyyEEE4withNCNvMNtNtBa_4hash6randomNtB1I_11RandomState3new0B21_ECs5HK7yca7OMW_10weavepy_vm _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtNtNtBa_11collections4hash3set7HashSetNtNtBZ_12shared_value9SharedStrNtNtBZ_8fasthash13FxBuildHasherEEE4withNCNvNtNtBZ_6stdlib3sys10sys_intern0INtNtCsevLNFiNqfJP_4core6result6ResultNtNtBZ_6object6ObjectNtNtBZ_5error12RuntimeErrorEEBZ_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtNtNtBa_11collections4hash3map7HashMapReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEE4withNCNvNtB1G_8builtins12vm_intrinsic0INtNtCsevLNFiNqfJP_4core6option6OptionB1C_EEB1G_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopebNCNvMs1s_BW_NtBW_6Object8containss0_0E0INtNtCsevLNFiNqfJP_4core6result6ResultbNtNtBY_5error12RuntimeErrorEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNvNtNtBY_6stdlib12weakref_real19remove_dead_weakref0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_5types10TypeObjectEEEE4withNCNvNtNtBZ_6stdlib12weakref_real8ref_type0B2e_EBZ_ @@ -7857,106 +6960,21 @@ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4c _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNCNvNtBY_8builtins11dict_lookup00E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionTNtBW_6ObjectB2V_EENCNCNvNtBY_8builtins11dict_remove00E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs5HK7yca7OMW_10weavepy_vm3gil8GilGuardEEE4withNCINvB24_18allow_threads_theniNCNvNtNtB26_6stdlib2os7os_read0Es_0uEB26_ -_RNvXNtNtCs2qMPZxtgKFx_10num_bigint7biguint8additionNtB4_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops5arith3AddRBN_E3add -_RNvNtCs5HK7yca7OMW_10weavepy_vm14descr_registry10descr_type -_RNvCs7usbkSbEEZs_16weavepy_compiler19collect_walrus_expr -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler23collect_comp_cells_expr -_RNvCs7usbkSbEEZs_16weavepy_compiler15clean_docstring -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler15emit_store_name _RNCNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB7_8Compiler28collect_uses_through_inlined0B7_ -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler16var_index_or_add -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler18emit_setup_no_line -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler14unwind_fblocks -_RNvMsP_Cs7usbkSbEEZs_16weavepy_compilerNtB5_10CodeObject10content_eq -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler14emit_pop_block -_RINvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_18compile_expr_inners2_0EB6_ -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler17starunpack_helper _RNvXsb_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8LazyBodyINtNtCsevLNFiNqfJP_4core7convert4FromNtB5_8CodeBodyE4from -_RNvNvCs7usbkSbEEZs_16weavepy_compiler21module_mentions_super7in_expr -_RNvCs7usbkSbEEZs_16weavepy_compiler19stmt_contains_yield -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler9free_scan -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler12compile_stmt -_RNCNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB7_8Compiler18compile_expr_inners1_0B7_ -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler14compile_assign -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler35import_flag_shadowed_by_module_comp -_RNvCs7usbkSbEEZs_16weavepy_compiler19expr_contains_yield -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler22analyze_scope_function -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler25push_body_exc_entries_ids -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler7emit_at -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler22super_attr_optimizable -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler24genexp_call_optimization -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler11intern_name -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler18classify_for_store -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler26compile_function_def_inner -_RNvCs7usbkSbEEZs_16weavepy_compiler21collect_reads_stmt_in -_RNvCs7usbkSbEEZs_16weavepy_compiler23collect_inner_free_impl -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler10emit_setup -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler22emit_pop_block_no_line -_RNvXsR_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8ConstantINtNtCsevLNFiNqfJP_4core7convert4FromNtNtCs5993W3JedWL_14weavepy_parser3ast8ConstantE4from -_RINvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_18compile_expr_inners4_0EB6_ -_RNvCs7usbkSbEEZs_16weavepy_compiler11emit_cmp_op -_RNCNvCs7usbkSbEEZs_16weavepy_compiler32collect_comp_walrus_targets_stmt0B3_ -_RNvNvCs7usbkSbEEZs_16weavepy_compiler32collect_comp_walrus_targets_stmt4walk -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler26build_function_object_full -_RNvCs7usbkSbEEZs_16weavepy_compiler26collect_reads_stmt_in_impl -_RNvCs7usbkSbEEZs_16weavepy_compiler27collect_reads_assign_target -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler17emit_pop_block_at -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler10patch_jump -_RNvCs7usbkSbEEZs_16weavepy_compiler20collect_target_names -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler19child_qualname_impl -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler28collect_uses_through_inlined -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler14emit_load_name -_RNvCs7usbkSbEEZs_16weavepy_compiler11bin_op_kind -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler25compile_default_arguments _RNvXsF_Cs7usbkSbEEZs_16weavepy_compilerNtB5_9WireMarksINtNtCsevLNFiNqfJP_4core7convert4FromINtNtCs1C1lLj4PWSY_5alloc3vec3VechEE4from -_RNvCs7usbkSbEEZs_16weavepy_compiler13collect_decls -_RNvXsQ_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8ConstantNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq -_RNvCs7usbkSbEEZs_16weavepy_compiler18collect_inner_free -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler17emit_entry_resume -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler21push_body_exc_entries -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler18compile_expr_inner -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler18close_unwind_holes -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler15compile_jump_if -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler18emit_make_function -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler15compile_subdict -_RNvCs7usbkSbEEZs_16weavepy_compiler14constant_slice _RNvCs7usbkSbEEZs_16weavepy_compiler16compile_eval_cow.llvm.4735248722991253286 _RNCNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB7_8Compiler23collect_comp_cells_expr0B7_ -_RNvCs7usbkSbEEZs_16weavepy_compiler18collect_reads_expr -_RNvCs7usbkSbEEZs_16weavepy_compiler27collect_pep695_header_reads -_RNvCs7usbkSbEEZs_16weavepy_compiler23collect_inner_free_expr -_RNCNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB7_8Compiler22analyze_scope_functions0_0B7_ -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler15compile_compare -_RNvCs7usbkSbEEZs_16weavepy_compiler43should_apply_two_element_slice_optimization _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterNtNtCsgHYyB3hU8Ec_3std4path7PathBufENvYB2l_INtNtB1f_7convert4IntoB2l_E4intoEB2l_ECscY2bcUAVtje_11weavepy_cli _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterTNtNtB6_6string6StringNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEENCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB3C_8JitState12get_compileds_0s9_0EB2m_EB3E_ _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectB2m_EENCNvMs7_B2q_NtB2q_11Interpreter13sort_with_keys1_0EB2m_EB2q_ -_RNvMse_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_8Registry6remove -_RNCNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB7_7GcState18collect_generation0B9_ -_RNvMse_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_8Registry5entry -_RNCINvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace13traverse_implKb1_NtB4_5TallyEs2_0B6_ -_RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState18maybe_auto_collect -_RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState18collect_generation.llvm.15809725932051974371 -_RNvMsi_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_5Graph9propagate -_RNvMsk_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_5Tally4edge _RNvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace18maybe_auto_collect -_RINvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace13traverse_implKb1_NtB2_5TallyEB4_ -_RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState19sweep_deferred_from.llvm.15809725932051974371 -_RNvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace14intrusive_slot -_RNvMse_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_8Registry10forget_key -_RNCNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB7_7GcState19sweep_deferred_from0B9_ -_RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState12collect_impl.llvm.15809725932051974371 -_RNvMsl_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_6Finder13find_uncached -_RNvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace19clear_object_fields _RINvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace10with_stateINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB4_6object6ObjectENCNvMs7_B4_NtB4_11Interpreter16drain_gc_garbage0EB4_ -_RNvCscY2bcUAVtje_11weavepy_cli8run_path _RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRNtNtCs1C1lLj4PWSY_5alloc6string6StringECs7usbkSbEEZs_16weavepy_compiler _RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEECs5HK7yca7OMW_10weavepy_vm _RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneReECs7usbkSbEEZs_16weavepy_compiler _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecjEINtB2_18SpecFromIterNestedjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters5chain5ChainINtNtNtB1B_7sources4once4OncejEINtNtB1z_10filter_map9FilterMapINtNtB1z_9enumerate9EnumerateNtNtNtB1D_3str4iter5BytesENCNCNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB4m_6Parser8line_col00EEE9from_iterB4o_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtB6_5drain5DrainB13_EE9from_iterB17_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtB8_6string6StringEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB22_5slice4iter4IterTReNtNtCs4oeOcPWpyDO_13weavepy_lexer5token4SpanEENCNvMs_NtCs7usbkSbEEZs_16weavepy_compiler8validateNtB42_9Validator14visit_functions0_0EE9from_iterB44_ -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtB6_6string6StringEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set8IntoIterB11_EE9from_iterCs7usbkSbEEZs_16weavepy_compiler _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTReRNtNtCs5993W3JedWL_14weavepy_parser3ast4ExprEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapINtNtB2n_3zip3ZipINtNtNtB2r_5slice4iter4IterNtB17_3ArgEIB3C_INtNtB2r_6option6OptionB15_EEENCNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB4U_8Compiler25compile_default_arguments0EE9from_iterB4U_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecyEINtB2_18SpecFromIterNestedyINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1z_6filter6FilterINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map4IteryIBS_INtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakNtNtB3H_16weakref_registry11WeakRefSlotEEENCNvMs3_B4h_NtB4h_15WeakRefRegistry15dead_target_ids0ENCB4X_s_0EE9from_iterB3H_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecINtNtCsevLNFiNqfJP_4core6option6OptionjEEINtB4_18SpecFromIterNestedB13_INtNtNtNtB18_4iter8adapters3map3MapINtNtNtB18_3ops5range5RangejENCNvMs0_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB3m_6Region3news1_0EE9from_iterB3o_ @@ -7965,18 +6983,14 @@ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs5HK7yca7 _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecjEINtB2_18SpecFromIterNestedjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtNtB1D_3ops5range5RangejENCNvMs0_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB2Z_6Region3news0_0EE9from_iterB31_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecjEINtB2_18SpecFromIterNestedjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtNtB1D_3ops5range5RangejENCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11dict_layouts0_0EE9from_iterB2X_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VechEINtB2_18SpecFromIterNestedhINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtNtB1D_3ops5range5RangehENCNvMs_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB2Y_3X6410saved_regs0EE9from_iterB30_ -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VeccEINtB2_18SpecFromIterNestedcNtNtNtCsevLNFiNqfJP_4core3str4iter5CharsE9from_iterCs5HK7yca7OMW_10weavepy_vm _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecbEINtB4_18SpecFromIterNestedbINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1F_3ops5range5RangejENCNvNtCs89hHMyD40Kn_15weavepy_codegen8liveness7analyzesa_0EE9from_iterB2T_ -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecReEINtB2_18SpecFromIterNestedB11_INtNtNtCsevLNFiNqfJP_4core3str4iter5SplitcEE9from_iterCs7usbkSbEEZs_16weavepy_compiler _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtCs7usbkSbEEZs_16weavepy_compiler12FinallyFrameEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB2p_4take4TakeINtNtNtB2t_5slice4iter4IterB13_EENvB15_19clone_finally_frameEE9from_iterB15_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecTNtNtB8_6string6StringNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtB2I_3map3MapINtNtNtB2M_5slice4iter4IterB1p_ENvMs1s_B1r_B1p_6to_strEINtNtB6_9into_iter8IntoIterB1p_EEE9from_iterB1t_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyNtB16_6ObjectEEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2F_3ops5range5RangexENCNvNtB18_5tier221laid_out_slots_layouts2_0EE9from_iterB18_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecjEINtB2_18SpecFromIterNestedjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtNtB1D_3ops5range5RangejENCNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11iter_layouts0_00EE9from_iterB2Z_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5BlockEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtB2j_6copied6CopiedINtNtNtB2n_5slice4iter4IterB11_EENCNvNtB15_8liveness7analyzes5_0EE9from_iterB15_ -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VeccEINtB2_18SpecFromIterNestedcNtNtNtCsevLNFiNqfJP_4core3str4iter5CharsE9from_iterCs7usbkSbEEZs_16weavepy_compiler _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecReEINtB2_18SpecFromIterNestedB11_INtNtNtCsevLNFiNqfJP_4core3str4iter7RSplitNcEE9from_iterCs5HK7yca7OMW_10weavepy_vm _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VeclEINtB2_18SpecFromIterNestedlINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtNtB1D_3str4iter5CharsNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10locale_mod7to_wide0EE9from_iterB2P_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB2l_5chain5ChainINtNtNtB2p_5slice4iter4IterB13_EB3v_EEE9from_iterB17_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecINtNtCsevLNFiNqfJP_4core6option6OptionReEEINtB4_18SpecFromIterNestedB13_INtNtNtNtB18_4iter8adapters5chain5ChainINtNtB2i_3map3MapINtNtNtB18_5slice4iter4IterB1F_ENCNCNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time16struct_time_type000EINtNtNtB18_5array4iter8IntoIterB13_Kj2_EEE9from_iterB3P_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecyEINtB4_18SpecFromIterNestedyINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1F_5slice4iter6ChunkshENCNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint7convert22from_bitwise_digits_le0EE9from_iterB2X_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtCs7usbkSbEEZs_16weavepy_compiler8ConstantEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2o_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENvB3y_18object_to_constantEE9from_iterB3y_ @@ -7986,60 +7000,13 @@ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTjjEEINtB2_18S _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs7usbkSbEEZs_16weavepy_compiler4name4NameEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2r_5slice4iter4IterNtNtB8_6string6StringENvYB13_INtNtB2r_7convert4FromRB3x_E4fromEE9from_iterCs5HK7yca7OMW_10weavepy_vm _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5BlockEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtB2j_6copied6CopiedINtNtNtB2n_5slice4iter4IterB11_EENCNvNtB15_8liveness7analyzes3_0EE9from_iterB15_ _RNvMs2_NtCsd5p0HaiaiO6_11weavepy_jit6engineNtB5_9JitEngine20compile_frame_lazily -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7addressB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7use_regB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4stubB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7consumeB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5allocB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6imm_ofB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5fusesB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E10param_regsB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5trackB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E8const_ofB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E3resB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7compareB4_ -_RINvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB3_3GenNtNtB5_3x643X64E4opndNvYBS_NtNtB5_3asm3Asm10cmp_imm_okEB5_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E9live_intoB4_ -_RNCNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB4_3GenNtNtB6_3x643X64E7consume0B6_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4edgeB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E11param_movesB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E3defB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6targetB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E3srcB4_ -_RNvNtCs89hHMyD40Kn_15weavepy_codegen7codegen8arg_locs -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6branchB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7untrackB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4callB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5movesB4_ -_RINvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB3_3GenNtNtB5_3x643X64E4opndNCNvB2_4insts2_0EB5_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4instB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6unusedB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4gotoB4_ -_RINvNtCs89hHMyD40Kn_15weavepy_codegen7codegen7compileNtNtB4_3x643X64EB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6in_regB4_ -_RNvMs16_NtCsgHYyB3hU8Ec_3std4pathNtB6_4Path12__starts_with -_RNvNtCs5HK7yca7OMW_10weavepy_vm13vm_singletons29push_pending_weakref_callback -_RNvNtCs5HK7yca7OMW_10weavepy_vm13vm_singletons24drain_pending_cext_drops _RNvXNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB2_8BTreeMapcNtNtB4_7set_val9SetValZSTENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCs5HK7yca7OMW_10weavepy_vm _RNvXNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB2_8BTreeMapjjENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCsd5p0HaiaiO6_11weavepy_jit _RNvMNtCskibSv91bgl1_9hashbrown11rustc_entryINtNtB4_3map7HashMapINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB14_3vec3VecTThmhEIB10_ShEEENtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE11rustc_entryCs5HK7yca7OMW_10weavepy_vm _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7io_full7io_open _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7io_full11finish_open _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7io_full15io_open_code_kw -_RNvNtCs7usbkSbEEZs_16weavepy_compiler7ast_opt9fold_expr -_RNvNtCs7usbkSbEEZs_16weavepy_compiler7ast_opt15optimize_format -_RNvMs1_NtCs4oeOcPWpyDO_13weavepy_lexer5tokenNtB5_12StringPrefix5parse -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtNtCs5993W3JedWL_14weavepy_parser3ast4StmtE6map_orNtNtCs4oeOcPWpyDO_13weavepy_lexer5token4SpanNCNvMNtBN_6parserNtB2l_6Parser15parse_class_def0EBN_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs7usbkSbEEZs_16weavepy_compiler8bytecode9BinOpKindE6map_ormNCNvNtBM_12cpython_code14map_to_cpython0EBM_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE6filterNCNvMs7_BN_NtBN_11Interpreter17leaf_type_getattr0EBN_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm8FrameExcEE18get_or_insert_withNvYBI_NtNtB5_7default7Default7defaultEB1j_ -_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs5HK7yca7OMW_10weavepy_vm4sync4CellbEE9drop_slowBL_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel17json_make_encoders5_0EBJ_ -_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtCs7usbkSbEEZs_16weavepy_compiler11TableBufferE9drop_slowBI_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtBG_6stdlib11sre_objects5StateEEBG_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real26make_ref_object_with_classs0_0EBJ_ _RNvXs1a_NtCs1C1lLj4PWSY_5alloc4syncINtB6_3ArceEINtNtCsevLNFiNqfJP_4core7convert4FromNtNtB8_6string6StringE4from -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object14bytes_contains _RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE5entryB7_ _RINvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB6_5TableuE12get_index_ofNtNtB8_6object7DictKeyEB8_ _RNvNtCs5HK7yca7OMW_10weavepy_vm7dictmap12table_layout @@ -8054,207 +7021,61 @@ _RINvMss_NtCs5HK7yca7OMW_10weavepy_vm7dictmapNtB6_6SetMap15insert_probe_ifNtNtB8 _RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE5clearB7_ _RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE13insert_hashedB7_ _RNvNtCs7usbkSbEEZs_16weavepy_compiler8validate19for_each_child_expr -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler8validateNtB4_9Validator22push_type_params_scope -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler8validateNtB4_9Validator10visit_expr -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler8validateNtB4_9Validator14visit_function -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler8validateNtB4_9Validator13mark_assigned -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler8validateNtB4_9Validator10visit_body -_RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler8validateNtB4_9Validator12visit_target _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB6_3VecTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValuehbEEINtB4_10SpecExtendBT_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2a_5slice4iter4IterBU_ENCNvMNtBY_7codegenINtB3p_3GenNtNtBY_3x643X64E8snapshot0EE11spec_extendBY_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB4_3VecNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueEINtB2_10SpecExtendBR_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtB20_6copied6CopiedINtNtNtB24_5slice4iter4IterBR_EENCNvMNtBV_7codegenINtB3N_3GenNtNtBV_3x643X64E4calls0_0EE11spec_extendBV_ -_RNvNtCs89hHMyD40Kn_15weavepy_codegen4fold8fold_one _RNvNtCs89hHMyD40Kn_15weavepy_codegen4fold4fold _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm6object12DICT_WATCHES00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB14_6option6OptionQIB1J_INtNtB14_4cell7RefCellINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapjTINtNtBa_2rc2RcINtNtBa_4sync4CellyEEjENtNtBa_8fasthash13FxBuildHasherEEEEEE9call_onceBa_.llvm.9250547820948799359 _RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBe_11collections4hash3map7HashMapjTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtB2C_4sync4CellyEEjENtNtB2C_8fasthash13FxBuildHasherEEuE16get_or_init_slowNvNvNtB2C_6object12DICT_WATCHES27___rust_std_internal_init_fnEB2C_ -_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageANtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrj4_uE16get_or_init_slowNvNvNtNtB1j_6stdlib13functools_mod12PARTIAL_KEYS27___rust_std_internal_init_fnEB1j_ -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtB19_5trace15MonitoringToolsEEB19_.llvm.16112649145315725652 -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyANtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrj4_EB19_.llvm.16112649145315725652 -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBa_11collections4hash3map7HashMapINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB2q_3vec3VecTThmhEIB2m_ShEEEEEECs5HK7yca7OMW_10weavepy_vm.llvm.16112649145315725652 _RNvYNCNKNvNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12vm_intrinsic5TABLE00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1e_6option6OptionQIB1T_INtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapReNtNtBc_6object6ObjectEEEEE9call_onceBc_.llvm.13937324807167308475 -_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBe_11collections4hash3map7HashMapINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB2A_3vec3VecTThmhEIB2w_ShEEEEEuE16get_or_init_slowNvNvCs5HK7yca7OMW_10weavepy_vm11SOURCE_CODE27___rust_std_internal_init_fnEB43_ _RNvYNCNKNvCs5HK7yca7OMW_10weavepy_vm11SOURCE_CODE00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtBU_6option6OptionQIB1z_INtNtBU_4cell7RefCellINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB3l_3vec3VecTThmhEIB3h_ShEEEEEEEEE9call_onceB8_ -_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtB1j_5trace15MonitoringToolsEuE16get_or_init_slowNvNvB1Y_16MONITORING_TOOLS27___rust_std_internal_init_fnEB1j_ -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyANtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyj5_EB19_.llvm.16112649145315725652 _RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBa_11collections4hash3map7HashMapjTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtB2s_4sync4CellyEEjENtNtB2s_8fasthash13FxBuildHasherEEEB2s_.llvm.16112649145315725652 -_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageANtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyj5_uE16get_or_init_slowNvNvNtB1j_16weakref_registry12WRAPPER_KEYS27___rust_std_internal_init_fnEB1j_ -_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtNtNtBe_11collections4hash3map7HashMapReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEuE16get_or_init_slowNvNvNvNtB20_8builtins12vm_intrinsic5TABLE27___rust_std_internal_init_fnEB20_ -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtNtNtBa_11collections4hash3map7HashMapReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEB1Q_.llvm.16112649145315725652 _RNvMsk_NtCs5HK7yca7OMW_10weavepy_vm12shared_valueINtB5_7ThinArcINtB5_12SliceStoragehEE15from_copy_sliceB7_ _RNvXsI_NtCs5HK7yca7OMW_10weavepy_vm12shared_valueNtB5_9SharedStrNtNtCsevLNFiNqfJP_4core3fmt7Display3fmt _RNvNtCs5HK7yca7OMW_10weavepy_vm10specialize27attempt_specialize_for_iter -_RNvNtCs5HK7yca7OMW_10weavepy_vm10specialize26kw_uncovered_have_defaults _RNvNtCs5HK7yca7OMW_10weavepy_vm10specialize34attempt_specialize_unpack_sequence _RNvNtCs5HK7yca7OMW_10weavepy_vm10specialize32attempt_specialize_call_kw_names -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm10specialize29attempt_specialize_store_attrs_0B5_ _RNvNtCs7usbkSbEEZs_16weavepy_compiler12cpython_code15raw_first_instr _RNvNtCs7usbkSbEEZs_16weavepy_compiler12cpython_code11decode_full _RNvNtCs7usbkSbEEZs_16weavepy_compiler12cpython_code11decode_raws.llvm.6600469782039157465 _RNvNtCs7usbkSbEEZs_16weavepy_compiler12cpython_code19decode_instructions.llvm.6600469782039157465 _RINvMsN_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree4nodeINtB6_6HandleINtB6_7NodeRefNtNtB6_6marker3MutcNtNtB8_7set_val9SetValZSTNtB1n_4LeafENtB1n_4EdgeE16insert_recursingNtNtBc_5alloc6GlobalNCNvMs4_NtNtB8_3map5entryINtB3b_11VacantEntrycB1E_E12insert_entry0ECs5HK7yca7OMW_10weavepy_vm -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecNtNtCs5HK7yca7OMW_10weavepy_vm5tier29AttrGuardEE9drop_slowBX_ -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecNtNtCs5HK7yca7OMW_10weavepy_vm5tier211MethodEntryEE9drop_slowBX_ _RINvMs1_NtCs5HK7yca7OMW_10weavepy_vm11frame_slotsNtB6_10FrameStack6extendINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB8_6object6ObjectEEB8_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15simple_delegate -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod14register_types -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod31register_classmethod_descriptor -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8ishl_imm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4icmp -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4jump -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7builderNtB2_15FunctionBuilder16import_signature -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4band -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder6iconst -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8iadd_imm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8band_imm -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7builderNtB2_15FunctionBuilder12create_block -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7builderNtB2_15FunctionBuilder39append_block_params_for_function_params -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7builderNtB2_15FunctionBuilder4push -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7builderNtB2_15FunctionBuilder15switch_to_block -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder6select -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fcmp _RINvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB5_15FuncInstBuilder6uload8lECs5HK7yca7OMW_10weavepy_vm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4brif -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7builderNtB2_15FunctionBuilder18append_block_param -_RINvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB5_15FuncInstBuilder5storelECs5HK7yca7OMW_10weavepy_vm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder14fcvt_from_sint -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8ushr_imm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder7ireduce -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder7bitcast -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8icmp_imm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder3bor -_RINvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB5_15FuncInstBuilder4loadlECs5HK7yca7OMW_10weavepy_vm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4iadd _RINvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB5_15FuncInstBuilder7uload32lECs5HK7yca7OMW_10weavepy_vm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder13call_indirect -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8bxor_imm -_RNvMs_NtCs3QF46a9Pg1X_8indexmap5innerINtB4_4CoreNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCs7usbkSbEEZs_16weavepy_compiler7BindingE10push_entryB1o_.llvm.17570286543906374572 _RNvMs_NtCs3QF46a9Pg1X_8indexmap5innerINtB4_4CoreNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCs7usbkSbEEZs_16weavepy_compiler7BindingE11insert_fullB1o_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native24namedtuple_register_make -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native16tuplegetter_init -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native19install_tuplegetter -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native19namedtuple_register -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native17tuplegetter_index -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native5build -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native5build0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native19install_defaultdict -_RINvMNtCs5HK7yca7OMW_10weavepy_vm8gen_fastNtB5_11Interpreter15gen_fast_resumeKb0_EB5_ -_RNvMNtCs5HK7yca7OMW_10weavepy_vm8gen_fastNtB4_11Interpreter14gen_fast_drain -_RNvNvNtNtNtCskRQrKhBUP4e_6memchr4arch6x86_646memchr10memchr_raw6detect -_RNvNvNtNtNtCskRQrKhBUP4e_6memchr4arch6x86_646memchr10memchr_raw9find_avx2 -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins15property_setterINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types30install_mutable_container_init12dict_init_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB2g_EEE4callB8_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real8ref_initINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1L_EEE4callB8_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10file_enterINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14str_replace_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1E_EEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins8str_joinINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod31register_classmethod_descriptorINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins4b_idINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod11IMPORT_LOCK0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceuE9call_onceBa_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins7set_popINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins6b_dictINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins8dict_getINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types20install_type_dunders12type_setattrINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RNvYNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12warnings_mod5builds_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRSNtNtBa_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1R_EEE9call_onceBa_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13str_format_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1D_EEE4callB6_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9file_exitINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16mappingproxy_getINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins8dict_popINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects14compile_cachedINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvXs1_NtNtNtCsevLNFiNqfJP_4core3ops8function5implsQNCNvMs3_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtBW_15WeakRefRegistry15dead_target_ids0INtB7_5FnMutTRTRyRINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBY_2rc4WeakNtBW_11WeakRefSlotEEEEE8call_mutBY_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11list_appendINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16str_isidentifierINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNvMNtCs5HK7yca7OMW_10weavepy_vm13builtin_typesNtB7_12BuiltinTypes5build9proxy_newINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB9_6object6ObjectEE4callB9_ _RNvYNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod5builds1_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRSNtNtBa_6object6ObjectEE9call_onceBa_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real16ref_subclass_newINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1U_EEE4callB8_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9file_readINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvXs1_NtNtNtCsevLNFiNqfJP_4core3ops8function5implsQNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4plan0INtB7_5FnMutTRTjRNtNtCs7usbkSbEEZs_16weavepy_compiler8bytecode11InstructionEEE8call_mutBW_ _RNvXs1_NtNtNtCsevLNFiNqfJP_4core3ops8function5implsQNCNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtBW_8Compiler25push_body_exc_entries_ids0INtB7_5FnMutTRRTmmmEEE8call_mutBW_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10dict_clearINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod15partial_new_forINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod12partial_callINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1R_EEE4callB8_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11list_removeINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types20install_type_dunders12type_delattrINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12b_memoryviewINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18mappingproxy_itemsINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10b_callableINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types19install_module_init11module_initINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7io_full15io_open_code_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1N_EEE4callB8_ -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod14register_typesINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12obj_containsINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm6object21dict_key_is_reentrantINtNtNtCsevLNFiNqfJP_4core3ops8function5FnMutTRNtB4_6ObjectEE8call_mutB6_.llvm.9250547820948799359 -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11list_insertINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7imp_mod5builds0_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRSNtNtBa_6object6ObjectEE9call_onceBa_ -_RNvNtCs89hHMyD40Kn_15weavepy_codegen4fold11annihilated _RNvMs7_NtCs89hHMyD40Kn_15weavepy_codegen2irNtB5_13JumpTableData3new -_RNvMs8_NtCs89hHMyD40Kn_15weavepy_codegen2irNtB5_13DataFlowGraph7results -_RNvMsa_NtCs89hHMyD40Kn_15weavepy_codegen2irNtB5_8Function5clear _RNvMsa_NtCs89hHMyD40Kn_15weavepy_codegen2irNtB5_8Function7reserve _RNvMs8_NtCs89hHMyD40Kn_15weavepy_codegen2irNtB5_13DataFlowGraph5slice _RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastINtNtB4_4sync4CellyEEB4_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12resource_mod5build _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12resource_mod18resource_getrusage _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12resource_mod7builtin -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11asyncio_mod16future_iter_send _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real1m -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time16compute_timezone -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time16compute_timezone0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time17time_monotonic_ns -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time1b -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12warnings_mod10builtin_kw -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12warnings_mod15default_filters -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12warnings_mod5build -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12warnings_mod15default_filters0B7_ _RINvMNtCsg55y0en7y7K_6chrono6offsetINtB3_11LocalResultNtNtB3_3utc3UtcE8and_thenINtNtB5_8datetime8DateTimeBQ_ENCNvYBQ_NtB3_8TimeZone19from_local_datetime0ECs5HK7yca7OMW_10weavepy_vm -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel17encode_value_impl -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel17json_make_scanner -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter11quoted_utf8 -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter11push_object -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel20write_encoded_string -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter8push_str -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel1b -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel17json_make_encoder -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel11encode_list0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel9json_kind -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel5builds_0B7_ -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel17json_make_encoders5_0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel12encode_value _RINvXs5_NtCs1C1lLj4PWSY_5alloc6stringNtB6_6StringINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorcE9from_iterINtNtNtBS_8adapters6filter6FilterNtNtNtBU_3str4iter5CharsNCNvNtCs5993W3JedWL_14weavepy_parser6parser12parse_number0EEB2Y_ _RNvXs1M_NtCs1C1lLj4PWSY_5alloc6stringxNtB6_12SpecToString14spec_to_string _RINvXs6_NtCs1C1lLj4PWSY_5alloc6stringNtB6_6StringINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorRcE9from_iterINtNtNtBU_5slice4iter4ItercEECs7usbkSbEEZs_16weavepy_compiler _RINvXs5_NtCs1C1lLj4PWSY_5alloc6stringNtB6_6StringINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorcE9from_iterINtNtNtBS_8adapters6filter6FilterNtNtNtBU_3str4iter5CharsNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16parse_float_text0EEB2Y_ -_RNvMNtCs1C1lLj4PWSY_5alloc6stringNtB2_6String9from_utf8 -_RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_Esb_0B8_ -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler13set_line_from -_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VeccE16extend_desugaredNtNtNtCsevLNFiNqfJP_4core3str4iter5CharsECs5HK7yca7OMW_10weavepy_vm _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real6keeperNtNtBK_4sync9RealRLockE0EBK_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real6keeperNtNtBK_4sync8RealLockE0EBK_ _RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_Est_0B8_ -_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable7ipnsortNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYBT_NtNtB8_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14operator_accel5build0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14operator_accel5build -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen3memNtB4_9CodeArena7install -_RNvNtNtCs89hHMyD40Kn_15weavepy_codegen3mem4near7reserve _RNvNtCs89hHMyD40Kn_15weavepy_codegen3mem7install -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10signal_mod31register_current_thread_pthread _RINvXss_NtCskibSv91bgl1_9hashbrown3setINtB6_8IntoIterNtNtCs1C1lLj4PWSY_5alloc6string6StringENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4folduNCINvNtNtB1y_8adapters3map8map_foldBP_TBP_uEuNCINvXs8_B6_INtB6_7HashSetBP_INtNtB1A_4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEEINtNtB1w_7collect6ExtendBP_E6extendINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetBP_B3F_EE0NCINvNvB1s_8for_each4callB35_NCINvXs1i_NtB8_3mapINtB7m_7HashMapBP_uB3F_EIB56_B35_E6extendINtB2y_3MapINtB5H_8IntoIterBP_EB3c_EE0E0E0EB4h_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastNtNtB4_16weakref_registry11WeakRefSlotEB4_ _RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtNtB6_6object6PyFileE3newB6_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtNtB6_5types10PyInstanceE3newB6_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtNtNtB6_6stdlib11sre_objects5StateE3newB6_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastINtNtB4_12shared_value12SliceStorageNtNtB4_6object7DictKeyEEB4_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastNtNtNtB4_6stdlib10json_accel10EncoderCfgEB4_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastNtNtB4_6object6PyFileEB4_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcINtNtB6_4sync7GilCellNtNtB6_7dictmap6SetMapEE3newB6_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastNtNtB4_5types12InstancePlanEB4_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtNtNtB6_6stdlib10json_accel10EncoderCfgE3newB6_ _RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB5_2RcNtNtB7_5types10TypeObjectE9downgradeB7_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastNtNtB4_6object14SlotDescriptorEB4_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastNtNtB4_5types10TypeObjectEB4_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtNtNtB6_6stdlib10json_accel10ScannerCfgE3newB6_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecIBA_INtNtB6_4sync7GilCellNtNtB6_6object6ObjectEEEE3newB6_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectE3newB6_ _RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit4UnitENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB10_ _RINvXs4_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB6_8IntoItercENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4folduNCINvNvBZ_8for_each4callcNCINvXsd_NtBa_6stringNtB2y_6StringINtNtB13_7collect6ExtendcE6extendBI_E0E0ECs5HK7yca7OMW_10weavepy_vm _RNvMs0_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectBX_EE32forget_allocation_drop_remainingB11_ @@ -8262,44 +7083,14 @@ _RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterINtNtCsevLNFiNqfJP_ _RINvXs4_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB6_8IntoIterTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectBY_EENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator8try_foldINtNtB8_13in_place_drop11InPlaceDropBY_ENCINvNtNtB1R_8adapters3map12map_try_foldBX_BY_B2P_INtNtB1T_6result6ResultB2P_zENCNvMs7_B12_NtB12_11Interpreter13sort_with_keys1_0NCINvNtB8_16in_place_collect24write_in_place_with_dropBY_E0E0B4h_EB12_ _RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterTNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyNtBZ_6ObjectEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB11_ _RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB11_16weakref_registry11WeakRefSlotEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB11_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9inst_dict16note_materialize0E0zEB1y_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockTxxEE10initializeNCINvB2_11get_or_initNCNvMs11_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB1E_10PyFunction12name_objects0E0zEB1G_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace11stats_debug0E0zEB1y_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockjE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10chunk_room0E0zEB1y_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6verify0E0zEB1y_ -_RNvCs5HK7yca7OMW_10weavepy_vm16exc_family_flags -_RNvNtCs5HK7yca7OMW_10weavepy_vm11burst_stats7enabled _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtCs5HK7yca7OMW_10weavepy_vm9SiteTableNtBW_8AttrPolyEE10initializeNCINvB2_11get_or_initNCINvMst_BW_NtBW_16CodeConstObjects11alloc_sitesB1w_FEB1w_E0E0zEBW_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtB7_4time7InstantE10initializeNCINvB2_11get_or_initNvMBV_BT_3nowE0zECs5HK7yca7OMW_10weavepy_vm -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9hot_gates9env_flags9jit_trace0E0zEB1A_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline7enabled0E0zEB1A_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCs89hHMyD40Kn_15weavepy_codegen3mem4near6RegionEE10initializeNCINvB2_11get_or_initNvB1x_7reserveE0zEB1B_.llvm.13936311991460135361 _RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm7reaches -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockjE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8chunk_ir0E0zEB1y_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs89hHMyD40Kn_15weavepy_codegen7codegen6timing0E0zEB1y_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtCs5HK7yca7OMW_10weavepy_vm9SiteTableNtBW_9FieldSlotEE10initializeNCINvB2_11get_or_initNCINvMst_BW_NtBW_16CodeConstObjects11alloc_sitesB1w_NvMsG_BW_B1w_5emptyE0E0zEBW_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7enabled0E0zEB1y_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexINtNtNtNtB7_11collections4hash3map7HashMapjjEEE10initializeNCINvB2_11get_or_initNvYBT_NtNtCsevLNFiNqfJP_4core7default7Default7defaultE0zECs5HK7yca7OMW_10weavepy_vm -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCsd5p0HaiaiO6_11weavepy_jit7runtime9ObjLayoutE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zECs5HK7yca7OMW_10weavepy_vm _RNvMsf_NtCs5HK7yca7OMW_10weavepy_vm4syncINtB5_7GilCellNtNtB7_9inst_dict11SplitValuesE10try_borrowB7_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace10root_debug0E0zEB1y_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCsd5p0HaiaiO6_11weavepy_jit7runtime9ObjLayoutE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEBX_.llvm.13143382369088262339 -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexINtNtNtNtB7_11collections4hash3map7HashMapyjEEE10initializeNCINvB2_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10signal_mod16pthread_registry0E0zEB2M_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexINtNtNtNtB7_11collections4hash3set7HashSetNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrNtNtB26_8fasthash13FxBuildHasherEEE10initializeNCINvB2_11get_or_initNCNvMs1y_NtB26_6objectNtB49_6Object12interned_str0E0zEB26_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockyE10initializeNCINvB2_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod12compiler_tag0E0zEB1A_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectBU_EE10initializeNCINvB2_11get_or_initNCNvBY_14code_gen_names0E0zEBY_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit5stats6decide0E0zEB1A_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBY_6string6StringEE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11op_disabled0E0zEB2q_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm9StoreInitEEE10initializeNCINvB2_11get_or_initNCNvB26_15code_store_init0E0zEB26_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5UJUBJEE7PZ_8lock_api5mutex5MutexNtNtCs2zRUMDvV71V_11parking_lot9raw_mutex8RawMutexINtNtCs1C1lLj4PWSY_5alloc3vec3VecRNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod12CompiledCodeEEE10initializeNCINvB2_11get_or_initNCNvB2V_8registry0E0zEB2Z_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockjE10initializeNCINvB2_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline9max_total0E0zEB1A_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB7_4path7PathBufEE10initializeNCINvB2_11get_or_initNCNvCs89hHMyD40Kn_15weavepy_codegen4dump0E0zEB2s_.llvm.13936311991460135361 -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcINtBW_12SliceStorageNtNtBY_6object7DictKeyEEE10initializeNCINvB2_11get_or_initNCNvNtBY_16weakref_registry21fixed_wrapper_storage0E0zEBY_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcDNtNtCsevLNFiNqfJP_4core3any3AnyNtNtB1z_6marker4SendNtB22_4SyncEL_EE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEBY_ -_RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB5_11WeakRefSlot11target_died -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcINtBW_12SliceStorageNtNtBY_6object7DictKeyEEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib11thread_real11lock_layout0E0zEBY_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit5stats6decide -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockTINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs1C1lLj4PWSY_5alloc6string6StringEBU_EE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13name_admitted0E0zEB2R_ _RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters5chainINtB5_5ChainIBP_IBP_IBP_INtNtNtBb_5slice4iter4IterNtNtCs5993W3JedWL_14weavepy_parser3ast3ArgEB1c_EB1c_EINtNtBb_6option4IterB1C_EEB2t_ENtNtNtB9_6traits8iterator8Iterator8try_folduNCINvNvB2Y_3any5checkRB1C_NCNvNvCs7usbkSbEEZs_16weavepy_compiler21module_mentions_super13in_args_outer0E0INtNtNtBb_3ops12control_flow11ControlFlowuEEB4c_ _RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters5chainINtB4_5ChainIBO_INtNtBa_6option8IntoIterTRNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyRNtB1v_6ObjectEEINtNtB6_3map3MapINtNtB6_7flatten7FlattenIB14_RINtNtCs1C1lLj4PWSY_5alloc3vec3VecTB1t_B2d_EEEENCNvMsq_NtB1x_5typesNtB44_11SlotStorage4iter0EEINtB2L_7FlatMapIB14_RNtB1v_8DictDataENtNtB1x_7dictmap4IterNCB3Y_s_0EENtNtNtB8_6traits8iterator8Iterator9size_hintB1x_ _RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters5chainINtB5_5ChainINtNtNtBb_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEB10_ENtNtNtB9_6traits8iterator8Iterator4folduNCINvNtB7_3map8map_foldRB1q_B1q_uNvYB1q_NtNtBb_5clone5Clone5cloneNCINvNvB2e_8for_each4callB1q_NCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB4x_3VecB1q_E14extend_trustedINtNtB7_6cloned6ClonedBO_EE0E0E0EB1u_ @@ -8316,85 +7107,35 @@ _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm6object16DICT_WATCH_COUNT0s_0INtNtNtCsevL _RNvYNCNKNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real10PROXY_TYPE00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1i_6option6OptionQIB1X_INtNtBc_4sync7GilCellIB1X_INtNtBc_2rc2RcNtNtBc_5types10TypeObjectEEEEEEE9call_onceBc_ _RNvYNCNKNvNvCs5HK7yca7OMW_10weavepy_vm20builtin_needs_interp4MEMOs_0s_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1e_6option6OptionQIB1T_AINtNtB1e_4cell4CellTjmEEj100_EEEE9call_onceBa_ _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm5trace16TRACING_SUPPRESS0s_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB19_6option6OptionQIB1O_INtNtBa_4sync7GilCellmEEEEE9call_onceBa_.llvm.4890245414193407415 -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12plan_rewrite _RNvMs0_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB5_6Region3new -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze13control_succs -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_impl.llvm.2091680242001868680 -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_once -_RNvNtNtCs2isY2vBRLTu_10std_detect6detect5cache21detect_and_initialize _RNvNtNtNtCsevLNFiNqfJP_4core9core_arch3x865xsave7__xgetbv _RNvMsf_NtCs5HK7yca7OMW_10weavepy_vm4syncINtB5_7GilCellDNtNtNtCsevLNFiNqfJP_4core2io5write5WriteNtNtBX_6marker4SendNtB1x_4SyncEL_E10borrow_mutB7_ _RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm4syncINtB5_7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB7_6object6ObjectEE7replaceB7_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm4sync3RefNtNtBG_6object6ObjectEEBG_.llvm.15809725932051974371 -_RNvMsf_NtCs5HK7yca7OMW_10weavepy_vm4syncINtB5_7GilCellNtNtB7_6object10PyIteratorE10borrow_mutB7_ -_RNCINvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace13traverse_implKb0_DG_INtNtNtCsevLNFiNqfJP_4core3ops8function5FnMutTRL0_NtNtB6_6object6ObjectEEp6OutputuEL_Es5_0B6_.llvm.15809725932051974371 _RNvNtCs89hHMyD40Kn_15weavepy_codegen8liveness7analyze -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter8chr_fast _RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter11chain_drain -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter14lazy_pure_next _RNCNvMs_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB8_11Interpreter9seq_drain0B8_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter9pure_iter -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter8max_fast -_RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB7_11Interpreter14lazy_core_next -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB6_11Interpreter12seq_pull_all -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter8ord_fast -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter11cursor_pair.llvm.16911827322050435359 _RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter10srcs_ready.llvm.16911827322050435359 -_RNCNvMs_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB8_11Interpreter12seq_pull_all0B8_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter12min_max_fast -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB6_11Interpreter9seq_call1 -_RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB7_11Interpreter13pure_callback -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter11decimal_i64 -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib3sys16build_with_states_0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib3sys10sys_intern -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib3sys22sys_getframemodulename -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower6binary -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower6int_op -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8h_return -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_site_call -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower14float_operands -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower8float_op -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_call_site -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10h_get_iter -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6h_call -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower12binary_plain _RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEEE11extend_withCsd5p0HaiaiO6_11weavepy_jit _RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionIBw_NtNtCsd5p0HaiaiO6_11weavepy_jit7analyze2SEEEE11extend_withB1p_ -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze2SEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze14boundary_stack _RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecjE14extend_trustedINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB17_5slice4iter4IterjENCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_onces1_0EEB2l_ -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftTjjENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB1m_11sort_by_keyTINtNtBa_3cmp7ReversejEjENCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4plans0_0E0EB2N_ _RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjIBJ_NtNtCsd5p0HaiaiO6_11weavepy_jit7analyze2SEEEENtB1n_10JitVerdictE11inspect_errNCNvB1n_12analyze_onces5_0EB1p_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionIBC_NtNtCsd5p0HaiaiO6_11weavepy_jit7analyze2SEEEEEB1C_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze9CtorStateEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir11GlobalGuardEEB1c_ _RINvXs7_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3setINtB6_7HashSetjINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEEINtNtNtNtB1a_4iter6traits7collect12FromIteratorjE9from_iterINtNtNtB2Q_8adapters6copied6CopiedINtNtNtB1a_5slice4iter4IterjEEECsd5p0HaiaiO6_11weavepy_jit -_RNvMs4_NtNtCs1C1lLj4PWSY_5alloc11collections9vec_dequeINtB5_8VecDequejE4growCsd5p0HaiaiO6_11weavepy_jit _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecjEINtB2_12SpecFromIterjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtB1m_6copied6CopiedINtNtNtNtB6_11collections5btree3set4IterjEENCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12build_blocks0EE9from_iterB3l_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records14h_direct_enter _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir8OsrEntryE8grow_oneBQ_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze2SEE8grow_oneBQ_ -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3fop _RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4swap -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjjINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertCsd5p0HaiaiO6_11weavepy_jit _RNvMs2_NtNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3map5entryINtB5_5EntryjjE9or_insertCsd5p0HaiaiO6_11weavepy_jit _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze2SEEENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEB1B_ _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEB1r_ _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtB5_3VecjENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalECsd5p0HaiaiO6_11weavepy_jit _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalECsd5p0HaiaiO6_11weavepy_jit -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjjEE14reserve_rehashNCINvNtB8_3map11make_hasherjjINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0ECsd5p0HaiaiO6_11weavepy_jit _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBV_6string6StringEEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCsd5p0HaiaiO6_11weavepy_jit _RNvXsb_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTmuEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCsd5p0HaiaiO6_11weavepy_jit _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTmuEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCsd5p0HaiaiO6_11weavepy_jit _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmmEE12remove_entryNCINvNtB8_3map14equivalent_keymmmE0ECsd5p0HaiaiO6_11weavepy_jit _RNvXsb_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTjuEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCsd5p0HaiaiO6_11weavepy_jit _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTjuEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCsd5p0HaiaiO6_11weavepy_jit -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14ResolvedGlobalINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE3getmEBT_ -_RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s1_0Bb_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215classify_global _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1z_6filter6FilterINtNtNtNtB6_11collections5btree3set4IterjENCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_once0ENCB3n_s_0EE9from_iterB3r_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecjEINtB2_18SpecFromIterNestedjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtNtB1D_3ops5range5RangejENCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_onces0_0EE9from_iterB2X_ -_RNvMsi_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_8BTreeMapjNtNtB7_7set_val9SetValZSTE6insertCsd5p0HaiaiO6_11weavepy_jit _RNvXNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB2_8BTreeMapjNtNtB4_7set_val9SetValZSTENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCsd5p0HaiaiO6_11weavepy_jit _RNvXsk_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_4IterjNtNtB7_7set_val9SetValZSTENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4nextCsd5p0HaiaiO6_11weavepy_jit _RINvXsd_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3setINtB6_8BTreeSetjEINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorjE9from_iterINtNtNtB1h_8adapters6filter6FilterINtNtB2r_6copied6CopiedINtB6_4IterjEENCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12build_blocks0EEB3B_ @@ -8405,88 +7146,28 @@ _RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze14compute_livein _RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze11infer_block _RNvMs2_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB5_9CtorState10note_store _RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12build_blocks -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze13step_abstract -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze16reachable_blocks _RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze11merge_entry -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze13num_spec_lane -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower5truth -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower8ref_call -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower6branch -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10ref_or_own -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline9call_argc -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12ListLoopMetaE8grow_oneBQ_ -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm8overflow -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertCsd5p0HaiaiO6_11weavepy_jit -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertCsd5p0HaiaiO6_11weavepy_jit -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjTmmmEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertCsd5p0HaiaiO6_11weavepy_jit -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmTmNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertBU_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjThjEEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0ECsd5p0HaiaiO6_11weavepy_jit -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjTmmmEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE3getjECsd5p0HaiaiO6_11weavepy_jit _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmmEE14reserve_rehashNCINvNtB8_3map11make_hashermmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0ECsd5p0HaiaiO6_11weavepy_jit -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmTmNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0EBX_ -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmTmNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE3getmEBV_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216grade_obj_global -_RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s4_0Bb_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtB8_6filter6FilterINtNtNtBc_3ops5range5RangejENCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze14innermost_loop0ENCINvNvNtNtNtBa_6traits8iterator8Iterator10max_by_key3keyjjNCB1N_s_0E0EB2P_4foldTjjENCINvNvB2P_6max_by4foldB40_INvB2N_7comparejjEE0EB1R_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze17dyn_attr_fallback -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8overflow.llvm.6216746210985195458 -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fadd _RNvXs1_NtNtNtCsevLNFiNqfJP_4core3ops8function5implsQNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_onces0_0INtB7_5FnMutTRjEE8call_mutBU_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15bin_result_type -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze8bin_kind -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12resolve_pair -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6h_calls_0B5_ -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11subscr_call -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10subscr_ref -_RNvMs2_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_6Native3ran -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze7pop_val _RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit2ir6TBlockEE11extend_withB1l_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12AttrSiteMetaENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBJ_ -_RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeNtNtBM_7analyze10JitVerdictE11inspect_errNCNvB1t_10emit_instrs0_0EBM_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecjEINtB2_12SpecFromIterjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6copied6CopiedINtNtNtB1q_5slice4iter4IterjEEE9from_iterCsd5p0HaiaiO6_11weavepy_jit -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir5TStmtE8grow_oneBQ_ -_RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze5ESlotEENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEB1B_ -_RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit2ir6TBlockENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEB1r_ -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjjINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE3getjECsd5p0HaiaiO6_11weavepy_jit _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTjjEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCsd5p0HaiaiO6_11weavepy_jit -_RNvNtCs89hHMyD40Kn_15weavepy_codegen4fold4icmp -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8h_copies _RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterjENtNtNtNtBb_4iter6traits8iterator8Iterator3anyNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_onces6_0EB1H_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze10seed_entry -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15infer_load_attr -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze10emit_instr -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze10stmt_start -_RNvMs_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB4_4Plan9hidden_at -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze10emit_block -_RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze10emit_instr0B5_ -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower5build -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_countdown -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit16never_ran_blocks -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10kernel_for -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit4left _RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower15binary_fallback _RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower4both -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir6TBlockE8push_mutBJ_ -_RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecmE8dedup_byNCNvMs5_B5_Bv_5dedup0ECsd5p0HaiaiO6_11weavepy_jit _RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBM_6object10PyFunctionEbEE14extend_trustedINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB6_9into_iter8IntoIterBH_ENCNvNtNtBM_9frame_jit6inline10callees_at0EEBM_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsd5p0HaiaiO6_11weavepy_jit2ir5TFuncEBF_ _RNvCs5HK7yca7OMW_10weavepy_vm19method_site_callees -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14CalleeSpanMetaE8grow_oneBQ_ _RINvMsi_NtCskibSv91bgl1_9hashbrown3rawINtB6_12RawIterRangeTmuEE9fold_implNCINvXsG_NtB8_3mapINtB1i_4ItermuENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4folduNCINvXsU_B1i_INtB1i_4KeysmuEB1G_4folduNCINvXsB_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3setINtB3s_12IntersectionmINtNtB1O_4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEEB1G_4folduNCINvNtNtB1M_8adapters6copied9copy_foldmuNCINvNtB6e_3map8map_foldmBU_uNCINvXs8_NtB8_3setINtB7o_7HashSetmB4y_EINtNtB1K_7collect6ExtendmE6extendINtB6c_6CopiedB4c_EE0NCINvNvB1G_8for_each4callBU_NCINvXs1i_B1i_INtB1i_7HashMapmuB4y_EIB7T_BU_E6extendINtB6R_3MapB8p_B7f_EE0E0E0E0E0E0E0uECsd5p0HaiaiO6_11weavepy_jit _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTjThjEEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCsd5p0HaiaiO6_11weavepy_jit _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTjNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze14CompHeaderPlanEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBU_ _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTmTmNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBW_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216probe_param_lane -_RINvNtCs5HK7yca7OMW_10weavepy_vm5tier214walk_attr_pathNtNtCs1C1lLj4PWSY_5alloc6string6StringEB4_.llvm.10617736694814397161 -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s6_0B7_ -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit16never_ran_blocks0E0zE0E0B2m_.llvm.6970241935485176696 _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13RangeLoopMetaENCNvNtB1r_7analyze12analyze_oncesc_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2M_8for_each4callB1n_NCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB42_3VecB1n_E14extend_trustedBN_E0E0EB1r_ _RNvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB5_3MapINtNtB7_6filter6FilterINtNtNtBb_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12ListLoopMetaENCNvNtB1M_7analyze12analyze_oncesf_0ENCB2x_sg_0ENtNtNtB9_6traits8iterator8Iterator4nextB1M_.llvm.9065829636569105838 _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterINtNtB1f_6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14MethodSiteMetaEENCNvNtB2M_7analyze12analyze_onces8_0EB2I_EB2M_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecmEINtB4_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1F_5slice4iter4IterjENCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_oncesl_0EE9from_iterB2T_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecjEINtB2_18SpecFromIterNestedjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1z_6filter6FilterINtNtB1z_5chain5ChainINtNtNtB1B_7sources4once4OncejEIB1v_INtNtNtB1D_5slice4iter4IterNtCs7usbkSbEEZs_16weavepy_compiler10ExcHandlerENCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit16never_ran_blockss0_0EENCB4O_s1_0ENCB4O_s2_0EE9from_iterB4S_ -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set8IntoItermEE9from_iterCsd5p0HaiaiO6_11weavepy_jit -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13CompSavedMetaEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6copied6CopiedINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map6ValuesmB11_EEE9from_iterB15_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12ListLoopMetaEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB2n_6filter6FilterINtNtNtB2r_5slice4iter4IterB11_ENCNvNtB15_7analyze12analyze_oncesd_0ENCB41_se_0EE9from_iterB15_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12IterLoopMetaEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB2n_6filter6FilterINtNtNtB2r_5slice4iter4IterNtB13_12ListLoopMetaENCNvNtB15_7analyze12analyze_oncesf_0ENCB4h_sg_0EE9from_iterB15_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13RangeLoopMetaEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2u_5slice4iter4IterB13_ENCNvNtB17_7analyze12analyze_oncesc_0EE9from_iterB17_ @@ -8495,488 +7176,137 @@ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18Spec _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map6ValuesjNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze14CompHeaderPlanENCNvB3f_12analyze_oncesp_0EE9from_iterB3h_ _RINvMNtCsevLNFiNqfJP_4core5sliceSNtNtCsd5p0HaiaiO6_11weavepy_jit2ir8OsrEntry20sort_unstable_by_keymNCNvNtBz_7analyze12analyze_onces9_0EBz_ _RINvMNtCsevLNFiNqfJP_4core5sliceSNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13CompSavedMeta20sort_unstable_by_keymNCNvNtBz_7analyze12analyze_oncesh_0EBz_ -_RINvMNtCsevLNFiNqfJP_4core5sliceSNtNtCsd5p0HaiaiO6_11weavepy_jit2ir8OsrEntry20sort_unstable_by_keymNCNvNtBz_7analyze12analyze_oncesa_0EBz_ _RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit2ir6TBlockEENtNtNtB11_3ops4drop4Drop4dropB1C_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit16never_ran_blocks0E0zEB1y_ _RNvMs4_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB5_5ESlot8is_plain -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12obj_recv_ref -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB2_9PathArena5names -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze17const_slice_shape -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower9load_attr -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower16load_method_site -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7h_build -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11load_method -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower15load_attr_plain -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline14method_call_pc _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBG_6string6StringEECsd5p0HaiaiO6_11weavepy_jit _RNvCs5HK7yca7OMW_10weavepy_vm14note_type_site -_RNvXs16_NtCsd5p0HaiaiO6_11weavepy_jit2irNtB6_14ResolvedGlobalNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjThmmEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertCsd5p0HaiaiO6_11weavepy_jit _RNvXsG_NtCskibSv91bgl1_9hashbrown3mapINtB5_4IterjuENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4nextCsd5p0HaiaiO6_11weavepy_jit -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze7PairSrcINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE3getjEBT_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214probe_obj_live -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s2_0B7_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier220attr_fingerprint_obj.llvm.10617736694814397161 -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0sa_0B7_ -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionTmbEEE10initializeNCINvB1a_11get_or_initNCNvNtCsd5p0HaiaiO6_11weavepy_jit6engine19generic_share_limit0E0zE0E0B32_.llvm.13143382369088262339 -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5spillB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4slotB4_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E9clear_regB4_ -_RNvNtCs89hHMyD40Kn_15weavepy_codegen4fold3alu -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze9lower_bin -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionTmbEEE10initializeNCINvB2_11get_or_initNCNvNtCsd5p0HaiaiO6_11weavepy_jit6engine19generic_share_limit0E0zEB2e_ -_RNvMs9_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_10DirectSite4fill -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11direct_body -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower5leave _RNvCs5HK7yca7OMW_10weavepy_vm20method_site_in_place -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17quiet_native_step _RINvYINtNtNtCsevLNFiNqfJP_4core3ops5range5RangejENtNtNtNtBa_4iter6traits8iterator8Iterator8try_folduNCINvNvBL_3any5checkjNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_onces2_0E0INtNtB8_12control_flow11ControlFlowuEEB21_ _RINvMNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree6appendINtNtB5_4node7NodeRefNtNtBW_6marker5OwnedjNtNtB5_7set_val9SetValZSTNtB1g_14LeafOrInternalE9bulk_pushINtNtB5_17dedup_sorted_iter15DedupSortedIterjB1z_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB9_3vec9into_iter8IntoIterjENCINvMse_NtB5_3setINtB4O_8BTreeSetjE16from_sorted_iterB46_E0EENtNtB9_5alloc6GlobalECsd5p0HaiaiO6_11weavepy_jit -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215probe_list_lane -_RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s_0Bb_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier218probe_method_entry -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s4_0B7_ -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s0_0B7_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit6engine6op_mix _RNvMs2_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB5_9CtorState10field_lane -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit21run_switched_directly -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower16compare_fallback -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower7compare -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower8truth_of -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_site_leaf -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8h_method -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline5admit -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit5StateEBF_ _RNvMs2_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7recordsNtB5_9DirectRec9take_slot -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm6fsetcc -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE12contains_keyjECsd5p0HaiaiO6_11weavepy_jit -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s1_0B7_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215probe_dict_lane -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze16MethodResolutionE7or_elseNCNvBK_13step_abstracts5_0EBM_ _RNvMs2_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB5_9CtorState12stored_field -_RNvMs9_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_10DirectSite7promote -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit19run_pushed_directly -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower6copy16 -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7h_store -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit9attr_miss -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11method_slow _RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetmINtNtBK_4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEEEE11extend_withCsd5p0HaiaiO6_11weavepy_jit _RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir8OsrEntryE8push_mutBJ_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14MethodSiteMetaEEEB1y_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12AttrSiteMetaEEB1c_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit2ir6TBlockEEEB1y_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13MathGuardMetaEEB1c_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7h_clone _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTmmmmEE8grow_oneCs89hHMyD40Kn_15weavepy_codegen -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3mov _RINvMs0_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6retainNCINvMs_NtB8_3setINtB2J_7HashSetmBQ_E6retainNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze22entry_unassigned_reads0E0EB3p_ _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetmINtNtBQ_4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEEENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalECsd5p0HaiaiO6_11weavepy_jit _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell4CellINtNtBZ_6option6OptionjEEE4withNCNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_onces7_00uEB25_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit6engine11loop_blocks _RNvYNCNKNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze7FAIL_PC0s_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB12_6option6OptionQIB1H_INtNtB12_4cell4CellIB1H_jEEEEEE9call_onceBa_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze26returns_none_syntactically -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze22entry_unassigned_reads -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15raised_in_place -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14site_leaf_fits _RNvNtCsd5p0HaiaiO6_11weavepy_jit5lower14build_function -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer10emit_block -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer9emit_stmt -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower14method_inlined -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12IterLoopMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecmENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCsd5p0HaiaiO6_11weavepy_jit -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir11GlobalGuardENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13CompSavedMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12AttrSiteMetaENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCs5HK7yca7OMW_10weavepy_vm _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir8OsrEntryENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12AttrSiteMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14CalleeSpanMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14MethodSiteMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13MathGuardMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsd5p0HaiaiO6_11weavepy_jit6engine13CompiledFrameECs5HK7yca7OMW_10weavepy_vm -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs89hHMyD40Kn_15weavepy_codegen2ir13DataFlowGraphECsd5p0HaiaiO6_11weavepy_jit -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtB4_6result6ResultNtNtCsd5p0HaiaiO6_11weavepy_jit6engine13CompiledFrameNtNtB12_7analyze10JitVerdictEINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectINtNtB2U_2rc2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEEEIB2j_NtNtB2U_5tier211MethodEntryEIB2j_NtNtB2n_6string6StringEEEB2U_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier29ArtifactsEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs89hHMyD40Kn_15weavepy_codegen2ir9SignatureECsd5p0HaiaiO6_11weavepy_jit -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsd5p0HaiaiO6_11weavepy_jit5lower7LowererEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier213GuardSnapshotEBF_ -_RINvYINtNtNtCsevLNFiNqfJP_4core5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir6TBlockENtNtNtNtBa_4iter6traits8iterator8Iterator8try_folduNCINvNvXs_NtNtB1v_8adapters9enumerateINtB2o_9EnumeratepEB1p_8try_fold9enumerateRBJ_uINtNtNtBa_3ops12control_flow11ControlFlowuENCINvNvB1p_3any5checkTjB3v_ENCNvMs2_NtBN_6engineNtB4R_9JitEngine21compile_tfunc_methodsse_0E0E0B3A_EBN_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records11note_direct _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEE8grow_oneB1z_ -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjTmmEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertCsd5p0HaiaiO6_11weavepy_jit _RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjjINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE12contains_keyjECsd5p0HaiaiO6_11weavepy_jit -_RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB5_8JitState23method_native_table_for -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier225scalar_field_update_shape -_RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB5_13GuardSnapshot3new -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier224scalar_field_update_plan -_RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB5_8JitState16native_table_for -_RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s2_0Bb_ -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCsd5p0HaiaiO6_11weavepy_jit6engine10attr_bound0E0zE0E0B2m_.llvm.13143382369088262339 _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB28_8JitState12get_compileds1_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB3e_8for_each4callNtNtB2a_6object6ObjectNCINvMsk_NtB1r_3vecINtB4M_3VecB4h_E14extend_trustedBN_E0E0EB2a_ -_RINvMsg_NtNtNtCsevLNFiNqfJP_4core4iter8adapters7flattenINtB6_13FlattenCompatINtNtB8_3map3MapINtNtNtBc_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir6TBlockENCNvMs2_NtB1W_6engineNtB2G_9JitEngine21compile_tfunc_methodssf_0EIB1t_NtB1U_5TStmtEE13iter_try_folduNCINvNvXsi_B6_IBS_ppENtNtNtBa_6traits8iterator8Iterator8try_fold7flattenB3B_uINtNtNtBc_3ops12control_flow11ControlFlowuENCINvNvB4v_3any5checkRB3G_NCB2A_sg_0E0E0B5p_EB1W_ _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterTmNtNtCs89hHMyD40Kn_15weavepy_codegen2ir7FuncRefNtNtCsd5p0HaiaiO6_11weavepy_jit6engine10DirectLeafEENCNvMs2_B39_NtB39_9JitEngine21compile_tfunc_methodssb_0ENtNtB3b_5lower10LeafTargetEB3b_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB16_6object10PyFunctionEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapINtNtNtB2I_5slice4iter4IterTNtB1E_6ObjectIB12_NtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEEENCNvMs6_NtB16_5tier2NtB5g_8JitState12get_compileds4_0EE9from_iterB16_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_5slice4iter4IterNtNtB8_6string6StringENCNvMs6_NtB17_5tier2NtB3Z_8JitState12get_compileds1_0EE9from_iterB17_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm5tier212NativeCalleeEEINtB4_18SpecFromIterNestedB13_INtNtNtNtB18_4iter8adapters3map3MapINtNtNtB18_5slice4iter4IterNtB1H_11MethodEntryENCNvMs6_B1H_NtB1H_8JitState23method_native_table_for0EE9from_iterB1J_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTNtNtB6_6string6StringNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapINtNtNtB2K_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir11GlobalGuardENCNvMs6_NtB1r_5tier2NtB4Y_8JitState12get_compileds0_0EE9from_iterB1r_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm5tier212NativeCalleeEEINtB4_18SpecFromIterNestedB13_INtNtNtNtB18_4iter8adapters3map3MapINtNtNtB18_5slice4iter4IterTNtNtB1J_6object6ObjectINtNtB1J_2rc2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEEENCNvMs6_B1H_NtB1H_8JitState16native_table_for0EE9from_iterB1J_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit6engine14is_scalar_leaf -_RNvMs2_NtCsd5p0HaiaiO6_11weavepy_jit6engineNtB5_9JitEngine7release -_RNvMs2_NtCsd5p0HaiaiO6_11weavepy_jit6engineNtB5_9JitEngine21compile_tfunc_methods -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze16MethodResolutionE7or_elseNCNvBK_10emit_instrs4_0EBM_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionjE7inspectNCINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11direct_callKb1_E0EBZ_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionbE7or_elseNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6h_calls2_0EBY_ _RINvMsN_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree4nodeINtB6_6HandleINtB6_7NodeRefNtNtB6_6marker3MutjjNtB1n_4LeafENtB1n_4EdgeE16insert_recursingNtNtBc_5alloc6GlobalNCNvMs4_NtNtB8_3map5entryINtB2N_11VacantEntryjjE12insert_entry0ECsd5p0HaiaiO6_11weavepy_jit -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtNtCs5HK7yca7OMW_10weavepy_vm5tier213GuardSnapshotE9drop_slowBH_ -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecNtNtCs5HK7yca7OMW_10weavepy_vm5tier29MathGuardEE9drop_slowBX_ -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtNtCs5HK7yca7OMW_10weavepy_vm5tier29ArtifactsE9drop_slowBH_ -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtNtCsd5p0HaiaiO6_11weavepy_jit6engine13CompiledFrameE9drop_slowCs5HK7yca7OMW_10weavepy_vm -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEE9drop_slowBX_ -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm5tier212NativeCalleeEEE9drop_slowB1z_ -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectINtNtBY_2rc2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEEEE9drop_slowBY_ -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8imul_imm -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4bxor _RINvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB5_15FuncInstBuilder4loadlECsd5p0HaiaiO6_11weavepy_jit -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCsd5p0HaiaiO6_11weavepy_jit6engine10attr_bound0E0zEB1y_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze9cmp_check -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze14emit_attr_lane -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze22resolve_dict_container -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11method_call -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower13method_kernel -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_store_slow -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_truth_stack -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer9emit_exit -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer15list_helper_sig -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer5guard -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBK_6object9BuiltinFnEE8push_mutBK_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5HK7yca7OMW_10weavepy_vm9InlineActEBD_.llvm.2449273802214287896 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm5FrameEEEB1y_ _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot8get_held -_RNvMs_NtCsd5p0HaiaiO6_11weavepy_jit2irNtB4_9StrMethod9from_name -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records11finish_rest -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs89hHMyD40Kn_15weavepy_codegen2ir4TypeE8grow_oneBQ_ _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTlsEE8grow_oneCs5HK7yca7OMW_10weavepy_vm -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapTmmENtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBV_6fxhash8FxHasherEE6insertBV_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueBN_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBR_6fxhash8FxHasherEE6insertBR_ _RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtB5_3VecTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5BlockNtNtB10_3ssa7EdgeRefEENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEB10_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueBQ_EE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BQ_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBU_6fxhash8FxHasherEE0EBU_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTmmENtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BU_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBY_6fxhash8FxHasherEE0EBY_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen3ssaNtB2_3Ssa10read_entry _RNvNtCs89hHMyD40Kn_15weavepy_codegen3ssa7resolve _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6filter6FilterINtNtNtNtB6_11collections5btree3set8IntoItermENCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze11root_livein0EE9from_iterB3e_ _RNvMsz_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_8IntoItermNtNtB7_7set_val9SetValZSTE10dying_nextCsd5p0HaiaiO6_11weavepy_jit.llvm.5823409500495256553 _RNvMsi_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_8BTreeMapmNtNtB7_7set_val9SetValZSTE6insertCsd5p0HaiaiO6_11weavepy_jit -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen7builderNtB2_15FunctionBuilder7use_var _RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze8LoopInfoENtNtNtNtBb_4iter6traits8iterator8Iterator3anyNCNvBS_12analyze_onces3_0EBU_ _RNvMs3_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB5_2SE8is_plain _RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze11root_livein -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15attr_stack_slow -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_attr_stack _RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecNtCs5HK7yca7OMW_10weavepy_vm9FieldSlotE16into_boxed_sliceBG_ _RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan2OpE16into_boxed_sliceBI_ -_RNvCs5HK7yca7OMW_10weavepy_vm17call_site_builtin _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan2OpE8grow_oneBQ_ _RNvXsV_NtNtCsevLNFiNqfJP_4core3cmp5implsjNtB7_3Ord5clamp _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTRemEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCs5HK7yca7OMW_10weavepy_vm _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB1a_11get_or_initNCNvMs7_B2V_NtB2V_11Interpreter14leaf_init_eval0E0zE0E0B2V_.llvm.6970241935485176696 -_RNvNtCs5HK7yca7OMW_10weavepy_vm3gil15maybe_yield_gil _RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB5_7Builder8push_new _RNvNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan5build _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionbE7or_elseNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB11_11Interpreter9leaf_coreKb1_Esk_0EB11_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13register_lazy -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit17fill_method_cache -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower12release_slot -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower11inline_body -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline9inline_op -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline16callee_never_ran -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower13inline_return -_RNvMNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB2_8FnLayout2of -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4PlanEBH_.llvm.4650670488983980854 _RNvCs5HK7yca7OMW_10weavepy_vm20leaf_kwonly_defaults _RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter9leaf_evalKb0_KBZ_EB6_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4PlanE8grow_oneBS_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline11InlineFrameE8grow_oneBS_ -_RINvXs_NtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elembNtB5_12SpecFromElem9from_elemNtNtB9_5alloc6GlobalECs5HK7yca7OMW_10weavepy_vm _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5BlockEEINtB4_18SpecFromIterNestedB13_INtNtNtNtB18_4iter8adapters3map3MapINtNtNtB18_5slice4iter4IterbENCNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB45_5Lower11inline_bodys5_0EE9from_iterB47_ _RINvMs8_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB8_11Interpreter12leaf_run_retKb0_KB1f_KB1f_EB8_.llvm.3987546058129701445 _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCINvMs7_B28_NtB28_11Interpreter9leaf_evalKb0_KB48_E0E0zEB28_ -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower10unpack_ref -_RNvCs5HK7yca7OMW_10weavepy_vm19builtin_method_site -_RNvCs5HK7yca7OMW_10weavepy_vm15slot_field_note _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14pure_leaf_call _RNvMs2_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7recordsNtB5_9DirectRec4grow -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records14h_direct_leave _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapPNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectTINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEbINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakBO_EEINtNtB1E_4hash18BuildHasherDefaultNtNtB31_5tier218CodeIdentityHasherEE6insertB31_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTPNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectTINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEbINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakBR_EEEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_B1B_INtNtB1H_4hash18BuildHasherDefaultNtNtB34_5tier218CodeIdentityHasherEE0EB34_ -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE3getmEBT_ -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s_0B7_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215callee_ret_lane _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBa_11collections4hash3map7HashMapPNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectTINtNtBZ_6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEbINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakB2c_EEINtNtBZ_4hash18BuildHasherDefaultNtNtB49_5tier218CodeIdentityHasherEEEE4withNCNvB5m_15callee_ret_infos2_0IB2Y_B2W_EEB49_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBa_11collections4hash3map7HashMapPNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectTINtNtBZ_6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEbINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakB2c_EEINtNtBZ_4hash18BuildHasherDefaultNtNtB49_5tier218CodeIdentityHasherEEEE4withNCNvB5m_15callee_ret_info0IB2Y_TB2X_bEEEB49_ _RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB5_7Builder12canonicalize _RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB5_7Builder8constant -_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBe_11collections4hash3map7HashMapPNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectTINtNtB1j_6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEbINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakB2w_EEINtNtB1j_4hash18BuildHasherDefaultNtNtB4u_5tier218CodeIdentityHasherEEEuE16get_or_init_slowNvNvB5I_14RET_LANE_CACHE27___rust_std_internal_init_fnEB4u_ _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm5tier214RET_LANE_CACHE00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB15_6option6OptionQIB1K_INtNtB15_4cell7RefCellINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapPNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectTIB1K_NtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEbINtNtBa_2rc4WeakB3u_EEINtNtB15_4hash18BuildHasherDefaultNtB8_18CodeIdentityHasherEEEEEEE9call_onceBa_.llvm.10617736694814397161 -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBa_11collections4hash3map7HashMapPNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectTINtNtB19_6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEbINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakB2m_EEINtNtB19_4hash18BuildHasherDefaultNtNtB4k_5tier218CodeIdentityHasherEEEEB4k_.llvm.16112649145315725652 _RINvMsN_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree4nodeINtB6_6HandleINtB6_7NodeRefNtNtB6_6marker3MutmNtNtB8_7set_val9SetValZSTNtB1n_4LeafENtB1n_4EdgeE16insert_recursingNtNtBc_5alloc6GlobalNCNvMs4_NtNtB8_3map5entryINtB3b_11VacantEntrymB1E_E12insert_entry0ECsd5p0HaiaiO6_11weavepy_jit _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4ushr _RINvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB5_15FuncInstBuilder7sload32lECs5HK7yca7OMW_10weavepy_vm _RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15analyze_for_ret -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze14native_getitem -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_subscr_ref -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_container -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14leaf_call_lane -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower9container -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower12field_guards -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower11inline_call -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline15builtin_in_line -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer3pop -_RINvCs5HK7yca7OMW_10weavepy_vm9push_growNtNtB2_6object6ObjectEB2_ -_RNvMsx_Cs5HK7yca7OMW_10weavepy_vmNtB5_8CallSlot3hit -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16settle_lazy_cold -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records11left_slowly -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records14left_uncleanly _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjTjmENtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCs5HK7yca7OMW_10weavepy_vm -_RNvMs1_NtCs7usbkSbEEZs_16weavepy_compiler8bytecodeNtB5_6OpCode4name _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecjEEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0ECsd5p0HaiaiO6_11weavepy_jit _RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjTjmENtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE7get_mutjECs5HK7yca7OMW_10weavepy_vm -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215callee_ret_infos0_0B5_ -_RNCINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11direct_doneKb1_Es0_0B6_ -_RNvXs1_NtNtNtCsevLNFiNqfJP_4core3ops8function5implsQNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtBW_8JitState12get_compileds0_0INtB7_5FnMutTRNtNtCsd5p0HaiaiO6_11weavepy_jit2ir11GlobalGuardEE8call_mutBY_ _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4urem -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower9call_with -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower19field_store_in_line -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower12setter_store -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer14pin_helper_sig -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline9h_release -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower11field_place _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTjjINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcSbEEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBN_ -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjjINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcSbEEEEEB2l_.llvm.4890245414193407415 -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215callee_ret_infos1_0B5_ -_RNCNvMNtCs89hHMyD40Kn_15weavepy_codegen3ssaNtB4_3Ssa10append_arg0B6_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjjINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcSbEEEEE4withNCNvNtB2a_9frame_jit7in_loop0bEB2a_ _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13mod_attr_note -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastSbEB4_ _RNvYNCNKNvNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7in_loop4MEMO00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB18_6option6OptionQIB1N_INtNtB18_4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjjINtNtBc_2rc2RcSbEEEEEEEE9call_onceBc_ -_RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15analyze_for_ret0B5_.llvm.2091680242001868680 _RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15analyze_for_rets_0B5_.llvm.2091680242001868680 -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze16infer_store_attr -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit17finished_in_place -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records11ctor_direct -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_local_method _RNCINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11direct_doneKb1_Es_0B6_ -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11flush_local -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower16store_subscr_ref _RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15attr_miss_quicks_0B5_ -_RNvXsB_NtNtCsevLNFiNqfJP_4core5slice3cmpmNtB5_13SliceContains14slice_contains -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214list_elem_lane -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_binop_site -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6h_call0B5_ -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3div -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fmul -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze22resolve_list_container -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_attr_local _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8len_fast -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower9build_map -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_truth_local -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_site_type -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14field_hit_slow -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit20fused_function_attrs -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_build_map -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer14emit_int_arith -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer9def_local -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12AttrSiteMetaE8push_mutBJ_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12AttrSiteMetaE8grow_oneBQ_ -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionlEE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit20inst_deferred_offset0E0zE0E0B2Z_.llvm.6970241935485176696 -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionlEE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit20inst_deferred_offset0E0zEB2b_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14class_poly_hit -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15class_poly_note _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectINtNtBG_2rc2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEEEBG_.llvm.4650670488983980854 -_RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_subscr_hotKm0_EB4_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins20sum_numeric_sequence -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins22sum_small_int_sequence -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower7call_kw -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_site_native -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_gen_return -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower15inline_callable -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline16h_inline_builtin -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTmIBC_INtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEEEEB1E_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4PlanEEB1e_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6CachesEBF_ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17leaf_pure_builtin -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11do_sum_call -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_info -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier217method_call_sites -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15builtin_counted0E0zE0E0B2m_.llvm.6970241935485176696 -_RNvNtCs89hHMyD40Kn_15weavepy_codegen4fold7is_bool -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder7uextend -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15builtin_counted0E0zEB1y_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier211guards_hold -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier218global_guards_hold _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtCs5HK7yca7OMW_10weavepy_vm5tier27JitBufsEE4withNCNvB1x_7put_u640uEB1z_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtCs5HK7yca7OMW_10weavepy_vm5tier27JitBufsEE4withNCNvB1x_7put_u320uEB1z_ _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm5tier28JIT_BUFS00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtBY_6option6OptionQIB1D_INtNtBY_4cell7RefCellNtB8_7JitBufsEEEEE9call_onceBa_ -_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtCs5HK7yca7OMW_10weavepy_vm5tier27JitBufsEuE16get_or_init_slowNvNvB1R_8JIT_BUFS27___rust_std_internal_init_fnEB1T_ -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtCs5HK7yca7OMW_10weavepy_vm5tier27JitBufsEEB1J_.llvm.16112649145315725652 -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15attr_local_slow -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier27CallCtxEBF_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier213CompiledEntryEBF_ -_RNvMs2_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower18inline_python_call -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18core_init_on_frame -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19sum_exact_int_range -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower11list_append _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_list_append _RNvMs2_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_6Native11call_chunks -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit9slot_note -_RNvMs9_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_10DirectSite9fill_leaf -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14leaf_site_call _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14compile_chunks -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower5is_op _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12chunk_ranges -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower8identity -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15h_for_iter_pair -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit9h_call_kw -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_store_attr -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_site_kernel -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower12operand_addr -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline11bind_levels.llvm.2449273802214287896 _RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecyE16into_boxed_sliceCs5HK7yca7OMW_10weavepy_vm _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs5HK7yca7OMW_10weavepy_vm5tier28SiteArgsENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBJ_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier211MethodEntryEBF_.llvm.4650670488983980854 -_RNvNtCs5HK7yca7OMW_10weavepy_vm13leaf_builtins13jit_method_op -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17shared_cell_index -_RNvMsi_Cs5HK7yca7OMW_10weavepy_vmNtB5_8SumState6finish -_RNvMsi_Cs5HK7yca7OMW_10weavepy_vmNtB5_8SumState7entered -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTmNtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline9FieldMemoEE8grow_oneBU_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5HK7yca7OMW_10weavepy_vm5tier211MethodEntryE8grow_oneBQ_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBU_6string6StringEB1m_EmNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCs5HK7yca7OMW_10weavepy_vm -_mi_prim_decommit -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBX_6string6StringEB1p_EmEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_mNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs5HK7yca7OMW_10weavepy_vm -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215attr_site_guard0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215attr_site_guard -_RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s8_0Bb_ -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s3_0B7_ -_mi_os_zalloc -_mi_os_alloc -_mi_os_has_virtual_reserve -_RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB1M_6string6StringEB2e_EECs5HK7yca7OMW_10weavepy_vm _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTjjyEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1G_6filter6FilterINtNtB1G_9enumerate9EnumerateINtNtNtB1K_5slice4iter4IterNtNtCs7usbkSbEEZs_16weavepy_compiler8bytecode11InstructionEENCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12chunk_ranges0ENCB4G_s_0EE9from_iterB4K_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecjEINtB2_18SpecFromIterNestedjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters5chain5ChainINtNtB1z_6filter6FilterINtNtNtB1D_3ops5range5RangejENCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12chunk_rangess2_0EINtNtNtB1D_5array4iter8IntoIterjKj1_EEE9from_iterB3i_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecINtNtNtCsevLNFiNqfJP_4core3ops5range5RangejEEINtB4_18SpecFromIterNestedB13_INtNtNtNtB1a_4iter8adapters3map3MapINtNtNtB1a_5slice4iter7WindowsjENCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12chunk_rangess4_0EE9from_iterB3r_ -_mi_arena_id_none -mi_arena_id_from_arena -mi_reserve_os_memory_ex2 -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fsub -__mi_stat_adjust_decrease_mt -_RNvCs5HK7yca7OMW_10weavepy_vm15class_attr_site -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze14escape_verdict -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter8sum_fast _RNvXs1i_NtCsevLNFiNqfJP_4core3fmtRxNtB6_7Display3fmtCs5HK7yca7OMW_10weavepy_vm -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier213rebuild_stack _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze14CompHeaderPlanINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertBS_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze14CompHeaderPlanEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0EBV_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTmReEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1G_6filter6FilterINtNtNtB1K_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14MethodSpanMetaENCNvNtCs5HK7yca7OMW_10weavepy_vm5tier213rebuild_stacks4_0ENCB44_s5_0EE9from_iterB48_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTjNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze14CompHeaderPlanEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map4IterjB13_ENCNvB15_12plan_rewrites5_0EE9from_iterB17_ _RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecTmReEE16extend_desugaredINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB19_6filter6FilterINtNtNtB1d_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14MethodSpanMetaENCNvNtCs5HK7yca7OMW_10weavepy_vm5tier213rebuild_stacks6_0ENCB3x_s7_0EEB3B_ -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen4foldNtB2_4Emit4push -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen4foldNtB2_4Emit3imm _RNvMs4_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7recordsNtB5_9DirectRec18extra_allows_clean _RNvMs4_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7recordsNtB5_9DirectRec12finish_extra -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_gen_yield -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13k_list_append -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit4h_is -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer13emit_attr_get -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline20h_inline_method_note -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline10leave_body -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline15h_inline_global -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline18inline_global_miss -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtB7_5boxed3BoxNtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline11MethodNotesEE8push_mutB13_ -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower10plain_call -_RNvCs5HK7yca7OMW_10weavepy_vm24inst_builtin_method_site -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter24call_object_with_globals -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4fimm _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmuEE12remove_entryNCINvNtB8_3map14equivalent_keymmuE0ECsd5p0HaiaiO6_11weavepy_jit -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier211split_index -_RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB5_7Builder11store_local -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8f64const -_RNvXs1_NtNtNtCsevLNFiNqfJP_4core4iter8adapters6filterINtB5_6FilterINtNtNtBb_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze5ESlotENCNvB1u_10emit_instrs5_0ENtNtNtB9_6traits8iterator8Iterator5countB1w_ _RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze26returns_self_syntactically -_RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15analyze_for_rets0_0B5_.llvm.2091680242001868680 -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_unpack_ref -_RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_subscr_hotKm3_EB4_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze13kw_call_names -_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtNtCs5HK7yca7OMW_10weavepy_vm5tier211DirectEntryE9drop_slowBH_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftNtNtCsd5p0HaiaiO6_11weavepy_jit2ir8OsrEntryNCINvMB8_SB1m_20sort_unstable_by_keymNCNvNtB1q_7analyze12analyze_onces9_0E0EB1q_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTjIBw_NtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4PlanEEE8push_mutBR_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier211DirectEntryEBF_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline13h_inline_call -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer12emit_int_cmp -_RNvMs1_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit2ir14MethodSiteMetaEE6resizeB1l_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB14_6string6StringENtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeIBC_TB1w_mEEbEEEB1X_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm5tier212NativeCalleeEEB11_.llvm.4650670488983980854 -_RNvCs5HK7yca7OMW_10weavepy_vm14code_call_slot -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_infos2_0B5_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_infos5_0B5_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_infos_0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216inline_fields_of -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216arm_method_guard -_RNvMs19_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB6_5EntrymINtNtCs1C1lLj4PWSY_5alloc3vec3VecjEE10or_defaultCsd5p0HaiaiO6_11weavepy_jit _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBc_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEEENCNvNtB2m_5tier218probe_method_entrys_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB3I_8for_each4callNtB38_8SiteArgsNCINvMsk_B1s_IB1q_B4L_E14extend_trustedBN_E0E0EB2m_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm5tier28SiteArgsEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2q_5slice4iter4IterTmIBU_INtNtB2q_6option6OptionNtNtB17_6object6ObjectEEEENCNvB15_18probe_method_entrys_0EE9from_iterB17_ -_RNvMNtCskibSv91bgl1_9hashbrown11rustc_entryINtNtB4_3map7HashMapmINtNtCs1C1lLj4PWSY_5alloc3vec3VecjEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE11rustc_entryCsd5p0HaiaiO6_11weavepy_jit _RNvMs1_NtCs5HK7yca7OMW_10weavepy_vm11frame_slotsNtB5_10FrameStack7reserve _RNvCs5HK7yca7OMW_10weavepy_vm13site_resolved -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB2_9PathArena3seg -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower13binary_helper -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertB1r_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTmNtNtCs1C1lLj4PWSY_5alloc6string6StringENtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_B1v_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0EB1z_ _RNvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecjEEE14insert_no_growCsd5p0HaiaiO6_11weavepy_jit -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEEEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0EB1u_ _RNvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTTmNtNtCs1C1lLj4PWSY_5alloc6string6StringENtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEE14insert_no_growB1y_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB2m_3rev3RevINtNtNtB2q_5slice4iter4IterNtNtB17_7analyze2SEEENCNvB3P_13step_abstracts6_0EE9from_iterB17_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer14stage_elements -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer11emit_dyn_op _RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable7ipnsortmNvYmNtNtB8_3cmp10PartialOrd2ltECs89hHMyD40Kn_15weavepy_codegen _RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12analyze_onces4_0B5_ _RNvMNtCskibSv91bgl1_9hashbrown11rustc_entryINtNtB4_3map7HashMapTmNtNtCs1C1lLj4PWSY_5alloc6string6StringENtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE11rustc_entryB1I_ _RNvMNtCskibSv91bgl1_9hashbrown11rustc_entryINtNtB4_3map7HashMapmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB15_6string6StringEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE11rustc_entryCsd5p0HaiaiO6_11weavepy_jit -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4PlanE8push_mutBL_ _RINvYINtNtNtCsevLNFiNqfJP_4core5slice4iter4IterNtNtCs7usbkSbEEZs_16weavepy_compiler8bytecode11InstructionENtNtNtNtBa_4iter6traits8iterator8Iterator8try_folduNCINvNvXs_NtNtB1M_8adapters9enumerateINtB2F_9EnumeratepEB1G_8try_fold9enumerateRBJ_uINtNtNtBa_3ops12control_flow11ControlFlowuENCINvNtB2H_6filter15filter_try_foldTjB3M_EuB3R_NCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212loop_headers0NCINvNtB2H_10filter_map19filter_map_try_foldB57_juB3R_NCB5l_s_0NCINvNtB2H_3map12map_try_foldjmuB3R_NCB5l_s0_0NCINvNvB1G_3all5checkmNCNvMs6_B5n_NtB5n_8JitState12get_compileds5_0E0E0E0E0E0B3R_EB5p_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze16settle_container -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline13h_inline_exit -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math7builtin -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math5build -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower16stack_store_attr -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13spread_direct -_RNvMs2_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_6Native9note_fail -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsd5p0HaiaiO6_11weavepy_jit2ir5TFuncECs5HK7yca7OMW_10weavepy_vm -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjIBC_NtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4PlanEEEEB1k_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEEB1y_.llvm.4650670488983980854 -_RINvCs5HK7yca7OMW_10weavepy_vm9push_growjEB2_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter27try_inline_call_ex_keywords -_RINvYINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterjENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator8try_folduNCINvNvBX_3any5checkRjNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12plan_rewrites0_0E0INtNtNtB15_3ops12control_flow11ControlFlowuEEB2u_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18elementtree_native9construct -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit3runKb1_EB6_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_infos9_0B5_ _RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_infos7_0B5_ -_RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB5_8JitState19resolve_native_func -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_infos0_0B5_ _RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_infosb_0B5_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterINtNtBc_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEENCNCNvNtB1N_5tier218probe_method_entrys_00ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB3a_8for_each4callIB1o_TyINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtB2z_11InlineFieldEEENCINvMsk_B4n_IB4l_B4d_E14extend_trustedBN_E0E0EB1N_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecINtNtCsevLNFiNqfJP_4core6option6OptionTyIBU_NtNtCs5HK7yca7OMW_10weavepy_vm5tier211InlineFieldEEEEINtB4_18SpecFromIterNestedB13_INtNtNtNtB18_4iter8adapters3map3MapINtNtNtB18_5slice4iter4IterIB14_NtNtB1P_6object6ObjectEENCNCNvB1N_18probe_method_entrys_00EE9from_iterB1P_ -_RNvMs2_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB5_5Owned7release _RINvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB5_15FuncInstBuilder7sload32lECsd5p0HaiaiO6_11weavepy_jit _RINvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB5_15FuncInstBuilder6uload8lECsd5p0HaiaiO6_11weavepy_jit -_RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze11infer_blocks2_0B5_ -_RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15analyze_for_rets8_0B5_.llvm.2091680242001868680 _RNvMsf_NtCs5HK7yca7OMW_10weavepy_vm4syncINtB5_7GilCellAjj3_E10borrow_mutB7_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecyE8grow_oneCs89hHMyD40Kn_15weavepy_codegen -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object11empty_cells _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier221native_exit_writeback -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier28take_u32 -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214entry_local_ok -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214enter_compiled -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier28take_u64 _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier221drain_activation_pins _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier24pack _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable9quicksort9quicksortmNvYmNtNtBa_3cmp10PartialOrd2ltECs89hHMyD40Kn_15weavepy_codegen @@ -8984,162 +7314,50 @@ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10 _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_19current_compile_gen0yEBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell4CellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs5HK7yca7OMW_10weavepy_vm5tier23PinEEE4withNCNvB21_8put_pins0uEB23_ _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm5tier210SPARE_PINS00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB11_6option6OptionQIB1G_INtNtB11_4cell4CellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtB8_3PinEEEEEE9call_onceBa_ -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell4CellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs5HK7yca7OMW_10weavepy_vm5tier23PinEEEB2e_.llvm.4890245414193407415 -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13global_len_of -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15class_poly_notes_0B5_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer14emit_const_pin -_RNCINvNtCs5HK7yca7OMW_10weavepy_vm8builtins9method_kwNvB4_9str_splitEs_0B6_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14direct_call_kw -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower8contains _RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower5unary -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer22call_method_helper_sig -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer16split_field_addr -_RNvMs2_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB5_10SharedKeys12names_before _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort18small_sort_networkjNvYjNtNtBa_3cmp10PartialOrd2ltECsd5p0HaiaiO6_11weavepy_jit -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21core_local_attr_chain -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable9quicksort9quicksortjNvYjNtNtBa_3cmp10PartialOrd2ltECsd5p0HaiaiO6_11weavepy_jit -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_infos3_0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215attr_chain_step -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod8category -_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable7ipnsortjNvYjNtNtB8_3cmp10PartialOrd2ltECsd5p0HaiaiO6_11weavepy_jit _RINvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB5_15FuncInstBuilder7uload32lECsd5p0HaiaiO6_11weavepy_jit -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fdiv -_RNvMNtCs5HK7yca7OMW_10weavepy_vm8gen_fastNtB4_11Interpreter13gen_fast_step -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9str_splitINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1y_EEE4callB6_ -_RNvYNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types22install_object_dunders19object_subclasshookINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RINvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15exclude_span_pcNtNtB4_2ir14CalleeSpanMetaEB4_ -_RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15analyze_for_rets1_0B5_.llvm.2091680242001868680 -_RINvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15exclude_span_pcNtNtB4_2ir14MethodSpanMetaEB4_ _RNvMsa_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_6Engine7release -_RNvXs8_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_10DirectSiteNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8AttrSiteEEB1e_.llvm.4650670488983980854 -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0sb_0B7_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier221probe_stack_iter_lane -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier220decompose_live_loops _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_13try_enter_osrs3_0uEBZ_ _RINvCs1HhT8J6xvUy_4zmij5writedEB2_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTmNtNvNtCs5HK7yca7OMW_10weavepy_vm5tier220decompose_live_loops8LiveLoopEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters5chain5ChainIB2H_INtNtB2L_3map3MapINtNtB2L_6filter6FilterINtNtNtB2P_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13RangeLoopMetaENCB15_0ENCB15_s_0EIB3E_IB3V_IB4i_NtB4K_12ListLoopMetaENCB15_s0_0ENCB15_s1_0EEIB3E_IB3V_IB4i_NtB4K_12IterLoopMetaENCB15_s2_0ENCB15_s3_0EEE9from_iterB19_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer17emit_dyn_attr_get -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer13emit_call_dyn _RNvMs0_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB5_6Region5depth -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10h_pop_slow -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15h_make_function -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_pop_checked _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects5PieceENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBL_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15spread_on_frame _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records12release_rest _RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze2SEENtNtNtNtBb_4iter6traits8iterator8Iterator3allNvMs3_BS_BQ_8is_plainEBU_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15fuse_int_result -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13prologue_cell -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit21h_make_function_attrs -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit19call_activation_out -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_inst_native -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit18h_store_subscr_ref -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower16inst_native_call -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15attr_miss_raise -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_load_closure -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer20emit_push_global_obj _RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB1a_5error12RuntimeErrorEEEB1a_.llvm.4890245414193407415 _RINvXsb_NtNtCs1C1lLj4PWSY_5alloc5boxed4iterINtB8_3BoxSNtCs5HK7yca7OMW_10weavepy_vm8LeafSiteEINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorBQ_E9from_iterINtNtNtB1z_8adapters3map3MapINtNtNtB1B_3ops5range5RangejENCNCINvMst_BS_NtBS_16CodeConstObjects11alloc_sitesBQ_NvMsK_BS_BQ_5emptyE0s0_0EEBS_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19core_leaf_site_call -_RNvCs5HK7yca7OMW_10weavepy_vm13leaf_site_set -_RINvCs5HK7yca7OMW_10weavepy_vm10h_list_setKm7_EB2_ -_RNvMsi_Cs5HK7yca7OMW_10weavepy_vmNtB5_8SumState3add _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter7repr_of -_RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter9leaf_evalKb0_Kb1_EB6_ _RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtB1a_6object14ReprGuardStateEEB1a_.llvm.4890245414193407415 _RINvNtCs5HK7yca7OMW_10weavepy_vm6object12repr_guardedNCNvMs7_B4_NtB4_11Interpreter7repr_ofs2_0EB4_ -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s9_0B7_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215probe_cell_lane -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockAbj80_E10initializeNCINvB1a_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17ascii_space_table0E0zE0E0B2r_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtCs5HK7yca7OMW_10weavepy_vm9SiteTableNtB1J_8LeafSiteEE10initializeNCINvB1a_11get_or_initNCINvMst_B1J_NtB1J_16CodeConstObjects11alloc_sitesB2j_NvMsK_B1J_B2j_5emptyE0E0zE0E0B1J_.llvm.6970241935485176696 -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE5countB9_ -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE7charsetB9_ -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE8snapshotB9_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtBZ_6object14ReprGuardStateEE4withNCINvB1E_12repr_guardedNCNvMs7_BZ_NtBZ_11Interpreter9stringify0Es0_0bEBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionNtNtBZ_5error12RuntimeErrorEEE4withNCNvNtBZ_6object15take_repr_error0B1C_EBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtBZ_6object14ReprGuardStateEE4withNCINvB1E_12repr_guardedNCNvMs7_BZ_NtBZ_11Interpreter9stringify0E0bEBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtBZ_6object14ReprGuardStateEE4withNCINvB1E_12repr_guardedNCNvMs7_BZ_NtBZ_11Interpreter9stringify0Es_0uEBZ_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecTbmEEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1L_5slice4iter4IterNtNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB2Z_5Lower13method_kernel3ArgENCNvMsc_B2Z_B3B_13method_kernel0EE9from_iterB31_ mi_arenas_page_singleton_alloc -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBN_6object10PyFunctionEE6filterNCNvMs7_BN_NtBN_11Interpreter16core_pure_method0EBN_ -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4ishl -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockAbj80_E10initializeNCINvB2_11get_or_initNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17ascii_space_table0E0zEB1D_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtCs5HK7yca7OMW_10weavepy_vm9SiteTableNtBW_8LeafSiteEE10initializeNCINvB2_11get_or_initNCINvMst_BW_NtBW_16CodeConstObjects11alloc_sitesB1w_NvMsK_BW_B1w_5emptyE0E0zEBW_ _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm6object10REPR_ERROR00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB12_6option6OptionQIB1H_INtNtBa_4sync7GilCellIB1H_NtNtBa_5error12RuntimeErrorEEEEEE9call_onceBa_.llvm.9250547820948799359 _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm6object10REPR_GUARD00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB12_6option6OptionQIB1H_INtNtBa_4sync7GilCellNtB8_14ReprGuardStateEEEEE9call_onceBa_.llvm.9250547820948799359 -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter14lazy_pure_pair -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit20subscr_raise_missing _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7LoweredEBF_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier221finish_deopted_callee -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214finish_deopted -_RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB5_8JitState21resolve_native_callee -_RNvXs2_NtNtCsevLNFiNqfJP_4core3num11float_parsedNtNtNtB9_3str6traits7FromStr8from_str _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_14note_osr_trips0bEBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_22try_call_native_directs2_0uEBZ_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer16emit_build_tuple _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftTmNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENCINvMB8_SB1m_20sort_unstable_by_keymNCNvNtB1s_5tier213rebuild_stacks3_0E0EB1s_ _RNvNtNtNtNtCsevLNFiNqfJP_4core3num3imp7dec2flt5parse12parse_number -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier212NativeCalleeEBF_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm9FrameRareEEEB1y_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter24run_py_exact_nofree_with _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17run_deopted_frame _RINvCs5HK7yca7OMW_10weavepy_vm10h_dict_getKm0_EB2_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_subscr_hotKm1_EB4_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze2SEEINtB4_18SpecFromIterNestedB13_INtNtB6_5drain5DrainB13_EE9from_iterB17_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14leaf_init_eval -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer15quad_helper_sig -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_store_deref -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15direct_call_out _RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_load_methods0_0B5_ _RNCNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB7_5Lower5unary0B9_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_contains_ref -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower12int_true_div -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit9h_call_ex -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer15inline_body_for -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer23emit_method_helper_call -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer13emit_attr_set -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline19h_inline_attr_local -_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneB1s_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB13_6object9BuiltinFnEIBC_NtB13_8LeafKindEbEEEB13_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11do_len_call _RNvCs5HK7yca7OMW_10weavepy_vm17slot_member_class.llvm.3987546058129701445 -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15store_fast_step -_RNvMsx_Cs5HK7yca7OMW_10weavepy_vmNtB5_8CallSlot8poly_hit _RINvMsm_NtCsevLNFiNqfJP_4core5arrayARej4_7try_mapINtNtNtB8_3ops9try_trait17NeverShortCircuitNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrENCINvMBO_BL_10wrap_mut_1By_NCNCNvNtNtB1w_6stdlib13functools_mod8lru_keys00E0EB1w_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object21bytearray_is_exported _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs5HK7yca7OMW_10weavepy_vm5tier29MathGuardE8grow_oneBQ_ -_RNCNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod8lru_type0s_0B9_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod18lru_flush_deferred -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod8lru_call -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod9lru_parts -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod12lru_make_key -_RNvMNtNtCsevLNFiNqfJP_4core4char7methodsc15is_alphanumeric -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE3getmECsd5p0HaiaiO6_11weavepy_jit -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockANtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrj4_E10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib13functools_mod8lru_keys0E0zE0E0B1L_.llvm.6970241935485176696 -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types20install_type_dunders12type_doc_get -_RNvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace10is_tracked -_RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState14is_tracked_obj -_RINvMs8_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB8_11Interpreter12leaf_run_retKb0_Kb1_KB1f_EB8_ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object9LeafProbeE6filterNCNvNtNtBM_6stdlib13functools_mod8lru_call0EBM_ -_RNvNtNtNtCsevLNFiNqfJP_4core7unicode12unicode_data1n11lookup_slow -_RNvNtNtNtCsevLNFiNqfJP_4core7unicode12unicode_data10alphabetic11lookup_slow _RNvXs0_NtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB7_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBZ_5types10TypeObjectEEINtB5_10SpecExtendBU_INtNtB7_9into_iter8IntoIterBU_EE11spec_extendBZ_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10os_process19register_at_fork_kw -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod10with_class.llvm.5678553137184841714 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod15native_new_pure _RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_Esq_0B8_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockANtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrj4_E10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib13functools_mod8lru_keys0E0zEBY_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCINvMs7_B28_NtB28_11Interpreter9leaf_evalKb0_Kb1_E0E0zEB28_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter8min_fast -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3neg -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4ineg -_RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15analyze_for_rets2_0B5_.llvm.2091680242001868680 _RNvMsa_NtCsevLNFiNqfJP_4core3fmtNtB5_9Formatter21write_formatted_parts _RNvMsa_NtCsevLNFiNqfJP_4core3fmtNtB5_9Formatter19pad_formatted_parts -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records10enter_more -_RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s5_0Bb_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan6subscr _RNvXs7_NtNtCsevLNFiNqfJP_4core3fmt5floatdNtB7_7Display3fmt _RINvNtNtCsevLNFiNqfJP_4core3fmt5float29float_to_decimal_common_exactdEB6_.llvm.3542948293797346914 _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer8leaf_for @@ -9147,367 +7365,126 @@ _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer12emit_call_py _RNvNtNtNtCsevLNFiNqfJP_4core3num3imp7flt2dec17digits_to_dec_str _RNvNvNtNtNtNtNtCsevLNFiNqfJP_4core3num3imp7flt2dec8strategy5grisu16format_exact_opt14possibly_round _RNvNtNtNtNtNtCsevLNFiNqfJP_4core3num3imp7flt2dec8strategy5grisu16format_exact_opt -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier222note_callee_roundtrips _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTmNtNtCs5HK7yca7OMW_10weavepy_vm5tier29SynthSeedEEBH_.llvm.4650670488983980854 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline10InlineSiteEEB1g_.llvm.4650670488983980854 -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_compare_site -_RNvMs_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB4_4Plan18comp_lane_for_body _RINvMsi_NtCskibSv91bgl1_9hashbrown3rawINtB6_12RawIterRangeTjNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze14CompHeaderPlanEE9fold_implNCINvXsG_NtB8_3mapINtB2a_4IterjBW_ENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4foldTjTRjRBW_EENCINvNtNtB2G_8adapters6filter11filter_foldB3C_B3A_NCNvMs_BY_NtBY_4Plan18comp_lane_for_body0NCINvNtB3S_3map8map_foldB3C_B3A_B3A_NCINvNvB2A_10max_by_key3keyB3C_jNCB4B_s_0E0NCINvNvB2A_6max_by4foldB3A_INvB5T_7compareB3C_jEE0E0E0E0B3A_EB10_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline17h_inline_for_iter -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCNvMs7_B28_NtB28_11Interpreter14leaf_init_eval0E0zEB28_ -_RINvMs8_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB8_11Interpreter12leaf_run_retKb0_Kb1_KB1j_EB8_ -_RNvXs8_NtNtCsevLNFiNqfJP_4core5slice5indexINtNtNtB9_3ops5range14RangeInclusivejEINtB5_10SliceIndexSPNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE5indexB1E_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17set_apply_inplace -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins20apply_set_inplace_op -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14truth_instance _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit5h_pop -_RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_contains_hotKm0_EB4_ _RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjNtNtCs5HK7yca7OMW_10weavepy_vm8builtins12SetInplaceOpEEEEB2j_.llvm.4890245414193407415 -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB12_6object11PyGeneratorEEEB12_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBG_6object11PyGeneratorEEBG_ -_RNvCs5HK7yca7OMW_10weavepy_vm20checked_repeat_count -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17leaf_instance_len -_RNvCs5HK7yca7OMW_10weavepy_vm17slot_member_unset _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot10set_getter -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16set_from_vm_iter _RNvNtCs5HK7yca7OMW_10weavepy_vm6object10repr_enter -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object11str_char_at _RNvNtCs5HK7yca7OMW_10weavepy_vm6object10repr_leave -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod20native_lru_tuple_key -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE21alternative_can_startB9_ -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE9req_holdsB9_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native7install -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native5build0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native5build _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeuNCNvNtBY_8builtins17set_apply_inplace0E0INtNtCsevLNFiNqfJP_4core6result6ResultuNtNtBY_5error12RuntimeErrorEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjNtNtCs5HK7yca7OMW_10weavepy_vm8builtins12SetInplaceOpEEEE4withNCNvB26_21take_deferred_set_ops0IB1w_B24_EEB28_ _RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState15forget_instance _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB16_16weakref_registry11WeakRefSlotEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapINtNtNtB2U_5slice4iter4IterINtB14_4WeakB1C_EENCNvMs3_B1E_NtB1E_15WeakRefRegistry14collect_strong0EE9from_iterB16_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod10count_core _RNvMNtCs5HK7yca7OMW_10weavepy_vm8gen_fastNtB4_11Interpreter16gen_native_yield -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer15method_leaf_for _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16SET_DEFERRED_OPS00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1a_6option6OptionQIB1P_INtNtB1a_4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjNtB8_12SetInplaceOpEEEEEEE9call_onceBa_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze17unary_result_type -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter9hash_fast _RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4fneg _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fneg _RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable14driftsort_mainTjjENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSBZ_11sort_by_keyTINtNtB8_3cmp7ReversejEjENCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4plans0_0E0INtNtB1b_3vec3VecBZ_EEB2p_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable5drift4sortTjjENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSBW_11sort_by_keyTINtNtBa_3cmp7ReversejEjENCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4plans0_0E0EB2m_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier218callee_guards_hold -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier213pin_memo_note -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math9sqrt_fast.llvm.9250547820948799359 _RNvXCskibSv91bgl1_9hashbrownNtNtCsgHYyB3hU8Ec_3std4path7PathBufINtB2_10EquivalentBq_E10equivalentCs5HK7yca7OMW_10weavepy_vm _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB12_5types10TypeObjectEEEB12_ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16missing_defaults _RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter9leaf_coreKb1_Esz_0B8_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_load_methods1_0B5_ _RINvCs5HK7yca7OMW_10weavepy_vm10h_dict_getKm1_EB2_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21leaf_fused_local_attr -_RNvCs5HK7yca7OMW_10weavepy_vm16builtin_recv_tag _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10k_dict_get _RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower12call_forward -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7h_catch -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer17emit_dyn_attr_set -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline14h_inline_store _RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm6smulhi _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math12is_fast_half -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer15emit_build_list -_RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4srem -_RNvMNtCs89hHMyD40Kn_15weavepy_codegen4foldNtB2_4Emit4sdiv -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValuexEBO_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBS_6fxhash8FxHasherEE6insertBS_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValuexEBR_EE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBV_6fxhash8FxHasherEE0EBV_ -_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValuexEBP_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBT_6fxhash8FxHasherEE3getBO_EBT_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13str_translates0_0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13str_translate _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_subscr_hotKm2_EB4_ _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_super_attr -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline20h_inline_truth_local _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueANtNtCs5HK7yca7OMW_10weavepy_vm6object6Objectj6_EBG_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter10cmp_method.llvm.3987546058129701445 _RINvCs5HK7yca7OMW_10weavepy_vm13try_alloc_vecNtNtB2_6object6ObjectEB2_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21normalize_hash_result _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter29leaf_instance_store_subscript -_RNvNtCs5HK7yca7OMW_10weavepy_vm13leaf_builtins7fast_kw -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19leaf_attr_store_any -_RINvMso_Cs5HK7yca7OMW_10weavepy_vmNtB6_14SortKindScalar2ofINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterRNtNtB6_6object6ObjectEEB6_ _RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtNtBc_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEBR_ENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvNvB24_3all5checkTRB1h_B38_ENCNvMs1s_B1j_B1h_8eq_value0E0INtNtNtBc_3ops12control_flow11ControlFlowuEEB1l_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict14od_update_fast -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict8order_of _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict10od_setitem -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict15od_setitem_leaf -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict14is_odict_class -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict10peek_order -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict8receiver _RNvMsr_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10PyInstance17laid_out_position -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod9lru_count -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod20scalar_lru_operation _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod14partial_inline -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod9lru_store -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze7PairSrcINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertBS_ _RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s6_0Bb_ -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrE10initializeNCINvB1a_11get_or_initNCNvNtNtB1K_6stdlib17collections_odict10order_name0E0zE0E0B1K_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB1a_11get_or_initNCNvMs3_NtB2T_3jitNtB4n_5Lower13inline_targets_0E0zE0E0B2V_.llvm.6970241935485176696 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod19code_range_has_mark -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE20repeat_body_has_markB9_ _RINvNtCs1C1lLj4PWSY_5alloc3str17join_generic_copyehINtNtB4_6borrow3CoweEECs5HK7yca7OMW_10weavepy_vm -_RNvXNtCsevLNFiNqfJP_4core3anyNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict9ViewTypesNtB2_3Any7type_idBx_ -_RNvXNtCsevLNFiNqfJP_4core3anyNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native5StateNtB2_3Any7type_idBx_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_20note_frameless_calls0INtNtB1P_6option6OptionbEEBZ_ -_RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB5_7Pending7release -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtBG_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VechEEEEBG_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native15tuplegetter_get -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native8tg_index -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13str_translateINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm6extend -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrE10initializeNCINvB2_11get_or_initNCNvNtNtBX_6stdlib17collections_odict10order_name0E0zEBX_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18core_leaf_property -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtCs5HK7yca7OMW_10weavepy_vm4sync6RefMutNtNtBH_6object8DictDataEBC_EEBH_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter12machine_step -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib3sys21sys_getrecursionlimit _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort31small_sort_general_with_scratchTjjENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB1s_11sort_by_keyTINtNtBa_3cmp7ReversejEjENCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4plans0_0E0EB2T_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable9quicksort9quicksortTjjENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB15_11sort_by_keyTINtNtBa_3cmp7ReversejEjENCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4plans0_0E0EB2w_ _RINvNtCs5HK7yca7OMW_10weavepy_vm6object16write_float_reprINtB2_9StackTextKj20_EEB4_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier27pin_any -_RINvNtCs5HK7yca7OMW_10weavepy_vm5tier226call_with_activation_shellINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB4_6object6ObjectNtNtB4_5error12RuntimeErrorENCNvB2_13call_dyn_impls2_0EB4_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214wpjit_call_dyn -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215dyn_call_result -_RNvMs8_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB5_7CallCtx14refresh_tables _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENCNvMs7_B1r_NtB1r_11Interpreter13do_round_call0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2S_8for_each4callB1n_NCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB48_3VecB1n_E14extend_trustedBN_E0E0EB1r_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_21note_generic_dyn_call0uEBZ_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer16emit_float_arith -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer14emit_unbox_int -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer12emit_pin_len -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer17emit_int_to_float -_RNCNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12plan_rewrites6_0B5_ _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins7b_round -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel5build -_RNvMs_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB4_4Plan12in_loop_span _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13do_round_call -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm5error12RuntimeErrorEEB11_.llvm.3361737253219229403 _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14core_attr_lane _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13for_iter_lane -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6k_body _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13for_iter_exit -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10h_property -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit17type_attr_resolve -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10h_property0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8run_body _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_for_iter_gen -_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs7usbkSbEEZs_16weavepy_compiler8bytecode11InstructionENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier218short_scalar_ranges1_0EB2C_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216wpjit_global_obj -_RNvCs5HK7yca7OMW_10weavepy_vm16class_entry_fill -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19property_dunder_get -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19call_annotate_value -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19code_synthetic_attrs2_0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14reentrant_call -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18function_descr_get -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9str_upper -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19mappingproxy_values -_RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_setitem_hotKm0_EB4_ -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser17fstring_parts_for -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser19parse_fstring_field -_RNvNtCs5993W3JedWL_14weavepy_parser6parser28scrub_fstring_field_comments -_RNvMNtCs5993W3JedWL_14weavepy_parser6parserNtB2_6Parser24parse_fstring_body_inner -_RNvNtCs5993W3JedWL_14weavepy_parser6parser16remap_expr_spans -_RNvNtCs5993W3JedWL_14weavepy_parser6parser27validate_fstring_conversion _RINvNtCs5HK7yca7OMW_10weavepy_vm5error10name_errorNtNtCs1C1lLj4PWSY_5alloc6string6StringEB4_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionTNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyNtB1k_6ObjectEEENtNtNtBK_3ops4drop4Drop4dropB1m_ -_RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE15append_elementsBI_ -_RNCNvNvNtCs5HK7yca7OMW_10weavepy_vm12type_surface21install_value_richcmp15richcmp_builtin0B7_ -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm12type_surface21install_value_richcmp7fam_int -_RINvMNtCsevLNFiNqfJP_4core3stre12trim_matchesNCNvMNtCs5993W3JedWL_14weavepy_parser6parserNtBM_6Parser19parse_fstring_field0EBO_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6result6ResultQNtCs5HK7yca7OMW_10weavepy_vm11InterpreterNtNtB10_5error12RuntimeErrorEEB10_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionTNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyNtB1x_6ObjectEEEEB1z_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTyIBC_INtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB18_6object9BuiltinFnEEhIBC_TB13_FG_RL0_SNtB1G_6ObjectEIBC_INtNtB4_6result6ResultB2n_NtNtB18_5error12RuntimeErrorEEEEEEEB18_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm6object8DictDataEBF_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real13ref_type_hash -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21percent_mod_left_slot -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter24function_annotation_dict -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13classdict_get -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17core_partial_call -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14leaf_next_step -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter36parse_source_emitting_warnings_flags -_RNvCs5HK7yca7OMW_10weavepy_vm8set_view _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12do_next_call -_RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter14core_fast_leafNCNvB2_19core_leaf_call_lane0EB6_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18jump_backward_step -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16templatelib_attr _RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter18lean_bind_keywordsINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtB6_7dictmap4IterNCNCNvB2_17core_partial_calls0_00EEB6_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17do_list_sort_call -_RNvCs5HK7yca7OMW_10weavepy_vm10compare_op -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18deopt_call_generic -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22core_leaf_next_resolve -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20core_partial_builtin -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21deep_order_collection -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter21core_local_attr_chains2_0B7_ -_RNvCs5HK7yca7OMW_10weavepy_vm12is_nan_value _RNvXs1i_NtCsevLNFiNqfJP_4core3fmtReNtB6_7Display3fmtCs5993W3JedWL_14weavepy_parser -_RNvMNtCs4oeOcPWpyDO_13weavepy_lexer7scannerNtB2_7Scanner19scan_fstring_extent -_RNvMNtCs4oeOcPWpyDO_13weavepy_lexer7scannerNtB2_7Scanner25scan_fstring_field_extent _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcNtNtBZ_13tuple_storage12TupleStorageEEINtB2_12SpecFromIterBU_INtNtNtCsevLNFiNqfJP_4core4iter8adapters12GenericShuntINtNtB2N_3map3MapINtNtNtB2R_5slice4iter4IterNtNtBZ_6object6ObjectENCNvNtNtBZ_6stdlib13itertools_mod12product_core0EINtNtB2R_6result6ResultNtNtB2R_7convert10InfallibleNtNtBZ_5error12RuntimeErrorEEE9from_iterBZ_ _RNvMs11_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_10PyFunction5slots -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object14int_like_value _RNvMs1s_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6Object3cmp -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict11values_iter -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict9make_view -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict10order_iter -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict9od_values -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict9view_iter _RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapINtNtNtB6_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENCNvNtNtB1A_6stdlib13itertools_mod12product_core0EINtNtB1A_12shared_value7ThinArcNtNtB1A_13tuple_storage12TupleStorageEINtNtB6_6result6ResultNtNtB6_7convert10InfallibleNtNtB1A_5error12RuntimeErrorENCINvXso_B4d_IB4b_INtNtCs1C1lLj4PWSY_5alloc3vec3VecB33_EB4X_EINtNtNtB4_6traits7collect12FromIteratorIB4b_B33_B4X_EE9from_iterBQ_E0B5I_EB1A_ _RNvMs0_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_modNtB5_9ArgsProbe3new _RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod17with_partial_callINtNtB6_2rc2RcNtNtB6_6object10PyFunctionENCNvMs7_B6_NtB6_11Interpreter17core_partial_calls0_0EB6_ _RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod17with_partial_callTINtNtB6_2rc2RcNtNtB6_6object9BuiltinFnEjENCNvMs7_B6_NtB6_11Interpreter20core_partial_builtins_0EB6_ _RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod17with_partial_callNtNtB6_6object6ObjectNCNvMs7_B6_NtB6_11Interpreter17core_partial_calls_0EB6_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod15lru_call_native -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types20install_type_dunders20type_annotations_get -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types20install_type_dunders17type_annotate_get -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE6searchB9_ -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE19max_until_recursiveB9_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENCNvNtNtB1r_6stdlib13itertools_mod12product_core0ENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvXB8_INtB8_12GenericShuntBN_INtNtBc_6result6ResultNtNtBc_7convert10InfallibleNtNtB1r_5error12RuntimeErrorEEB2U_8try_folduNCINvNvB2U_12try_for_each4callINtNtB1r_12shared_value7ThinArcNtNtB1r_13tuple_storage12TupleStorageEINtNtNtBc_3ops12control_flow11ControlFlowB67_ENcNtB7e_5Break0E0B7e_E0IB7f_B7e_EEB1r_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterjENCNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter12machine_steps1_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2m_8for_each4callNtNtB1v_6object6ObjectNCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB3U_3VecB3p_E14extend_trustedBN_E0E0EB1v_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtB8_3zip3ZipINtNtNtBc_5slice4iter4IterINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcNtNtB1I_13tuple_storage12TupleStorageEEIB1e_jEENCNvNtB1I_7seqiter12machine_steps0_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB3Q_8for_each4callNtNtB1I_6object6ObjectNCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB5o_3VecB4T_E14extend_trustedBN_E0E0EB1I_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterjENCNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter12machine_steps2_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2m_8for_each4callNtNtB1v_6object6ObjectNCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB3U_3VecB3p_E14extend_trustedBN_E0E0EB1v_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNvMs7_BY_NtBY_11Interpreter4stepsF_0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNvNtNtBY_6stdlib13functools_mod8lru_calls_0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeuNCNvNtNtBY_6stdlib13functools_mod9lru_store0E0INtNtCsevLNFiNqfJP_4core6result6ResultuNtNtBY_5error12RuntimeErrorEEBY_ -_RNCNvNCNvCs7usbkSbEEZs_16weavepy_compiler25body_reads_super_or_class09any_class0B7_ -_RNvCs7usbkSbEEZs_16weavepy_compiler25body_reads_super_or_class -_RNvCs7usbkSbEEZs_16weavepy_compiler19function_free_names _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB2l_3zip3ZipINtNtNtB2p_5slice4iter4IterINtNtB17_12shared_value7ThinArcNtNtB17_13tuple_storage12TupleStorageEEIB3m_jEENCNvNtB17_7seqiter12machine_steps0_0EE9from_iterB17_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecjEINtB4_18SpecFromIterNestedjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3rev3RevINtNtNtB1F_3ops5range14RangeInclusivejEEE9from_iterCs5HK7yca7OMW_10weavepy_vm _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_5slice4iter4IterjENCNvNtB17_7seqiter12machine_steps1_0EE9from_iterB17_ -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedNtNtB15_7dictmap6ValuesEE9from_iterB15_ -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecINtNtCsevLNFiNqfJP_4core6option6OptionTNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyNtB1G_6ObjectEEEINtB2_18SpecFromIterNestedB11_INtNtNtNtB16_4iter8adapters3map3MapNtNtB1I_7dictmap8IntoIterNcNtB11_4Some0EE9from_iterB1I_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_5slice4iter4IterjENCNvNtB17_7seqiter12machine_steps2_0EE9from_iterB17_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyNtB14_6ObjectEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtB16_7dictmap4IterNCNvNtB16_8builtins8dict_iors_0EE9from_iterB16_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_5slice4iter4IterINtNtB17_12shared_value7ThinArcNtNtB17_13tuple_storage12TupleStorageEENCNvNtB17_7seqiter12machine_steps_0EE9from_iterB17_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_5slice4iter4IterNtNtCs7usbkSbEEZs_16weavepy_compiler4name4NameEINvMs1y_B15_B13_8from_strRB3v_EEE9from_iterB17_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1z_6filter6FilterINtNtB1z_9enumerate9EnumerateINtNtNtB1D_5slice4iter4IterNtNtCs7usbkSbEEZs_16weavepy_compiler12cpython_code10DecodedRawEENCNvB3B_11decode_fulls0_0ENCB4D_s1_0EE9from_iterB3D_ -_RINvMs9_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB8_11Interpreter11plan_getterKb0_EB8_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBG_6object14SlotDescriptorEEBG_ -_RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types20install_type_dunders20type_dunder_dict_get -_RNvNtCsi2ENRQxi4yp_12weavepy_capi5types11live_tp_doc -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10string_mod7builtin -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10string_mod5build _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod17native_new_interp -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod10native_new.llvm.5678553137184841714 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod12product_core -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod17native_new_interps_0B7_.llvm.5678553137184841714 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod17permutations_core -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins18function_descr_getINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_.llvm.13937324807167308475 -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19property_dunder_getINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9str_upperINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19mappingproxy_valuesINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod9pure_poolINtNtNtCsevLNFiNqfJP_4core3ops8function5FnMutTRNtNtB8_6object6ObjectEE8call_mutB8_.llvm.5678553137184841714 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7ast_mod5build -_RINvXs8_NtCskibSv91bgl1_9hashbrown3setINtB6_7HashSetNtNtCs1C1lLj4PWSY_5alloc6string6StringINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler6fxhash8FxHasherEEINtNtNtNtB1v_4iter6traits7collect6ExtendBO_E6extendINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetBO_B1q_EEB2h_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastNtNtB4_6object6ObjectEB4_ -_RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterNtNtCs5HK7yca7OMW_10weavepy_vm7dictmap6BucketENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB10_ -_RNvMsh_NtCs5HK7yca7OMW_10weavepy_vm4syncINtB5_7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionReEE3getB7_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter19itertools_pure_next.llvm.16911827322050435359 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12tokenize_mod5build -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214try_dyn_native _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier211pin_reusing _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier213wpjit_call_py _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215try_native_call _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier211fresh_child -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier211unpack_pins -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier218wpjit_dyn_attr_get _RNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint7convert20to_bitwise_digits_le -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core11random_init -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core11random_seed -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core8store_mt -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core17seed_from_entropy -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math8exp_fast.llvm.9250547820948799359 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math8log_fast.llvm.9250547820948799359 _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_17note_short_region0bEBZ_ _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer14emit_float_cmp -_RNvMs4_Cs7usbkSbEEZs_16weavepy_compilerNtB5_7JitHint9loop_free _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_setitem_hotKm1_EB4_ -_RNvCs5HK7yca7OMW_10weavepy_vm20property_site_getter _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline11getter_plan _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit17for_iter_gen_lazy _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit19for_iter_gen_switch -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_fold_yield -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13k_str_replace _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit9k_set_add _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12binop_method _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_contains_hotKm2_EB4_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit16k_str_startswith _RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB5_7Builder4edge -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit6verify0E0zEB1A_ _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_call_forward _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4udiv -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit6verify0E0zE0E0B2o_.llvm.6970241935485176696 -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_5Lower4body -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_5Lower2op -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_5Lower7set_out -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit7compile -_RNvMs2_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_6Engine7release -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_5Lower4call -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_5Lower5frame _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5BlockEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_3ops5range5RangejENCNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB3F_5Lower5frame0EE9from_iterB3J_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14operator_accel12is_fast_half _RINvNtCs5HK7yca7OMW_10weavepy_vm7timsort4sortNtNtB4_6object6ObjectNtNtB4_5error12RuntimeErrorNCINvMs7_B4_NtB4_11Interpreter10sort_keyedBH_NCNvB1y_13sort_with_keys_0Es2_0EB4_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm7timsort10MergeStateNtNtBG_6object6ObjectNCINvMs7_BG_NtBG_11Interpreter10sort_keyedB1q_NCNvB1Q_13sort_with_keys_0Es2_0EEBG_ -_RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter10sort_keyedNtNtB8_6object6ObjectNCNvB4_13sort_with_keys_0Es2_0B8_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer13emit_iter_new -_RINvXsd_NtCs1C1lLj4PWSY_5alloc6stringNtB6_6StringINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect6ExtendcE6extendINtNtNtBS_7sources8repeat_n7RepeatNcEECs5HK7yca7OMW_10weavepy_vm -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18do_isinstance_call _RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15class_attr_note0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15class_attr_note -__divti3 -_RNvNtNtCs4d4ibTJ6dSQ_17compiler_builtins3int19specialized_div_rem12u128_div_rem _RNvMs_NtCs7usbkSbEEZs_16weavepy_compiler9flowgraphNtB4_5Block18insert_instruction -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13dict_fromkeys -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins7set_add -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins21bytes_from_source_obj _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_setter_store _RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit17builtin_attr_read0B5_ _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_setitem_hotKm7_EB4_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer10emit_truth _RNvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB2_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE10try_insertBW_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm5error11index_errorReEB4_ -_RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE10insert_mutBI_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtB7_5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10DirectSiteEE8push_mutB11_ -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftNtNtCs7usbkSbEEZs_16weavepy_compiler4name4NameNCINvMB8_SB1m_20sort_unstable_by_keyTjjNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvMsV_B1q_NtB1q_8Compiler6finish0E0EB1q_ -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftTjjENvYB1m_NtNtBa_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionThINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB14_6object9BuiltinFnEEEEB14_ _RNvXs0_NtNtCs2qMPZxtgKFx_10num_bigint6bigint8additionNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops5arith3AddRBP_E3add -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel5build -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22leaf_pure_builtin_kind -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18start_generator_at _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14leaf_setter_at -_RNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint8division11div_rem_ref -_RNvXsf_NtNtCs2qMPZxtgKFx_10num_bigint6bigint14multiplicationRNtB7_6BigIntNtNtNtCsevLNFiNqfJP_4core3ops5arith3Mul3mul -_RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s7_0Bb_ _RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215method_ret_infosa_0B5_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier218inline_method_bodys2_0B5_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier218inline_method_bodys1_0B5_ -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native9SlotNamesE10initializeNCINvB1a_11get_or_initNCNvB1I_5names0E0zE0E0B1M_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0B1K_.llvm.6970241935485176696 _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_3ops5range5RangejENCNvMs1_NtCs7usbkSbEEZs_16weavepy_compiler9flowgraphNtB1x_3Cfg26insert_prefix_instructions0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2T_8for_each4callTjjENCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB49_3VecB3W_E14extend_trustedBN_E0E0EB1z_ -_RNvXs9_NtCs1C1lLj4PWSY_5alloc5boxedINtB5_3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10DirectSiteENtNtCsevLNFiNqfJP_4core7default7Default7defaultBL_ -_RNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint14multiplication10scalar_mul -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler13closure_index -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler18cell_or_free_index _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_3ops5range5RangejENCNvNtB17_9frame_jit7h_build0EE9from_iterB17_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2q_5slice4iter4IterTNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueB13_EENCNvMNtB17_5lowerNtB4q_7Lowerer15inline_body_for0EE9from_iterB17_ -_RNCINvMNtCsevLNFiNqfJP_4core5sliceSNtNtCs7usbkSbEEZs_16weavepy_compiler4name4Name20sort_unstable_by_keyTjjNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvMsV_BB_NtBB_8Compiler6finish0E0BB_.llvm.18265934342920026857 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native15new_named_tuple -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13dict_fromkeysINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins7set_addINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native9SlotNamesE10initializeNCINvB2_11get_or_initNCNvBV_5names0E0zEBZ_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEBX_ _RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters5chainINtB5_5ChainIBP_IBP_INtNtBb_6option8IntoIterTRNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyRNtB1A_6ObjectEEINtNtB7_3map3MapINtNtB7_7flatten7FlattenIB19_RINtNtCs1C1lLj4PWSY_5alloc3vec3VecTB1y_B2i_EEEENCNvMsq_NtB1C_5typesNtB49_11SlotStorage4iter0EEINtB2Q_7FlatMapIB19_RNtB1A_8DictDataENtNtB1C_7dictmap4IterNCB43_s_0EEIB4N_IB19_TRINtNtB1C_12shared_value7ThinArcINtB68_12SliceStorageB1y_EERSB2i_EEINtNtB7_3zip3ZipINtNtNtBb_5slice4iter4IterB1y_EIB7q_B2i_EENCB43_s0_0EENtNtNtB9_6traits8iterator8Iterator8try_folduNCINvNtB7_6filter15filter_try_foldB1w_uINtNtNtBb_3ops12control_flow11ControlFlowuENCB43_s1_0NCINvNvB8h_3any5checkB1w_NCNvB1C_25exception_holds_nonatomics_0E0E0B9C_EB1C_ -_RNvXsZ_NtCs1C1lLj4PWSY_5alloc6stringNtB5_6StringNtNtCsevLNFiNqfJP_4core3fmt5Write10write_char _RNvMs2_NtNtNtCsevLNFiNqfJP_4core3num3imp6bignumNtB5_8Big32x408mul_pow2 _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier210wpjit_poll _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214wpjit_attr_get _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier213erased_global _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215try_native_ctor -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable5drift4sortTmNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSBW_7sort_byNCNvMNtB12_7codegenINtB2w_3GenNtNtB12_3x643X64E11choose_pinss0_0E0EB12_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core12state_buffer.llvm.6970241935485176696 _RNvMs_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_coreNtB4_7MtBytes11genrand_u32.llvm.6970241935485176696 _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core16getrandbits_leaf @@ -9515,115 +7492,42 @@ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core18random_getrandbits _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_22note_callee_roundtrips0uEBZ_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecmEINtB4_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1F_5slice4iter6ChunkshENCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core16seed_from_object0EE9from_iterB2X_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort31small_sort_general_with_scratchTmNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB1s_7sort_byNCNvMNtB1y_7codegenINtB33_3GenNtNtB1y_3x643X64E11choose_pinss0_0E0EB1y_ -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort12sort8_stableTmNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB19_7sort_byNCNvMNtB1f_7codegenINtB2K_3GenNtNtB1f_3x643X64E11choose_pinss0_0E0EB1f_ _RNvNtNtNtNtNtCsevLNFiNqfJP_4core3num3imp7flt2dec8strategy6dragon9mul_pow10 _RNvNtNtNtNtNtCsevLNFiNqfJP_4core3num3imp7flt2dec8strategy6dragon12format_exact -_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable14driftsort_mainTmNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSBZ_7sort_byNCNvMNtB15_7codegenINtB2z_3GenNtNtB15_3x643X64E11choose_pinss0_0E0INtNtB1S_3vec3VecBZ_EEB15_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm5tier27CallCtxEEEB1A_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSNtNtCs5HK7yca7OMW_10weavepy_vm5tier23PinEBG_ -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable9quicksort9quicksortTmNtNtCs89hHMyD40Kn_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB15_7sort_byNCNvMNtB1b_7codegenINtB2G_3GenNtNtB1b_3x643X64E11choose_pinss0_0E0EB1b_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11class_lacks _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20alloc_plain_instance _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtCs5HK7yca7OMW_10weavepy_vm4sync6RefMutNtNtBH_6object8DictDataEINtBF_3RefB1j_EEEBH_ _RINvCs5HK7yca7OMW_10weavepy_vm10h_dict_setKm1_EB2_ -_RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter18lean_bind_keywordsINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1d_7flatten7FlatMapINtNtB1h_6option4IterINtNtB6_4sync3RefNtNtB6_6object8DictDataEENtNtB6_7dictmap4IterNCNvB2_27try_inline_call_ex_keywords0ENCB3I_s_0EEB6_ _RINvCs5HK7yca7OMW_10weavepy_vm13make_functionNCNvNtB2_9frame_jit15h_make_function0EB2_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10k_list_pop -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit9type_attr _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15h_list_to_tuple _RNvNtCs5HK7yca7OMW_10weavepy_vm6object10float_repr -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records10new_direct -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCINvMs8_B26_NtB28_11Interpreter12leaf_run_retKb0_KB4c_KB4c_E0E0zEB28_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit6NativeEE10initializeNCINvB2_11get_or_initNCINvB1x_3runKb0_E0E0zEB1B_ _RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE20insert_unique_hashedB7_ -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit6NativeEE10initializeNCINvB1a_11get_or_initNCINvB2k_3runKb0_E0E0zE0E0B2o_.llvm.6970241935485176696 _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBJ_ -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13CompSavedMetaINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertBS_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13CompSavedMetaEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE0EBV_ _RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCsd5p0HaiaiO6_11weavepy_jit7analyze5ESlotENtNtNtNtBb_4iter6traits8iterator8Iterator3allNvMs4_BS_BQ_8is_plainEBU_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline17h_inline_defaults _RNvCs5HK7yca7OMW_10weavepy_vm13code_recurses _RINvMNtCs5HK7yca7OMW_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1t_3ops5range5RangejENCNvNtNtB5_6stdlib11sre_objects11marks_tuples4_0EEB5_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterReENCNCNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native7layouts000ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB2C_8for_each4callNtNtB1C_6object7DictKeyNCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB4b_3VecB3F_E14extend_trustedBN_E0E0EB1C_ -_RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRThReEECs5HK7yca7OMW_10weavepy_vm -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockAINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcINtBX_12SliceStorageNtNtBZ_6object7DictKeyEEj4_E10initializeNCINvB2_11get_or_initNCNvNtNtBZ_6stdlib15datetime_native7layouts0E0zEBZ_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects10group_text -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects10with_matchINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_11match_group0E0B8_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects11group_index -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects11match_group -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapThReENtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBW_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTThReENtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BV_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EBZ_ -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockAINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcINtB1K_12SliceStorageNtNtB1M_6object7DictKeyEEj4_E10initializeNCINvB1a_11get_or_initNCNvNtNtB1M_6stdlib15datetime_native7layouts0E0zE0E0B1M_.llvm.6970241935485176696 -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter23leaf_builtin_method_ptr -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze12infer_append -_RNvXsd_NtNtNtCsevLNFiNqfJP_4core3fmt3num3impyNtB9_7Display3fmt -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7abc_mod19abc_instance_cacheds_0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7abc_mod19abc_instance_cached -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7abc_mod17abc_instancecheck -_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir9StrMethodE8grow_oneBQ_ -_RNvNtCs7usbkSbEEZs_16weavepy_compiler9flowgraph15to_ast_constant -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10bytes_find -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins20bytes_needle_guarded _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_contains_hotKm3_EB4_ -_RNvMsc_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_5Lower12load_special _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10h_end_send _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit8gen_call -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_load_special _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_await_iter _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6h_send -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12core_dict_kw _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtB4_6result6ResultNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectNtNtB1n_5error12RuntimeErrorEEEB1n_ -_RINvMNtCs5HK7yca7OMW_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainNtNtB5_6object6ObjectEEB5_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14format_obj_str.llvm.3987546058129701445 _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15load_fast_value -_RNvCs5HK7yca7OMW_10weavepy_vm14core_bignum_op -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17core_load_special -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19dispatch_inplace_op -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16dict_of_keywords -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13box_gen_frame _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16invoke_finalizer -_RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter17core_local_methodKb0_Es0_0B8_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14core_push_init _RNvNtCskRQrKhBUP4e_6memchr6memmem4find -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real15thread_shutdown -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real9lock_exit -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real13get_native_id -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real20resolve_acquire_args -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real17thread_handle_new -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real25make_thread_handle_objects0_0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real21lock_try_acquire_leaf -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real4heldNtNtB6_4sync8RealLockEB6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real25make_thread_handle_object -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real25make_thread_handle_object0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real21get_main_thread_ident -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real19is_main_interpreter _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real13parse_timeout _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real15new_lock_object -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real4heldNtNtB8_4sync8RealLockE0B8_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real12lock_acquire -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real18make_thread_handle _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCs5993W3JedWL_14weavepy_parser3ast8ConstantEINtB2_12SpecFromIterBU_INtNtNtCsevLNFiNqfJP_4core4iter8adapters12GenericShuntINtNtB26_3map3MapINtNtNtB2a_5slice4iter4IterNtCs7usbkSbEEZs_16weavepy_compiler8ConstantENvNtB3F_9flowgraph15to_ast_constantEINtNtB2a_6option6OptionNtNtB2a_7convert10InfallibleEEE9from_iterB3F_ _RNvMsM_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_8DictData20track_deferred_owner -_RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapINtNtNtB6_5slice4iter4IterNtCs7usbkSbEEZs_16weavepy_compiler8ConstantENvNtB1y_9flowgraph15to_ast_constantENtNtCs5993W3JedWL_14weavepy_parser3ast8ConstantINtNtB6_6option6OptionNtNtB6_7convert10InfallibleENCINvXsI_B3C_IB3A_INtNtCs1C1lLj4PWSY_5alloc3vec3VecB2O_EEINtNtNtB4_6traits7collect12FromIteratorIB3A_B2O_EE9from_iterBQ_E0B4F_EB1y_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18elementtree_native13sequence_iter -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject29invalidate_getattribute_cache -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject20forget_display_names -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records14ctor_direct_kw _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapyINtNtCs1C1lLj4PWSY_5alloc4sync3ArcNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real17ThreadHandleStateENtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertB1s_ -_RNvMNtCs7usbkSbEEZs_16weavepy_compiler4nameNtB2_4Name9to_string _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTxINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtBW_4sync7GilCellNtNtNtBW_6stdlib8ssl_real6MemBioEEEE14reserve_rehashNCINvNtB8_3map11make_hasherxBR_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EBW_ -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0sc_0B7_ _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216probe_pair_lanes -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm15thread_registry14ThreadRegistryE10initializeNCINvB1a_11get_or_initNvMs0_B1I_B1G_3newE0zE0E0B1K_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvCs5HK7yca7OMW_10weavepy_vm14fusion_enabled0E0zE0E0B2k_.llvm.6970241935485176696 _RNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types20overrides_dunder_new _RINvNtCs5HK7yca7OMW_10weavepy_vm3gil18allow_threads_thenuNCNvNtNtB4_6stdlib11thread_real15thread_shutdown0EB4_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_5types10TypeObjectEEEE4withNCNvNtNtBZ_6stdlib11thread_real18thread_handle_type0B2e_EBZ_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm14descr_registry13live_c_doc_of -_RNvNtCs5HK7yca7OMW_10weavepy_vm14descr_registry9module_of -_RNvCs7usbkSbEEZs_16weavepy_compiler23method_references_class -_RNvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB5_8Compiler15emit_super_attr -_RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterNtNtCs5993W3JedWL_14weavepy_parser3ast8ConstantENvYNtCs7usbkSbEEZs_16weavepy_compiler8ConstantINtNtB1f_7convert4FromB2l_E4fromEB3a_EB3c_ _RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState18complete_finalizer _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtNtB1D_3str4iter5CharsNCNvNtCs7usbkSbEEZs_16weavepy_compiler7ast_opt10str_points0EE9from_iterB2N_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecINtNtB6_4sync3ArcNtNtCs5HK7yca7OMW_10weavepy_vm15thread_registry11ThreadEntryEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB2R_6filter6FilterINtNtNtNtB6_11collections5btree3map6ValuesyB11_ENCNvMs0_B1k_NtB1k_14ThreadRegistry15join_non_daemon0EEE9from_iterB1m_ @@ -9633,39 +7537,26 @@ _RNvMs_NtCsd5p0HaiaiO6_11weavepy_jit6engineNtB4_12InlineMethod2of _RNvMs0_NtCsd5p0HaiaiO6_11weavepy_jit6engineNtB5_13CompiledFrame18direct_method_leaf _RNvNtCs5HK7yca7OMW_10weavepy_vm13vm_singletons26try_push_pending_finalizer _RNvXsM_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_6ValuesyINtNtBb_4sync3ArcNtNtCs5HK7yca7OMW_10weavepy_vm15thread_registry11ThreadEntryEENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator4nextB1r_ -_RNvNtCs7usbkSbEEZs_16weavepy_compiler7ast_opt5py_eq _RNvNtCs7usbkSbEEZs_16weavepy_compiler7ast_opt8dedup_py -_RNvCs5HK7yca7OMW_10weavepy_vm11builtin_doc _RINvMs1_NtCs5HK7yca7OMW_10weavepy_vm11frame_slotsNtB6_10FrameStack8with_vecuNCNvB2_7reserve0EB8_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native12deque_append -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native9deque_len _RNCNvNtCs5HK7yca7OMW_10weavepy_vm8gen_fast10steps_body0B5_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10bytes_findINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11asyncio_mod17finalizer_is_noop -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real25make_thread_handle_object0EBJ_ _RNvXNtNtCs2qMPZxtgKFx_10num_bigint6bigint11subtractionRNtB4_6BigIntNtNtNtCsevLNFiNqfJP_4core3ops5arith3Sub3sub _RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm15thread_registryNtB5_14ThreadRegistry15join_non_daemon _RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterINtNtB9_4sync3ArcNtNtCs5HK7yca7OMW_10weavepy_vm15thread_registry11ThreadEntryEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB1h_ _RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterNtNtCs5993W3JedWL_14weavepy_parser3ast8ConstantENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCs7usbkSbEEZs_16weavepy_compiler -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm15thread_registry14ThreadRegistryE10initializeNCINvB2_11get_or_initNvMs0_BV_BT_3newE0zEBX_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5UJUBJEE7PZ_8lock_api5mutex5MutexNtNtCs2zRUMDvV71V_11parking_lot9raw_mutex8RawMutexINtNtNtNtB7_11collections4hash3map7HashMapyINtNtCs1C1lLj4PWSY_5alloc4sync3ArcNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real17ThreadHandleStateEEEE10initializeNCINvB2_11get_or_initNCNvB3C_15handle_registry0E0zEB3G_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvCs5HK7yca7OMW_10weavepy_vm14fusion_enabled0E0zEB1w_ -_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterhENtNtNtNtBb_4iter6traits8iterator8Iterator8positionNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod4scanhNvB1L_8uni_wordE0EB1P_ _RNvYNCNKNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real18THREAD_HANDLE_TYPE00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1p_6option6OptionQIB24_INtNtBc_4sync7GilCellIB24_INtNtBc_2rc2RcNtNtBc_5types10TypeObjectEEEEEEE9call_onceBc_ -_RNvXs_NtNtCs2qMPZxtgKFx_10num_bigint7biguint11subtractionNtB6_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops5arith9SubAssignRBT_E10sub_assign _RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter19lazy_special_method _RINvMNtNtCskRQrKhBUP4e_6memchr6memmem8searcherNtB3_8Searcher3newNtNtNtNtB7_4arch3all10packedpair20DefaultFrequencyRankECs5HK7yca7OMW_10weavepy_vm.llvm.9250547820948799359 _RNvNtNtCskRQrKhBUP4e_6memchr6memmem8searcher22searcher_kind_one_byte _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14coerce_f64_opt -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214wpjit_attr_set _RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier214wpjit_attr_gets0_0B5_ _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm11DunderTableEE10initializeNCINvB1a_11get_or_initNvYB1G_NtNtCsevLNFiNqfJP_4core7default7Default7defaultE0zE0E0B2h_.llvm.6970241935485176696 -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer13emit_list_get _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer16emit_unbox_float _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm11DunderTableEE10initializeNCINvB2_11get_or_initNvYBT_NtNtCsevLNFiNqfJP_4core7default7Default7defaultE0zEB1u_ _RNvXs2_NtNtCsevLNFiNqfJP_4core5slice3cmpNtNtCs1C1lLj4PWSY_5alloc6string6StringINtB5_14SlicePartialEqBC_E17equal_same_lengthCsd5p0HaiaiO6_11weavepy_jit _RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtCs5HK7yca7OMW_10weavepy_vm10DunderSeenE8push_mutBH_.llvm.3987546058129701445 -_RNvCs5HK7yca7OMW_10weavepy_vm11dunder_note _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline11dunder_plan _RINvCs5HK7yca7OMW_10weavepy_vm10h_dict_setKm3_EB2_ _RNvNvCs5HK7yca7OMW_10weavepy_vm32collect_compiler_syntax_warnings12visit_target @@ -9680,20 +7571,12 @@ _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit9h_fstring _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit16h_for_iter_drain _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_build_set _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14for_iter_drain -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12h_str_eq_ref _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_setitem_hotKm3_EB4_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10k_str_join -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit17h_attr_local_slot -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11k_str_split -_RNvMs3_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB5_5Owned3own _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable5merge5mergeTjjENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSBX_11sort_by_keyTINtNtBa_3cmp7ReversejEjENCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline4plans0_0E0EB2n_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze14check_dict_key _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer12emit_str_get _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer11emit_str_eq _RNvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTmmEE14insert_no_growCsd5p0HaiaiO6_11weavepy_jit _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215wpjit_tuple_len -_RNvMNtCskibSv91bgl1_9hashbrown11rustc_entryINtNtB4_3map7HashMapmmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE11rustc_entryCsd5p0HaiaiO6_11weavepy_jit -_RINvMsV_Cs7usbkSbEEZs_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_14compile_assign0EB6_ _RINvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB6_5TableuE12get_index_ofNtNtB8_6object9LeafProbeEB8_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod16lru_native_store _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod16lru_enter_native @@ -9701,12 +7584,10 @@ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod17lru_native_lookup _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_modNtB5_10LruPending15release_wrapper _RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod15native_store_inNtNtB6_6object9LeafProbeEB6_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod16lru_uncount_miss -_RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters4takeINtB4_4TakeINtNtB6_9enumerate9EnumerateINtNtNtBa_5slice4iter7IterMutPNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEENtNtNtB8_6traits8iterator8Iterator3nthB1X_ _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder6smulhi _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4imul _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder8sshr_imm _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectBY_EEEB12_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit3CtxEBH_ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13core_lru_miss _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter14core_lru_probe _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit8h_binary @@ -9714,73 +7595,27 @@ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17subscr_get_public _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17dict_getitem_leaf _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs5HK7yca7OMW_10weavepy_vm8gc_trace17DeferredContainerE6retainNCNvMsg_BH_NtBH_7GcState19sweep_deferred_froms_0EBJ_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm8gc_trace17DeferredContainerEBF_.llvm.4650670488983980854 -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcDNtNtB4_3any3AnyNtNtB4_6marker4SendNtB1u_4SyncEL_EEBG_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9str_stripINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellNtNtB7_6object8DictDataEE9downgradeB7_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxSINtNtNtCsevLNFiNqfJP_4core4sync6atomic6AtomicbEEE10initializeNCINvB2_11get_or_initNCNvCs5HK7yca7OMW_10weavepy_vm16native_site_notes_0E0zEB2R_ _RNvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB2_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcDNtNtCsevLNFiNqfJP_4core3any3AnyNtNtB1y_6marker4SendNtB21_4SyncEL_EE10try_insertBX_ -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE12quick_assertB9_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcDNtNtB4_3any3AnyNtNtB4_6marker4SendNtB1Q_4SyncEL_EEEB12_ -_RNvMsn_Cs5HK7yca7OMW_10weavepy_vmNtB5_8SortKind6str_lt _RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter8abs_fast -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9str_strip -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native15construct_names -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native7recycle -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier217wpjit_list_append -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214wpjit_iter_new _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216wpjit_build_list -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer21emit_list_append_keep _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_13try_enter_osrs1_0uEBZ_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer12emit_str_mod -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16parse_int_string _RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math7builtin0B7_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math14freshen_result -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter19core_store_new_attr0B7_ -_RNvMsi_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtNtB7_5types10PyInstance13attr_peek_has -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier219deliver_call_result -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxShEE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zECs5HK7yca7OMW_10weavepy_vm -_RNvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB2_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxShEE10try_insertCs5HK7yca7OMW_10weavepy_vm _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214pure_leaf_call _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier218wpjit_dyn_attr_set -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxShEE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0Cs5HK7yca7OMW_10weavepy_vm.llvm.6970241935485176696 -_RNvMNtCs5HK7yca7OMW_10weavepy_vm8gen_fastNtB4_11Interpreter17gen_fast_for_iter -__udivti3 _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer17emit_contains_dyn _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer13emit_dyn_call _RNvXs5_NtNtCs1C1lLj4PWSY_5alloc3vec5drainINtB5_5DrainTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectyEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBU_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier214ClassCtorEntryEBF_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216probe_ctor_field -_RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s8_0B7_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline17keywords_in_place -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer20emit_call_str_method -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10k_str_find -_RNvMs5_NtCs5HK7yca7OMW_10weavepy_vm9frame_jitNtB5_8ModCache4note -_RNvMsK_Cs5HK7yca7OMW_10weavepy_vmNtB5_8LeafSite8poly_hit _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13truth_release -_RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objectsNtB2_7Subject5slice.llvm.16112649145315725652 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecThReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0B2l_.llvm.6970241935485176696 -_RINvNtCsevLNFiNqfJP_4core5array11try_from_fnINtNtNtB4_3ops9try_trait17NeverShortCircuitINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcINtB1q_12SliceStorageNtNtB1s_6object7DictKeyEEEKj4_NCINvMBJ_BG_10wrap_mut_1jNCINvXsk_B2_B1n_NtB2_14SpecArrayClone5cloneKB30_E0E0EB1s_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14datetime_accel5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14datetime_accel11date_fields -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14datetime_accel11time_fields -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14datetime_accel15timedelta_parts -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtBG_6stdlib15datetime_native5StateEEBG_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapNtNtB15_7dictmap4IterNCNvNtNtB15_6stdlib15datetime_native7installs6_0EE9from_iterB15_ -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecThReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapINtNtNtB2s_5slice4iter4IterThB13_EENCNvNtNtB19_6stdlib15datetime_native7installs5_0EE9from_iterB19_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtNtNtB6_6stdlib15datetime_native5StateE3newB6_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecThReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEB1y_ -_RNvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB2_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecThReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEE10try_insertB1x_ _RINvMNtCs5HK7yca7OMW_10weavepy_vm13tuple_storageNtB3_12TupleStorage10from_arrayKj5_EB5_ -_RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState13untrack_young _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc3vec3VecThReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEEEB1C_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueAINtNtCs5HK7yca7OMW_10weavepy_vm12shared_value7ThinArcINtBF_12SliceStorageNtNtBH_6object7DictKeyEEj1_EBH_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native7install -_RNvMs2_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_nativeNtB5_5Names3new -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE16branch_can_startB9_ -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE12branch_firstB9_ _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10list_clear -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19coerce_index_object -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isupper _RNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins21bytes_from_source_obj0B5_ mi_bbitmap_set_chunk_bin _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13gen_call_done @@ -9789,109 +7624,48 @@ _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10lazy_await _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_send_step _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11h_send_lazy _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline13h_inline_left -_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE14extend_trustedINtNtCsevLNFiNqfJP_4core6option8IntoIterBG_EEBK_ -_RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEE11extend_withB1l_ -_RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTjINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBM_5types10PyInstanceEEE6retainNCNvMs7_BM_NtBM_11Interpreter27prune_globals_missing_hooks0EBM_ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTNtNtB7_6string6StringNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneB15_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1m_NtNtBa_3cmp10PartialOrd2ltECs5HK7yca7OMW_10weavepy_vm -_RNvXsF_NtNtCs2qMPZxtgKFx_10num_bigint6bigint8divisionNtB7_6BigIntNtNtNtCsevLNFiNqfJP_4core3ops5arith3Div3div _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10select_mod6method _RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inTNtNtB8_6string6StringNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalEB1a_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5HK7yca7OMW_10weavepy_vm8LeafStopEBD_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectINtNtCs1C1lLj4PWSY_5alloc3vec3VecBY_EIB1H_TNtNtB1L_6string6StringBY_EEEEEB12_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm7timsort10MergeStateTNtNtBG_6object6ObjectB1r_ENCINvMs7_BG_NtBG_11Interpreter10sort_keyedB1q_NCNvB1W_13sort_with_keys0_0Es2_0EEBG_ -_RNvXs_NtNtCs2qMPZxtgKFx_10num_bigint6bigint8additionRNtB6_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops5arith3AddBP_E3add _RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter4stepss_0B7_ _RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter18leaf_function_read0B7_ -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter13core_gen_make0B7_ _RNCINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB8_11Interpreter10sort_keyedTNtNtB8_6object6ObjectB13_ENCNvB4_13sort_with_keys0_0Es2_0B8_ -_RNCNvCs5HK7yca7OMW_10weavepy_vm11range_slices_0B3_ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21dict_view_set_compare -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter23class_assign_compatible -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12format_value -_RNvCs5HK7yca7OMW_10weavepy_vm11range_slice _RNvCs5HK7yca7OMW_10weavepy_vm14gen_stack_room _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter12lazy_box_new _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter27prune_globals_missing_hooks -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21deep_equal_collection -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17make_seq_iterator -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16check_int_result _RINvCs5HK7yca7OMW_10weavepy_vm9push_growINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtB2_9LeanFrameEEB2_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter29register_globals_missing_hook -_RNCNvCs5HK7yca7OMW_10weavepy_vm11range_slice0B3_ -_RNvXs4_NtCs2qMPZxtgKFx_10num_bigint6bigintNtB5_6BigIntNtNtCsevLNFiNqfJP_4core3cmp3Ord3cmp -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11thread_real13rlock_release -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10atexit_mod7builtin -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10atexit_mod5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10atexit_mod10a_register _RNvXsu_NtNtCsevLNFiNqfJP_4core3fmt3nummNtB7_8LowerHex3fmt -_RNvMst_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_5Range6bounds _RINvMs11_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB7_10PyFunction15code_names_keptNCNvNtB9_9frame_jit10lazy_await0EB9_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object24bytearray_export_acquire -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object16range_len_bigint -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object24bytearray_export_release -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject18layout_struct_base -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject13adds_own_dict -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject15solid_base_name -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject19member_slots_sorted -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject13display_names.llvm.4890245414193407415 -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject16adds_own_weakref _RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject14changes_layout _RNvMsr_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10PyInstance7set_cls -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject9best_base _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBS_5types10TypeObjectENtNtNtBS_6stdlib7ast_mod7CheckedEE8grow_oneBS_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects14pattern_search _RNvNtCs5HK7yca7OMW_10weavepy_vm12unicode_case11str_isupper _RINvNtCs5HK7yca7OMW_10weavepy_vm7timsort4sortTNtNtB4_6object6ObjectBI_ENtNtB4_5error12RuntimeErrorNCINvMs7_B4_NtB4_11Interpreter10sort_keyedBH_NCNvB1D_13sort_with_keys0_0Es2_0EB4_ _RINvMs0_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapINtNtCs1C1lLj4PWSY_5alloc4sync3ArceEuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs7usbkSbEEZs_16weavepy_compiler4name2FxEE6retainNCINvMs_NtB8_3setINtB3b_7HashSetBO_B1p_E6retainNCNvMs1_B2e_NtB2e_4Pool6intern0E0EB2g_ _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtB1L_4sync7GilCellNtNtB1L_6object8DictDataEEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib7csv_mod8dialects0E0zE0E0B1L_.llvm.6970241935485176696 -_RNCNvMNtCs5HK7yca7OMW_10weavepy_vm13builtin_typesNtB4_12BuiltinTypes5builds7_0B6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native8new_dict _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native11new_context -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native12installed_as _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtNtCsevLNFiNqfJP_4core3mem13manually_drop12ManuallyDropINtNtB11_4cell7RefCellNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEE4withNCNvNtNtB2h_6stdlib18contextvars_native7current0B2d_EB2h_ _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterINtNtB1f_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEENCNvMs7_B2M_NtB2M_11Interpreter18function_type_call0EB2I_EB2M_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtB6_6string6StringEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB1W_6filter6FilterINtNtNtB20_5slice4iter4IterB11_ENCNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB3M_10TypeObject19member_slots_sorted0EEE9from_iterB3O_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtB15_7dictmap4KeysNCNvB15_19dict_view_set_elems0EE9from_iterB15_ _RINvNtCs5HK7yca7OMW_10weavepy_vm10specialize7kw_permINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtBX_5slice4iter4IterNtNtB4_6object6ObjectENCNvNtNtB4_9frame_jit7records14ctor_direct_kws_0EEB4_ -_RNvMs_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_nativeNtB4_4Fast7popleft -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native13deque_popleft _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10list_clearINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10atexit_mod10a_registerINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1M_EEE4callB8_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isupperINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod9pure_iterINtNtNtCsevLNFiNqfJP_4core3ops8function5FnMutTRNtNtB8_6object6ObjectEE8call_mutB8_.llvm.5678553137184841714 _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins5b_setINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time7time_ns _RNvXsc_NtNtCs2qMPZxtgKFx_10num_bigint6bigint11subtractionNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops5arith3SublE3sub _RNvXs0_NtNtCs2qMPZxtgKFx_10num_bigint6bigint11subtractionNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops5arith3SubRBT_E3sub -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtNtB6_6object10PyFunctionE3newB6_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter37prune_globals_missing_hooks_sometimes -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexINtNtNtNtB7_11collections4hash3map7HashMapjTINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakINtNtB29_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VechEEEjEEEE10initializeNCINvB2_11get_or_initNCNvNtB29_6object20bytearray_export_map0E0zEB29_ _RNvYNCNKNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native7CURRENT0s_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1m_6option6OptionQIB21_INtNtNtB1m_3mem13manually_drop12ManuallyDropINtNtB1m_4cell7RefCellNtNtBc_6object6ObjectEEEEEE9call_onceBc_.llvm.10617736694814397161 -_RNvXs2_NtNtCs2qMPZxtgKFx_10num_bigint7biguint11subtractionNtB7_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops5arith9SubAssignmE10sub_assign -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB6_11Interpreter13seq_strict_kw -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB6_11Interpreter9seq_build -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10struct_mod14install_structINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins7b_bytesINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19format_template_str -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10bytes_data _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13bytes_argview -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10b_bytes_kw -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10struct_mod14install_struct -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10struct_mod5build -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier218wpjit_dyn_attr_get0B5_ _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier26key_is -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214wpjit_list_get -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier212pin_memo_hit _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_20retire_native_driver0uEBZ_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer11pinned_list -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer9list_elem -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer13emit_list_set _RNvNtCs5HK7yca7OMW_10weavepy_vm13vm_singletons15not_implemented -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE7or_elseNCNvNtBM_5tier218wpjit_dyn_attr_gets_0EBM_ _RNvMsf_NtCs5HK7yca7OMW_10weavepy_vm4syncINtB5_7GilCellINtNtB7_2rc2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEE10try_borrowB7_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB12_6object10PyPropertyEEEB12_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16leaf_site_getter _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19leaf_getter_code_ok _RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter9leaf_evalKb1_Kb0_EB6_ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16leaf_getter_read @@ -9905,24 +7679,15 @@ _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_setitem_hotKm4_EB4_ _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit10ctor_drain _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit16plain_class_attr _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14h_contains_hotKm1_EB4_ -_RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15str_accumulator -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmTNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeBP_EINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertBT_ _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer14laid_out_slots -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionTRNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyRNtBM_6ObjectEE6filterNCNvMs7_BO_NtBO_11Interpreter26leaf_cached_instance_field0EBO_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE7or_elseNCNvMs7_BN_NtBN_11Interpreter26leaf_cached_instance_fields0_0EBN_ _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionTRNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyRNtBM_6ObjectEE6filterNCNvNtBO_5tier214wpjit_attr_gets1_0EBO_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11set_discardINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11set_discard _RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_load_globals3_0B5_ -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared5pivot11median3_recjNvYjNtNtBa_3cmp10PartialOrd2ltECsd5p0HaiaiO6_11weavepy_jit _RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB5_5TableuE17swap_remove_indexB7_ _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer13emit_cell_get _RNvMNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod9lru_stateNtB2_5Links4push _RNvMNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod9lru_stateNtB2_5Links5touch _RNvNtCs5HK7yca7OMW_10weavepy_vm6object25bytearray_check_resizable _RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE20replace_index_uniqueB7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit7h_unary -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5error14TracebackEntryEBF_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14operator_accel15itemgetter_callINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native7dd_initINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1Q_EEE4callB8_ _RINvCs5HK7yca7OMW_10weavepy_vm15h_inst_dict_getKm2_EB2_ @@ -9931,74 +7696,48 @@ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native7dd_init _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14operator_accel15itemgetter_call _RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm11weak_object10WeakObjectE16extend_desugaredINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1X_6filter6FilterINtNtB6_5drain5DrainNtNtBK_8gc_trace17DeferredContainerENCNvMsg_B3p_NtB3p_7GcState19sweep_deferred_froms0_0ENvMso_B3p_B3n_9into_weakEEBK_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters3map3MapINtNtBG_6filter6FilterINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainNtNtCs5HK7yca7OMW_10weavepy_vm8gc_trace17DeferredContainerENCNvMsg_B2e_NtB2e_7GcState19sweep_deferred_froms0_0ENvMso_B2e_B2c_9into_weakEEB2g_.llvm.4650670488983980854 -_RNvNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan13new_container _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot16get_inst_unbound -_RNvNtCs5HK7yca7OMW_10weavepy_vm5error19stop_iteration_with -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_delete_fast _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtB4_6option6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEBC_EEB12_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15gen_method_send _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapINtNtNtB2x_5slice4iter4IterNtNtB15_6object6ObjectENCNvNtNtB15_6stdlib14decimal_native7install0EE9from_iterB15_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtB8_6string6StringEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB22_5slice4iter4IterTB13_NtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEENCNvMs7_B3h_NtB3h_11Interpreter16bind_python_argss_0EE9from_iterB3h_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VechEINtB2_18SpecFromIterNestedhINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtNtB1D_3str4iter5CharsNCNvCs5HK7yca7OMW_10weavepy_vm9binary_ops6_0EE9from_iterB2L_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapINtNtNtB2n_5slice4iter4IterB11_ENCNvMs7_B15_NtB15_11Interpreter11do_pow_calls0_0EE9from_iterB15_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtNtCsgHYyB3hU8Ec_3std4sync9once_lock8OnceLockIBC_NtNtNtBG_6stdlib14decimal_native5StateEEEEBG_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtBG_6stdlib14decimal_native5StateEEBG_ -_RNvCs5HK7yca7OMW_10weavepy_vm20builtin_display_name -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10str_lstripINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14decimal_native7installINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtNtNtB6_6stdlib14decimal_native5StateE3newB6_ _RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcINtNtNtCsgHYyB3hU8Ec_3std4sync9once_lock8OnceLockIBA_NtNtNtB6_6stdlib14decimal_native5StateEEE3newB6_ _RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterThReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB14_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtBY_6stdlib14decimal_native5StateEE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEBY_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecTRexEEE10initializeNCINvB2_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10locale_mod18langinfo_constants0E0zEB2c_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10locale_mod5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10locale_mod7builtin -_RNvNtCs5HK7yca7OMW_10weavepy_vm14descr_registry20builtin_module_value _RNvNtCs5HK7yca7OMW_10weavepy_vm14descr_registry17module_of_builtin _RNvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB2_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtBX_6stdlib14decimal_native5StateEE10try_insertBX_ -_RNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint5shift12biguint_shr2 _RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecThReNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEE8push_mutBN_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod13lower_unicode _RNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint8division7div_rem _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtB12_6stdlib14decimal_native5StateEEEB12_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14decimal_native7install _RNvMs2_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14decimal_nativeNtB5_5Names3new -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14decimal_native8interned _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14decimal_native5build _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11do_pow_call _RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter11do_pow_calls_0B7_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17core_native_binop _RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtNtBc_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrEIBS_TReNtNtNtB1l_6stdlib14decimal_native5RoundEEENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvNvB2X_3any5checkTRB1h_RB2e_ENCNvB2j_7installs_0E0INtNtNtBc_3ops12control_flow11ControlFlowuEEB1l_ _RNvXsi_NtNtCs2qMPZxtgKFx_10num_bigint6bigint8divisionRNtB7_6BigIntNtNtNtCsevLNFiNqfJP_4core3ops5arith3Rem3rem _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins5b_pow _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11bigint_from -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10str_lstrip -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native10leaf_binop -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecTRexEEE10initializeNCINvB1a_11get_or_initNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10locale_mod18langinfo_constants0E0zE0E0B30_.llvm.6970241935485176696 _RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject19is_super_proxy_type -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215wpjit_iter_next _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_23try_borrowed_dyn_scalar0INtNtB1P_6option6OptionNtB2n_18BorrowedScalarCallEEBZ_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11spread_ctor -_RNvCs5HK7yca7OMW_10weavepy_vm22certain_miss_error_obj _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215wpjit_const_str _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit6NativeEE10initializeNCINvB2_11get_or_initNCINvB1x_3runKb1_E0E0zEB1B_ _RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm5fsqrt _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math6to_f64 _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math9math_sqrt -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21leaf_attr_store_ready _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit8h_global _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit6NativeEE10initializeNCINvB1a_11get_or_initNCINvB2k_3runKb1_E0E0zE0E0B2o_.llvm.6970241935485176696 _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer19emit_math_intrinsic -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer15emit_list_slice _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder10stack_addr _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4sqrt _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder11stack_store _RNvMNtCs89hHMyD40Kn_15weavepy_codegen7builderNtB2_15FunctionBuilder7def_var -_RINvNtCs5HK7yca7OMW_10weavepy_vm5tier226call_with_activation_shellINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB4_6object6ObjectNtNtB4_5error12RuntimeErrorENCNvB2_23wpjit_call_method_inners6_0EB4_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier217wpjit_call_method -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier218finish_interp_call -_RINvMs9_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB8_11Interpreter11plan_getterKb1_EB8_ -_RNvMs4_NtCs5HK7yca7OMW_10weavepy_vm9leaf_planNtB5_7Pending6latest _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4sdiv _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier218finish_native_call _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer16emit_dyn_setitem @@ -10006,105 +7745,46 @@ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core13random_random _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11random_core11random_from.llvm.6970241935485176696 _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyuEEINtB2_12SpecFromIterBU_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_5drain5DrainINtNtBZ_7dictmap6BucketuEENCINvMs6_B3f_INtB3f_5TableuE5drainNtNtNtB2d_3ops5range9RangeFullE0EE9from_iterBZ_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9set_clearINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel8siftdown -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel7heap_lt -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel6siftup _RINvMNtCs5HK7yca7OMW_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1t_3ops5range5RangejENCNvNtB5_5tier217wpjit_build_tuples0_0EEB5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215wpjit_unbox_int _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier217wpjit_build_tuple _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer14emit_build_map -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer16emit_list_append -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects10with_matchINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_14match_position0E0B8_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects9match_end -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects14match_position -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline8kw_names -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBG_6object6PyFileEEBG_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10file_writeINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13file_getvalueINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9str_countINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib2io20stringio_newline_arg -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib2io18wrap_memory_stream -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib2io12stringio_new _RNvYNCNKNvNtCs5HK7yca7OMW_10weavepy_vm3gil14NO_YIELD_DEPTH0s_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB15_6option6OptionQIB1K_INtNtB15_4cell4CellmEEEEE9call_onceBa_.llvm.16911827322050435359 -_RNvXs0_NvMs_NtNtCs1C1lLj4PWSY_5alloc3ffi5c_strNtBa_7CString3newReNtB5_11SpecNewImpl13spec_new_impl _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectB19_EEEB1d_ -_RNvCs5HK7yca7OMW_10weavepy_vm10format_int _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile11set_newline _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile8writable -_RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_7PyFrame8set_back _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile8getvalue _RNvMs1l_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB6_6PyFile15mem_text_append _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13file_getvalue -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12substr_count -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9str_count _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10file_write _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir9StrMethodENCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier216str_method_table00ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB35_8for_each4callINtNtB2e_2rc2RcNtNtB2e_6object9BuiltinFnENCINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB4W_3VecB48_E14extend_trustedBN_E0E0EB2e_ _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13k_str_isdigit _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13k_str_isalpha _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB18_6object9BuiltinFnEEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2I_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir9StrMethodENCNCNvNtB18_5tier216str_method_table00EE9from_iterB18_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isalphaINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isdigitINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB1v_6object9BuiltinFnEEE10initializeNCINvB2_11get_or_initNCNvNtB1v_5tier216str_method_table0E0zEB1v_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit8h_subscr -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit7h_fieldKb0_EB6_ -_RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_5Lower17inline_class_attr _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216wpjit_str_method _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isalpha -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isdigit _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB2i_6object9BuiltinFnEEE10initializeNCINvB1a_11get_or_initNCNvNtB2i_5tier216str_method_table0E0zE0E0B2i_.llvm.6970241935485176696 -_RNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecNtB5_11RawVecInner17try_reserve_exactCs5HK7yca7OMW_10weavepy_vm -_RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters4skipINtB5_4SkipINtNtB7_9enumerate9EnumerateINtNtNtBb_5slice4iter4IterINtNtBb_6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEEEENtNtNtB9_6traits8iterator8Iterator8try_folduNCINvNvB2Z_3all5checkTjRB1Q_ENCNvMs_NtB2g_6engineNtB4h_12InlineMethod2ofs1_0E0INtNtNtBb_3ops12control_flow11ControlFlowuEEB2g_ _RNvXsf_NtNtCsevLNFiNqfJP_4core5slice3cmpNtNtCsd5p0HaiaiO6_11weavepy_jit6engine7FieldAtNtB5_13SliceContains14slice_containsBG_ -_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12AttrSiteMetaENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvMs_NtBU_6engineNtB2t_12InlineMethod2ofs3_0EBU_ -_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir5TStmtENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvMs_NtBU_6engineNtB2l_12InlineMethod2ofs5_0EBU_ _RNvMs_NtCsd5p0HaiaiO6_11weavepy_jit6engineNtB4_12InlineMethod11with_fields -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsd5p0HaiaiO6_11weavepy_jit6engine12InlineMethodEBF_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16leaf_eval_nested -_RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapINtNtNtB6_5slice4iter4IterINtNtB6_6option6OptionNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEENCNvMs_NtB1W_6engineNtB2K_12InlineMethod2ofs4_0EB1S_IB1x_NtNtB6_7convert10InfallibleENCINvXsI_B1z_IB1x_INtNtCs1C1lLj4PWSY_5alloc3vec3VecB1S_EEINtNtNtB4_6traits7collect12FromIteratorB1w_E9from_iterBQ_E0B4i_EB1W_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer19inline_method_guard -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer23emit_call_method_inline _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEINtB2_12SpecFromIterBU_INtNtNtCsevLNFiNqfJP_4core4iter8adapters12GenericShuntINtNtB24_3map3MapINtNtNtB28_5slice4iter4IterINtNtB28_6option6OptionBU_EENCNvMs_NtBY_6engineNtB4a_12InlineMethod2ofs4_0EIB3C_NtNtB28_7convert10InfallibleEEE9from_iterBY_ -_RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemNtNtCsd5p0HaiaiO6_11weavepy_jit6engine7FieldAtNtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEBP_ -_RINvXs_NtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elembNtB5_12SpecFromElem9from_elemNtNtB9_5alloc6GlobalECsd5p0HaiaiO6_11weavepy_jit -_RINvXs_NtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemyNtB5_12SpecFromElem9from_elemNtNtB9_5alloc6GlobalECsd5p0HaiaiO6_11weavepy_jit _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtB8_3zip3ZipIBY_INtNtNtBc_5slice4iter4IterNtNtCs1C1lLj4PWSY_5alloc6string6StringEIB1i_NtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEEIB1i_mEENCNvNtCs5HK7yca7OMW_10weavepy_vm5tier218inline_method_bodysf_0ENtNtNtBa_6traits8iterator8Iterator4folduNCINvNvB4j_8for_each4callNtNtB2t_6engine7FieldAtNCINvMsk_NtB1L_3vecINtB5S_3VecB5m_E14extend_trustedBN_E0E0EB3o_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecmEINtB4_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1F_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12AttrSiteMetaENCNvMs_NtB2P_6engineNtB3F_12InlineMethod2ofs9_0EE9from_iterB2P_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir3TOpEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2j_5slice4iter4IterNtB15_5TStmtENCNvMs_NtB17_6engineNtB3J_12InlineMethod2ofs6_0EE9from_iterB17_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit5value7JitTypeEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2q_5slice4iter4IterNtNtB17_2ir12AttrSiteMetaENCNvMs_NtB17_6engineNtB43_12InlineMethod2ofs8_0EE9from_iterB17_ -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtB8_6string6StringEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB22_5slice4iter4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir12AttrSiteMetaENCNvMs_NtB3c_6engineNtB42_12InlineMethod2ofs7_0EE9from_iterB3c_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrBG_EENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBK_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtNtBW_6stdlib12pickle_accel6encode9ClassPlanEEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_NtNtBW_8fasthash13FxBuildHasherE0EBW_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm6importNtB4_11ModuleCache6remove _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11dunder_call _RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit11dunder_call0B5_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects15pattern_findall -_RNCNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects15pattern_findall00B9_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects13pattern_split -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_15pattern_findall0E0B8_ -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_13pattern_split0E0B8_ -_RNCNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects13pattern_split00B9_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNCNvB2n_13try_enter_osrs_00uEBZ_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14sqlite3_native14install_getset _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjINtNtCs1C1lLj4PWSY_5alloc4sync3ArcNtNtCs5HK7yca7OMW_10weavepy_vm4sync8RealLockEEE12remove_entryNCINvNtB8_3map14equivalent_keyjjBR_E0EB1t_ _RINvMNtCsevLNFiNqfJP_4core3stre18trim_start_matchesNvMNtNtB5_4char7methodsc13is_whitespaceECs5HK7yca7OMW_10weavepy_vm -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13str_split_sep _RINvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE12get_index_ofNtNtNtB8_6stdlib13functools_mod9ArgsProbeEB8_ _RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod9lru_probes_0B7_ _RNvXs1_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_modNtB5_9ArgsProbeNtNtB9_7dictmap5Probe8probe_eq -_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBL_5types10PyInstanceEE14extend_trustedINtNtCsevLNFiNqfJP_4core6option8IntoIterBG_EEBL_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir6TBlockEEB1c_ -_RNvCs5HK7yca7OMW_10weavepy_vm21lookup_exception_init _RNvMsy_NtCs5HK7yca7OMW_10weavepy_vm12shared_valueNtB5_9SharedStr10ascii_char -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native10valid_date -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native10new_packed -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native11verify_slow.llvm.10617736694814397161 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native6new_dt -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native9td_fields -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native5tz_of -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native6new_td _RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_nativeNtB2_11PackedSlots5clear _RINvXsx_NtCs5HK7yca7OMW_10weavepy_vm7dictmapNtB6_6SetMapINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorNtNtB8_6object7DictKeyE9from_iterINtNtNtBZ_8adapters6cloned6ClonedINtNtB2u_6filter6FilterINtB6_4KeysuENCNCNCNvB8_17set_algebra_plain000EEEB8_ -_RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objectsNtB2_7Subject5group _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE19max_until_iterativeB9_ _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12code_replace _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins8set_copy @@ -10133,7 +7813,6 @@ _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTlsEE6retainNCNvNtNtCs5HK7yca7OMW_10 _RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE6retainNCNvNtNtBJ_6stdlib11asyncio_mod18awaited_by_discard0EBJ_ _RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectNtNtNtBK_6stdlib11asyncio_mod9CbContextEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBK_ _RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecTNtNtB8_6string6StringNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEE14extend_trustedINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtNtB2b_5slice4iter4IterBG_EEEB16_ -_RNvMsb_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB5_11SplitValues8get_memo _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort31small_sort_general_with_scratchNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectNCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB1s_11sort_by_keyNtNtB2i_6string6StringNCNvNtNtB1w_6stdlib2os19os_get_exports_lists_0E0EB1w_ _RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort12sort8_stableNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectNCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB19_11sort_by_keyNtNtB1Z_6string6StringNCNvNtNtB1d_6stdlib2os19os_get_exports_lists_0E0EB1d_ _RNvNvNtCs5HK7yca7OMW_10weavepy_vm12type_surface21install_value_richcmp9fam_tuple @@ -10148,8 +7827,6 @@ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10select_mod1b _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10select_mod13poll_register _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10select_mod9poll_poll _RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtB1a_6object6ObjectEEB1a_.llvm.4890245414193407415 -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueANtNtCs5HK7yca7OMW_10weavepy_vm6object6Objectj4_EBG_.llvm.2221200793792468279 -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm6object14GeneratorStateEBF_.llvm.3987546058129701445 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11asyncio_mod7FutColdEEEB1C_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtBG_4sync7GilCellNtNtBG_7dictmap6SetMapEEEBG_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtNtBG_6stdlib11asyncio_mod8FutStateEEBG_ @@ -10193,7 +7870,6 @@ _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14asyncio_events5NamesE10initializeNCINvB1a_11get_or_initNCNvB1I_5names0E0zE0E0B1M_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib11asyncio_mod21future_iter_class_ref0E0zE0E0B1L_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE10initializeNCINvB1a_11get_or_initNCNvNtNtB1K_6stdlib11asyncio_mod18task_step_callable0E0zE0E0B1K_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6NativeEEE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0B2V_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrE10initializeNCINvB1a_11get_or_initNCNvNtNtB1K_6stdlib11asyncio_mod10handle_key0E0zE0E0B1K_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once9call_onceNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11asyncio_mod17register_gc_hooks0E0B16_ _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib11asyncio_mod16future_class_ref0E0zE0E0B1L_.llvm.6970241935485176696 @@ -10203,18 +7879,12 @@ _RNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types12any_elements _RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types29install_numeric_class_methods11self_as_int _RINvNtCs5HK7yca7OMW_10weavepy_vm3gil18allow_threads_thenINtNtCsevLNFiNqfJP_4core6result6ResultjNtNtNtBX_2io5error5ErrorENCINvNtNtB4_6stdlib10select_mod14blocking_retryNCNvB1Z_9poll_polls0_0Es0_0EB4_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native12copy_current -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native5enter _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native5state.llvm.10617736694814397161 _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native7data_of _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native12context_over -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native6run_in -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native4call -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native16fire_switch_hook _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native12copy_context -_RNvYNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native10is_context0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRNtB6_5StateEE9call_onceBa_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native12current_data _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native14run_in_context -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18contextvars_native4exit _RINvNtCs1C1lLj4PWSY_5alloc3str17join_generic_copyehNtNtB4_6string6StringECs5HK7yca7OMW_10weavepy_vm _RNvNtCskWRQMoMZ5YU_7socket23sys15set_nonblocking _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs1C1lLj4PWSY_5alloc4sync3ArcINtNtCs5UJUBJEE7PZ_8lock_api5mutex5MutexNtNtCs2zRUMDvV71V_11parking_lot9raw_mutex8RawMutexNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11asyncio_mod8TaskSlotEEE4withNCNvB2W_15leave_task_impl0INtNtCsevLNFiNqfJP_4core6result6ResultNtNtB30_6object6ObjectB53_EEB30_ @@ -10228,7 +7898,6 @@ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtNtCsevLNFiNqfJP_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtBZ_6object6ObjectEE4withNCNvNtNtBZ_6stdlib11asyncio_mod16set_running_loops_0uEBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_5types10TypeObjectEEEE4withNCNvNtNtBZ_6stdlib4time19time_get_clock_info0B2e_EBZ_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtBZ_6object6ObjectEE4withNCNvNtNtBZ_6stdlib11asyncio_mod15is_running_loop0bEBZ_ -_RNvMsg_NtCs5HK7yca7OMW_10weavepy_vm8gc_traceNtB5_7GcState12untrack_slot.llvm.15809725932051974371 _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB2j_6filter6FilterINtNtNtB2n_5slice4iter4IterNtNtCs1YyxYnRES6i_4libc4unix6pollfdENCNvNtNtB15_6stdlib10select_mod9poll_polls1_0ENCB4s_s2_0EE9from_iterB15_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtB8_6string6StringEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB22_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENvNvMs1s_B3a_B38_4repr15type_param_reprEE9from_iterB3c_ _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecReEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1J_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENCNvMs7_B2T_NtB2T_11Interpreter15leaf_burst_slows1_0EE9from_iterB2T_ @@ -10263,12 +7932,6 @@ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod19chain_from_iterable _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod10chain_core _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod16filterfalse_core _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4bnot -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native15deque_make_iter -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native10deque_iter -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native8receiver -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native7head_of -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native10deque_next -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native19deque_iterator_next _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib3sys22sys_set_asyncgen_hooksINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1Q_EEE4callB8_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10socket_mod10sock_closeINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvYNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib3sys5buildsc_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRSNtNtBa_6object6ObjectEE9call_onceBa_ @@ -10341,7 +8004,6 @@ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11asyncio_mod19native_future_await _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11asyncio_mod15future_iter_new _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11asyncio_mod15leave_task_impl _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11asyncio_mod24fut_remove_done_callback -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time14time_monotonic _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time19time_get_clock_info _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8ssl_real5build _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8ssl_real7builtin @@ -10368,7 +8030,6 @@ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10w _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockTFG_RL0_NtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEbFG_RL0_B11_EuEE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEB15_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrE10initializeNCINvB2_11get_or_initNCNvNtNtBX_6stdlib11asyncio_mod10handle_key0E0zEBX_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib11asyncio_mod14task_class_ref0E0zEBY_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCINvMs8_B26_NtB28_11Interpreter12leaf_run_retKb0_Kb1_KB4c_E0E0zEB28_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE10initializeNCINvB2_11get_or_initNCNvNtNtBX_6stdlib11asyncio_mod20task_wakeup_callable0E0zEBX_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib10socket_mod12herror_class0E0zEBY_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14asyncio_events5NamesE10initializeNCINvB2_11get_or_initNCNvBV_5names0E0zEBZ_ @@ -10406,7 +8067,6 @@ _RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdli _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14bytes_split_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1E_EEE4callB6_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10struct_mod10b_calcsizeINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11bytes_countINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins15bytes_maketransINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11hashlib_mod13hasher_digestINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11hashlib_mod16hasher_hexdigestINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvNtCshVRm6FbZCmu_7zlib_rs7adler327adler32 @@ -10418,7 +8078,6 @@ _RINvXs4_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB6_8IntoIterINtB8_3VechEENtNtN _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib11hashlib_mod13blake2s_class0E0zEBY_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib11hashlib_mod13blake2b_class0E0zEBY_ _RNvMsf_NtCs5HK7yca7OMW_10weavepy_vm4syncINtB5_7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VechEE14try_borrow_mutB7_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib8zlib_mod16zlib_error_class0E0zEBY_ _RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexINtNtNtNtB7_11collections4hash3map7HashMapxINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtB28_4sync7GilCellNtNtNtB28_6stdlib11hashlib_mod9AnyHasherEEEEE10initializeNCINvB2_11get_or_initNCNvB32_10hasher_reg0E0zEB28_ _RNvYNCNKNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10struct_mod9BY_STRING00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1e_6option6OptionQIB1T_INtNtB1e_4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtBc_12shared_value9SharedStrINtNtB2M_2rc2RcNtB8_14CompiledFormatEEEEEEEE9call_onceBc_ _RNvYNCNKNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod8ONE_SHOT00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1a_6option6OptionQIB1P_INtNtB1a_4cell7RefCellIB1P_TTxxENtNtCsiffXY6Ju0YY_6flate23mem8CompressEEEEEEE9call_onceBc_ @@ -10430,7 +8089,6 @@ _RNvXs3_NtCsjmbvDdRzfi9_4sha28core_apiNtB5_13Sha256VarCoreNtNtCs2UaUYYC4cvx_6dig _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterINtB4_3VechEENCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14bytes_split_kw0ENtNtB2E_6object6ObjectEB2E_ _RNvMNtNtNtNtCskRQrKhBUP4e_6memchr4arch6x86_644avx210packedpairNtB2_6Finder9find_impl _RNvMNtNtNtNtCskRQrKhBUP4e_6memchr4arch6x86_644avx210packedpairNtB2_6Finder14with_pair_impl -mi_malloc_aligned _RNvNtCshVRm6FbZCmu_7zlib_rs7inflate22inflate_fast_help_avx2 _RNvNtCshVRm6FbZCmu_7zlib_rs7inflate3end _RNvNtCshVRm6FbZCmu_7zlib_rs7inflate4init.llvm.6306339924579622046 @@ -10473,24 +8131,18 @@ _RINvMs1y_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB7_6Object12new_set_fromINtNtNtNt _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16bytes_split_args _RNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11bytes_counts_0B5_ _RNCINvNtCs5HK7yca7OMW_10weavepy_vm8builtins9method_kwNvB4_14bytes_split_kwEs_0B6_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins15bytes_maketrans _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11bytes_count _RNvNtNtCskRQrKhBUP4e_6memchr6memmem8searcher18searcher_kind_avx2 _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod15zlib_decompress _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod12deflate_step _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod12inflate_step -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod5build _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod13zlib_compress _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod16build_decompress -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod1b _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod14build_compress -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod4b_kw _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib8zlib_mod13reject_kwargs _RNvNtNtCsjmbvDdRzfi9_4sha26sha2564soft8compress _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringINtNtBR_2rc2RcNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10struct_mod14CompiledFormatENtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertB1J_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapxINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtBT_4sync7GilCellNtNtNtBT_6stdlib11hashlib_mod9AnyHasherEENtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBT_ -mi_good_size -_mi_bin_size _RNvNtNtCshVRm6FbZCmu_7zlib_rs7inflate8inftrees13inflate_table _RNvNtNtNtCshVRm6FbZCmu_7zlib_rs7deflate9algorithm6medium14deflate_medium _RNvNtNtCshVRm6FbZCmu_7zlib_rs7deflate13longest_match13longest_match @@ -10525,16 +8177,11 @@ _RNvNtCshVRm6FbZCmu_7zlib_rs7deflate16flush_block_only _RNvMs7_NtCshVRm6FbZCmu_7zlib_rs7deflateNtB5_5State6header _RNvMsa_NtCshVRm6FbZCmu_7zlib_rs7deflateNtB5_4Heap10pqdownheap mi_theap_malloc_zero_aligned_at_overalloc -mi_theap_malloc_zero_aligned_at_generic -mi_theap_malloc_aligned _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib11hashlib_mod13blake2b_class0E0zE0E0B1L_.llvm.6970241935485176696 -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib8zlib_mod16zlib_error_class0E0zE0E0B1L_.llvm.6970241935485176696 _RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib11hashlib_mod13blake2s_class0E0zE0E0B1L_.llvm.6970241935485176696 _RNvNtNtCsbDT9VZrAVwy_3md58compress4soft8compress _RNvNtNtNtCskRQrKhBUP4e_6memchr4arch3all9rabinkarp12is_equal_raw -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12binascii_mod11register_kw _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12binascii_mod13b2a_base64_kw -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12binascii_mod5build _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12binascii_mod12buffer_bytes _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12binascii_mod13a2b_base64_kw _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12binascii_mod11input_bytes @@ -10549,44 +8196,31 @@ _RINvCs5HK7yca7OMW_10weavepy_vm10h_list_setKm1_EB2_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTmmINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBN_9inst_dict10SharedKeysEEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBN_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakNtNtBH_6object10PyFunctionEINtBF_2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEjEEBH_.llvm.4650670488983980854 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtB4_6result6ResultINtNtB4_6option6OptionbENtNtCs5HK7yca7OMW_10weavepy_vm5error12RuntimeErrorEbEEB1q_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm8gc_trace19clear_object_fields0B5_ _RNvCs5HK7yca7OMW_10weavepy_vm20code_name_leaf_probe _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter22load_attr_certain_miss _RINvCs5HK7yca7OMW_10weavepy_vm15h_inst_dict_setKm0_EB2_ _RINvCs5HK7yca7OMW_10weavepy_vm10h_dict_setKm4_EB2_ _RNvMsQ_Cs5HK7yca7OMW_10weavepy_vmNtB5_10MethodSlot10set_static -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20leaf_instance_dunder _RINvCs5HK7yca7OMW_10weavepy_vm10h_dict_setKm2_EB2_ _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_setitem_hotKm2_EB4_ _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit12k_str_format _RINvNtCs5HK7yca7OMW_10weavepy_vm6object20with_key_eq_deferredINtNtCsevLNFiNqfJP_4core6result6ResultINtNtB12_6option6OptionbENtNtB4_5error12RuntimeErrorENCNvMs7_B4_NtB4_11Interpreter17leaf_builtin_calls4_0EB4_ _RINvMs0_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapPNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs5HK7yca7OMW_10weavepy_vm5tier210CacheEntryEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtB2a_18CodeIdentityHasherEE6retainNCNvB2a_11cache_entry0EB2c_ -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer11emit_is_obj _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxShEECs7usbkSbEEZs_16weavepy_compiler.llvm.3546700407397947748 _RNvMs3_NtCs5HK7yca7OMW_10weavepy_vm16weakref_registryNtB5_15WeakRefRegistry12notify_clear -_RNvNvNtCs7usbkSbEEZs_16weavepy_compiler11native_code12check_nested14check_constant.llvm.3546700407397947748 -_RNvNtCs7usbkSbEEZs_16weavepy_compiler11native_code6decode _RNvYNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types22install_object_dunders16object_class_getINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastNtNtB4_9inst_dict10SharedKeysEB4_ _RNvNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types22install_object_dunders16object_class_get _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionbENCNCNvMs7_BY_NtBY_11Interpreter17leaf_builtin_calls4_00E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ -_RNvYINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxShENtCs7usbkSbEEZs_16weavepy_compiler9CodeBytes4readBG_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod18lru_store_returned _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit15lru_miss_switch -_RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer12emit_int_neg _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod10LruPendingEEB13_ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18lru_store_returned _RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter18leaf_bind_keywordsINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1d_7flatten7FlatMapINtNtB1h_6option8IntoIterRNtNtB6_6object8DictDataENtNtB6_7dictmap4IterNCNvB2_16try_leaf_call_exs_0ENCB3v_s0_0EEB6_ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter10lru_finish _RNvXs_NtNtNtCsevLNFiNqfJP_4core5array4iter10iter_innerAINtNtNtBa_3mem12maybe_uninit11MaybeUninitNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEj4_NtB4_11PartialDrop12partial_dropB1A_ -_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native16chainmap_maps_of8MapsNameE10initializeNCINvB1a_11get_or_initNCB1I_0E0zE0E0B1O_.llvm.6970241935485176696 _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object8DictDataE18get_or_insert_withNCNvMs7_BM_NtBM_11Interpreter17core_pure_kw_call0EBM_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict15od_popitem_leaf -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict19od_move_to_end_leaf -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib17collections_odict11leaf_unlink _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel12bisect_rightINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1Q_EEE4callB8_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel12insort_rightINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1Q_EEE4callB8_ -_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native16chainmap_maps_of8MapsNameE10initializeNCINvB2_11get_or_initNCBV_0E0zEB11_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel7item_at _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel9do_insert _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel12bisect_right @@ -10594,12 +8228,8 @@ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel21internal_bisect_right _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel12insort_right _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel10parse_args _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12bisect_accel14resolve_bounds -_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterTINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakNtNtBW_6object10PyFunctionEINtBU_2RcNtCs7usbkSbEEZs_16weavepy_compiler10CodeObjectEjEENtNtNtNtBb_4iter6traits8iterator8Iterator3anyNCNvNtNtBW_6stdlib18collections_native18namedtuple_replace0EBW_ _RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE14extend_trustedINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1O_5slice4iter4IterINtNtB1O_6option6OptionRBG_EENCNvMs7_BK_NtBK_11Interpreter19core_native_kw_calls0_0EEBK_ _RINvCs5HK7yca7OMW_10weavepy_vm15h_inst_dict_setKm4_EB2_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native23namedtuple_replace_leaf -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native18namedtuple_replace -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native21chainmap_getitem_leaf _RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcINtNtB6_4sync7GilCellNtNtB6_6object6ObjectEE3newB6_ _RNvMs1_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB5_2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecIBB_INtNtB7_4sync7GilCellNtNtB7_6object6ObjectEEEE8make_mutB7_ _RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib3sys16build_with_states1_0B7_ @@ -10671,7 +8301,6 @@ _RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_nativeNtB2_11PackedSlots13c _RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultINtNtCs5HK7yca7OMW_10weavepy_vm4sync3RefNtNtBN_6object8DictDataENtBL_11BorrowErrorE9is_ok_andNCNvBN_21default_lookup_missess_0EBN_ _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier217wpjit_dyn_getitem _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter11module_attr -_RNvCs5HK7yca7OMW_10weavepy_vm10bm_builtin _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter25materialize_departing_top _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16object_reduce_ex _RINvCs5HK7yca7OMW_10weavepy_vm15h_type_containsKm2_EB2_ @@ -10679,23 +8308,14 @@ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19reduce_ex_proto_arg _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19reduce_newobj_plain.llvm.3987546058129701445 _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15reduce_ex_plain _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter21object_default_reduce -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9list_copy -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9list_copyINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types8exc_init _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_12charge_deopt0uEBZ_ _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7h_raise _RINvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB6_11Interpreter19seed_exception_argsINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtNtB1i_5slice4iter4IterNtNtB6_6object6ObjectEEEB6_ _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17core_raise_return _RINvNtCs5HK7yca7OMW_10weavepy_vm5error11value_errorNtNtCs1C1lLj4PWSY_5alloc6string6StringEB4_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins16parse_int_strings_0B5_ _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier213wpjit_str_mod -_RNvXs_NtNtCs2qMPZxtgKFx_10num_bigint7biguint7convertNtB6_7BigUintNtCshpbnKYGRzWO_10num_traits3Num14from_str_radix -_RNvMsn_NtCs2qMPZxtgKFx_10num_bigint6bigintNtB5_6BigInt11parse_bytes -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm13builtin_types8exc_initINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvXs0_NtCs89hHMyD40Kn_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4fabs _RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math13make_checked10B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math8sin_fast.llvm.9250547820948799359 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math8cos_fast.llvm.9250547820948799359 _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter20store_new_attr_ready _RNvMs2_NtCsd5p0HaiaiO6_11weavepy_jit7analyzeNtB5_9CtorState9elem_root _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit7h_store @@ -10703,9 +8323,7 @@ _RINvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit6h_callKb1_EB6_ _RNvMs_NtCs89hHMyD40Kn_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fabs _RNvMNtCsgHYyB3hU8Ec_3std3f64d3cos _RNvMNtCsgHYyB3hU8Ec_3std3f64d3sin -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215wpjit_list_next _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216exemplar_element -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier215wpjit_list_next0B5_ _RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterINtNtB9_5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm9InlineActEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB1g_ _RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecINtNtB8_5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm9InlineActEE14extend_trustedINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3rev3RevINtNtB6_9into_iter8IntoIterBG_EEEB10_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs5HK7yca7OMW_10weavepy_vm8ChainRecEECsfhlKP0AX26y_7weavepy.llvm.6436589534629793051 @@ -10725,63 +8343,25 @@ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel13heappush_impl _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel12heappop_impl _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter17subscr_set_public _RNvNtCs5HK7yca7OMW_10weavepy_vm6object14leaf_tuples_eq -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier214pack_iter_elem -_RNvNtCs5HK7yca7OMW_10weavepy_vm5tier220wpjit_iter_next_pair _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier217wpjit_dyn_setitem _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier217wpjit_const_tuple _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier215wpjit_build_map -_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB2l_3rev3RevINtNtNtB2p_5slice4iter4IterB13_EEEE9from_iterB17_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel7heappopINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel8heappushINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecmE16extend_desugaredINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtNtB19_3str4iter5CharsNvYmINtNtB19_7convert4FromcE4fromEECs5HK7yca7OMW_10weavepy_vm _RINvXs4_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB6_8IntoIterTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectBY_EENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator8try_foldINtNtB8_13in_place_drop11InPlaceDropBY_ENCINvNtNtB1R_8adapters3map12map_try_foldBX_BY_B2P_INtNtB1T_6result6ResultB2P_zENCNvNtNtB12_6stdlib10json_accel10sort_items0NCINvNtB8_16in_place_collect24write_in_place_with_dropBY_E0E0B4h_EB12_ -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStruNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBR_ _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectB2m_EENCNvNtNtB2q_6stdlib10json_accel10sort_items0EB2m_EB2q_ -_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStruEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_uNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EBU_ -_RNvXNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accelhNtB2_8JsonChar3key -_RNvXNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accelhNtB2_8JsonChar6string -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel12write_indent -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel13finish_object -_RNCNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel17json_make_scanners_00B9_ -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel9scan_oncehEB6_ _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter14unicode_escape _RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel12decode_uxxxxhEB6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel10sort_items -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel12parse_objecthEB6_ -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel21scan_string_with_memohEB6_ _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter6escape -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib10json_accel11parse_arrayhEB6_ -_RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrEB1J_ _RINvMsm_NtCs1C1lLj4PWSY_5alloc2rcINtB6_2RcSNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyE15from_iter_exactINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1L_5chain5ChainINtNtNtB1P_5slice4iter4IterReEB2P_ENCNCNCNvNtNtBJ_6stdlib4time16struct_time_keys000EEBJ_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib2os9os_getpid -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time7checktm -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time14strftime_chunk -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time13time_strftime -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time14time_localtime -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time8gettmarg -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time16strftime_bridged -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time8gettmargs0_0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12weakref_real11ref_type_eq -floor _RNvMsf_NtCs5HK7yca7OMW_10weavepy_vm4syncINtB5_7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionINtNtB7_2rc2RcIBD_INtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB7_6object6ObjectEEEEE10try_borrowB7_ _RNvYNCNKNvNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4time8zone_str4LAST00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTINtNtB1d_6option6OptionQIB1S_INtNtB1d_4cell7RefCellIB1S_TINtNtCs1C1lLj4PWSY_5alloc3vec3VechENtNtBe_6object6ObjectEEEEEEE9call_onceBe_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtBZ_6option6OptionTINtNtCs1C1lLj4PWSY_5alloc3vec3VechENtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEEE4withNCNvNtNtB2v_6stdlib4time8zone_str0B2r_EB2v_ _RINvMs3_NtCs1C1lLj4PWSY_5alloc3stre7replaceReECs5HK7yca7OMW_10weavepy_vm -_RINvMs3_NtCs1C1lLj4PWSY_5alloc3stre7replaceAcj2_ECs5HK7yca7OMW_10weavepy_vm -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtNtCsevLNFiNqfJP_4core4cell4once8OnceCellINtNtCs1C1lLj4PWSY_5alloc2rc2RcSNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyEEEB2o_.llvm.4890245414193407415 -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtB1a_6option6OptionTINtNtCs1C1lLj4PWSY_5alloc3vec3VechENtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEEEEB2H_.llvm.4890245414193407415 -_RNvCs5HK7yca7OMW_10weavepy_vm27percent_format_leaf_mapping -_RNvCs5HK7yca7OMW_10weavepy_vm19percent_format_with -fmod -_RNvNtNtNtCs4d4ibTJ6dSQ_17compiler_builtins4math9libm_math4fmod4fmod -_RNvMs4_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_7PyFrame14current_lineno -_RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_7PyFrame10back_frame -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object21bigint_from_f64_trunc -_RINvMNtNtCsevLNFiNqfJP_4core4cell4onceINtB3_8OnceCellINtNtCs1C1lLj4PWSY_5alloc2rc2RcSNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyEE8try_initNCINvB2_11get_or_initNCNCNvNtNtB1p_6stdlib4time16struct_time_keys00E0zEB1p_.llvm.15809725932051974371 _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13k_str_isspace _RINvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_setitem_hotKm5_EB4_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isspaceINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isalnumINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_5Lower12inline_store _RINvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit7h_fieldKb1_EB6_ _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier213wpjit_str_get @@ -10789,15 +8369,10 @@ _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier212wpjit_str_eq _RNvCs5HK7yca7OMW_10weavepy_vm15code_field_slot _RINvCs5HK7yca7OMW_10weavepy_vm10h_dict_setKm5_EB2_ _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isspace -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isalnum _RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE6spliceINtNtNtCsevLNFiNqfJP_4core3ops5range5RangejEBw_EBK_ -_RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE5drainINtNtNtCsevLNFiNqfJP_4core3ops5range5RangejEEBJ_ _RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter17core_container_ops3_0B7_ -_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_16try_enter_resume0INtNtB1P_6option6OptionNtB2n_13CompiledEntryEEBZ_ _RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvNtBU_9frame_jit10ctor_drain0EBU_ _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216try_enter_resume -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline14h_inline_deref -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inlineNtB7_5Lower17inline_load_deref _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_5Lower8set_bool _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jitNtB5_5Lower5truth _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9leaf_plan3jit8h_method @@ -10824,111 +8399,27 @@ _RNvMs8_NtCs89hHMyD40Kn_15weavepy_codegen2irNtB5_13DataFlowGraph6intern _RINvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE12find_by_hashNCNvNtNtNtB8_6stdlib12pickle_accel7classes8pure_get0EB8_ _RNvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE11try_reserveB7_ _RINvMs6_NtCs5HK7yca7OMW_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE12find_by_hashNCNvMsc_NtNtB8_6stdlib12pickle_accelNtB1A_7Decoder8setitems0EB8_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBL_5types10TypeObjectEIBw_NtNtBL_6object6ObjectEEE8push_mutBL_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir11GlobalGuardE8push_mutBJ_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectyEE8push_mutBK_ _RNvXsp_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel10PlainClassENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBL_ -_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtB7_6string6StringE8push_mutCs5HK7yca7OMW_10weavepy_vm -_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE14extend_trustedINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB6_5drain5DrainTBG_yEENCNvMsc_NtNtBK_6stdlib12pickle_accelNtB32_7Decoder6extend0EEBK_ _RNvMsf_NtNtCsevLNFiNqfJP_4core3str4iterINtB5_13SplitInternalcE4nextCs5HK7yca7OMW_10weavepy_vm -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell4CellINtNtB1a_6option6OptionNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel7ScratchEEEB26_.llvm.4890245414193407415 -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable9quicksort9quicksortNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB15_NtNtBa_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler _RNvMsh_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB5_8InstDict10get_shared -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBG_6object7PyFrameEEBG_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encode9ClassPlanEBJ_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectBD_EEBH_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtNtB12_6stdlib12pickle_accel6encode9ClassPlanEEEB12_ _RINvMNtCs5HK7yca7OMW_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainTNtNtB5_6object6ObjectyEENCNvMsc_NtNtB5_6stdlib12pickle_accelNtB3m_7Decoder5tuple0EEB5_ _RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtNtBc_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEBR_ENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvNvB24_3all5checkTRB1h_B38_ENCNvMs0_NtNtNtB1l_6stdlib12pickle_accel6encodeNtB3q_7Encoder10class_plans_0E0INtNtNtBc_3ops12control_flow11ControlFlowuEEB1l_ -_RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipNtNtCs5HK7yca7OMW_10weavepy_vm7dictmap4IterINtNtNtBc_5slice4iter4IterTINtNtBV_2rc4WeakNtNtBV_5types10TypeObjectENtNtNtBV_6stdlib12pickle_accel13FunctionGuardEEENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvNvB3r_3all5checkTTRNtNtBV_6object7DictKeyRNtB4z_6ObjectERB1Y_ENCNvMs7_B2H_NtB2H_12PicklerGuard5holdss_0E0INtNtNtBc_3ops12control_flow11ControlFlowuEEBV_ _RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapINtNtB2_6filter6FilterNtNtCs5HK7yca7OMW_10weavepy_vm7dictmap4IterNCNvMs5_NtNtB1w_6stdlib12pickle_accelNtB2h_19ClassFunctionsGuard3new0ENCB2b_s_0ENtB2h_13FunctionGuardINtNtB6_6option6OptionNtNtB6_7convert10InfallibleENCINvXsI_B3P_IB3N_INtNtCs1C1lLj4PWSY_5alloc3vec3VecB3r_EEINtNtNtB4_6traits7collect12FromIteratorIB3N_B3r_EE9from_iterBQ_E0B4S_EB1w_ _RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapNtNtCs5HK7yca7OMW_10weavepy_vm7dictmap4IterNCNvMs7_NtNtB1a_6stdlib12pickle_accelNtB1V_12PicklerGuard3new0ETINtNtB1a_2rc4WeakNtNtB1a_5types10TypeObjectENtB1V_13FunctionGuardEINtNtB6_6option6OptionNtNtB6_7convert10InfallibleENCINvXsI_B3W_IB3U_INtNtCs1C1lLj4PWSY_5alloc3vec3VecB2O_EEINtNtNtB4_6traits7collect12FromIteratorIB3U_B2O_EE9from_iterBQ_E0B4Z_EB1a_ _RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapINtNtNtB6_5slice4iter4IterReENCNvMs_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB1G_20ModuleFunctionsGuard3new0ETB1w_NtB1G_13FunctionGuardEINtNtB6_6option6OptionNtNtB6_7convert10InfallibleENCINvXsI_B3x_IB3v_INtNtCs1C1lLj4PWSY_5alloc3vec3VecB33_EEINtNtNtB4_6traits7collect12FromIteratorIB3v_B33_EE9from_iterBQ_E0B4A_EB1K_ _RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapNtNtCs5HK7yca7OMW_10weavepy_vm7dictmap4IterNCNvMs4_NtNtB1a_6stdlib12pickle_accelNtB1V_14UnpicklerGuard3new0EThNtB1V_13FunctionGuardEINtNtB6_6option6OptionNtNtB6_7convert10InfallibleENCINvXsI_B3h_IB3f_INtNtCs1C1lLj4PWSY_5alloc3vec3VecB2Q_EEINtNtNtB4_6traits7collect12FromIteratorIB3f_B2Q_EE9from_iterBQ_E0B4k_EB1a_ -_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell4CellINtNtB1a_6option6OptionNtNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encode9MemoTableEEEB28_.llvm.4890245414193407415 -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared5pivot11median3_recNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB14_NtNtBa_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object20materialize_stack_at -_RNvMs4_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_7PyFrame15locals_snapshot -_RNvMs4_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_7PyFrame22has_live_hidden_locals -_RNvNtCs5HK7yca7OMW_10weavepy_vm6object21materialize_stack_top -_RNvMs4_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB5_7PyFrame14compute_locals -_RNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecNtB5_11RawVecInner11try_reserveCs5HK7yca7OMW_10weavepy_vm -_RNvMs0_NtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder4save -_RNvMs_NtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB4_9MemoTable4grow -_RNvMNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB2_6Framer4data -_RNvMs0_NtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder18memoized_container _RNvMs0_NtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder4long -_RNvMs0_NtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder13save_instance -_RNvMNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB2_6Framer9end_frame -_RNvMs0_NtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder15save_dict_items -_RNvMs0_NtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder7integer -_RNvMs0_NtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder7memoize -_RNvNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encode6encode -_RNvMNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB2_6Framer4open -_RNvMs0_NtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder3get -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtNtBT_6stdlib12pickle_accel6encode9ClassPlanENtNtBT_8fasthash13FxBuildHasherE6insertBT_ -_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjThjEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCs89hHMyD40Kn_15weavepy_codegen6fxhash8FxHasherEE6insertCsd5p0HaiaiO6_11weavepy_jit _RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterNtNtB6_6string6StringEINvMs1y_NtCs5HK7yca7OMW_10weavepy_vm6objectNtB2P_6Object8from_strB2l_EEB3o_EB2R_ -_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable14driftsort_mainNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYBZ_NtNtB8_3cmp10PartialOrd2ltINtNtB13_3vec3VecBZ_EECs7usbkSbEEZs_16weavepy_compiler -_RINvNtCs1C1lLj4PWSY_5alloc5slice11stable_sortNtNtB4_6string6StringNvYBH_NtNtCsevLNFiNqfJP_4core3cmp10PartialOrd2ltECs5HK7yca7OMW_10weavepy_vm _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecThNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel13FunctionGuardEEINtB2_12SpecFromIterBU_INtNtNtCsevLNFiNqfJP_4core4iter8adapters12GenericShuntINtNtB2u_3map3MapNtNtB12_7dictmap4IterNCNvMs4_BY_NtBY_14UnpicklerGuard3new0EINtNtB2y_6option6OptionNtNtB2y_7convert10InfallibleEEE9from_iterB12_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecTReNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel13FunctionGuardEEINtB2_12SpecFromIterBU_INtNtNtCsevLNFiNqfJP_4core4iter8adapters12GenericShuntINtNtB2v_3map3MapINtNtNtB2z_5slice4iter4IterBV_ENCNvMs_BZ_NtBZ_20ModuleFunctionsGuard3new0EINtNtB2z_6option6OptionNtNtB2z_7convert10InfallibleEEE9from_iterB13_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecTINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakNtNtB10_5types10TypeObjectENtNtNtB10_6stdlib12pickle_accel13FunctionGuardEEINtB2_12SpecFromIterBU_INtNtNtCsevLNFiNqfJP_4core4iter8adapters12GenericShuntINtNtB3b_3map3MapNtNtB10_7dictmap4IterNCNvMs7_B21_NtB21_12PicklerGuard3new0EINtNtB3f_6option6OptionNtNtB3f_7convert10InfallibleEEE9from_iterB10_ _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel13FunctionGuardEINtB2_12SpecFromIterBU_INtNtNtCsevLNFiNqfJP_4core4iter8adapters12GenericShuntINtNtB2r_3map3MapINtNtB2r_6filter6FilterNtNtB10_7dictmap4IterNCNvMs5_BW_NtBW_19ClassFunctionsGuard3new0ENCB4h_s_0EINtNtB2v_6option6OptionNtNtB2v_7convert10InfallibleEEE9from_iterB10_ -_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable5drift4sortNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYBW_NtNtBa_3cmp10PartialOrd2ltECs7usbkSbEEZs_16weavepy_compiler _RNvXsg_NtCskibSv91bgl1_9hashbrown3rawINtB5_8RawTableTjINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtNtBV_6stdlib12pickle_accel6encode9ClassPlanEEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBV_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectyEE6filterNCNvMsc_NtNtBN_6stdlib12pickle_accelNtB1J_7Decoder5parses_0EBN_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionINtNtCs1C1lLj4PWSY_5alloc3vec3VechEE6map_orNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectNCNCNvNtNtB1t_6stdlib12pickle_accel10make_dumps0s_0EB1t_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectE6map_orBI_NCNCNvNtNtBM_6stdlib12pickle_accel10make_loads0s1_0EBM_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtNtNtBG_6stdlib12pickle_accel6encode9ClassPlanEEBG_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4iter4IterReENCNvMs_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB1x_20ModuleFunctionsGuard3new0ENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvXB8_INtB8_12GenericShuntBN_INtNtBc_6option6OptionNtNtBc_7convert10InfallibleEEB2U_8try_folduNCINvNvB2U_12try_for_each4callTB1n_NtB1x_13FunctionGuardEINtNtNtBc_3ops12control_flow11ControlFlowB5F_ENcNtB66_5Break0E0B66_E0IB67_B66_EEB1B_ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapNtNtCs5HK7yca7OMW_10weavepy_vm7dictmap4IterNCNvMs7_NtNtB11_6stdlib12pickle_accelNtB1M_12PicklerGuard3new0ENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvXB8_INtB8_12GenericShuntBN_INtNtBc_6option6OptionNtNtBc_7convert10InfallibleEEB2F_8try_folduNCINvNvB2F_12try_for_each4callTINtNtB11_2rc4WeakNtNtB11_5types10TypeObjectENtB1M_13FunctionGuardEINtNtNtBc_3ops12control_flow11ControlFlowB5q_ENcNtB6v_5Break0E0B6v_E0IB6w_B6v_EEB11_ _RNvXs5_NtNtCs1C1lLj4PWSY_5alloc3vec5drainINtB5_5DrainTINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtNtBV_5types10TypeObjectEINtB7_3VecNtNtBV_6object6ObjectEEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropBV_ -_RNvNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel7classes10slot_names -_RNvNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel7classes14resolve_global -_RNvNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel7classes16benign_metaclass -_RNvNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel7classes8pure_get -_RNvNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel7classes12plain_layout -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel10make_dumpsINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel10make_loadsINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RNvMs_NtCs5HK7yca7OMW_10weavepy_vm2rcINtB4_2RcNtNtNtNtB6_6stdlib12pickle_accel6encode9ClassPlanE3newB6_ -_RINvNtCs5HK7yca7OMW_10weavepy_vm2rc12release_lastNtNtNtNtB4_6stdlib12pickle_accel6encode9ClassPlanEB4_ -_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCsd5p0HaiaiO6_11weavepy_jit2ir11GlobalGuardENtNtNtNtBb_4iter6traits8iterator8Iterator3anyNCNvNtBU_7analyze12plan_rewritesf_0EBU_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellINtNtNtNtBa_11collections4hash3set7HashSetNtNtBZ_12shared_value9SharedStrNtNtBZ_8fasthash13FxBuildHasherEEE4withNCNvNtNtBZ_6stdlib3sys13intern_shared0B2i_EBZ_ -_RNvMs_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB4_20ModuleFunctionsGuard3new -_RNCNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel10make_dumps00B9_ -_RNvMs0_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_12BuiltinGuard5holds -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel10make_loads -_RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB2_13FunctionGuard14holds_function -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_11ImportGuard3new -_RNvMs1_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_11ImportGuard7modules -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6extend -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6intern -_RINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel6decodeNCNCNvB2_10make_loads0s0_0EB6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel5build -_RNvMs0_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_12BuiltinGuard3new -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel10make_loads0B7_ -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder10build_from -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder16apply_dict_state -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder9push_memo -_RNCNvMs4_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB7_14UnpicklerGuard3news_0Bb_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel10make_dumps -_RNvMs5_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_19ClassFunctionsGuard3new -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6global -_RNCNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel10make_loads00B9_ -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder8setitems -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder7recycle -_RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB2_13FunctionGuard3new -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder7memoize -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accel10make_dumps0B7_ -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6newobj -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder5tuple -_RNvMs4_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_14UnpicklerGuard5holds -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6finish -_RNvMsb_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Scratch4keep -_RNvMs_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB4_20ModuleFunctionsGuard5holds -_RNvMsc_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder5parse _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs5HK7yca7OMW_10weavepy_vm5tier29MathGuardEBF_.llvm.4650670488983980854 _RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsd5p0HaiaiO6_11weavepy_jit2ir13MathGuardMetaE8grow_oneBQ_ _RNvNtCs5HK7yca7OMW_10weavepy_vm5tier216math_attr_object @@ -10936,31 +8427,9 @@ _RNCNCNvNtCs5HK7yca7OMW_10weavepy_vm5tier212warm_compile0s5_0B7_ _RNCNCNvMs6_NtCs5HK7yca7OMW_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s0_0Bb_ _RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze15infer_math_load _RNvNtCsd5p0HaiaiO6_11weavepy_jit7analyze14emit_math_load -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects7SubjectEBH_ _RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapxTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectINtNtBT_2rc2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtNtBT_6stdlib11sre_objects5PieceEEENtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBT_ _RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTxTNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectINtNtBW_2rc2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtNtBW_6stdlib11sre_objects5PieceEEEEE14reserve_rehashNCINvNtB8_3map11make_hasherxBR_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EBW_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12scanner_iter -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12scanner_step -_RNvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objectsNtB2_7Subject3new -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects11pattern_sub -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects8sub_fast -_RNvMs_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objectsNtB4_4Sink8push_obj -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects7installs_0B7_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects15cached_template -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects16pattern_finditer -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects9class_ext -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects7run_sub -_RINvMNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objectsNtB3_7Subject4execTINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB7_6object6ObjectNtNtB7_5error12RuntimeErrorEjjENCNvB3_12scanner_steps1_0EB7_ -_RNvMs_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objectsNtB4_4Sink9push_span -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects16pattern_sub_full -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects8sub_full -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects15pattern_scanner -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects8dispatch -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects7run_sub0B7_ -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_15pattern_scanner0E0B8_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12scanner_next _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects13match_getitem -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6option6OptionINtNtB1b_6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorEENCNvB4_8sub_fast0E0B8_ _RNvMs3_NtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE7restoreB9_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod8uni_word _RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterhENtNtNtNtBb_4iter6traits8iterator8Iterator8positionNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7sre_mod4scanhNCNvMs3_B1L_INtB1L_7MatcherhE5counts0_0E0EB1P_ @@ -11510,12 +8979,9 @@ _RNvMs_NtCs5HK7yca7OMW_10weavepy_vm7timsortINtB4_10MergeStateNtNtB6_6object6Obje _RNvNtCs5HK7yca7OMW_10weavepy_vm12type_surface20obj_contains_builtin _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13itertools_mod12groupby_core _RNvXNtNtCs2qMPZxtgKFx_10num_bigint6bigint8divisionRNtB4_6BigIntNtNtNtCsevLNFiNqfJP_4core3ops5arith3Div3div -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isasciiINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12dict_getitemINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14set_issupersetINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12bytes_rstripINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod6reduceINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1K_EEE4callB8_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13str_partitionINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14int_bit_lengthINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins7b_sliceINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9set_unionINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ @@ -11523,137 +8989,69 @@ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins22float_as_integer_ratioINtNtNtCsevL _RINvNtNtCs2qMPZxtgKFx_10num_bigint6bigint5shift14shr_round_downjECs5HK7yca7OMW_10weavepy_vm _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib16statistics_accel5build _RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter14cursor_advance -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native8verified.llvm.10617736694814397161 _RNvXsg_NtCs2qMPZxtgKFx_10num_bigint7biguintNtB5_7BigUintNtNtCsf6box2L2WUV_11num_integer5roots5Roots4sqrt _RNvXsa_NtNtCs2qMPZxtgKFx_10num_bigint7biguint5powerNtB7_7BigUintINtNtCshpbnKYGRzWO_10num_traits3pow3PowmE3pow _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_16key_cmp_deferredINtNtCsevLNFiNqfJP_4core6option6OptionjENCNvNtNtBY_6stdlib13functools_mod20scalar_lru_operations_0E0TINtNtB2q_6result6ResultB2l_NtNtBY_5error12RuntimeErrorEbEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopebNCNCNvMs1s_BW_NtBW_6Object8contains00E0INtNtCsevLNFiNqfJP_4core6result6ResultbNtNtBY_5error12RuntimeErrorEEBY_ _RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs5HK7yca7OMW_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_20with_key_eq_deferredINtNtCsevLNFiNqfJP_4core6result6ResultbNtNtBY_5error12RuntimeErrorENCNvMs1s_BW_NtBW_6Object8contains0E0TB2p_bEEBY_ _RNCNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit18call_leaf_in_place0B5_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit14k_str_endswith -_RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13k_list_extend _RNCINvNvNtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator3any5checkyNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline15builtin_in_line0E0B1k_ _RNvMNtCsd5p0HaiaiO6_11weavepy_jit5lowerNtB2_7Lowerer14emit_str_slice -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7pwd_mod5build -_RNvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB5_10TypeObject20fully_qualified_name _RINvMsd_NtCs5HK7yca7OMW_10weavepy_vm5typesNtB6_10TypeObject25with_fully_qualified_nameNtNtB8_5error12RuntimeErrorNCNvB8_22certain_miss_error_obj0EB8_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib13functools_mod6reduce -_RNvXs1_NtNtCs2qMPZxtgKFx_10num_bigint7biguint4bitsNtB7_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops3bit5BitOrRBM_E5bitor _RNvXs_NtNtCs2qMPZxtgKFx_10num_bigint7biguint4bitsNtB6_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops3bit6BitAndRBL_E6bitand -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib9fcntl_mod5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib9fcntl_mod7builtin _RNvMsn_NtCs2qMPZxtgKFx_10num_bigint6bigintNtB5_6BigInt12from_biguint.llvm.12009107880039722081 _RNvXsk_NtCs2qMPZxtgKFx_10num_bigint6bigintNtB5_6BigIntNtCsf6box2L2WUV_11num_integer7Integer13div_mod_floor -_RNvMsn_NtCs2qMPZxtgKFx_10num_bigint6bigintNtB5_6BigInt3pow _RNvXs8_NtNtCsevLNFiNqfJP_4core3fmt3numjNtB7_8UpperHex3fmt _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs5HK7yca7OMW_10weavepy_vm7NewInitEBD_ _RNvMs_NtCs5HK7yca7OMW_10weavepy_vm7timsortINtB4_10MergeStateNtNtB6_6object6ObjectNCINvMs7_B6_NtB6_11Interpreter10sort_keyedBW_NCNvB1m_13sort_with_keys_0Es0_0E11gallop_leftB6_ -_RNvNtNtCsevLNFiNqfJP_4core4char7methods15encode_utf8_raw -_RNCNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB7_11Interpreter4calls0_0B7_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15deopt_binary_op _RNvCs5HK7yca7OMW_10weavepy_vm14heap_site_note _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter13do_float_call _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter18check_float_result _RNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint14multiplication4mul3 -_RNvXs8_NtNtCs2qMPZxtgKFx_10num_bigint7biguint14multiplicationRNtB7_7BigUintNtNtNtCsevLNFiNqfJP_4core3ops5arith3Mul3mul -_RNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint14multiplication4mac3.llvm.13201530613138360178 -_RNvXs5_NtNtCs2qMPZxtgKFx_10num_bigint6bigint4bitsNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops3bit12BitXorAssignRBL_E13bitxor_assign _RNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit7records10chain_init _RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter13native_key_eq _RNvMs1_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB7_11Interpreter12groupby_step _RNvNtCs5HK7yca7OMW_10weavepy_vm7seqiter18is_current_grouper _RNvMs0_NtCs5HK7yca7OMW_10weavepy_vm7seqiterNtB7_11Interpreter17groupby_step_pure _RNvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_iterINtB4_3VecyEINtB2_12SpecFromIteryINtNtNtCsevLNFiNqfJP_4core4iter8adapters12GenericShuntINtNtB1k_3map3MapINtNtNtB1o_5slice4iter4IterNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENCNvNtNtB2V_6stdlib4math8math_gcd0EINtNtB1o_6option6OptionNtNtB1o_7convert10InfallibleEEE9from_iterB2V_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib2os19path_splitroot_fast -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib2os24path_like_type_singleton0B7_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math10math_isqrt _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math8math_gcd _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib4math12index_bigint _RNvNtNtCs2qMPZxtgKFx_10num_bigint7biguint8division12div_rem_core _RINvXsc_NtNtCsevLNFiNqfJP_4core4iter5rangeINtNtNtBa_3ops5range14RangeInclusiveyENtB6_26RangeInclusiveIteratorImpl13spec_try_folduNCINvNvNtNtNtB8_6traits8iterator8Iterator3any5checkyNCNvNtNtCs5HK7yca7OMW_10weavepy_vm9frame_jit6inline15builtin_in_line0E0INtNtBJ_12control_flow11ControlFlowuEEB31_ __powidf2 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7grp_mod5build -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib7grp_mod7builtin -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native11dt_strftime -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native11date_fields -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native14date_toordinal -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native15dt_shift_in_day -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native12dt_isoformat -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native8push_ymd -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native11text_object _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native7ord2ymd -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native9dt_fields -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native7ymd2ord -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native16strftime_numeric _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native8dt_shift -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native6dt_add.llvm.10617736694814397161 -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native8push_num -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native12date_weekday -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native8push_hms -_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB15_7dictmap4KeysuEEE9from_iterB15_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins29bytes_from_iterable_reentrant _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins15set_result_like _RNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12dict_getitems_0B5_ _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14int_bit_length -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins11str_isascii -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13byteorder_str _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12bytes_rstrip -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins13str_partition -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14set_issuperset _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins7b_slice -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins21fromhex_wrap_subclass -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins15byte_item_value _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9set_union _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12dict_getitem -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14set_iter_items -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins21int_from_bytes_method _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14float_receiver -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins20b_int_from_bytes_cls _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins22float_as_integer_ratio _RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtNtCs5HK7yca7OMW_10weavepy_vm6object9LeafProbeE11map_or_elsexNCNvNtNtBN_6stdlib13functools_mod20scalar_lru_operations0_0NCB1L_s1_0EBN_ -_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionTRNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyRNtBM_6ObjectEE6filterNCNvMs7_BO_NtBO_11Interpreter21specialized_load_attrs0_0EBO_ -_RNvMsb_NtCs5HK7yca7OMW_10weavepy_vm11frame_slotsNtB5_11FrameLocals6borrow _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9dict_copy _RNvNtCs5HK7yca7OMW_10weavepy_vm9frame_jit13h_str_keys_eq _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9dict_copyINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native9tally_one -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native14count_elements -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18collections_native10tally_dict0B7_ -_RNvMs0_NtNtCsevLNFiNqfJP_4core3fmt3numo10__fmt_inner.llvm.3542948293797346914 _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel11heapreplaceINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14str_capitalizeINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins17str_expandtabs_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1H_EEE4callB6_ -_RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel7heapifyINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12list_reverseINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins10b_reversedINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins12list_reverse -_RNCINvNtCs5HK7yca7OMW_10weavepy_vm8builtins9method_kwNvB4_17str_expandtabs_kwEs_0B6_ _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14str_capitalize _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel16heapreplace_impl -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11heapq_accel12heapify_impl -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14operator_accel15itemgetter_fast -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib14operator_accel15itemgetter_fast0B7_.llvm.3774527374720384575 _RNvCs5HK7yca7OMW_10weavepy_vm12finish_float _RNvCs5HK7yca7OMW_10weavepy_vm18format_float_fixed -_RNvCs5HK7yca7OMW_10weavepy_vm10fixed_core _RNvCs5HK7yca7OMW_10weavepy_vm12obj_as_float _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native14td_fields_slow _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native9construct -_RNCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native7installs4_0B7_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native7td_bool -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native12leaf_compare -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native6td_cmp -_RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects12match_groups -_RNCINvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11sre_objects10with_matchINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_12match_groups0E0B8_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter19core_native_compare _RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter25recursive_isinstance_type _RNvXNtCsevLNFiNqfJP_4core3anyNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib15datetime_native5StateNtB2_3Any7type_idBx_ _RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9str_indexINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ -_RNvYNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14set_isdisjointINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ _RNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins19str_apply_start_ends0_0B5_ -_RNCNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14set_isdisjoints1_0B5_ _RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins9str_index -_RNvNtCs5HK7yca7OMW_10weavepy_vm8builtins14set_isdisjoint _RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_3ops5range14RangeInclusivejENCNCNCNvNtNtB17_6stdlib11sre_objects15pattern_findall000EE9from_iterB17_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11pyexpat_mod13parser_createINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1Q_EEE4callB8_ _RNvYNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18elementtree_native7installINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ @@ -11693,7 +9091,6 @@ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib1 _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18elementtree_native7SessionEEEB1C_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18elementtree_native5VisitEBH_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionAINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyNtB1y_6ObjectEEj3_EEB1A_ -_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtCs5HK7yca7OMW_10weavepy_vm12shared_value9SharedStrB19_EEEB1d_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtB12_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB12_6object6ObjectEEEEEB12_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm4sync7GilCellNtNtNtBG_6stdlib11pyexpat_mod10ExpatStateEEBG_ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18elementtree_native3OutEBH_ @@ -11704,8 +9101,6 @@ initScanPrologNS _INTERNAL_trim_to_complete_utf8_characters utf8_toUtf8 _RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellTxINtNtCs5HK7yca7OMW_10weavepy_vm2rc4WeakINtNtB1N_4sync7GilCellNtNtNtB1N_6stdlib11pyexpat_mod10ExpatStateEEEEEB1N_ -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter16core_delete_attr -_RNvMs7_Cs5HK7yca7OMW_10weavepy_vmNtB5_11Interpreter15default_delattr XML_ErrorString parserInit doProlog @@ -11863,7 +9258,6 @@ _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcNtN _RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs5HK7yca7OMW_10weavepy_vm2rc2RcINtNtBG_4sync7GilCellNtNtNtBG_6stdlib11pyexpat_mod10ExpatStateEEEBG_ _RNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib18elementtree_native9iter_self _RNvMsb_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtB5_11SplitValues10remove_str -_RNvMsi_NtCs5HK7yca7OMW_10weavepy_vm9inst_dictNtNtB7_5types10PyInstance12split_remove _RINvMsm_NtCsevLNFiNqfJP_4core5arrayARej4_7try_mapINtNtNtB8_3ops9try_trait17NeverShortCircuitNtNtCs5HK7yca7OMW_10weavepy_vm6object6ObjectENCINvMBO_BL_10wrap_mut_1By_NCNvNtNtB1w_6stdlib18elementtree_native7installs0_0E0EB1w_ _RINvNtCsevLNFiNqfJP_4core5array11try_from_fnINtNtNtB4_3ops9try_trait17NeverShortCircuitINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtCs5HK7yca7OMW_10weavepy_vm6object7DictKeyNtB1X_6ObjectEEEKj3_NCINvMBJ_BG_10wrap_mut_1jNCNvNtNtB1Z_6stdlib18elementtree_native7installs5_0E0EB1Z_ _RNvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB5_3MapINtNtNtBb_3ops5range5RangejENCNvNtNtCs5HK7yca7OMW_10weavepy_vm6stdlib11pyexpat_mod16tr_start_element0ENtNtNtB9_6traits8iterator8Iterator4nextB1w_ @@ -11872,3 +9266,3712 @@ _RINvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB6_3MapINtNtNtBc_5slice4i XmlInitEncoding XmlGetUtf8InternalEncodingNS XmlInitEncodingNS +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCNvMNtBa_9lazy_lockINtB1a_8LazyLockINtNtCs7UfkFU4le9s_8lock_api6rwlock6RwLockNtNtCs3pgaDf2SUin_11parking_lot10raw_rwlock9RawRwLockINtNtNtNtBc_11collections4hash3map7HashMapjNtNtCs9NJVNhcGWEq_10weavepy_vm14descr_registry10StoredMetaINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtB3X_8fasthash14ObjectIdHasherEEEE5force0E0B3X_ +_RINvNtNtCsgHYyB3hU8Ec_3std3sys9backtrace28___rust_begin_short_backtraceNCNCNCINvNtNtB6_6thread9lifecycle15spawn_uncheckedNCNCINvNvNtCs9765AG8vcZx_19weavepy_conformance8regrtest17wait_with_timeout5drainNtNtB6_7process11ChildStderrE00uEs_000uEB26_ +_RNCNvCs9NJVNhcGWEq_10weavepy_vm15os_args_bridged0B3_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtB7_6string6StringE8grow_oneCsgHYyB3hU8Ec_3std +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtB7_3vec3VecINtNtB7_5boxed3BoxNtCs9NJVNhcGWEq_10weavepy_vm9InlineActEEE8grow_oneB1m_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBV_8fasthash14ObjectIdHasherEE0EBV_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18lookup_method_memo +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object7new_set +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VechEEE9drop_lastB7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object10PyPropertyE9drop_lastB7_ +_RNvMsz_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_8IntoIterNtNtBb_6string6StringNtNtCs4sNZbxEcDZG_10serde_json5value5ValueE10dying_nextB1w_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtNtNtBa_11collections4hash3map7HashMapTjjENtNtBZ_6object6ObjectNtNtBZ_8fasthash13FxBuildHasherEEE8try_withNCNvNtNtBZ_6stdlib2os15static_name_key0NtB2o_7DictKeyEBZ_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBZ_13vm_singletons13ThreadHandlesEEE8try_withNCNvXs_B2b_NtB2b_18ThreadHandlesGuardNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop0uEBZ_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs7UfkFU4le9s_8lock_api5mutex5MutexNtNtCs3pgaDf2SUin_11parking_lot9raw_mutex8RawMutexINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc4sync3ArcNtNtNtCs9VcX4bXVYC5_6rustls6client11client_conn12ClientConfigEEEE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8ssl_real18shared_client_slot0E0zE0E0B61_ +_RNvMsj_NtCsgHYyB3hU8Ec_3std2fsNtB5_11OpenOptions5__open +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier211cache_entrys_0B5_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtCsPlFyi5y0Kx_9addr2line8function15InlinedFunctionINtNtNtCsiK12aF3ve0B_5gimli4read12endian_slice11EndianSliceNtNtB1L_9endianity12LittleEndianEEE8grow_oneCsgHYyB3hU8Ec_3std +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object19str_from_codepoints +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2os14dir_entry_type +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE13insert_hashedB7_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtB7_5boxed3BoxDNtNtCsevLNFiNqfJP_4core3any3AnyEL_EE8grow_oneCs9NJVNhcGWEq_10weavepy_vm +_RNvXsw_NtNtCsevLNFiNqfJP_4core3str7patternNtB5_11StrSearcherNtB5_15ReverseSearcher15next_match_back +_RINvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace10with_statebNCNvB2_11track_built0EB4_ +_RNvMsr_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage3get +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance18dies_by_plain_drop +_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable7ipnsortNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectNCINvMB6_SBT_16sort_unstable_byNCNvMNtBX_8builtinsNtB2b_8DirNames6sorted0E0EBX_ +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_Eso_0B8_ +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance3cls.1156 +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap5TableuEEBG_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins20dict_setdefault_leaf +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object12FrozenSetObjE9drop_lastB7_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtB8_6string6StringEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB22_5slice4iter4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectENCNvMs7_B3c_NtB3c_11Interpreter4steps1a_0EE9from_iterB3c_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21super_property_getter +_RNvMs1t_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyIterator10next_value +_RNvXs1_NtNtNtCsevLNFiNqfJP_4core4iter8adapters6filterINtB5_6FilterINtNtNtBb_5slice4iter4IterNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB2d_11Interpreter24finalize_class_namespaces6_0ENtNtNtB9_6traits8iterator8Iterator5countB2d_ +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object15int_from_bigint +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter23activate_thread_handles +_RNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction5attrs +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7abc_modNtB4_8ClassSet5clear +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSINtCs4vf5tvaTb4E_8indexmap6BucketyNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7abc_mod4HeldEEB1g_ +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object9type_name +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0B5_ +_RNvMsu_NtCs9NJVNhcGWEq_10weavepy_vm12shared_valueNtB5_9SharedStr6concat +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object10FrameShellE9drop_lastB7_ +_RNvNvCs9NJVNhcGWEq_10weavepy_vm18core_plain_compare5quiet +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14core_attr_hook +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile5flush +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile15sibling_offsets +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtB4_4cell4once8OnceCellNtCs9NJVNhcGWEq_10weavepy_vm7LeafFnsEECs2GDADXmuQ1X_11weavepy_cli +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtB7_5boxed3BoxSINtNtCsevLNFiNqfJP_4core6option6OptionTTjjENtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrEEEE8grow_oneB1Q_ +_RNvNtNtCs2GDADXmuQ1X_11weavepy_cli9text_trim3sys8segments +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtB7_4time7InstantE10initializeNCINvB2_11get_or_initNvMBV_BT_3nowE0zECs2GDADXmuQ1X_11weavepy_cli +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtBc_4time7InstantE10initializeNCINvB1a_11get_or_initNvMB1I_B1G_3nowE0zE0E0Cs2GDADXmuQ1X_11weavepy_cli +_RINvMsa_NtCskibSv91bgl1_9hashbrown3rawNtB6_13RawTableInner22fallible_with_capacityNtNtCs1C1lLj4PWSY_5alloc5alloc6GlobalECshfZExtisgX1_16weavepy_compiler +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE12get_index_ofNtBU_7DictKeyEB8_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_6object12FrozenSetObjEE10initializeNCINvB1a_11get_or_initNCINvMs1B_B2j_NtB2j_6Object18new_frozenset_fromINtNtCs1C1lLj4PWSY_5alloc3vec3VecB3y_EE0E0zE0E0B1L_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtBW_12SliceStoragehEEE10initializeNCINvB2_11get_or_initNCINvMs1B_NtBY_6objectNtB2P_6Object9new_bytesINtNtCs1C1lLj4PWSY_5alloc3vec3VechEE0E0zEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtB1J_12SliceStoragehEEE10initializeNCINvB1a_11get_or_initNCINvMs1B_NtB1L_6objectNtB3E_6Object9new_bytesINtNtCs1C1lLj4PWSY_5alloc3vec3VechEE0E0zE0E0B1L_ +_RNvXsw_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_6StrKeyNtNtB7_7dictmap5Probe8probe_eq.1229 +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter13cached_imports_0B7_ +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE18shift_remove_indexB7_ +_RINvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6PyFile3newReBW_EB9_ +_RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VechE15append_elementsCs9NJVNhcGWEq_10weavepy_vm +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm6importNtB4_11ModuleCache13frozen_source +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStruNtNtBS_8fasthash13FxBuildHasherE13get_key_valueeEBS_ +_RNvMsf_NtCs9NJVNhcGWEq_10weavepy_vm4syncINtB5_7GilCellINtNtB7_2rc2RcNtCshfZExtisgX1_16weavepy_compiler10CodeObjectEE6borrowB7_ +_RINvMNtCsevLNFiNqfJP_4core3stre10split_oncecECs9NJVNhcGWEq_10weavepy_vm +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCshfZExtisgX1_16weavepy_compiler10CodeObjectECs2GDADXmuQ1X_11weavepy_cli +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object9make_iter +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance8slot_get +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance8slot_set +_RNvMsp_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage5unfix +_RNvMso_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage12from_entries +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance17ensure_gc_tracked +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjuEE14reserve_rehashNCINvNtB8_3map11make_hasherjuNtNtCs9NJVNhcGWEq_10weavepy_vm8fasthash13FxBuildHasherE0EB1H_ +_RNvXs5_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneB7_ +_RNvXsQ_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_8DictDataNtNtNtCsevLNFiNqfJP_4core3ops5deref8DerefMut9deref_mut +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB2i_8CallSlotEEE10initializeNCINvB1a_11get_or_initNCINvMst_B2i_NtB2i_16CodeConstObjects11alloc_sitesB2S_FEB2S_E0E0zE0E0B2i_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17lean_pending_exit +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins20dict_setdefault_leaf0B5_ +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object6to_str +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecIB1H_INtNtB1L_4sync7GilCellNtNtB1L_6object6ObjectEEEEE10initializeNCINvB1a_11get_or_initNCNvMs11_B3h_NtB3h_10PyFunction14lean_cells_refs0_0E0zE0E0B1L_ +_RNvXs1_NtNtNtCsevLNFiNqfJP_4core4iter8adapters6filterINtB5_6FilterINtNtNtBb_5slice4iter4IterNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB2d_11Interpreter24finalize_class_namespaces3_0ENtNtNtB9_6traits8iterator8Iterator5countB2d_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object10PyDictViewE9drop_lastB7_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218sync_native_locals0B5_ +_RNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction8attr_get +_RINvMss_NtCs9NJVNhcGWEq_10weavepy_vm12shared_valueNtB6_10StrStorage5allocNCNvMsu_B6_NtB6_9SharedStr10with_count0EB8_ +_RNvMso_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_4WeakINtNtB7_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB7_6object6ObjectEEE7upgradeB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtCs9NJVNhcGWEq_10weavepy_vm8LeafRecvReINtNtB1b_2rc2RcNtNtB1b_6object9BuiltinFnEEEECs2GDADXmuQ1X_11weavepy_cli +_RNvXs4_NtCs9NJVNhcGWEq_10weavepy_vm3gilNtB5_8GilScopeNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellNtNtB1a_13vm_singletons11InterpStackEEB1a_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm5types10type_cache4park +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCsevLNFiNqfJP_4core4cell10UnsafeCellAThINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB19_6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEj40_EEB2O_ +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE12push_growingB7_ +_RNvXs1i_NtCsevLNFiNqfJP_4core3fmtReNtB6_7Display3fmtCs2GDADXmuQ1X_11weavepy_cli +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtNtNtBc_11collections4hash3map7HashMapINtNtB2t_5boxed3BoxeEINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB1L_6object6ObjectENtNtB1L_8fasthash13FxBuildHasherEEEE10initializeNCINvB1a_11get_or_initNCNvNtB1L_8builtins18lookup_method_memo0E0zE0E0B1L_ +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter11build_class0B7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object7PySliceE9drop_lastB7_ +_RNvXsl_NtCsgHYyB3hU8Ec_3std4pathNtB5_10ComponentsNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq.1401 +_RNvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB5_3MapINtNtB7_6filter6FilterIBN_INtNtNtBb_3str4iter5SplitcENvMB1r_e4trimENCNvNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12register_all0ENvYINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtBb_7convert4FromReE4fromENtNtNtB9_6traits8iterator8Iterator4nextB27_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakINtNtBR_4sync7GilCellNtNtBR_6object8DictDataEEE8grow_oneBR_ +_RNvMsh_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtB5_8InstDict3get.1184 +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableuE13rebuild_slotsB7_ +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE12get_index_ofNtBU_13LeafNameProbeEB8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13codecs_engine17utf8_decode_named +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2os17dir_entry_methods0B7_ +_RNvMsf_NtNtCsevLNFiNqfJP_4core3str4iterINtB5_13SplitInternalcE9next_backCs2GDADXmuQ1X_11weavepy_cli +_RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRINtNtCs1C1lLj4PWSY_5alloc3vec3VechEECs9VcX4bXVYC5_6rustls +_RNvMs11_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction14lean_cells_ref +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace16auto_collect_due +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6removeeECs9NJVNhcGWEq_10weavepy_vm +_RINvMsr_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB6_11SlotStorage15insert_with_keyNCNvB2_6insert0EB8_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort19bidirectional_mergeNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectNCINvMB8_SB1g_16sort_unstable_byNCNvMNtB1k_8builtinsNtB2z_8DirNames6sorted0E0EB1k_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB1v_8CallSlotEEE10initializeNCINvB2_11get_or_initNCINvMst_B1v_NtB1v_16CodeConstObjects11alloc_sitesB25_FEB25_E0E0zEB1v_ +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot11set_builtin +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE13with_capacityB7_ +_RINvXs8_NtCs9NJVNhcGWEq_10weavepy_vm11compact_vecINtB6_10CompactVecTNtNtCs1C1lLj4PWSY_5alloc6string6StringNtNtB8_6object6ObjectEEINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorB13_E9from_iterINtNtNtB2a_8adapters10filter_map9FilterMapNtNtB8_7dictmap4IterNCNvB8_22set_function_attributes_0EEB8_ +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE12get_index_ofNtBU_12StrKeyHashedEB8_ +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter11leaf_globals0_0B7_ +_RNvXsZ_NtCs1C1lLj4PWSY_5alloc6stringNtB5_6StringNtNtCsevLNFiNqfJP_4core3fmt5Write9write_str.1278 +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object4repr +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object8from_strNtNtCs1C1lLj4PWSY_5alloc6string6StringECsgCuzAuzbPOX_7weavepy +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile9is_memory +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcNtNtB1d_13tuple_storage12TupleStorageEEECs2GDADXmuQ1X_11weavepy_cli +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1y_6object10FrameShellEEEECs2GDADXmuQ1X_11weavepy_cli +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjxNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyEEEEB2k_ +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB1P_6Object11from_static7StaticsEEB1R_ +0x00000000020050c0 +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object9BuiltinFnE9drop_lastB7_ +_RNvMs_NtNtCsgHYyB3hU8Ec_3std6thread6threadNtB4_6Thread3new +0x0000000002005100 +_RNvMs1w_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_7SipMemo8allocate +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync4CellbEE9drop_lastB7_ +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtNtB6_6object14SlotDescriptorE3newB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib3sys17venv_cfg_contents +_RNvMsy_NtCs9NJVNhcGWEq_10weavepy_vm12shared_valueNtB5_9SharedStr9to_string +_RNvXs1i_NtCsevLNFiNqfJP_4core3fmtRNtNtCs1C1lLj4PWSY_5alloc6string6StringNtB6_7Display3fmtCs2GDADXmuQ1X_11weavepy_cli +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs7UfkFU4le9s_8lock_api5mutex5MutexNtNtCs3pgaDf2SUin_11parking_lot9raw_mutex8RawMutexINtNtNtNtBc_11collections4hash3map7HashMapjINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtB3U_4sync7GilCellNtNtNtB3U_6stdlib8mmap_mod9MmapStateEEEEE10initializeNCINvB1a_11get_or_initNCNvB4O_8registry0E0zE0E0B3U_ +_RNvMsp_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage10unset_over +_RNvNtCs1C1lLj4PWSY_5alloc5boxed14box_new_uninit.1006 +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object12new_set_fromINtNtCs1C1lLj4PWSY_5alloc3vec3VecBG_EEB9_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecPNtNtCs9NJVNhcGWEq_10weavepy_vm6object10PyFunctionE8grow_oneBR_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCsgHYyB3hU8Ec_3std4sync9once_lock8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxANtNtCs9NJVNhcGWEq_10weavepy_vm6object6Objectj3_EEEB22_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakNtNtBS_6object9BuiltinFnERSReFG_RL0_SNtB1s_6ObjectEINtNtCsevLNFiNqfJP_4core6option6OptionINtNtB2k_6result6ResultB21_NtNtBS_5error12RuntimeErrorEEEE8grow_oneBS_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEBG_ +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyENtNtNtNtBb_4iter6traits8iterator8Iterator8positionNCNvMsr_NtBU_5typesNtB2w_11SlotStorage3get0EBU_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecIBB_INtNtB7_4sync7GilCellNtNtB7_6object6ObjectEEEE9drop_lastB7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object10PyFunctionE9drop_lastB7_ +_RNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction15plant_slot_seed +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared5pivot11median3_recNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectNCINvMB8_SB14_16sort_unstable_byNCNvMNtB18_8builtinsNtB2n_8DirNames6sorted0E0EB18_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier213note_backedge0B5_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB1v_10MethodSlotEEE10initializeNCINvB2_11get_or_initNCINvMst_B1v_NtB1v_16CodeConstObjects11alloc_sitesB25_FEB25_E0E0zEB1v_ +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_EsB_0B8_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm11frame_slots24release_cells_and_locals +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableuE13with_capacityB7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object8PyModuleE9drop_lastB7_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecIBU_INtNtBY_4sync7GilCellNtNtBY_6object6ObjectEEEEE10initializeNCINvB2_11get_or_initNCNvMs11_B2s_NtB2s_10PyFunction14lean_cells_refs0_0E0zEBY_ +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object8from_strNtNtCs1C1lLj4PWSY_5alloc6string6StringEB9_ +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object6as_i64 +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecmEE9drop_lastB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB12_6object6ObjectEEEEB12_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons19current_frame_stack +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object9is_truthy +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB2i_9StampSlotEEE10initializeNCINvB1a_11get_or_initNCINvMst_B2i_NtB2i_16CodeConstObjects11alloc_sitesB2S_FEB2S_E0E0zE0E0B2i_ +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtB15_7dictmap4IterNCNvMs7_B15_NtB15_11Interpreter16collect_iterables4_0EE9from_iterB15_ +_RNvMsu_NtCs9NJVNhcGWEq_10weavepy_vm12shared_valueNtB5_9SharedStr10try_append +_RNvXsv_NtNtCsevLNFiNqfJP_4core3str7patternNtB5_11StrSearcherNtB5_8Searcher10next_match.1453 +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance12class_dunder +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs3dBmIZHfUWS_6anyhow7wrapper12MessageErrorNtNtCs1C1lLj4PWSY_5alloc6string6StringEECs9765AG8vcZx_19weavepy_conformance +_RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan1VE16into_boxed_sliceBI_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellTyINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapjTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakNtNtB20_6object9BuiltinFnENtNtB20_13leaf_builtins5EntryENtNtB20_8fasthash13FxBuildHasherEINtNtB13_3set7HashSetjB3s_EEEECs2GDADXmuQ1X_11weavepy_cli +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapNtNtB15_4path7PathBufTNtNtCs9NJVNhcGWEq_10weavepy_vm6import8DirStampINtNtCs1C1lLj4PWSY_5alloc2rc2RcINtNtB11_3set7HashSetNtNtNtB15_3ffi6os_str8OsStringEEEEEEB2h_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons12exit_process +_RNvMs_CsgCuzAuzbPOX_7weavepyNtB4_10RunOptions10with_flags +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtCsevLNFiNqfJP_4core6option6OptionjEE8grow_oneCshfZExtisgX1_16weavepy_compiler +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object11from_static +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE11insert_fullB7_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtCs4vf5tvaTb4E_8indexmap6BucketNtNtB7_6string6StringxEE8grow_oneCs9NJVNhcGWEq_10weavepy_vm +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcNtNtB1j_13tuple_storage12TupleStorageEuE16get_or_init_slowNvNvNvMs1B_NtB1j_6objectNtB3c_6Object9new_tuple11EMPTY_TUPLE27___rust_std_internal_init_fnEB1j_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellNtNtB7_7dictmap6SetMapEE9drop_lastB7_ +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object9new_bytesINtNtCs1C1lLj4PWSY_5alloc3vec3VechEEB9_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTjjEINtNtCs1C1lLj4PWSY_5alloc2rc2RcSNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyEEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BU_NtNtB1u_8fasthash13FxBuildHasherE0EB1u_ +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types22install_object_dunders19object_setattr_fast +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecPNtNtCs9NJVNhcGWEq_10weavepy_vm5types10PyInstanceE8grow_oneBR_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringjEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_jNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs9NJVNhcGWEq_10weavepy_vm +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtNtCsgHYyB3hU8Ec_3std3ffi6os_str8OsStringuNtNtNtBU_4hash6random11RandomStateE12contains_keyNtBQ_5OsStrECs9NJVNhcGWEq_10weavepy_vm +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCsgHYyB3hU8Ec_3std4sync9once_lock8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs9NJVNhcGWEq_10weavepy_vm11DunderTableEEEB1Z_ +_RNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction4code +_RINvCs9NJVNhcGWEq_10weavepy_vm9h_seq_getKm3_EB2_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjuNtNtCs9NJVNhcGWEq_10weavepy_vm8fasthash13FxBuildHasherE6insertBT_ +_RNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction10slots_cell +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot5empty +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter23core_super_class_method +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBV_5types10TypeObjectEENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvMs7_BV_NtBV_11Interpreter24finalize_class_namespaces5_0EBV_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB1v_9StampSlotEEE10initializeNCINvB2_11get_or_initNCINvMst_B1v_NtB1v_16CodeConstObjects11alloc_sitesB25_FEB25_E0E0zEB1v_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs9NJVNhcGWEq_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_20with_key_eq_deferredTjbENCNvMs7_BY_NtBY_11Interpreter17leaf_builtin_calls5_0E0TB2p_bEEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB1a_11get_or_initNCINvMs7_B2V_NtB2V_11Interpreter9leaf_evalKb0_KB4W_E0E0zE0E0B2V_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_piece +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakINtNtB1n_4sync7GilCellINtBG_3VecNtNtB1n_6object6ObjectEEEEEB1n_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm6import11ModuleCacheECs2GDADXmuQ1X_11weavepy_cli +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtB1y_4sync7GilCellIBX_NtNtB1y_6object6ObjectEEEEEECs2GDADXmuQ1X_11weavepy_cli +_RNvXs2_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7recordsNtB5_10DirectRecsNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCsevLNFiNqfJP_4core6option6OptionONtB1a_11InterpreterEEEEB1a_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6result6ResultuNtNtNtB4_2io5error5ErrorEECs2GDADXmuQ1X_11weavepy_cli +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm5types10type_cache6unpark +_RNvNtNtNtCsgHYyB3hU8Ec_3std3sys6random5linux19hashmap_random_keys +_RNvXs3_NtNtCsevLNFiNqfJP_4core4hash3sipINtB5_6HasherNtB5_11Sip13RoundsENtB7_6Hasher5writeCs9765AG8vcZx_19weavepy_conformance +_RNvMsu_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapNtB5_6SetMap11insert_full.1297 +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object9new_tuple +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtNtNtB7_11collections4hash3map7HashMapINtNtB1G_5boxed3BoxeEINtNtCsevLNFiNqfJP_4core6option6OptionNtNtBY_6object6ObjectENtNtBY_8fasthash13FxBuildHasherEEEE10initializeNCINvB2_11get_or_initNCNvNtBY_8builtins18lookup_method_memo0E0zEBY_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellNtNtB7_6object8DictDataEE9drop_lastB7_ +_RNvNtCs1C1lLj4PWSY_5alloc5boxed14box_new_uninit.1254 +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellNtNtB7_6object10PyIteratorEE9drop_lastB7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object12PyMemoryViewE9drop_lastB7_ +_RNvMs16_NtCsgHYyB3hU8Ec_3std4pathNtB6_4Path6parent +_RNvXs1_NtCs9NJVNhcGWEq_10weavepy_vm13vm_singletonsNtB5_16InterpreterGuardNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance11dict_shared +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile10set_errors +_RNvMsu_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapNtB5_6SetMap13insert_hashed +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtCsiB9L21keqcX_7walkdir8AncestorEECs9765AG8vcZx_19weavepy_conformance +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtCshfZExtisgX1_16weavepy_compiler10CodeObjectE9drop_lastB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCsgHYyB3hU8Ec_3std4sync9once_lock8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectB1Y_EEEEB22_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17note_tier2_callee +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once9call_onceNCNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB18_11Interpreter8leaf_fns00E0B18_ +_RINvMs0_NtCs9NJVNhcGWEq_10weavepy_vm5errorNtB6_11PyException12from_builtinNtNtCs1C1lLj4PWSY_5alloc6string6StringEB8_ +_RNvMsr_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage7get_mut +_RNCINvNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map12map_try_foldRNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectINtNtBa_6result6ResultNtNtCs1C1lLj4PWSY_5alloc6string6StringNtNtB14_5error12RuntimeErrorEuINtNtNtBa_3ops12control_flow11ControlFlowIB3b_B24_EENCNCNvMs7_B14_NtB14_11Interpreter11import_star00NCINvXB6_INtB6_12GenericShuntINtB4_3MapQDNtNtNtB8_6traits8iterator8Iteratorp4ItemBZ_EL_B40_EIB1J_NtNtBa_7convert10InfallibleB2G_EEB5r_8try_folduNCINvNvB5r_12try_for_each4callB24_B3P_NcNtB3P_5Break0E0B3P_E0E0B14_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18fill_deferred_spec +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable9quicksort9quicksortNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectNCINvMB8_SB17_16sort_unstable_byNCNvMNtB1b_8builtinsNtB2q_8DirNames6sorted0E0EB1b_ +_RNvCs9NJVNhcGWEq_10weavepy_vm10site_ranks +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot8set_leaf +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value12SliceStoragemEE9drop_slowBL_ +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object9as_bigint +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBR_6object11PyGeneratorEE8grow_oneBR_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object13AsyncGenAwaitE9drop_lastB7_ +_RINvMso_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB6_11SlotStorage9exceptionKj0_EB8_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValuexEB1x_INtNtB4_4hash18BuildHasherDefaultNtNtB1B_6fxhash8FxHasherEEEB1B_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons17flush_host_stdout +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons17host_stdout_drain +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs9NJVNhcGWEq_10weavepy_vm8GenPartsECs2GDADXmuQ1X_11weavepy_cli +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapReTINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEIB2i_ShEEEEEBG_ +0x0000000002005050 +_RNCNvNtCs2GDADXmuQ1X_11weavepy_cli9text_trim7install0B5_ +_RNvXs10_Cs9NJVNhcGWEq_10weavepy_vmNtB6_16InterpreterFlagsNtNtCsevLNFiNqfJP_4core5clone5Clone5clone +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell10UnsafeCellAThINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB1j_6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEj40_EuE16get_or_init_slowNvNvNtB2Y_8builtins13RECENT_METHOD27___rust_std_internal_init_fnEB2Y_ +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object7is_same +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB7_6object6ObjectEEE9drop_lastB7_ +_RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBP_5types10TypeObjectENtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalEBP_ +_RNvMsf_NtCs9NJVNhcGWEq_10weavepy_vm4syncINtB5_7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB7_2rc2RcNtNtB7_5types10TypeObjectEEE10borrow_mutB7_ +_RNCNvCs9NJVNhcGWEq_10weavepy_vm14is_object_init0B3_ +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance12new_deferred +_RNvNtNtCsgHYyB3hU8Ec_3std3sys2fs12canonicalize +_RNvXs_NtNtCs4sNZbxEcDZG_10serde_json5value5indexeNtB4_5Index10index_into +_RINvMNtCsevLNFiNqfJP_4core3stre12trim_matchesNvMNtNtB5_4char7methodsc13is_whitespaceECs2GDADXmuQ1X_11weavepy_cli +_RNvMs1l_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6IoKind9from_mode +_RINvMsr_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB6_11SlotStorage15insert_with_keyNCNvB2_13insert_shared0EB8_ +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableuE12push_growingB7_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13cached_import +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object15new_tuple_arrayKj3_EB9_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16core_module_attr +_RINvMso_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB6_11SlotStorage9exceptionKj1_EB8_ +_RNvXsk_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorageNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object11PyTracebackE9drop_lastB7_ +_RNvCs9NJVNhcGWEq_10weavepy_vm13is_object_new +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapNtB5_12ProbeVacancy6insertB7_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB2i_10MethodSlotEEE10initializeNCINvB1a_11get_or_initNCINvMst_B2i_NtB2i_16CodeConstObjects11alloc_sitesB2S_FEB2S_E0E0zE0E0B2i_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCNvMNtBa_9lazy_lockINtB1a_8LazyLockINtNtCs7UfkFU4le9s_8lock_api5mutex5MutexNtNtCs3pgaDf2SUin_11parking_lot9raw_mutex8RawMutexINtNtNtNtBc_11collections4hash3map7HashMapjNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13testcapi_call12FixtureFlagsEEE5force0E0B3U_ +_RINvMso_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB6_11SlotStorage9exceptionKj2_EB8_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_5slice4iter4IterINtNtB17_2rc2RcNtNtB17_5types10TypeObjectEENCNvMs7_B17_NtB17_11Interpreter11build_classs4_0EE9from_iterB17_ +_RNvCs9NJVNhcGWEq_10weavepy_vm17varkw_stays_local +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19core_super_property +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object18new_frozenset_fromINtNtCs1C1lLj4PWSY_5alloc3vec3VecBG_EEB9_ +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object13new_bytearrayINtNtCs1C1lLj4PWSY_5alloc3vec3VechEEB9_ +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE12get_index_ofNtBU_9LeafProbeEB8_ +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7abc_modNtB4_8ClassSet4live +_RINvMNtCs9NJVNhcGWEq_10weavepy_vm8lazy_arcINtB3_7LazyArcINtNtB5_4sync7GilCellNtNtB5_6object8DictDataEE10initializeNCNvMss_NtB5_5typesNtB1W_10PyInstance9dict_cell0EB5_ +_RNvMNtCs1C1lLj4PWSY_5alloc6stringNtB2_6String4push.1370 +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxANtNtCs9NJVNhcGWEq_10weavepy_vm6object6Objectj3_EE10initializeNCINvB1a_11get_or_initNCNCNCNvNtB2k_8builtins19code_synthetic_attr000E0zE0E0B2k_ +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile9is_closed +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArceE9drop_slowCsbsLF5VKjj0H_14regex_automata +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjINtNtBG_2rc2RcNtNtBG_5types10PyInstanceEEEEECs2GDADXmuQ1X_11weavepy_cli +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellINtNtB4_6option6OptionTyNtCs9NJVNhcGWEq_10weavepy_vm11NativeTruthEEEECs2GDADXmuQ1X_11weavepy_cli +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtNtCskis0sZ8PIOa_12clap_builder4util9any_value8AnyValueEEECs2GDADXmuQ1X_11weavepy_cli +_RINvMNtNtCskis0sZ8PIOa_12clap_builder6parser5errorNtB3_12MatchesError6unwrapINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs1C1lLj4PWSY_5alloc6string6StringEECs2GDADXmuQ1X_11weavepy_cli +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object13MethodWrapperE9drop_lastB7_ +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE13rebuild_slotsB7_ +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object8new_dict +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_6object12FrozenSetObjEE10initializeNCINvB2_11get_or_initNCINvMs1B_B1w_NtB1w_6Object18new_frozenset_fromINtNtNtNtCsevLNFiNqfJP_4core4iter7sources5empty5EmptyB2J_EE0E0zEBY_ +_RNvXsN_NtCs9NJVNhcGWEq_10weavepy_vm12shared_valueNtNtB7_13tuple_storage12TupleStorageNtB5_11ThinPayload12release_last +_RNvXNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB2_8BTreeMapNtNtB8_6string6StringNtNtCs4sNZbxEcDZG_10serde_json5value5ValueENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropCs9NJVNhcGWEq_10weavepy_vm +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecFUKCONtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit5StateEmE8grow_oneBV_ +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter20core_offload_in_loopKh2_E0B8_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit4SlotEBF_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTReINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtCs9NJVNhcGWEq_10weavepy_vm8LeafRecvINtNtB1s_2rc2RcNtNtB1s_6object9BuiltinFnEEEEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BS_NtNtB1s_8fasthash13FxBuildHasherE0EB1s_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19str_partition_exact +_RNvXst_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstanceNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE12shift_removeNtBU_7DictKeyEB8_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort12sort4_stableNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectNCINvMB8_SB19_16sort_unstable_byNCNvMNtB1d_8builtinsNtB2s_8DirNames6sorted0E0EB1d_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs9NJVNhcGWEq_10weavepy_vm9CallShapeEBD_ +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter16leaf_import_from0B7_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18super_attr_resolve +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBG_6string6StringEECs95FNv3kP1st_12regex_syntax +_RNCNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15builtin_counted000B9_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16heap_result_note +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter13seq_ctor_pure +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object10PyLazyIterE9drop_lastB7_ +_RNvYNCNvMNtCs9NJVNhcGWEq_10weavepy_vm13builtin_typesNtB7_12BuiltinTypes5builds0_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRINtNtB9_2rc2RcNtNtB9_5types10TypeObjectERSNtNtB9_6object6ObjectEE9call_onceB9_ +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter15do_getattr_call0B7_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecPNtNtCs9NJVNhcGWEq_10weavepy_vm6object11PyGeneratorE8grow_oneBR_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std4sync6poison5mutex10MutexGuardINtNtCs1C1lLj4PWSY_5alloc3vec3VecRNtNtCskEmZ9gTcSHg_12weavepy_capi5types11ReadiedTypeEEEB28_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjyEE14reserve_rehashNCINvNtB8_3map11make_hasherjyNtNtCs9NJVNhcGWEq_10weavepy_vm8fasthash13FxBuildHasherE0ECskEmZ9gTcSHg_12weavepy_capi +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16bytes_from_slice +_RNvMst_NtCs9NJVNhcGWEq_10weavepy_vm12shared_valueINtB5_7ThinArcNtB5_10StrStorageE17try_extend_unique +_RNvMsr_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage8index_of +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE5drainNtNtNtCsevLNFiNqfJP_4core3ops5range9RangeFullEB8_ +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile17rewind_read_ahead +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm11frame_slots10FrameStackEEECs2GDADXmuQ1X_11weavepy_cli +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell7RefCellINtNtB4_6option6OptionTyIBX_INtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1t_6object9BuiltinFnEEhIBX_TB1o_FG_RL0_SNtB21_6ObjectEIBX_INtNtB4_6result6ResultB2I_NtNtB1t_5error12RuntimeErrorEEEEEEEECs2GDADXmuQ1X_11weavepy_cli +_RNvXsB_NtCs9NJVNhcGWEq_10weavepy_vm12shared_valueNtB5_9SharedStrINtNtCsevLNFiNqfJP_4core7convert4FromReE4from +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectENtNtB25_8fasthash13FxBuildHasherE3geteEB25_ +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastINtNtB4_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VechEEEB4_ +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE12get_index_ofNtBU_6StrKeyEB8_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object5RangeE9drop_lastB7_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTReFG_RL0_NtNtCs9NJVNhcGWEq_10weavepy_vm6import11ModuleCacheEINtNtB13_2rc2RcNtNtB13_6object8PyModuleEEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BS_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EB13_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcDNtNtCsevLNFiNqfJP_4core3any3AnyNtNtB2m_6marker4SendNtB2P_4SyncEL_EE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0B1L_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit7analyze6CarvedECs9NJVNhcGWEq_10weavepy_vm +_RNvXs1N_CshfZExtisgX1_16weavepy_compilerNtB6_8ConstantNtNtCsevLNFiNqfJP_4core5clone5Clone5clone.1292 +_RNvXs1i_NtCsevLNFiNqfJP_4core3fmtRNtNtNtCskis0sZ8PIOa_12clap_builder7builder3str3StrNtB6_7Display3fmtBC_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object11BoundMethodE9drop_lastB7_ +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object8new_list +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_5types10PyInstanceE9drop_lastB7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13leaf_builtins6lookup +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellNtNtB7_6object6ObjectEE9drop_lastB7_ +_RNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction4slot +_RNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction8set_slot +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter17builtin_ctor_arms +_RNvXs5_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableuENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneB7_ +_RNvCs9NJVNhcGWEq_10weavepy_vm25builtin_takes_no_keywords +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNCINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB13_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecIB1V_INtNtB1Z_4sync7GilCellNtNtB1Z_6object6ObjectEEEEE10initializeNCINvB12_11get_or_initNCNvMs11_B3v_NtB3v_10PyFunction14lean_cells_refs0_0E0zE0EEB1Z_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter22lean_pending_exit_cold +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object7PyFrameE9drop_lastB7_ +_RINvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace10with_stateuNCNvB2_15track_generator0EB4_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object11PyGeneratorE9drop_lastB7_ +_RNvMsu_NtCs9NJVNhcGWEq_10weavepy_vm12shared_valueNtB5_9SharedStr6repeat +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12descr_getter +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxANtNtCs9NJVNhcGWEq_10weavepy_vm6object6Objectj3_EE10initializeNCINvB2_11get_or_initNCNCNCNvNtB1x_8builtins19code_synthetic_attr000E0zEB1x_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib16interpreters_mod10current_id +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile14get_extra_attr +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile15flush_write_buf +_RNvXs3_NtCs9NJVNhcGWEq_10weavepy_vm13vm_singletonsNtB5_10HostStdoutNtNtNtCsevLNFiNqfJP_4core2io5write5Write5flush +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapReINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtCs9NJVNhcGWEq_10weavepy_vm8LeafRecvINtNtB28_2rc2RcNtNtB28_6object9BuiltinFnEEENtNtB28_8fasthash13FxBuildHasherEECs2GDADXmuQ1X_11weavepy_cli +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser12parse_bit_or +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser11parse_shift +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser17parse_dotted_name +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser5ident +_RNvNvCshfZExtisgX1_16weavepy_compiler21module_mentions_super7in_expr +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB4_9Validator10visit_expr +_RINvMs6_NtCs35FjVCGSOXt_9hashbrown3rawINtB6_8RawTablejE14reserve_rehashNCINvNtCs4vf5tvaTb4E_8indexmap5inner8get_hashNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCshfZExtisgX1_16weavepy_compiler7BindingE0EB2u_ +_RNvCshfZExtisgX1_16weavepy_compiler19stmt_contains_yield +_RNvCshfZExtisgX1_16weavepy_compiler23collect_inner_free_impl +_RNvNvNtNtNtCs4H1No5ph5dL_6memchr4arch6x86_646memchr10memchr_raw6detect +_RNvNvNtNtNtCs4H1No5ph5dL_6memchr4arch6x86_646memchr10memchr_raw9find_avx2 +_RNvNvNtCsgHYyB3hU8Ec_3std2fs4read5inner +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser11parse_unary +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler11intern_name +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler18classify_for_store +_RNvCshfZExtisgX1_16weavepy_compiler19expr_contains_yield +_RNCNvMsV_CshfZExtisgX1_16weavepy_compilerNtB7_8Compiler22analyze_scope_functions0_0B7_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler7emit_at +_RNvMs1_NtCshfZExtisgX1_16weavepy_compiler9flowgraphNtB5_3Cfg21scan_block_for_locals +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler18emit_make_function +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser10parse_atom +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser21parse_arguments_inner +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser15parse_call_args +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCslbMUDoFrEqM_14weavepy_parser3ast4ExprEE8grow_oneB1s_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringuEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_uINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEE0EB37_ +_RNvCshfZExtisgX1_16weavepy_compiler19collect_walrus_expr +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCshfZExtisgX1_16weavepy_compiler8validate5ScopeE8grow_oneBQ_ +_RNvNtCshfZExtisgX1_16weavepy_compiler7ast_opt9fold_expr +_RNCNvCshfZExtisgX1_16weavepy_compiler32collect_comp_walrus_targets_stmt0B3_ +_RINvMs3_NtCs4vf5tvaTb4E_8indexmap3mapINtB6_8IndexMapNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCshfZExtisgX1_16weavepy_compiler7BindingINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtB1s_6fxhash8FxHasherEE3geteEB1s_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler9free_scan +_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtB8_6string6StringE16extend_desugaredINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set8IntoIterBG_EECshfZExtisgX1_16weavepy_compiler +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCslbMUDoFrEqM_14weavepy_parser3ast9ArgumentsECshfZExtisgX1_16weavepy_compiler +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser13parse_bit_xor +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser12parse_addsub +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser12parse_import +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser6expect +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB4_9Validator14visit_function +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtB7_3vec3VecmEE8grow_oneCshfZExtisgX1_16weavepy_compiler +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCslbMUDoFrEqM_14weavepy_parser3ast8ExprKindECshfZExtisgX1_16weavepy_compiler +_RNvMs2_NtCs4vf5tvaTb4E_8indexmap3mapINtB5_8IndexMapNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCshfZExtisgX1_16weavepy_compiler7BindingINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtB1r_6fxhash8FxHasherEE11insert_fullB1r_ +_RNvMs_NtCs4vf5tvaTb4E_8indexmap5innerINtB4_4CoreNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCshfZExtisgX1_16weavepy_compiler7BindingE10push_entryB1o_ +_RNCNvMsV_CshfZExtisgX1_16weavepy_compilerNtB7_8Compiler23collect_comp_cells_stmt0B7_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler18compile_expr_inner +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler12display_name +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtB6_6string6StringEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set8IntoIterB11_EE9from_iterCshfZExtisgX1_16weavepy_compiler +_RNvXNtCskibSv91bgl1_9hashbrown3mapINtB2_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEENtNtB1s_5clone5Clone5cloneB2e_ +_RNvCshfZExtisgX1_16weavepy_compiler18collect_inner_free +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1m_NtNtBa_3cmp10PartialOrd2ltECs9765AG8vcZx_19weavepy_conformance +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler28collect_uses_through_inlined +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEE12contains_keyeEB2i_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler23collect_comp_cells_expr +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler22analyze_scope_function +_RNvCshfZExtisgX1_16weavepy_compiler27collect_pep695_header_reads +_RNvCs9NJVNhcGWEq_10weavepy_vm24percent_args_need_bridge +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser8parse_or +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser9parse_and +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser9parse_not +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCslbMUDoFrEqM_14weavepy_parser3ast5AliasE8grow_oneBQ_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCslbMUDoFrEqM_14weavepy_parser3ast3ArgE8grow_oneBQ_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser10at_keyword +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser22expect_or_forgot_comma +_RINvXs8_NtCskibSv91bgl1_9hashbrown3setINtB6_7HashSetNtNtCs1C1lLj4PWSY_5alloc6string6StringINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEEINtNtNtNtB1v_4iter6traits7collect6ExtendBO_E6extendINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetBO_B1q_EEB2h_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler13set_line_from +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler15emit_store_name +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler19child_qualname_impl +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler17emit_entry_resume +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler14emit_load_name +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler14unwind_fblocks +_RNvCs9NJVNhcGWEq_10weavepy_vm26percent_render_plain_value +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecThjEE8grow_oneCs4U5RMT44ivg_13weavepy_lexer +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser24parse_ternary_or_starred +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser13parse_bit_and +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser12parse_muldiv +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecReE8grow_oneCslbMUDoFrEqM_14weavepy_parser +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser5check +_RNvNvCshfZExtisgX1_16weavepy_compiler32collect_comp_walrus_targets_stmt4walk +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler26build_function_object_full +_RNvCshfZExtisgX1_16weavepy_compiler21collect_reads_stmt_in +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtB4_4iter8adapters9enumerate9EnumerateINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainNtCshfZExtisgX1_16weavepy_compiler8ConstantEEEB24_ +_RNvCs9NJVNhcGWEq_10weavepy_vm20percent_render_plain +_RNvCshfZExtisgX1_16weavepy_compiler13collect_decls +_RNvXsQ_CshfZExtisgX1_16weavepy_compilerNtB5_8ConstantNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq +_RNvCshfZExtisgX1_16weavepy_compiler26collect_reads_stmt_in_impl +_RNvCshfZExtisgX1_16weavepy_compiler23collect_inner_free_expr +_RINvMs3_NtCs4vf5tvaTb4E_8indexmap3mapINtB6_8IndexMapNtNtCs1C1lLj4PWSY_5alloc6string6StringNtCshfZExtisgX1_16weavepy_compiler7BindingINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtB1s_6fxhash8FxHasherEE12get_index_ofBO_EB1s_ +_RNCNvMsV_CshfZExtisgX1_16weavepy_compilerNtB7_8Compiler18compile_expr_inners1_0B7_ +_RNCNvMsV_CshfZExtisgX1_16weavepy_compilerNtB7_8Compiler18compile_stmt_inners0_0B7_ +_RNvMsU_CshfZExtisgX1_16weavepy_compilerNtB5_9LineIndex8line_for +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler25compile_default_arguments +_RNvMs1_NtCshfZExtisgX1_16weavepy_compiler9flowgraphNtB5_3Cfg20const_loading_instrs +_RNvNtNtCs2isY2vBRLTu_10std_detect6detect5cache21detect_and_initialize +_RNvNtNtNtCsevLNFiNqfJP_4core9core_arch3x865xsave7__xgetbv.857 +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler24genexp_call_optimization +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser13parse_ternary +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser11parse_power +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser24check_import_alias_debug +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser18try_arg_annotation +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEE6insertB2h_ +_RNvCshfZExtisgX1_16weavepy_compiler18collect_reads_expr +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler16var_index_or_add +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler18close_unwind_holes +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser21parse_expression_list +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser24check_string_expr_string +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtNtCslbMUDoFrEqM_14weavepy_parser3ast4StmtE6map_orNtNtCs4U5RMT44ivg_13weavepy_lexer5token4SpanNCNvMNtBN_6parserNtB2l_6Parser15parse_class_def0EBN_ +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB4_9Validator13mark_assigned +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCslbMUDoFrEqM_14weavepy_parser3ast8ConstantECshfZExtisgX1_16weavepy_compiler +_RINvNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB8_11RawVecInnerpE7reserve21do_reserve_and_handleNtNtBa_5alloc6GlobalECslbMUDoFrEqM_14weavepy_parser +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser18parse_function_def +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser23take_colon_type_comment +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser8parse_if +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB4_9Validator10visit_body +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler26compile_function_def_inner +_RNvMs1_NtCs4U5RMT44ivg_13weavepy_lexer5tokenNtB5_12StringPrefix5parse +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser22parse_simple_statement +_RNvXs1b_NtCslbMUDoFrEqM_14weavepy_parser3astNtB6_8ConstantNtNtCsevLNFiNqfJP_4core5clone5Clone5clone +_RNvXsR_CshfZExtisgX1_16weavepy_compilerNtB5_8ConstantINtNtCsevLNFiNqfJP_4core7convert4FromNtNtCslbMUDoFrEqM_14weavepy_parser3ast8ConstantE4from +_RINvMNtNtCsevLNFiNqfJP_4core4cell4onceINtB3_8OnceCellINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBU_5types10TypeObjectEE8try_initNCINvB2_11get_or_initNCNCNvNtNtBU_6stdlib4time16struct_time_type00E0zEBU_ +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser15cps_to_constant +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser27take_def_body_type_comments +_RNvMNtCs4U5RMT44ivg_13weavepy_lexer7scannerNtB2_7Scanner11scan_string +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser4bump +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCslbMUDoFrEqM_14weavepy_parser3ast5CmpOpE8grow_oneBQ_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler14compile_assign +_RINvMsV_CshfZExtisgX1_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_18compile_expr_inners2_0EB6_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler10patch_jump +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler15compile_jump_if +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time5build +_RNvNtCsgHYyB3hU8Ec_3std3env11current_dir +_RINvMsV_CshfZExtisgX1_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_18compile_expr_inners4_0EB6_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser13decode_string +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser15prev_token_span +_RINvMNtNtCsevLNFiNqfJP_4core4cell4onceINtB3_8OnceCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecjEE8try_initNCINvB2_11get_or_initNCNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB1Y_6Parser8line_col0E0zEB20_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler22super_attr_optimizable +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time1b +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time16compute_timezone +_RNvMNtNtCs5QN7kbomi5h_6chrono6offset3utcNtB2_3Utc3now +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser16constant_str_cps +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser26collect_pep695_type_params +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser12parse_return +_RNvCshfZExtisgX1_16weavepy_compiler11emit_cmp_op +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser13string_prefix +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser11parse_block +_RNvMs1_NtCshfZExtisgX1_16weavepy_compiler9flowgraphNtB5_3Cfg36is_exit_or_eval_check_without_lineno +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler15compile_compare +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time16compute_timezone0B7_ +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtNtCsevLNFiNqfJP_4core4cell4once8OnceCellINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1T_5types10TypeObjectEEEB1T_ +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser19split_string_prefix +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser12strip_quotes +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser15decode_str_body +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB4_9Validator22push_type_params_scope +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEE12contains_keyBO_EB2i_ +_RNvMNtNtCs5QN7kbomi5h_6chrono5naive4dateNtB2_9NaiveDate25from_num_days_from_ce_opt +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13codecs_engineNtB4_6EncCtx3new +_RNvCshfZExtisgX1_16weavepy_compiler15clean_docstring +_RNvXsZ_NtCs1C1lLj4PWSY_5alloc6stringNtB5_6StringNtNtCsevLNFiNqfJP_4core3fmt5Write9write_str.952 +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser26take_trailing_type_comment +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBG_6string6StringEECs2GDADXmuQ1X_11weavepy_cli +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10codecs_mod14encode_special0B7_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser16consume_stmt_end +_RNvCshfZExtisgX1_16weavepy_compiler20collect_target_names +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEE6insertB1G_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmuEE14reserve_rehashNCINvNtB8_3map11make_hashermuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEE0EB2u_ +mi_bchunk_popcountNC +_RNvXs3_NtCs9NJVNhcGWEq_10weavepy_vm13vm_singletonsNtB5_10HostStdoutNtNtNtCsevLNFiNqfJP_4core2io5write5Write5write +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEENtNtBK_5clone5Clone5cloneB1l_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler35import_flag_shadowed_by_module_comp +_RNvCs9NJVNhcGWEq_10weavepy_vm19code_names_anywhere +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter8do_print +_RNvXNvNtNtCsevLNFiNqfJP_4core2io5write17default_write_fmtINtB2_7AdapterNtNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons10HostStdoutENtNtB8_3fmt5Write9write_strB1b_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10codecs_mod10encode_obj +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10codecs_mod10encode_str +_RNvCs9NJVNhcGWEq_10weavepy_vm25decode_source_bytes_inner +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser19find_invalid_target +_RNvMsr_NtCsevLNFiNqfJP_4core3numx27from_ascii_bytes_radix_impl +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCshfZExtisgX1_16weavepy_compiler8bytecode9BinOpKindE6map_ormNCNvNtBM_12cpython_code14map_to_cpython0EBM_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCsgHYyB3hU8Ec_3std4path7PathBufEECs2GDADXmuQ1X_11weavepy_cli +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecReEINtB2_18SpecFromIterNestedB11_INtNtNtCsevLNFiNqfJP_4core3str4iter5SplitcEE9from_iterCshfZExtisgX1_16weavepy_compiler +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13codecs_engine6EncCtxEBH_ +_RNvCs9NJVNhcGWEq_10weavepy_vm25translate_source_newlines +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser12parse_number +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE5entryB7_ +_RNvYNtNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons10HostStdoutNtNtNtCsevLNFiNqfJP_4core2io5write5Write9write_allB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13codecs_engine11utf8_encode +_RNvXs3_NtCsevLNFiNqfJP_4core4bstrNtB5_7ByteStrNtNtB7_3fmt7Display3fmt +_RNvCshfZExtisgX1_16weavepy_compiler11bin_op_kind +_RNvMNtCs4U5RMT44ivg_13weavepy_lexer7scannerNtB2_7Scanner20verify_end_of_number +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB4_9Validator12visit_target +_RNvMsb_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapNtB5_11VacantEntry6insertB7_ +_RNvYNtNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons10HostStdoutNtNtNtCsevLNFiNqfJP_4core2io5write5Write9write_fmtB6_ +_RNvCs2GDADXmuQ1X_11weavepy_cli8run_path +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB12_6string6StringEEECs2GDADXmuQ1X_11weavepy_cli +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtCshfZExtisgX1_16weavepy_compiler9LoopFrameE8push_mutBH_ +_RNvCshfZExtisgX1_16weavepy_compiler27collect_reads_assign_target +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtCshfZExtisgX1_16weavepy_compiler9LoopFrameE8grow_oneBO_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser20parse_target_or_star +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser9parse_for +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser26parse_target_list_no_tuple +_RNvMsr_NtCsevLNFiNqfJP_4core3numx27from_ascii_bytes_radix_impl.1373 +_RNvXs1i_NtCsevLNFiNqfJP_4core3fmtRiNtB6_7Display3fmtCskis0sZ8PIOa_12clap_builder +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter11decimal_i64 +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler17starunpack_helper +_RNvMsP_CshfZExtisgX1_16weavepy_compilerNtB5_10CodeObject10content_eq +_RNvNtCs1C1lLj4PWSY_5alloc5boxed14box_new_uninit.1077 +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time17time_monotonic_ns +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance7recycle +_RNvMsp_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage6retire +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler19compile_load_target +_RNvMsb_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtB5_11SplitValues5reset +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB27_5types10PyInstanceEEEE8try_withNCNvMss_B2F_B2D_7recycles_0uEB27_ +_RNvNvCs9NJVNhcGWEq_10weavepy_vm19code_names_anywhere17constant_mentions +_RNvCshfZExtisgX1_16weavepy_compiler43should_apply_two_element_slice_optimization +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser22parse_subscript_single +_RNvXsZ_NtCslbMUDoFrEqM_14weavepy_parser3astNtB5_8ExprKindNtNtCsevLNFiNqfJP_4core5clone5Clone5clone +_RNvMsp_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage11from_layout +_RNvMs0_NtCshfZExtisgX1_16weavepy_compiler9flowgraphNtB5_3Cfg15make_load_const +_RNvCshfZExtisgX1_16weavepy_compiler25body_reads_super_or_class +_RNCNvNCNvCshfZExtisgX1_16weavepy_compiler25body_reads_super_or_class09any_class0B7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterTNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyNtB1s_6ObjectEEEB1u_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler18cell_or_free_index +_RNvCshfZExtisgX1_16weavepy_compiler19function_free_names +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB7_2fs4FileEE10initializeNCINvB2_11get_or_initNCNvNtNtCs2GDADXmuQ1X_11weavepy_cli9text_trim3sys5statm0E0zEB2r_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtBc_2fs4FileEE10initializeNCINvB1a_11get_or_initNCNvNtNtCs2GDADXmuQ1X_11weavepy_cli9text_trim3sys5statm0E0zE0E0B3f_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB1v_9FieldSlotEEE10initializeNCINvB2_11get_or_initNCINvMst_B1v_NtB1v_16CodeConstObjects11alloc_sitesB25_NvMsG_B1v_B25_5emptyE0E0zEB1v_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB2i_9FieldSlotEEE10initializeNCINvB1a_11get_or_initNCINvMst_B2i_NtB2i_16CodeConstObjects11alloc_sitesB2S_NvMsG_B2i_B2S_5emptyE0E0zE0E0B2i_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjjNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCs9NJVNhcGWEq_10weavepy_vm +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs4bqUF11K40R_11weavepy_jit7runtime9ObjLayoutE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEBX_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze11carve_start +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze12analyze_once +_RINvMsa_NtCskibSv91bgl1_9hashbrown3rawNtB6_13RawTableInner22fallible_with_capacityNtNtCs1C1lLj4PWSY_5alloc5alloc6GlobalECs4bqUF11K40R_11weavepy_jit +_RNvMsi_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_8BTreeMapjNtNtB7_7set_val9SetValZSTE6insertCs4bqUF11K40R_11weavepy_jit +_RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit2ir6TBlockENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEB1r_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB1D_6string6StringEB25_EmEECs9NJVNhcGWEq_10weavepy_vm +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier211size_budget +_RNvMs5_NtCs1C1lLj4PWSY_5alloc7raw_vecNtB5_11RawVecInner11finish_growCs4bqUF11K40R_11weavepy_jit +_RNvXNtCskibSv91bgl1_9hashbrown3mapINtB2_7HashMapmuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEENtNtBR_5clone5Clone5cloneCs4bqUF11K40R_11weavepy_jit +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze17assigned_on_entry +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjjINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE3getjECs4bqUF11K40R_11weavepy_jit +_RNvCshfZExtisgX1_16weavepy_compiler23method_references_class +_RNvNtNtCs2GDADXmuQ1X_11weavepy_cli9text_trim3sys11proc_number +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218publish_obj_layout +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexINtNtNtNtB7_11collections4hash3map7HashMapjjEEE10initializeNCINvB2_11get_or_initNvYBT_NtNtCsevLNFiNqfJP_4core7default7Default7defaultE0zECs9NJVNhcGWEq_10weavepy_vm +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm5tier23PinEEB1c_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3map8BTreeMapjjEECs4bqUF11K40R_11weavepy_jit +_RNvXNtCskibSv91bgl1_9hashbrown3mapINtB2_7HashMapjuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEENtNtBR_5clone5Clone5cloneCs4bqUF11K40R_11weavepy_jit +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze13step_abstract +_RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemINtNtCsevLNFiNqfJP_4core6option6OptionINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit7analyze5ESlotEENtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEB1B_ +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit7analyze2SEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapmNtNtCshfZExtisgX1_16weavepy_compiler8bytecode6OpCodeINtNtB4_4hash18BuildHasherDefaultNtNtB1B_6fxhash8FxHasherEEEB1B_ +_RNvNtCs2GDADXmuQ1X_11weavepy_cli6memory4tick +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier213try_enter_osr +_RNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB7_8JitState12get_compileds_0B9_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier221laid_out_slots_layout +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCs4bqUF11K40R_11weavepy_jit7runtime9ObjLayoutE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0B1K_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertCs4bqUF11K40R_11weavepy_jit +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterjENtNtNtNtBb_4iter6traits8iterator8Iterator3anyNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12analyze_onces7_0EB1H_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze10emit_instr +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17core_pure_kw_call +_RNvMse_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_5CBody3set +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3set8BTreeSetjEECs4bqUF11K40R_11weavepy_jit +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionIBC_NtNtCs4bqUF11K40R_11weavepy_jit7analyze2SEEEEEB1C_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmuEE14reserve_rehashNCINvNtB8_3map11make_hashermuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0ECs4bqUF11K40R_11weavepy_jit +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9hot_gates9env_flags9jit_trace0E0zE0E0B2o_ +_RNvMsr_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage14store_position +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm5tier23PinE8push_mutBJ_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjjINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertCs4bqUF11K40R_11weavepy_jit +_RNvXNtNtNtCs1C1lLj4PWSY_5alloc11collections9vec_deque14spec_from_iterINtB4_8VecDequejEINtB2_12SpecFromIterjINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6copied6CopiedINtNtNtB1Q_5slice4iter4IterjEEE14spec_from_iterCs4bqUF11K40R_11weavepy_jit +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze10emit_block +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtNtBa_6poison5mutex5MutexINtNtNtNtBc_11collections4hash3map7HashMapjjEEE10initializeNCINvB1a_11get_or_initNvYB1G_NtNtCsevLNFiNqfJP_4core7default7Default7defaultE0zE0E0Cs9NJVNhcGWEq_10weavepy_vm +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze12analyze_impl +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze13control_succs +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze12plan_rewrite +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjuEE14reserve_rehashNCINvNtB8_3map11make_hasherjuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0ECs4bqUF11K40R_11weavepy_jit +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit2ir6TBlockEEB11_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5tier23PinEBF_ +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm5tier211MethodEntryEE9drop_slowBX_ +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm5tier29AttrGuardEE9drop_slowBX_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze16reachable_blocks +_RNvXs1_NtNtNtCsevLNFiNqfJP_4core4iter8adapters6filterINtB5_6FilterINtNtNtBb_3ops5range5RangejENCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12analyze_onces1_0ENtNtNtB9_6traits8iterator8Iterator4nextB1A_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4bqUF11K40R_11weavepy_jit7analyze2SEE8grow_oneBQ_ +_RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultNtNtCs4bqUF11K40R_11weavepy_jit2ir6TBlockNtNtBM_7analyze10JitVerdictE11inspect_errNCNvB1p_12analyze_onces8_0EBM_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit7analyze9CtorStateEBF_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9hot_gates9env_flags9jit_trace0E0zEB1A_ +_RINvNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB8_11RawVecInnerpE7reserve21do_reserve_and_handleNtNtBa_5alloc6GlobalECs4bqUF11K40R_11weavepy_jit +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs4bqUF11K40R_11weavepy_jit7runtime9ObjLayoutE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zECs9NJVNhcGWEq_10weavepy_vm +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjjEE14reserve_rehashNCINvNtB8_3map11make_hasherjjINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0ECs4bqUF11K40R_11weavepy_jit +_RNvMs4_NtNtCs1C1lLj4PWSY_5alloc11collections9vec_dequeINtB5_8VecDequejE4growCs4bqUF11K40R_11weavepy_jit +_RNvNvCshfZExtisgX1_16weavepy_compiler23class_body_reads_dunder10stmt_reads +_RNvNvCshfZExtisgX1_16weavepy_compiler27collect_comp_scope_walruses5visit +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler20comp_inline_eligible +_RNvCshfZExtisgX1_16weavepy_compiler20stmt_needs_classdict +_RNvNvCshfZExtisgX1_16weavepy_compiler24collect_self_attr_stores6target +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcDNtNtCsevLNFiNqfJP_4core3any3AnyNtNtB1z_6marker4SendNtB22_4SyncEL_EE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEBY_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter22meta_store_transparent +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCslbMUDoFrEqM_14weavepy_parser3ast13ComprehensionE8grow_oneBQ_ +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB4_9Validator19visit_comprehension +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler28compile_deferred_annotations +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCslbMUDoFrEqM_14weavepy_parser3ast7KeywordEECshfZExtisgX1_16weavepy_compiler +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins22construct_staticmethod +_RNvMs5_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_13LeafAttrCache4grow +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16core_class_store +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs9NJVNhcGWEq_10weavepy_vm9StoreInitEEE10initializeNCINvB2_11get_or_initNCNvB26_15code_store_init0E0zEB26_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs9NJVNhcGWEq_10weavepy_vm9StoreInitEEE10initializeNCINvB1a_11get_or_initNCNvB2T_15code_store_init0E0zE0E0B2T_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtCshfZExtisgX1_16weavepy_compiler11TableBufferE9drop_slowBI_ +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmTmNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE3getmEBV_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4bqUF11K40R_11weavepy_jit2ir12ListLoopMetaE8grow_oneBQ_ +_RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCslbMUDoFrEqM_14weavepy_parser3ast4StmtNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalECshfZExtisgX1_16weavepy_compiler +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCshfZExtisgX1_16weavepy_compiler6mangle7ManglerEBF_ +_RNvNvCshfZExtisgX1_16weavepy_compiler25reject_walrus_in_iterable4scan +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCshfZExtisgX1_16weavepy_compiler12LazyClassCtxEBD_ +_RNvMs1_NtCshfZExtisgX1_16weavepy_compiler9flowgraphNtB5_3Cfg11jump_thread +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler19compile_class_value +_RNCNvCshfZExtisgX1_16weavepy_compiler32class_body_defs_claim_class_cell0B3_ +_RNvMNtCshfZExtisgX1_16weavepy_compiler6mangleNtB2_7Mangler9arguments +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18construct_property +_RNvMsI_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_9DictWatch3new +_RNvMs5_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_13LeafAttrCache4free +_RNvMs5_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_13LeafAttrCache9table_mut +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15core_store_init +_RINvXs1_NtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemhNtB6_12SpecFromElem9from_elemNtNtBa_5alloc6GlobalECs9NJVNhcGWEq_10weavepy_vm +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir6TBlockE8push_mutBJ_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtCshfZExtisgX1_16weavepy_compiler10ExcHandlerE8grow_oneBO_ +_RNvCshfZExtisgX1_16weavepy_compiler17compile_comp_body +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler17compile_class_def +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler16build_class_body +_RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCslbMUDoFrEqM_14weavepy_parser3ast3ArgNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalECshfZExtisgX1_16weavepy_compiler +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins21property_init_members +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14core_dict_next +_RNvXsK_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_9DictWatchNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcNtNtBG_13tuple_storage12TupleStorageEEBG_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm17frozen_code_cache7PayloadEBF_ +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile00B7_ +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze10emit_instr0B5_ +mi_bbitmap_chunkmap_try_clear.isra.0 +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser11parse_while +_RNvNtCshfZExtisgX1_16weavepy_compiler6mangle17mangle_class_body +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser15parse_class_def +_RNCNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB6_9Validator10visit_stmt0B8_ +_RNvCshfZExtisgX1_16weavepy_compiler22check_comp_walrus_nest +_RINvXs7_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3setINtB6_7HashSetNtNtCs1C1lLj4PWSY_5alloc6string6StringINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEEINtNtNtNtB1L_4iter6traits7collect12FromIteratorB14_E9from_iterINtNtNtB3s_8adapters6cloned6ClonedINtB6_5UnionB14_B1G_EEEB2x_ +_RNvXsM_NtCslbMUDoFrEqM_14weavepy_parser3astNtB5_9ArgumentsNtNtCsevLNFiNqfJP_4core5clone5Clone5clone +_RINvMsV_CshfZExtisgX1_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_14compile_assign0EB6_ +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastINtNtB4_12shared_value12SliceStorageNtNtB4_6object7DictKeyEEB4_ +_RNvMs_NtCs4bqUF11K40R_11weavepy_jit7analyzeNtB4_4Plan9hidden_at +_RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeNtNtBM_7analyze10JitVerdictE11inspect_errNCNvB1t_10emit_instrs0_0EBM_ +_RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterINtNtB1f_6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit2ir14MethodSiteMetaEENCNvNtB2M_7analyze12analyze_onces9_0EB2I_EB2M_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir11GlobalGuardEEB1c_ +_RNvMNtCshfZExtisgX1_16weavepy_compiler6mangleNtB2_7Mangler4name +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler21compile_comprehension +_RNvCshfZExtisgX1_16weavepy_compiler19stamp_comp_elt_span +_RNvCshfZExtisgX1_16weavepy_compiler24collect_self_attr_stores +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCslbMUDoFrEqM_14weavepy_parser3ast9TypeParamENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCshfZExtisgX1_16weavepy_compiler +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCslbMUDoFrEqM_14weavepy_parser3ast13ComprehensionECshfZExtisgX1_16weavepy_compiler +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins23reentrant_load_attr_opt +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object9DictWatchEEB11_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14core_leaf_init +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215classify_global +_RINvMNtCsevLNFiNqfJP_4core5sliceSNtNtCs4bqUF11K40R_11weavepy_jit2ir8OsrEntry20sort_unstable_by_keymNCNvNtBz_7analyze12analyze_oncesa_0EBz_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtCshfZExtisgX1_16weavepy_compiler12FinallyFrameE8grow_oneBO_ +_RNvCshfZExtisgX1_16weavepy_compiler19expr_contains_await +_RNvCshfZExtisgX1_16weavepy_compiler24expr_contains_async_comp +_RNvNvCshfZExtisgX1_16weavepy_compiler22check_comp_walrus_nest5visit +_RINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB6_11Interpreter16lean_init_extendNtNtB6_11frame_slots10StackDrainEB6_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4bqUF11K40R_11weavepy_jit2ir5TStmtE8grow_oneBQ_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze7pop_val +_RNvMNtCshfZExtisgX1_16weavepy_compiler6mangleNtB2_7Mangler4stmt +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEE6removeeEB2i_ +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB4_9Validator13record_walrus +_RNvNtCshfZExtisgX1_16weavepy_compiler8validate22collect_walrus_targets +_RNvCshfZExtisgX1_16weavepy_compiler20comp_clause_is_async +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11core_new_kw +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13core_new_bind +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier219resolve_plain_dicts +_RNCNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s1_0Bb_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterINtNtB4_6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit2ir6TBlockEEEB1P_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze14boundary_stack +_RNvMNtCshfZExtisgX1_16weavepy_compiler6mangleNtB2_7Mangler4expr +_RNvCshfZExtisgX1_16weavepy_compiler23class_body_reads_dunder +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser14parse_comp_for +_RNvNtCshfZExtisgX1_16weavepy_compiler8validate20collect_name_targets +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtCs9NJVNhcGWEq_10weavepy_vm6object11DictWatchesEuE16get_or_init_slowNvNvB1R_12DICT_WATCHES27___rust_std_internal_init_fnEB1T_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmNtNtCs4bqUF11K40R_11weavepy_jit2ir14ResolvedGlobalEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0EBV_ +_RNCNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB9_8JitState12get_compileds_00Bb_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4bqUF11K40R_11weavepy_jit2ir11GlobalGuardE8grow_oneBQ_ +_RNvNtCs1C1lLj4PWSY_5alloc5boxed14box_new_uninit.1063 +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtCs9NJVNhcGWEq_10weavepy_vm6object11DictWatchesEEB1J_ +_RNvCshfZExtisgX1_16weavepy_compiler18collect_comp_reads +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler29collect_global_walrus_shallow +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler27collect_nested_comp_symbols +_RNvCs9NJVNhcGWEq_10weavepy_vm17make_pep604_union +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21release_call_operands +_RNvCs9NJVNhcGWEq_10weavepy_vm19dict_view_set_elems +_RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VechE16into_boxed_sliceCs9NJVNhcGWEq_10weavepy_vm +_RNvMs1t_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyIterator18next_value_checked +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod14register_typesINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real14lock_method_kw +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexINtNtNtNtB7_11collections4hash3map7HashMapyjEEE10initializeNCINvB2_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10signal_mod16pthread_registry0E0zEB2M_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native19install_tuplegetter +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastNtNtB4_6object14SlotDescriptorEB4_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict13install_odict +_RNvMs6_NtCs4bqUF11K40R_11weavepy_jit7analyzeNtB5_5ESlot8is_plain +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertCs4bqUF11K40R_11weavepy_jit +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit2ir5TFuncEBF_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertCs4bqUF11K40R_11weavepy_jit +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler22emit_pop_block_no_line +_RNvCshfZExtisgX1_16weavepy_compiler28collect_target_names_ordered +_RINvMNtCsevLNFiNqfJP_4core3stre18trim_start_matchescECs9NJVNhcGWEq_10weavepy_vm +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm14descr_registry9DescrMetaEBF_ +_RNvCs9NJVNhcGWEq_10weavepy_vm16exc_family_flags +_RNvMse_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_11PyTraceback5frame +_RNvCs9NJVNhcGWEq_10weavepy_vm17is_union_eligible +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16type_method_pair +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod31register_classmethod_descriptor +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib14operator_accel5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real1b +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real9lock_type0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10signal_mod31register_current_thread_pthread +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTyjEE14reserve_rehashNCINvNtB8_3map11make_hasheryjNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs9NJVNhcGWEq_10weavepy_vm +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakNtNtBS_6object9BuiltinFnEhEE8grow_oneBS_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object14SlotDescriptorE9drop_lastB7_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmNtNtCshfZExtisgX1_16weavepy_compiler8bytecode6OpCodeEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBV_6fxhash8FxHasherEE0EBV_ +_RNvNtCshfZExtisgX1_16weavepy_compiler9flowgraph15to_ast_constant +_RNvCshfZExtisgX1_16weavepy_compiler20expr_yields_in_scope +_RNvCshfZExtisgX1_16weavepy_compiler12comp_inlines +_RNvNtCs9NJVNhcGWEq_10weavepy_vm14descr_registry10descr_type +_RNvMs15_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_11BoundMethod16is_pymethod_type +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter24build_exception_instance +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16leaf_load_method +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot9poly_peek +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real5build +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real10proxy_type0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13leaf_builtins19register_jit_method +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter22load_method_ic_resolve +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set8IntoItermEE9from_iterCs4bqUF11K40R_11weavepy_jit +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir12IterLoopMetaEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB2n_6filter6FilterINtNtNtB2r_5slice4iter4IterNtB13_12ListLoopMetaENCNvNtB15_7analyze12analyze_oncesg_0ENCB4h_sh_0EE9from_iterB15_ +_RINvMNtCsevLNFiNqfJP_4core5sliceSNtNtCs4bqUF11K40R_11weavepy_jit2ir13CompSavedMeta20sort_unstable_by_keymNCNvNtBz_7analyze12analyze_oncesi_0EBz_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit7analyze6RegionEBF_ +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12local_native5SpaceEEEB2j_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler21collect_names_shallow +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod14register_types +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object16py_hash_long_i64 +_RNvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB5_3MapINtNtB7_6filter6FilterINtNtNtBb_5slice4iter4IterNtNtCs4bqUF11K40R_11weavepy_jit2ir12ListLoopMetaENCNvNtB1M_7analyze12analyze_oncesg_0ENCB2x_sh_0ENtNtNtB9_6traits8iterator8Iterator4nextB1M_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecmEINtB4_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1F_5slice4iter4IterjENCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12analyze_oncesm_0EE9from_iterB2T_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapmTmNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEINtNtB4_4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEEEB1D_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjNtNtCs4bqUF11K40R_11weavepy_jit7analyze7PairSrcEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0EBV_ +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmNtNtCs4bqUF11K40R_11weavepy_jit2ir14ResolvedGlobalINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE3getmEBT_ +_RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCslbMUDoFrEqM_14weavepy_parser3ast7KeywordNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalECshfZExtisgX1_16weavepy_compiler +_RNvCshfZExtisgX1_16weavepy_compiler29collect_comp_scope_inner_free +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler34emit_inlined_comprehension_restore +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter24instantiate_raised_class +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot11poly_getter +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib14operator_accel5build0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real5build +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtNtBa_6poison5mutex5MutexINtNtNtNtBc_11collections4hash3map7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringRAmj100_EEE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10codecs_mod17sbcs_decode_table0E0zE0E0B4i_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native13install_deque +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjTmmmEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertCs4bqUF11K40R_11weavepy_jit +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEE6removeBO_EB2i_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler12comp_symbols +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_EsH_0B8_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter23attach_implicit_context +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native5build0B7_ +_RNvMso_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_10PyProperty4fset +_RNCNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s4_0Bb_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmTmNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0EBX_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4bqUF11K40R_11weavepy_jit2ir14CalleeSpanMetaE8grow_oneBQ_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjThjEEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0ECs4bqUF11K40R_11weavepy_jit +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler10emit_setup +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11hash_object +_RINvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB6_10TypeObject12memo_verdictNCNvMs7_B8_NtB8_11Interpreter19plain_store_verdict0EB8_ +_RINvMsb_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtB6_11SplitValues10first_pushNCINvMsi_B6_NtNtB8_5types10PyInstance14split_store_atNvMs7_B8_NtB8_11Interpreter14core_droppableE0EB8_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs9NJVNhcGWEq_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_20note_frameless_calls0INtNtB1P_6option6OptionbEEBZ_ +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot6getter +_RNvMs2_Cs9NJVNhcGWEq_10weavepy_vmNtB5_5Frame12skip_end_for +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtB4_5array4iter8IntoIterTReB16_INtNtCs1C1lLj4PWSY_5alloc5boxed3BoxDG_INtNtNtB4_3ops8function2FnTRL0_SNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEp6OutputINtNtB4_6result6ResultB2k_NtNtB2o_5error12RuntimeErrorENtNtB4_6marker4SendNtB47_4SyncEL_EEKj3_EEB2o_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_5types10TypeObjectEEEE8try_withNCNvNtNtBZ_6stdlib11thread_real10rlock_type0B2e_EBZ_ +_RNvMso_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_10PyProperty4fdel +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir13RangeLoopMetaEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2u_5slice4iter4IterB13_ENCNvNtB17_7analyze12analyze_oncesd_0EE9from_iterB17_ +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterjENCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12analyze_oncesl_0EE9from_iterB3i_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze12resolve_pair +_RNvXs2_NtNtCsevLNFiNqfJP_4core3num11float_parsedNtNtNtB9_3str6traits7FromStr8from_str +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler14comp_own_cells +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins22coexist_builtin_dunder +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14sync_exc_attrs +_RNvCs9NJVNhcGWEq_10weavepy_vm18is_union_initiator +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object17materialize_shell +_RNCNvCs9NJVNhcGWEq_10weavepy_vm17make_pep604_union0B3_ +_RINvXs8_NtCs9NJVNhcGWEq_10weavepy_vm11compact_vecINtB6_10CompactVecNtNtB8_6object6ObjectEINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorB13_E9from_iterINtNtNtB1w_8adapters6cloned6ClonedINtNtNtB1y_5slice4iter4IterB13_EEEB8_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier219jit_off_for_process +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real8ref_type0B7_ +_RNvMs1t_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyIterator15dict_iter_guard +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod31register_classmethod_descriptorINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real1b +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real19callable_proxy_type0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier216grade_obj_global +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir12ListLoopMetaEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB2n_6filter6FilterINtNtNtB2r_5slice4iter4IterB11_ENCNvNtB15_7analyze12analyze_oncese_0ENCB41_sf_0EE9from_iterB15_ +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir13CompSavedMetaEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6copied6CopiedINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map6ValuesmB11_EEE9from_iterB15_ +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1z_6filter6FilterINtNtNtB1D_3ops5range5RangejENCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12analyze_oncesn_0ENCB3a_so_0EE9from_iterB3e_ +_RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecmE8dedup_byNCNvMs5_B5_Bv_5dedup0ECs4bqUF11K40R_11weavepy_jit +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetmINtNtB4_4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEEEB28_ +_RNvNtCs4bqUF11K40R_11weavepy_jit6engine6op_mix +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmNtNtCshfZExtisgX1_16weavepy_compiler8bytecode6OpCodeINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBS_6fxhash8FxHasherEE6insertBS_ +_RNvXs4_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterTNtNtB9_6string6StringNtCshfZExtisgX1_16weavepy_compiler7CompSymEENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator10advance_byB1k_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19normalize_exception +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12do_hash_call +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real11lock_method +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real24install_proxy_forwarding +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native19install_defaultdict +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm6object14SlotDescriptorEBF_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmTmNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertBU_ +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecmEINtB2_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map6ValuesjNtNtCs4bqUF11K40R_11weavepy_jit7analyze14CompHeaderPlanENCNvB3f_12analyze_oncesq_0EE9from_iterB3h_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze8bin_kind +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze15bin_result_type +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser19at_expression_start +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexINtNtNtNtB7_11collections4hash3set7HashSetNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrNtNtB26_8fasthash13FxBuildHasherEEE10initializeNCINvB2_11get_or_initNCNvMs1B_NtB26_6objectNtB49_6Object12interned_str0E0zEB26_ +_RNCNvCs9NJVNhcGWEq_10weavepy_vm13is_object_new0B3_ +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot13poly_remember +_RINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB6_11Interpreter18lean_bind_keywordsINtNtNtNtCsevLNFiNqfJP_4core4iter7sources5empty5EmptyTRNtNtB6_6object6ObjectB20_EEEB6_ +_RNvMsN_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_8DictData24with_capacity_and_hasher +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins8str_join +_RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters5chainINtB4_5ChainIBO_IBO_INtNtBa_6option8IntoIterTRNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyRNtB1z_6ObjectEEINtNtB6_3map3MapINtNtB6_7flatten7FlattenIB18_RINtNtCs1C1lLj4PWSY_5alloc3vec3VecTB1x_B2h_EEEENCNvMsr_NtB1B_5typesNtB48_11SlotStorage4iter0EEINtB2P_7FlatMapIB18_RNtB1z_8DictDataENtNtB1B_7dictmap4IterNCB42_s_0EEIB4M_IB18_TRINtNtB1B_12shared_value7ThinArcINtB67_12SliceStorageB1x_EERSB2h_EEINtNtB6_3zip3ZipINtNtNtBa_5slice4iter4IterB1x_EIB7p_B2h_EENCB42_s0_0EENtNtNtB8_6traits8iterator8Iterator9size_hintB1B_ +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot16get_inst_builtin +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot8get_held +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze15infer_load_attr +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze13num_spec_lane +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB2_15FunctionBuilder18append_block_param +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6in_regB4_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen3memNtB4_9CodeArena7install +_RNvCsjIWZ3EBbJCG_15weavepy_codegen4dump +_RNvNtCsjIWZ3EBbJCG_15weavepy_codegen4fold11annihilated +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler21note_identifier_const +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib3sys13intern_shared +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter16bind_python_argss8_0B7_ +_RNvMs2_NtCs9NJVNhcGWEq_10weavepy_vm9leaf_planNtB5_5Owned7release +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19leaf_instance_truth +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvNtBU_7seqiter17builtin_ctor_armss2_0EBU_ +_RNvXNtNtNtCsevLNFiNqfJP_4core5array4iter10iter_innerSINtNtNtB8_3mem12maybe_uninit11MaybeUninitNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectENtB2_11PartialDrop12partial_dropB1y_ +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_EsA_0B8_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB2i_8AttrPolyEEE10initializeNCINvB1a_11get_or_initNCINvMst_B2i_NtB2i_16CodeConstObjects11alloc_sitesB2S_FEB2S_E0E0zE0E0B2i_ +_RNvMsA_Cs9NJVNhcGWEq_10weavepy_vmNtB5_8AttrPoly5empty +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefNtNtBG_6object10PyIteratorEEBG_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins15object_identity +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier222probe_class_ctor_shape +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir8AbiParamE8grow_oneCs4bqUF11K40R_11weavepy_jit +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4instB4_ +_RNCNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB4_3GenNtNtB6_3x643X64E7consume0B6_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB4_3X646alu_rr +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6branchB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4stubB4_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB4_3X647jcc_raw +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm6finish +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4iadd +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder3bor +_RINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB6_11Interpreter18lean_bind_keywordsQDNtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iteratorp4ItemTRNtNtB6_6object6ObjectB2c_EEL_EB6_ +_RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3zipINtB4_3ZipINtNtNtBa_5slice4iter4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEBV_ENtNtNtB8_6traits8iterator8Iterator4nextB1p_ +_RNvCs9NJVNhcGWEq_10weavepy_vm20function_stores_none +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecIBw_INtNtB7_5boxed3BoxNtCs9NJVNhcGWEq_10weavepy_vm9InlineActEEE8push_mutB13_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB1v_8AttrPolyEEE10initializeNCINvB2_11get_or_initNCINvMst_B1v_NtB1v_16CodeConstObjects11alloc_sitesB25_FEB25_E0E0zEB1v_ +_RNvCs9NJVNhcGWEq_10weavepy_vm13leaf_site_set +_RNvXs16_NtCs4bqUF11K40R_11weavepy_jit2irNtB6_14ResolvedGlobalNtNtCsevLNFiNqfJP_4core3cmp9PartialEq2eq +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir4TypexENtBT_5ValueEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_B1A_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBV_6fxhash8FxHasherEE0EBV_ +_RINvNtCsjIWZ3EBbJCG_15weavepy_codegen7codegen7compileNtNtB4_3x643X64EB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E10param_regsB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7consumeB4_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCsjIWZ3EBbJCG_15weavepy_codegen3mem4near6RegionEE10initializeNCINvB2_11get_or_initNvB1x_7reserveE0zEB1B_ +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm9store_imm +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3jmp +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB1v_8LeafSiteEEE10initializeNCINvB2_11get_or_initNCINvMst_B1v_NtB1v_16CodeConstObjects11alloc_sitesB25_NvMsK_B1v_B25_5emptyE0E0zEB1v_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxINtCs9NJVNhcGWEq_10weavepy_vm9SiteTableNtB2i_8LeafSiteEEE10initializeNCINvB1a_11get_or_initNCINvMst_B2i_NtB2i_16CodeConstObjects11alloc_sitesB2S_NvMsK_B2i_B2S_5emptyE0E0zE0E0B2i_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19core_leaf_site_call +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject14verdict_cached +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtNtBa_6poison5mutex5MutexINtNtNtNtBc_11collections4hash3set7HashSetNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrNtNtB2T_8fasthash13FxBuildHasherEEE10initializeNCINvB1a_11get_or_initNCNvMs1B_NtB2T_6objectNtB4X_6Object12interned_str0E0zE0E0B2T_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm11burst_stats7enabled +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11b_enumerate +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13core_push_new +_RNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction5slots +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm10specialize29attempt_specialize_store_attrs_0B5_ +_RNvMsr_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage13get_index_mut +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter10core_new_ns0_0B7_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB2_15FunctionBuilder4push +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB4_3X644emit +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCsjIWZ3EBbJCG_15weavepy_codegen3mem4near6RegionEE10initializeNCINvB1a_11get_or_initNvB2k_7reserveE0zE0E0B2o_ +_RNvNtNtCsjIWZ3EBbJCG_15weavepy_codegen3mem4near7reserve +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6imm_ofB4_ +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm5store +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsjIWZ3EBbJCG_15weavepy_codegen3x643X64EBF_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCslbMUDoFrEqM_14weavepy_parser3ast7KeywordE8grow_oneBQ_ +_RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3zipINtB4_3ZipINtNtNtBa_5slice4iter4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEBV_ENtNtNtB8_6traits8iterator8Iterator9size_hintB1p_ +_RNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_7GcState18maybe_auto_collect +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object15dict_watch_bump +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableuE12get_index_ofNtNtB8_6object7DictKeyEB8_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21deopt_load_attr_taken +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter22deopt_store_attr_taken +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter9sync_recs +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15native_truth_of +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13core_new_user +_RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters4skipINtB5_4SkipINtNtNtBb_5slice4iter4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEENtNtNtB9_6traits8iterator8Iterator8try_folduNCINvNvB28_3any5checkRB1o_NvB1s_20object_needs_vm_iterE0INtNtNtBb_3ops12control_flow11ControlFlowuEEB1s_ +_RNvMsr_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage4iter +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15core_store_slot +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit7analyze4PlanEBF_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier216probe_class_ctor +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze17const_slice_shape +_RINvNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB8_11RawVecInnerpE7reserve21do_reserve_and_handleNtNtBa_5alloc6GlobalECsjIWZ3EBbJCG_15weavepy_codegen +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5movesB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5allocB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4gotoB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7compareB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5fusesB4_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB4_3X646alu_ri +_RNvMNtCsgHYyB3hU8Ec_3std4timeNtB2_7Instant7elapsed +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB7_4path7PathBufEE10initializeNCINvB2_11get_or_initNCNvCsjIWZ3EBbJCG_15weavepy_codegen4dump0E0zEB2s_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir13DataFlowGraphECs4bqUF11K40R_11weavepy_jit +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16leaf_contains_eq +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins5b_lenINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvCs9NJVNhcGWEq_10weavepy_vm16class_dunder_new +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13lookup_method +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtCs9NJVNhcGWEq_10weavepy_vm9InlineActEEEB1s_ +_RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters5chainINtB4_5ChainIBO_INtNtBa_6option8IntoIterTRNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyRNtB1v_6ObjectEEINtNtB6_3map3MapINtNtB6_7flatten7FlattenIB14_RINtNtCs1C1lLj4PWSY_5alloc3vec3VecTB1t_B2d_EEEENCNvMsr_NtB1x_5typesNtB44_11SlotStorage4iter0EEINtB2L_7FlatMapIB14_RNtB1v_8DictDataENtNtB1x_7dictmap4IterNCB3Y_s_0EENtNtNtB8_6traits8iterator8Iterator9size_hintB1x_ +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter17core_local_methodKb1_Es0_0B8_ +_RNvMsx_Cs9NJVNhcGWEq_10weavepy_vmNtB5_8CallSlot3hit +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze10seed_entry +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4icmp +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E9live_intoB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5trackB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7addressB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E3srcB4_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCsjIWZ3EBbJCG_15weavepy_codegen7codegen6timing0E0zEB1y_ +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm8epilogue +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB4_3X6410saved_regs +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsjIWZ3EBbJCG_15weavepy_codegen8liveness8AnalysisEBF_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtBc_4path7PathBufEE10initializeNCINvB1a_11get_or_initNCNvCsjIWZ3EBbJCG_15weavepy_codegen4dump0E0zE0E0B3g_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm11stdlib_tree8contains +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object12interned_str +_RINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB6_4Once15call_once_forceNCNvMNtB8_9lazy_lockINtB18_8LazyLockNtNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace7GcStateE5force0EB1H_ +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object3len +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot16get_held_unbound +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtNtB6_5types10PyInstanceE3newB6_ +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtNtB6_6object12FrozenSetObjE3newB6_ +_RNvMsf_NtCs9NJVNhcGWEq_10weavepy_vm4syncINtB5_7GilCellNtNtB7_6object10PyIteratorE10try_borrowB7_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins4b_idINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze12obj_recv_ref +_RNCNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s5_0Bb_ +_RNvMs4_NtCs4bqUF11K40R_11weavepy_jit7analyzeNtB5_9CtorState10note_store +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir4InstE8grow_oneBQ_ +_RINvMsa_NtCskibSv91bgl1_9hashbrown3rawNtB6_13RawTableInner22fallible_with_capacityNtNtCs1C1lLj4PWSY_5alloc5alloc6GlobalECsjIWZ3EBbJCG_15weavepy_codegen +_RNCNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB4_3GenNtNtB6_3x643X64E9next_uses0B6_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E8const_ofB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E3resB4_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtB7_3vec3VecTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValuehbEEE8grow_oneB17_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir13StackSlotDataE8grow_oneBQ_ +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3alu +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm10alu_imm_ok +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtB7_6string6StringENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCshfZExtisgX1_16weavepy_compiler +_RNvCshfZExtisgX1_16weavepy_compiler31collect_inlined_comp_inner_free +_RNvCs9NJVNhcGWEq_10weavepy_vm19function_miss_class +_RNvMs3_NtCs9NJVNhcGWEq_10weavepy_vm9leaf_planNtB5_5Owned3own +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot3set +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot7peek_fn +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter23leaf_builtin_method_ptr +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecTNtNtB8_6string6StringNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtB2I_3map3MapINtNtNtB2M_5slice4iter4IterB1p_ENvMs1v_B1r_B1p_6to_strEINtNtB6_9into_iter8IntoIterB1p_EEE9from_iterB1t_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter10flush_lean +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTNtNtB7_6string6StringNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEE8grow_oneB1c_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15kwonly_defaults +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins8str_joinINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18join_exact_strings +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter16leaf_load_methods_0B7_ +_RNvCs9NJVNhcGWEq_10weavepy_vm14code_call_slot +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBN_6object10PyFunctionEE6filterNCNvMs7_BN_NtBN_11Interpreter16core_pure_method0EBN_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjTmmEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertCs4bqUF11K40R_11weavepy_jit +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueNtBP_5BlockNtBP_8VariableEE8grow_oneBR_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder6iconst +_RNvNtCsjIWZ3EBbJCG_15weavepy_codegen4fold8fold_one +_RNvNtCsjIWZ3EBbJCG_15weavepy_codegen7codegen8arg_locs +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7use_regB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6unusedB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E7untrackB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4edgeB4_ +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3imm +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3cmp +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCsjIWZ3EBbJCG_15weavepy_codegen7codegen6timing0E0zE0E0B2m_ +_RINvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB3_3GenNtNtB5_3x643X64E4opndNCNvB2_4insts2_0EB5_ +_RNvMs16_NtCsgHYyB3hU8Ec_3std4pathNtB6_4Path12__starts_with +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18set_membership_key +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15default_setattr +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6result6ResultNtCs9NJVNhcGWEq_10weavepy_vm11StepOutcomeNtNtBZ_5error12RuntimeErrorEEBZ_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15core_new_finish +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter9pure_iter +_RNvMsA_Cs9NJVNhcGWEq_10weavepy_vmNtB5_8AttrPoly6record +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16core_pure_method +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRxE6map_orTjjENCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB14_11Interpreter16core_pure_methods_0EB14_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215small_py_callee +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s7_0B7_ +_RNvMsa_NtCsjIWZ3EBbJCG_15weavepy_codegen2irNtB5_8Function5clear +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir13JumpTableDataE8grow_oneBQ_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB2_15FunctionBuilder39append_block_params_for_function_params +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4brif +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB2_15FunctionBuilder15seal_all_blocks +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5resetB4_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E3defB4_ +_RNvMs1_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X647load_rm +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20leaf_load_super_attr +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19do_dict_update_call +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins17dict_insert_exact +_RNvCs9NJVNhcGWEq_10weavepy_vm15meta_entry_fill +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects11native_hash +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtNtNtBe_11collections4hash3map7HashMapReNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEuE16get_or_init_slowNvNvNvNtB20_8builtins12vm_intrinsic5TABLE27___rust_std_internal_init_fnEB20_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14pooled_scratch +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler11native_codeNtB4_6Writer4code +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler11native_codeNtB4_6Writer4u32s +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter27dynamic_type_call_with_meta0B7_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib3sys16build_with_states_0B7_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod13build_partials_00E0zEB1C_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod13build_partials_00E0zE0E0B2q_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20core_builtin_kw_lane +_RNvMs0_NtCs9NJVNhcGWEq_10weavepy_vm5errorNtB5_11PyException9type_name +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze17dyn_attr_fallback +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s6_0B7_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0EBV_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder8ishl_imm +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBa_11collections4hash3map7HashMapINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB2q_3vec3VecTThmhEIB2m_ShEEEEEECs9NJVNhcGWEq_10weavepy_vm +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib3sys18intern_shared_memo +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtB12_4sync7GilCellNtNtB12_6object8DictDataEEEEB12_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11dict_insert +_RNvCs9NJVNhcGWEq_10weavepy_vm15code_stamp_slot +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object21type_hash_is_identity +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB6_11Interpreter10zip2_pairs +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11b_frozenset +_RNCNvNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins12vm_intrinsic5build0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib3sys10sys_intern +_RNvNvCs9NJVNhcGWEq_10weavepy_vm32collect_compiler_syntax_warnings10visit_body +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler11native_codeNtB4_6Writer4name +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod12partial_call +_RINvMsb_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtB6_11SplitValues11reserve_forNCNvMs7_B8_NtB8_11Interpreter15core_store_inits2_0EB8_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter9iter_step +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3jcc +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCslbMUDoFrEqM_14weavepy_parser3ast4ExprE8push_mutBJ_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCshfZExtisgX1_16weavepy_compiler8validate5ScopeE8push_mutBJ_ +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot16set_inst_builtin +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15core_seq_concat +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16str_isidentifierINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser17parse_eval_module +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler11native_codeNtB4_6Writer8constant +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod15partial_new_fors_0B7_ +_RINvMsb_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtB6_11SplitValues10fill_freshNCNCNvMs7_B8_NtB8_11Interpreter15core_store_inits5_00NCB1e_s_0EB8_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecIBw_TNtNtB7_6string6StringNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEE8push_mutB19_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir12AttrSiteMetaEEB1c_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtB4_6result6ResultNtNtCs4bqUF11K40R_11weavepy_jit6engine13CompiledFrameNtNtB12_7analyze10JitVerdictEINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectINtNtB2U_2rc2RcNtCshfZExtisgX1_16weavepy_compiler10CodeObjectEEEIB2j_NtNtB2U_5tier211MethodEntryEIB2j_NtNtB2n_6string6StringEEEB2U_ +_RINvYINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterjENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator8try_folduNCINvNvBX_3any5checkRjNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12range_prefix0E0INtNtNtB15_3ops12control_flow11ControlFlowuEEB2u_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder8icmp_imm +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E11param_movesB4_ +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyANtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrj4_EB19_ +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtNtNtBa_11collections4hash3map7HashMapReNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEB1Q_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBG_6string6StringEECs3LlOjCpN6r_18tracing_subscriber +_RNvNtCshfZExtisgX1_16weavepy_compiler7ast_opt18eval_unaryop_const +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15dict_merge_from +_RNvCs9NJVNhcGWEq_10weavepy_vm14meta_entry_hit +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object8contains +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins15ensure_dict_key +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs9NJVNhcGWEq_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNvMs7_BY_NtBY_11Interpreter11instantiate0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapReNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBT_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13b_set_tp_name +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter25exec_eval_compile_options +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter41parse_eval_source_emitting_warnings_flags +_RNvNvCs9NJVNhcGWEq_10weavepy_vm32collect_compiler_syntax_warnings10visit_args +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageANtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrj4_uE16get_or_init_slowNvNvNtNtB1j_6stdlib13functools_mod12PARTIAL_KEYS27___rust_std_internal_init_fnEB1j_ +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4csel +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTymEE14reserve_rehashNCINvNtB8_3map11make_hasherymNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECshfZExtisgX1_16weavepy_compiler +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object8eq_value +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16dict_update_fast +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter9iter_next +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6result6ResultNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectNtNtB11_5error12RuntimeErrorEEB11_ +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBe_11collections4hash3map7HashMapINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB2A_3vec3VecTThmhEIB2w_ShEEEEEuE16get_or_init_slowNvNvCs9NJVNhcGWEq_10weavepy_vm11SOURCE_CODE27___rust_std_internal_init_fnEB43_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser18parse_eval_element +_RNvCshfZExtisgX1_16weavepy_compiler31compile_owned_eval_with_options +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native19namedtuple_register +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native24namedtuple_register_make +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib3sys22sys_getframemodulename +_RNvXNtCsevLNFiNqfJP_4core3anyNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod10PartialRegNtB2_3Any7type_idBx_ +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE12contains_keyjECs4bqUF11K40R_11weavepy_jit +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder8iadd_imm +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder6select +_RINvMsa_NtCskibSv91bgl1_9hashbrown3rawNtB6_13RawTableInner13drop_elementsTINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtB1f_3vec3VecTThmhEIB1b_ShEEEEECs9NJVNhcGWEq_10weavepy_vm +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellAINtNtB1a_6option6OptionTNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrB25_EEj40_EEB29_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetNtNtCs1C1lLj4PWSY_5alloc6string6StringINtNtB4_4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEEEB2J_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10codecs_mod5build +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13dict_pop_leaf +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm5error12RuntimeErrorEEB11_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21try_dict_from_mapping +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14wstr_attr_dict +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_Esx_0B8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real19weakref_native_hash +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtNtNtBa_11collections4hash3map7HashMapReNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEE4withNCNvNtB1G_8builtins12vm_intrinsic0INtNtCsevLNFiNqfJP_4core6option6OptionB1C_EEB1G_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCsevLNFiNqfJP_4core4cell4CellTyyEEE4withNCNvMNtNtBa_4hash6randomNtB1I_11RandomState3new0B21_ECs9NJVNhcGWEq_10weavepy_vm +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod15partial_new_for +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins12obj_contains +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12do_eval_call +_RNvNtCshfZExtisgX1_16weavepy_compiler11native_code6encode +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler11native_codeNtB4_6Writer5table +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler11native_codeNtB4_6Writer4strs +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxeEINtNtBV_3vec3VecTThmhEIBR_ShEEEEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_B1r_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs9NJVNhcGWEq_10weavepy_vm +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakNtNtBS_6object10PyFunctionEINtBQ_2RcNtCshfZExtisgX1_16weavepy_compiler10CodeObjectEjEE8grow_oneBS_ +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod12partial_callINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1R_EEE4callB8_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214list_elem_lane +_RNvNtNtCs2GDADXmuQ1X_11weavepy_cli9text_trim3sys8resident +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftTmNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB1m_7sort_byNCNvMNtB1s_7codegenINtB2X_3GenNtNtB1s_3x643X64E11choose_pinss0_0E0EB1s_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTNtNtCsjIWZ3EBbJCG_15weavepy_codegen3asm5LabelINtNtB7_3vec3VecBN_EEE8grow_oneBR_ +_RNvCs9NJVNhcGWEq_10weavepy_vm12attr_name_of +_RNvCs9NJVNhcGWEq_10weavepy_vm11bind_method +_RNvMs0_NtCs9NJVNhcGWEq_10weavepy_vm9leaf_planNtB5_7Builder11store_local +_RINvMNtCs9NJVNhcGWEq_10weavepy_vm8gen_fastNtB5_11Interpreter15gen_fast_resumeKb0_EB5_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod8lru_type +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object20ByteArrayExportGuardEEB11_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17merge_exec_kwargs +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod11partial_new +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod13build_partial +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10b_callable +_RINvMs9_NtCs9NJVNhcGWEq_10weavepy_vm9leaf_planNtB8_11Interpreter11plan_getterKb0_EB8_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir13MathGuardMetaEEB1c_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertCs4bqUF11K40R_11weavepy_jit +_RINvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB3_3GenNtNtB5_3x643X64E4opndNvYBS_NtNtB5_3asm3Asm10cmp_imm_okEB5_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser3eat +_RINvXs7_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3setINtB6_7HashSetNtNtCs1C1lLj4PWSY_5alloc6string6StringINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCshfZExtisgX1_16weavepy_compiler6fxhash8FxHasherEEINtNtNtNtB1L_4iter6traits7collect12FromIteratorB14_E9from_iterINtNtNtB18_3vec9into_iter8IntoIterB14_EEB2x_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object21meta_hash_is_identity +_RINvMNtCs9NJVNhcGWEq_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtNtB1t_5slice4iter4IterNtNtB5_6object6ObjectEEEB5_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18core_subclass_iter +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17instance_gen_call +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16dict_merge_plain +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod5build +_RNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod8lru_type00B9_ +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB6_11Interpreter9seq_drain +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16str_isidentifier +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins12obj_containsINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvCslbMUDoFrEqM_14weavepy_parser21eval_backslash_at_eof +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtCshfZExtisgX1_16weavepy_compiler10CodeObjectE3newB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native16tuplegetter_init +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins20try_coerce_index_i64 +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier216probe_param_lane +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjNtNtCs4bqUF11K40R_11weavepy_jit7analyze7PairSrcINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE3getjEBT_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB2_15FunctionBuilder16import_signature +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4callB4_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsjIWZ3EBbJCG_15weavepy_codegen7codegen3SrcE8grow_oneBQ_ +_RNvCshfZExtisgX1_16weavepy_compiler14constant_slice +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12leaf_setattr +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcINtNtB6_4sync7GilCellNtNtB6_7dictmap6SetMapEE3newB6_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap6BucketE8push_mutBJ_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter25leaf_load_meta_class_attr +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter23type_dunder_transparent +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter30winner_aware_dynamic_type_call +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod15partial_new_forINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvMs1t_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyIterator9remaining +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB6_11Interpreter9seq_call1 +_RNvMs0_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB7_11Interpreter13pure_callback +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins24bytearray_receiver_guard +_RNvCs9NJVNhcGWEq_10weavepy_vm15source_code_get +_RNvNvCs9NJVNhcGWEq_10weavepy_vm32collect_compiler_syntax_warnings10visit_expr +_RNvCs9NJVNhcGWEq_10weavepy_vm15source_code_put +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs1C1lLj4PWSY_5alloc6string6StringmEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_mNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECshfZExtisgX1_16weavepy_compiler +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10b_callableINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBN_6object6ObjectEENtBL_11BorrowErrorE9is_ok_andNCNvMs7_BN_NtBN_11Interpreter17leaf_builtin_calls9_0EBN_ +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjTmmmEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE3getjECs4bqUF11K40R_11weavepy_jit +_RNvNtNtCs2GDADXmuQ1X_11weavepy_cli9text_trim3sys6traced +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder13call_indirect +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtBG_6string6StringNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEECsgCuzAuzbPOX_7weavepy +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types30install_mutable_container_init12dict_init_kw +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter23leaf_plain_class_dunder +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins6b_dictINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter17plain_class_value0B7_ +_RNvCs9NJVNhcGWEq_10weavepy_vm27type_attr_certainly_missing +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter22instance_native_dunder +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types10object_new +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types21overrides_dunder_init +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter15native_truth_ofs_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15unicodedata_mod7builtin +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_mod8register +_RNvYNCNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types22install_value_type_news0_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRSNtNtB8_6object6ObjectEE9call_onceB8_ +_RNvYNvNvMNtCs9NJVNhcGWEq_10weavepy_vm13builtin_typesNtB7_12BuiltinTypes5build9proxy_newINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB9_6object6ObjectEE4callB9_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter8chr_fast +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEE8push_mutB1l_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod14codeseq_to_vec +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod14codeseq_to_vec0B7_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod13quick_asserts0B7_ +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject19class_read_is_plain +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionTjyyTINtNtBZ_2rc4WeakIBV_NtNtBZ_6object8DictDataEEB2j_EEEEE4withNCNvMs7_BZ_NtBZ_11Interpreter17enum_value_members1_0uEBZ_ +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter17enum_value_member0B7_ +_RNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyFunction12name_objects +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15simple_delegate +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18core_iter_collapse +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit2ir6TBlockEEEB1y_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder8band_imm +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyAINtNtCs9NJVNhcGWEq_10weavepy_vm4sync4CelljEj3_EB1b_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftTjjENvYB1m_NtNtBa_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object16bytes_membership +_RNvCs9NJVNhcGWEq_10weavepy_vm14format_int_hex +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10str_result +_RNvNvCs9NJVNhcGWEq_10weavepy_vm16set_algebra_fast3len +_RNCNvMs1t_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB8_10PyIterator10next_values0_0Ba_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11delete_attr +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter27descriptor_protocol_changed +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20park_suspended_boxed +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11do_str_call +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14kw_lane_callee +_RNvNtNtCscdyiIoZL7b2_10num_bigint6bigint7convert20from_signed_bytes_le +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter22meta_store_transparent0B7_ +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB2_13MarshalWriter10into_bytes +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_mod8CodePlanEEB13_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockyE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod12compiler_tag0E0zE0E0B2o_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_mod8loads_kw +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader8fill_ref +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecRNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod12CompiledCodeE8grow_oneBT_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE14do_match_innerB9_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects9new_match +_RINvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types25make_exception_with_classReEB4_ +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects14compile_cachedINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod20simple_first_checked +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14numeric_dunders2_0B5_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionTmbEEE10initializeNCINvB1a_11get_or_initNCNvNtCs4bqUF11K40R_11weavepy_jit6engine19generic_share_limit0E0zE0E0B32_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser16parse_dict_value +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler15compile_subdict +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object14bytes_contains +_RNvCs9NJVNhcGWEq_10weavepy_vm9with_sign +_RNvYNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types30install_mutable_container_init12dict_init_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB2g_EEE4callB8_ +_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VeccE16extend_desugaredNtNtNtCsevLNFiNqfJP_4core3str4iter5CharsECs9NJVNhcGWEq_10weavepy_vm +_RNvCs9NJVNhcGWEq_10weavepy_vm14class_entry_of +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17native_store_fast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16mappingproxy_get +_RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefNtNtBN_9inst_dict11SplitValuesENtBL_11BorrowErrorE9is_ok_andNCNvBN_21default_lookup_missess0_0EBN_ +_RNvYNCNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types22install_value_type_new0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRSNtNtB8_6object6ObjectEE9call_onceB8_ +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtCs9NJVNhcGWEq_10weavepy_vm8FrameExcEE18get_or_insert_withNvYBI_NtNtB5_7default7Default7defaultEB1j_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter27specialized_unpack_sequence +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12class_layout +_RNvNtCs9NJVNhcGWEq_10weavepy_vm16weakref_registry16id_of_by_variant +_RNvNtCs9NJVNhcGWEq_10weavepy_vm17frozen_code_cache11result_path +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader10read_value +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader16read_value_inner +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs7UfkFU4le9s_8lock_api5mutex5MutexNtNtCs3pgaDf2SUin_11parking_lot9raw_mutex8RawMutexINtNtCs1C1lLj4PWSY_5alloc3vec3VecRNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod12CompiledCodeEEE10initializeNCINvB1a_11get_or_initNCNvB3I_8registry0E0zE0E0B3M_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12pattern_exec +_RNvCs9NJVNhcGWEq_10weavepy_vm11dunder_note +_RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefNtNtBN_6object8DictDataENtBL_11BorrowErrorE9is_ok_andNCNCNvMs7_BN_NtBN_11Interpreter17enum_value_members0_00EBN_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTjyyTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakINtNtB17_4sync7GilCellNtNtB17_6object8DictDataEEB12_EEEEB17_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockTxxEE10initializeNCINvB2_11get_or_initNCNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB1E_10PyFunction12name_objects0E0zEB1G_ +_RINvMs0_NtCs9NJVNhcGWEq_10weavepy_vm5errorNtB6_11PyException12from_builtinReEB8_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17type_setattr_pair +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects19compile_cached_fast +_RNvCs9NJVNhcGWEq_10weavepy_vm22instance_native_dunder +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionTjyyTINtNtB1a_2rc4WeakIB16_NtNtB1a_6object8DictDataEEB2u_EEEEEB1a_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler13closure_index +_RNvCshfZExtisgX1_16weavepy_compiler25expr_contains_typeparamfn +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBG_5types10PyInstanceEEBG_ +_RNvCs9NJVNhcGWEq_10weavepy_vm18split_format_field +_RNvCs9NJVNhcGWEq_10weavepy_vm15apply_alignment +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter24leaf_builtin_dunder_attr +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter25materialize_class_mapping +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableuE12get_index_ofNtNtB8_6object9LeafProbeEB8_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21type_dunder_unclaimed +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19dispatch_compare_op +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15common_constant +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14core_gen_yield +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11core_new_ex +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16core_new_mapping +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types10base_facts +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12core_reraise +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcINtNtCs1C1lLj4PWSY_5alloc3vec3VecIBA_INtNtB6_4sync7GilCellNtNtB6_6object6ObjectEEEE3newB6_ +_RNvCs9NJVNhcGWEq_10weavepy_vm15leaf_issubclass +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15compare_op_step +_RNvNtNtCscdyiIoZL7b2_10num_bigint7biguint7convert22from_bitwise_digits_le +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object26instance_has_custom_dunder +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter18dict_from_zip_pure4rest +_RNCNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB8_11Interpreter10zip2_pairs0B8_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins12b_int_compat +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19int_bit_length_leaf +_RNvNvMNtCs9NJVNhcGWEq_10weavepy_vm13builtin_typesNtB4_12BuiltinTypes5build9proxy_new +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader8note_ref +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_mod13MarshalReaderEBH_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs7UfkFU4le9s_8lock_api5mutex5MutexNtNtCs3pgaDf2SUin_11parking_lot9raw_mutex8RawMutexINtNtCs1C1lLj4PWSY_5alloc3vec3VecRNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod12CompiledCodeEEE10initializeNCINvB2_11get_or_initNCNvB2V_8registry0E0zEB2Z_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE8do_matchB9_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockTxxEE10initializeNCINvB1a_11get_or_initNCNvMs12_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB2s_10PyFunction12name_objects0E0zE0E0B2u_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectB2g_EEE10initializeNCINvB1a_11get_or_initNCNvB2k_14code_gen_namess_0E0zE0E0B2k_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11asyncio_mod16future_iter_send +_RNvCs9NJVNhcGWEq_10weavepy_vm15exception_value +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit2ir14MethodSiteMetaEEEB1y_ +_RNvXNtNtCscdyiIoZL7b2_10num_bigint7biguint8additionNtB4_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops5arith3AddRBN_E3add +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9method_kwNvB4_13str_format_kwEs_0B6_ +_RNvCs9NJVNhcGWEq_10weavepy_vm20format_via_spec_impl +_RNvCs9NJVNhcGWEq_10weavepy_vm20mangle_class_private +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18class_ns_store_key +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins17dict_setitem_leaf +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins8dict_getINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins6b_dict +_RNvYNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types20install_type_dunders12type_delattrINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14inline_deliver +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan6subscr +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins7set_popINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17seq_contains_rich +_RNvCs9NJVNhcGWEq_10weavepy_vm8eq_class +_RNvMNtCs9NJVNhcGWEq_10weavepy_vm8gen_fastNtB4_11Interpreter15gen_native_next +_RNvCs9NJVNhcGWEq_10weavepy_vm13payload_truth +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter22specialized_compare_op +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18mappingproxy_items +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter18dict_from_zip_pure +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter8ord_fast +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockjE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zECs9NJVNhcGWEq_10weavepy_vm +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB2_13MarshalWriter10write_body +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader4take +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod13register_code +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_12pattern_exec0E0B8_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectB1t_EEE10initializeNCINvB2_11get_or_initNCNvB1x_14code_gen_namess_0E0zEB1x_ +_RNCNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB9_11Interpreter17enum_value_members_00B9_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native17tuplegetter_index +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTyNtCs9NJVNhcGWEq_10weavepy_vm11NativeTruthEEBF_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir11GlobalGuardE8push_mutBJ_ +_RNCINvMNtCsevLNFiNqfJP_4core5sliceSNtNtCshfZExtisgX1_16weavepy_compiler4name4Name20sort_unstable_by_keyTjjNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvMsV_BB_NtBB_8Compiler6finish0E0BB_ +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types30install_mutable_container_init12self_payload +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter14leaf_type_name0B7_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16mappingproxy_getINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types20install_type_dunders12type_setattr +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16rich_compare_obj +_RNvCs9NJVNhcGWEq_10weavepy_vm19container_init_call +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtNtNtB6_6stdlib11sre_objects5StateE3newB6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11do_int_call +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib3sys15str_is_interned +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod13sre_cache_get +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects13pattern_match +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17enum_value_member +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter17enum_value_members0_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects14compile_cached +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15data_descr_kind +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13str_format_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1D_EEE4callB6_ +_RNvCs9NJVNhcGWEq_10weavepy_vm17scan_format_field +_RNvCs9NJVNhcGWEq_10weavepy_vm19render_format_field +_RNvCs9NJVNhcGWEq_10weavepy_vm19int_precision_apply +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject14verdict_record +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13class_ns_load +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins8dict_get +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11dict_lookup +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object15new_tuple_arrayKj2_EB9_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs9NJVNhcGWEq_10weavepy_vm10QuietEntryEBD_ +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object9from_char +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins17mappingproxy_args +_RNvMsu_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapNtB5_6SetMap3pop +_RNvCs9NJVNhcGWEq_10weavepy_vm21native_scalar_compare +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types26make_exception_with_object +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvMs7_BU_NtBU_11Interpreter17core_container_ops0_0EBU_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects7install +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20native_value_payload +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_mod8dumps_kw +_RNvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object13as_bytes_view +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader8read_int +_RNvXNtCsevLNFiNqfJP_4core3anyNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects5StateNtB2_3Any7type_idBx_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12pattern_code +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21binop_instance_dunder +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs9NJVNhcGWEq_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionxENCNvBW_13py_hash_values_0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze10stmt_start +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCslbMUDoFrEqM_14weavepy_parser3ast4ExprEE8push_mutB1l_ +mi_bitmap_chunkmap_try_clear.isra.0 +_RNvCs9NJVNhcGWEq_10weavepy_vm15str_format_auto +_RNvCs9NJVNhcGWEq_10weavepy_vm19split_name_trailers +_RNvXs1M_NtCs1C1lLj4PWSY_5alloc6stringxNtB6_12SpecToString14spec_to_string.1356 +_RNvCs9NJVNhcGWEq_10weavepy_vm16group_int_digits +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance11with_native +_RINvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace10with_statebNvMsg_B2_NtB2_7GcState18maybe_auto_collectEB4_ +_RINvCs9NJVNhcGWEq_10weavepy_vm9h_str_getKm3_EB2_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap5TableNtNtBG_6object6ObjectEEBG_ +_RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefNtNtBN_7dictmap6SetMapENtBL_11BorrowErrorE9is_ok_andNCNvNvBN_16set_algebra_fast5plains_0EBN_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm12type_surface11unwrap_shim0B5_ +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm12type_surface11unwrap_shim14check_receiver +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types20install_type_dunders12type_delattr +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20del_type_attr_direct +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE6filterNCNvMs7_BN_NtBN_11Interpreter17leaf_type_getattr0EBN_ +_RNvYNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types20install_type_dunders12type_setattrINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvCs9NJVNhcGWEq_10weavepy_vm25detect_yield_from_subiter +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types19native_seed_for_new +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15pull_for_unpack +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19generator_next_fast +_RNvMNtCs9NJVNhcGWEq_10weavepy_vm8gen_fastNtB4_11Interpreter20yield_from_iter_item +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins20function_get_builtin +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18mappingproxy_itemsINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_mod5build +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtB6_5drain5DrainB13_EE9from_iterB17_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6NativeEEE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0B2V_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtNtBG_6stdlib11sre_objects5StateEEBG_ +_RNvCs9NJVNhcGWEq_10weavepy_vm13bind_int_args +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockyE10initializeNCINvB2_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod12compiler_tag0E0zEB1A_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12make_pattern +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter26fire_caught_stop_iteration +_RNvXs0_NtNtCscdyiIoZL7b2_10num_bigint6bigint8additionNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops5arith3AddRBP_E3add.1468 +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE3getmEBT_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit7analyzeNtB2_9PathArena5names +_RINvNtCs9NJVNhcGWEq_10weavepy_vm5tier214walk_attr_pathNtNtCs1C1lLj4PWSY_5alloc6string6StringEB4_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecIBC_NtNtCs95FNv3kP1st_12regex_syntax3ast4SpanEEEB1g_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser17expect_dict_colon +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftNtNtCshfZExtisgX1_16weavepy_compiler4name4NameNCINvMB8_SB1m_20sort_unstable_by_keyTjjNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvMsV_B1q_NtB1q_8Compiler6finish0E0EB1q_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecThcEE8grow_oneCslbMUDoFrEqM_14weavepy_parser +_RNvCs9NJVNhcGWEq_10weavepy_vm14spec_parent_of +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VeccEINtB2_18SpecFromIterNestedcNtNtNtCsevLNFiNqfJP_4core3str4iter5CharsE9from_iterCs9NJVNhcGWEq_10weavepy_vm +_RINvXs_NvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_incNtB5_10ConvertVec6to_vecNtNtBa_5alloc6GlobalECs9NJVNhcGWEq_10weavepy_vm +_RINvXs5_NtCs1C1lLj4PWSY_5alloc6stringNtB6_6StringINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorcE9from_iterINtNtNtB8_3vec9into_iter8IntoItercEECs9NJVNhcGWEq_10weavepy_vm +_RINvCs9NJVNhcGWEq_10weavepy_vm15h_inst_dict_setKm7_EB2_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins21mappingproxy_delegate +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins7set_pop +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtBK_4sync7GilCellNtNtBK_6object6ObjectEEE8push_mutBK_ +_RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE5drainINtNtNtCsevLNFiNqfJP_4core3ops5range5RangejEEBJ_ +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB2_13MarshalWriter11write_value +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB5_13MarshalReader9read_byte +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8gen_fast14send_iter_step +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSTNtNtCs1C1lLj4PWSY_5alloc6string6StringNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEB1j_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object15leaf_tuple_item +_RNCNvCs9NJVNhcGWEq_10weavepy_vm19percent_format_withs6_0B3_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionTmbEEE10initializeNCINvB2_11get_or_initNCNvNtCs4bqUF11K40R_11weavepy_jit6engine19generic_share_limit0E0zEB2e_ +_RINvMNtCsevLNFiNqfJP_4core3stre12trim_matchesNCNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtBM_6Parser19parse_fstring_field0EBO_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser17fstring_parts_for +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser11parse_raise +_RNCNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s_0Bb_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7enabled0E0zE0E0B2m_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit5stats6decide +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit5stats6decide0E0zE0E0B2o_ +_RNvMNtCs4U5RMT44ivg_13weavepy_lexer7scannerNtB2_7Scanner25scan_fstring_field_extent +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir9ValueDataE8grow_oneBQ_ +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser28scrub_fstring_field_comments +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins27transform_decimal_and_space +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218probe_method_entry +_RNvMsr_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage9get_index +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze9lower_bin +_RNvNtCs4bqUF11K40R_11weavepy_jit6engine11loop_blocks +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s4_0B7_ +mi_malloc_aligned +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser17parse_import_from +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapymNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertCshfZExtisgX1_16weavepy_compiler +_RNCNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s2_0Bb_ +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser16remap_expr_spans +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser19parse_fstring_field +_RNvNtCshfZExtisgX1_16weavepy_compiler7ast_opt10str_points +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel1b +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16load_attr_public +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze22entry_unassigned_reads +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder8bxor_imm +_RINvNvNtCshfZExtisgX1_16weavepy_compiler6intern13constant_hash4hashNtNtNtCsgHYyB3hU8Ec_3std4hash6random13DefaultHasherEB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16parse_float_text +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs4bqUF11K40R_11weavepy_jit7analyze16MethodResolutionE7or_elseNCNvBK_13step_abstracts5_0EBM_ +_RNvMsz_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree3mapINtB5_8IntoIterNtNtNtCsbsLF5VKjj0H_14regex_automata4util10primitives7StateIDNtNtB7_7set_val9SetValZSTE10dying_nextB1d_ +_RNvXs8_NtNtNtCsevLNFiNqfJP_4core3fmt3num3impmNtB9_7Display3fmt +_RNvNtCs4U5RMT44ivg_13weavepy_lexer7scanner8tokenize +_RNvMNtCs4U5RMT44ivg_13weavepy_lexer7scannerNtB2_7Scanner19scan_fstring_extent +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel17json_make_scanner +_RNvMs3_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_4Slot11try_compile +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7enabled0E0zEB1y_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit5stats6decide0E0zEB1A_ +mi_theap_malloc_aligned +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser24parse_fstring_body_inner +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler19compile_import_from +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtNtNtB6_6stdlib10json_accel10ScannerCfgE3newB6_ +_RNvNtCshfZExtisgX1_16weavepy_compiler6intern9name_hash +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s2_0B7_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockjE10initializeNCINvB1a_11get_or_initNCNvNtCs4bqUF11K40R_11weavepy_jit6engine11call_weight0E0zE0E0B2m_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer5guard +_RNvMs2_NtCs4bqUF11K40R_11weavepy_jit6engineNtB5_9JitEngine7release +_RINvMsg_NtNtNtCsevLNFiNqfJP_4core4iter8adapters7flattenINtB6_13FlattenCompatINtNtB8_3map3MapINtNtNtBc_5slice4iter4IterNtNtCs4bqUF11K40R_11weavepy_jit2ir6TBlockENCNvMs2_NtB1W_6engineNtB2G_9JitEngine21compile_tfunc_methodssf_0EIB1t_NtB1U_5TStmtEE13iter_try_folduNCINvNvXsi_B6_IBS_ppENtNtNtBa_6traits8iterator8Iterator8try_fold7flattenB3B_uINtNtNtBc_3ops12control_flow11ControlFlowuENCINvNvB4v_3any5checkRB3G_NCB2A_sg_0E0E0B5p_EB1W_ +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir9StrMethodENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir11GlobalGuardENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockTINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs1C1lLj4PWSY_5alloc6string6StringEB1H_EE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13name_admitted0E0zE0E0B3G_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder7ireduce +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower4push +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std4sync6poison5mutex10MutexGuardINtNtB4_6option6OptionIB1x_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6EngineEEEEB21_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once9call_onceNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10background6submits_0E0B16_ +_RNvMs1_NtNtNtCsgHYyB3hU8Ec_3std4sync4mpmc4listINtB5_7ChannelTINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit4UnitEINtNtB12_4sync3ArcNtNtB1w_10background3JobEEE4readB1y_ +mi_collect +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5tier29ArtifactsEBF_ +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEE9drop_slowBX_ +_RINvMsV_CshfZExtisgX1_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_18compile_expr_inners3_0EB6_ +_RNvNtNtCscdyiIoZL7b2_10num_bigint7biguint14multiplication10scalar_mul +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20call_python_kw_names +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s1_0B7_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12core_call_kw +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter23core_specialize_call_kw +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier220attr_fingerprint_obj +_RNvMs_NtCs4bqUF11K40R_11weavepy_jit2irNtB4_9StrMethod9from_name +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter8min_fast +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir14CalleeSpanMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir13MathGuardMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCsbsLF5VKjj0H_14regex_automata3dfa5dense11MatchStatesINtNtCs1C1lLj4PWSY_5alloc3vec3VecmEEEBI_ +_RNvMs0_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB5_13GuardSnapshot3new +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9native_at +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11iter_layouts0_0B5_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline7enabled0E0zEB1A_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB1L_6string6StringEE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11op_disabled0E0zE0E0B3f_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower9slot_addr +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10store_fast +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline9call_argc +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower14check_released +_RINvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB5_15FuncInstBuilder4loadlECs9NJVNhcGWEq_10weavepy_vm +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB2_15FunctionBuilder5push1 +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockjE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10chunk_room0E0zE0E0B2m_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6verify0E0zEB1y_ +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm5tier212NativeCalleeEEE9drop_slowB1z_ +_RNSNvYNCINvNtNtCsgHYyB3hU8Ec_3std6thread9lifecycle15spawn_uncheckedNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10background6submits0_0uEs_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceuE9call_once6vtableB1b_ +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm7add_mem +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtNtCs4bqUF11K40R_11weavepy_jit6engine13CompiledFrameE9drop_slowCs9NJVNhcGWEq_10weavepy_vm +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser16parse_else_block +_RNvNtCshfZExtisgX1_16weavepy_compiler7ast_opt6int_of +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler23compile_slice_two_parts +_RNvXs8_NtNtCscdyiIoZL7b2_10num_bigint7biguint14multiplicationRNtB7_7BigUintNtNtNtCsevLNFiNqfJP_4core3ops5arith3Mul3mul +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze22resolve_dict_container +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB2_15FunctionBuilder7use_var +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer9emit_exit +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit5lower7LowererEBF_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier225scalar_field_update_shape +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB16_6object10PyFunctionEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapINtNtNtB2I_5slice4iter4IterTNtB1E_6ObjectIB12_NtCshfZExtisgX1_16weavepy_compiler10CodeObjectEEENCNvMs6_NtB16_5tier2NtB5g_8JitState12get_compileds5_0EE9from_iterB16_ +_RNvMsa_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_6Engine3new +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline4plan +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower20inline_settle_fields +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTmbNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5BlockEE8grow_oneCs9NJVNhcGWEq_10weavepy_vm +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11leave_block +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower9load_fast +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10local_addr +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10branch_out +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14InstMethodSiteEEEB1u_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockjE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10chunk_room0E0zEB1y_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10background7enabled0E0zEB1A_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E6targetB4_ +_RNvNtCshfZExtisgX1_16weavepy_compiler7ast_opt10eval_binop +_RNvNtCshfZExtisgX1_16weavepy_compiler7ast_opt8make_str +_RNvNtCs9NJVNhcGWEq_10weavepy_vm10specialize26kw_uncovered_have_defaults +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir4TypeE8grow_oneBQ_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer9emit_stmt +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueEE8grow_oneCs4bqUF11K40R_11weavepy_jit +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir14MethodSiteMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5tier213CompiledEntryEBF_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline10call_start +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline10callees_at +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower3sig +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower15after_helper_if +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower16load_method_site +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10copy_value +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower4goto +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower14fill_side_exit +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10MethodSiteEEEB1u_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6verify0E0zE0E0B2m_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10background6submit +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8generate +_RNvNtCs2GDADXmuQ1X_11weavepy_cli5alloc19collect_thread_heap +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectINtNtBY_2rc2RcNtCshfZExtisgX1_16weavepy_compiler10CodeObjectEEEE9drop_slowBY_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler14compile_delete +_RINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB6_11Interpreter18lean_bind_keywordsINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtNtB1h_5slice4iter4IterNtNtB6_6object6ObjectEB1W_EEB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215probe_dict_lane +_RINvNtCs9NJVNhcGWEq_10weavepy_vm10specialize21specialize_call_kw_byINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1c_5slice4iter4IterNtNtB4_6object6ObjectENCNvB2_32attempt_specialize_call_kw_namess_0EEB4_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs4bqUF11K40R_11weavepy_jit6engine10attr_bound0E0zEB1y_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTmmENtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BU_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBY_6fxhash8FxHasherEE0EBY_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer10emit_block +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen3ssaNtB2_3Ssa10read_entry +_RNCNvMs2_NtCs4bqUF11K40R_11weavepy_jit6engineNtB7_9JitEngine21compile_tfunc_methodssc_0B9_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier224scalar_field_update_plan +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockTINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs1C1lLj4PWSY_5alloc6string6StringEBU_EE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13name_admitted0E0zEB2R_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15worth_compilings6_0B5_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockjE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8chunk_ir0E0zEB1y_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBY_6string6StringEE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11op_disabled0E0zEB2q_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB2_15FunctionBuilder15switch_to_block +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline14method_call_pc +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8SideExitE8grow_oneBQ_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8AttrSiteEEEB1u_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtCshfZExtisgX1_16weavepy_compiler10CodeObjectEEEB1d_ +pthread_atfork +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm8br_table +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E8lea_intoB4_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14format_obj_str +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VeccEINtB2_18SpecFromIterNestedcNtNtNtCsevLNFiNqfJP_4core3str4iter5CharsE9from_iterCshfZExtisgX1_16weavepy_compiler +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter12min_max_fast +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockjE10initializeNCINvB2_11get_or_initNCNvNtCs4bqUF11K40R_11weavepy_jit6engine11call_weight0E0zEB1y_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueBQ_EE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BQ_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBU_6fxhash8FxHasherEE0EBU_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir12AttrSiteMetaEECs9NJVNhcGWEq_10weavepy_vm +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit4tags +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockjE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline9max_total0E0zE0E0B2o_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower6tag_at +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1d_6object9BuiltinFnEEEB1d_ +_RNvMs8_NtCsjIWZ3EBbJCG_15weavepy_codegen2irNtB5_13DataFlowGraph7results +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower8for_iter +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjuINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE12contains_keyjECs4bqUF11K40R_11weavepy_jit +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs4bqUF11K40R_11weavepy_jit6engine10attr_bound0E0zE0E0B2m_ +_RNvMs2_NtCs4bqUF11K40R_11weavepy_jit6engineNtB5_9JitEngine21compile_tfunc_methods +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapTmmENtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBV_6fxhash8FxHasherEE6insertBV_ +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir12IterLoopMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RNvNtCs4bqUF11K40R_11weavepy_jit6engine14is_scalar_leaf +_RNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB5_8JitState16native_table_for +_RINvNvNtCsgHYyB3hU8Ec_3std9panicking12catch_unwind7do_callINtNtNtCsevLNFiNqfJP_4core5panic11unwind_safe16AssertUnwindSafeNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7compile0EINtNtB11_6option6OptionTINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtB1Z_4UnitENtB1Z_5PartsEEEB21_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockjE10initializeNCINvB2_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline9max_total0E0zEB1A_ +_RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB12_6object10PyFunctionEbEENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB12_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower5flush +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower21plain_release_in_line +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10call_typed +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11materialize +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower15store_from_slot +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower9exit_with +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11load_global +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10DirectSiteEEEB1u_ +_RNvMs0_NtNtNtCsgHYyB3hU8Ec_3std4sync4mpmc5wakerNtB5_9SyncWaker6notify +_RINvNtNtCsgHYyB3hU8Ec_3std3sys9backtrace28___rust_begin_short_backtraceNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10background6submits0_0uEB1f_ +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtNtCs9NJVNhcGWEq_10weavepy_vm5tier29ArtifactsE9drop_slowBH_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit6engine13CompiledFrameECs9NJVNhcGWEq_10weavepy_vm +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser9parse_del +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler20unwind_for_loop_exit +_RNvMs5_NtNtNtCsgHYyB3hU8Ec_3std4sync6poison5mutexINtB5_5MutexINtNtCsevLNFiNqfJP_4core6option6OptionIBY_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6EngineEEE4lockB1H_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline7enabled0E0zE0E0B2o_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12block_starts +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11lower_range +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder8ushr_imm +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11lower_block +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower4exit +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7in_loop +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower6copy16 +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11load_method +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10store_last +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10top_to_mem +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9SuperSiteEEEB1u_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6define +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit5parts +_RNvMs3_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_4Slot12poll_pending +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtNtCs9NJVNhcGWEq_10weavepy_vm5tier213GuardSnapshotE9drop_slowBH_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser11parse_yield +_RNvNtCshfZExtisgX1_16weavepy_compiler7ast_opt15optimize_format +_RNvMNtCs1C1lLj4PWSY_5alloc5sliceSm6repeatCshfZExtisgX1_16weavepy_compiler +_RNvCs9NJVNhcGWEq_10weavepy_vm15slot_field_note +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer16writeback_locals +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB4_3X645widen +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir8FunctionECs4bqUF11K40R_11weavepy_jit +_RINvYINtNtNtCsevLNFiNqfJP_4core5slice4iter4IterNtNtCs4bqUF11K40R_11weavepy_jit2ir6TBlockENtNtNtNtBa_4iter6traits8iterator8Iterator8try_folduNCINvNvXs_NtNtB1v_8adapters9enumerateINtB2o_9EnumeratepEB1p_8try_fold9enumerateRBJ_uINtNtNtBa_3ops12control_flow11ControlFlowuENCINvNvB1p_3any5checkTjB3v_ENCNvMs2_NtBN_6engineNtB4R_9JitEngine21compile_tfunc_methodsse_0E0E0B3A_EBN_ +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir13CompSavedMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir12AttrSiteMetaENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir8OsrEntryENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB5_8JitState23method_native_table_for +_RNvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB5_3MapINtNtB7_6filter6FilterINtNtB7_9enumerate9EnumerateINtNtNtBb_5slice4iter4IterNtNtCshfZExtisgX1_16weavepy_compiler8bytecode11InstructionEENCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline4plan0ENCB3a_s_0ENtNtNtB9_6traits8iterator8Iterator4nextB3g_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1v_6object10PyFunctionEbjEEEB1v_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockjE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8chunk_ir0E0zE0E0B2m_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit20maybe_unbound_locals +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11instruction +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB2_15FunctionBuilder12create_block +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower15after_helper_to +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower9call_site +_RINvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB5_15FuncInstBuilder5storelECs9NJVNhcGWEq_10weavepy_vm +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8TypeSiteEEEB1u_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10background7enabled0E0zE0E0B2o_ +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10backgroundNtB4_7Pending4park +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5tier213GuardSnapshotEBF_ +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcINtNtB7_3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm5tier29MathGuardEE9drop_slowBX_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtCshfZExtisgX1_16weavepy_compiler12FinallyFrameE8push_mutBH_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCslbMUDoFrEqM_14weavepy_parser3ast8ExprKindEBF_ +_RNvNtCshfZExtisgX1_16weavepy_compiler8validate21check_annotation_expr +_RNvNvCshfZExtisgX1_16weavepy_compiler24class_nested_scope_reads11expr_nested +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser13expr_children +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler15emit_send_dance +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftTjjENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB1m_11sort_by_keyTINtNtBa_3cmp7ReversejEjENCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline4plans0_0E0EB2N_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12format_value +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser17skip_field_string +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler21emit_annotate_closure +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm8overflow +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser15parse_with_item +_RNvNvCshfZExtisgX1_16weavepy_compiler24class_nested_scope_reads12stmts_nested +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCslbMUDoFrEqM_14weavepy_parser3ast13ExceptHandlerE8grow_oneBQ_ +_RNvMs_NtCshfZExtisgX1_16weavepy_compiler8validateNtB4_9Validator16visit_annotation +_RNCNvNtCshfZExtisgX1_16weavepy_compiler8validate21check_annotation_exprs_0B5_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler25push_body_exc_entries_ids +_RNvXsa_NtNtCscdyiIoZL7b2_10num_bigint6bigint5powerNtB7_6BigIntINtNtCsiImLG5VQbrW_10num_traits3pow3PowyE3pow +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler13make_lazy_ctx +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler19except_unbind_stmts +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E4slotB4_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder8imul_imm +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15h_for_iter_rest +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler15emit_with_setup +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser10parse_with +_RNvCshfZExtisgX1_16weavepy_compiler28class_body_propagating_reads +_RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters6clonedINtB4_6ClonedINtNtB6_6filter6FilterINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterNtNtCs1C1lLj4PWSY_5alloc6string6StringENCNvCshfZExtisgX1_16weavepy_compiler28class_body_propagating_reads0EENtNtNtB8_6traits8iterator8Iterator4nextB2W_ +_RNvXsa_NtNtCscdyiIoZL7b2_10num_bigint7biguint14multiplicationNtB7_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops5arith9MulAssignRBX_E10mul_assign +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecRNtNtCslbMUDoFrEqM_14weavepy_parser3ast4ExprE8grow_oneBR_ +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtCshfZExtisgX1_16weavepy_compiler12LazyClassCtxE9drop_slowBF_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCslbMUDoFrEqM_14weavepy_parser3ast8WithItemEECshfZExtisgX1_16weavepy_compiler +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower7call_op +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower9write_tag +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10background3JobE9drop_slowBM_ +_RNvMs0_NtNtCsevLNFiNqfJP_4core3fmt3numo10__fmt_inner +_RNvMNtCs4U5RMT44ivg_13weavepy_lexer7scannerNtB2_7Scanner19note_invalid_escape +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCslbMUDoFrEqM_14weavepy_parser3ast8WithItemE8grow_oneBQ_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser9parse_try +_RNvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB5_3MapINtNtB7_6filter6FilterINtNtNtBb_5slice4iter4IterTmmmEENCNvMsV_CshfZExtisgX1_16weavepy_compilerNtB1W_8Compiler25push_body_exc_entries_ids0ENCB1Q_s_0ENtNtNtB9_6traits8iterator8Iterator4nextB1W_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler12compile_stmt +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCslbMUDoFrEqM_14weavepy_parser3ast4StmtEECshfZExtisgX1_16weavepy_compiler +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler19compile_await_dance +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s0_0B7_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder8overflow +_RNvCs9NJVNhcGWEq_10weavepy_vm10fixed_core +_RINvXsd_NtCs1C1lLj4PWSY_5alloc6stringNtB6_6StringINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect6ExtendcE6extendINtNtNtBS_7sources8repeat_n7RepeatNcEECs9NJVNhcGWEq_10weavepy_vm +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler12compile_with +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser16parse_async_stmt +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtCshfZExtisgX1_16weavepy_compiler18DeferredAnnotationE8grow_oneBO_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler18emit_setup_no_line +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler20compile_ex_call_args +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler14emit_pop_block +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower7operand +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4band +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13install_codes +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10h_for_iter +_RINvYINtNtNtCsevLNFiNqfJP_4core5slice4iter4IterNtNtCslbMUDoFrEqM_14weavepy_parser3ast4StmtENtNtNtNtBa_4iter6traits8iterator8Iterator8try_folduNCINvNvB1r_12try_for_each4callRBJ_INtNtBa_6result6ResultuNtCshfZExtisgX1_16weavepy_compiler12CompileErrorENCNvMsV_B3d_NtB3d_8Compiler12compile_with0E0B2O_EB3d_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler21push_body_exc_entries +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler23emit_with_except_finish +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler17emit_pop_block_at +_RNvMs5_NtCs4bqUF11K40R_11weavepy_jit7analyzeNtB5_2SE8is_plain +_RNvCsjIWZ3EBbJCG_15weavepy_codegen7install +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6NativeEEE10initializeNCINvB2_11get_or_initNCNvB26_7publish0E0zEB28_ +_RNCNvNvCshfZExtisgX1_16weavepy_compiler24class_level_reads_dunder6nested0B5_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCslbMUDoFrEqM_14weavepy_parser3ast8ConstantEBF_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCslbMUDoFrEqM_14weavepy_parser3ast13ComprehensionEBF_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCslbMUDoFrEqM_14weavepy_parser3ast4StmtEEB1c_ +_RNvMNtCshfZExtisgX1_16weavepy_compiler8validateNtB2_5Scope13directive_for +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler25emit_call_exit_with_nones +_RNvCshfZExtisgX1_16weavepy_compiler27collect_class_visible_reads +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time14time_monotonic +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215probe_list_lane +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E5spillB4_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7publish +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionNCINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB13_8OnceLockIBC_INtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6NativeEEE10initializeNCINvB12_11get_or_initNCNvB2z_7publish0E0zE0EEB2B_ +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser27import_as_target_diagnostic +_RNvMNtCslbMUDoFrEqM_14weavepy_parser6parserNtB2_6Parser16parse_assign_rhs +_RNvXs0_NtCshfZExtisgX1_16weavepy_compiler6fxhashINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set7HashSetNtNtCs1C1lLj4PWSY_5alloc6string6StringINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtB5_8FxHasherEENtB5_7NameSet8add_name +_RNvNtCshfZExtisgX1_16weavepy_compiler7ast_opt9int_const +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtCshfZExtisgX1_16weavepy_compiler18DeferredAnnotationE8push_mutBH_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler23annotation_child_prefix +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCslbMUDoFrEqM_14weavepy_parser3ast13ExceptHandlerECshfZExtisgX1_16weavepy_compiler +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter19leaf_load_attr_withs_0B7_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen7codegenINtB2_3GenNtNtB4_3x643X64E9clear_regB4_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6NativeEEE10initializeNCINvB1a_11get_or_initNCNvB2T_7publish0E0zE0E0B2V_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11global_miss +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower5build +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter8sum_fast +_RNvXs1_NtNtNtCsevLNFiNqfJP_4core4iter8adapters6filterINtB5_6FilterINtNtNtBb_5slice4iter4IterNtNtCs4bqUF11K40R_11weavepy_jit7analyze5ESlotENCNvB1u_10emit_instrs5_0ENtNtNtB9_6traits8iterator8Iterator5countB1w_ +_RNvXs1_NtNtNtCsevLNFiNqfJP_4core3ops8function5implsQNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtBW_8JitState12get_compileds0_0INtB7_5FnMutTRNtNtCs4bqUF11K40R_11weavepy_jit2ir11GlobalGuardEE8call_mutBY_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze14emit_attr_lane +_RNvMsp_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_11SlotStorage21values_for_layout_mut +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer15list_helper_sig +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit16never_ran_blocks0E0zE0E0B2m_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower6branch +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder14fcvt_from_sint +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_5types12InstancePlanE9drop_lastB7_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fcmp +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18core_fill_extended +_RNvMs1_NtCshfZExtisgX1_16weavepy_compiler8bytecodeNtB5_6OpCode4name +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10kernel_for +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze9cmp_check +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze16infer_store_attr +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit16never_ran_blocks0E0zEB1y_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8h_global +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8h_return +_RINvCs9NJVNhcGWEq_10weavepy_vm10h_list_setKm7_EB2_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit16never_ran_blocks +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower5truth +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer3pop +_RNCNvMNtCsjIWZ3EBbJCG_15weavepy_codegen3ssaNtB4_3Ssa10append_arg0B6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11h_site_call +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records14h_direct_enter +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11h_call_site +_RNCNvMs1_NtNtNtCsgHYyB3hU8Ec_3std4sync4mpmc4listINtB7_7ChannelTINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit4UnitEINtNtB14_4sync3ArcNtNtB1y_10background3JobEEE4recvs_0B1A_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7h_build +_RINvXs_NtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elembNtB5_12SpecFromElem9from_elemNtNtB9_5alloc6GlobalECs9NJVNhcGWEq_10weavepy_vm +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower14method_inlined +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB1a_6object6ObjectEEEB1a_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBW_6string6StringEEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0ECs4bqUF11K40R_11weavepy_jit +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjNtNtCs4bqUF11K40R_11weavepy_jit7analyze14CompHeaderPlanEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0EBV_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower15load_attr_plain +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4jump +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower12operand_site +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_5types10TypeObjectE9drop_lastB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5types12InstancePlanEBF_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower8truth_of +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4bqUF11K40R_11weavepy_jit2ir12AttrSiteMetaE8grow_oneBQ_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBI_16weakref_registry11WeakRefSlotEINtNtB4_6option6OptionNtNtBI_6object6ObjectEEEBI_ +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastNtNtB4_5types12InstancePlanEB4_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze26returns_none_syntactically +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3mov +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8h_method +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214probe_obj_live +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakINtNtBG_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBG_6object6ObjectEEEEBG_ +_RNvCs9NJVNhcGWEq_10weavepy_vm16method_site_leaf +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer9def_local +_RNvMNtNtNtCsgHYyB3hU8Ec_3std4sync4mpmc7contextNtB2_7Context3new +_RNvCs9NJVNhcGWEq_10weavepy_vm17tier2_takes_calls +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower7require +_RNvMse_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_8Registry6remove +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13leaf_builtins13jit_method_op +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10ref_or_own +_RNvCs9NJVNhcGWEq_10weavepy_vm11callee_warm +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0sa_0B7_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir12AttrSiteMetaE8push_mutBJ_ +_RNvMse_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_8Registry10forget_key +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline5admit +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline9inline_op +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCNvMNtBa_9lazy_lockINtB1a_8LazyLockNtNtCs9NJVNhcGWEq_10weavepy_vm16weakref_registry15WeakRefRegistryE5force0E0B1J_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_splitINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1y_EEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14split_keywords +_RNvMs4_NtCs4bqUF11K40R_11weavepy_jit7analyzeNtB5_9CtorState12stored_field +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower9load_attr +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower9container +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower5leave +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell4CellINtNtB1j_6option6OptionNtNtNtNtBe_4sync4mpmc7context7ContextEEuE16get_or_init_slowNvNvNvMB2b_B29_4with7CONTEXT27___rust_std_internal_init_fnECs9NJVNhcGWEq_10weavepy_vm +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10h_get_iter +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline16callee_never_ran +_RNvMs3_NtCs9NJVNhcGWEq_10weavepy_vm16weakref_registryNtB5_15WeakRefRegistry3new +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9method_kwNvB4_9str_splitEs_0B6_ +_RNvMs4_NtCs4bqUF11K40R_11weavepy_jit7analyzeNtB5_9CtorState10field_lane +_RNvMs0_NtNtNtCsgHYyB3hU8Ec_3std4sync4mpmc5wakerNtB5_9SyncWaker8register +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline15builtin_in_line +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder7bitcast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11h_countdown +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4fcmp +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4fjcc +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6h_call +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm14fcvt_from_sint +_RNvMsk_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_5Tally4edge +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE8snapshotB9_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier211guards_hold +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs4bqUF11K40R_11weavepy_jit7analyze16MethodResolutionE7or_elseNCNvBK_10emit_instrs4_0EBM_ +_RNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_7GcState12collect_impl +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace13traverse_implKb1_NtB4_5TallyEs2_0B6_ +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastNtNtB4_5types10TypeObjectEB4_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5types10TypeObjectEBF_ +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_Esu_0B8_ +_RNvXsB_NtNtCsevLNFiNqfJP_4core5slice3cmpmNtB5_13SliceContains14slice_contains +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer14pin_helper_sig +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer15quad_helper_sig +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins17str_replace_exact +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCsgHYyB3hU8Ec_3std4sync9once_lock8OnceLockINtNtB4_6option6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtB1N_12SliceStorageNtNtB1P_6object7DictKeyEEEEEB1P_ +_RNvMsf_NtCs9NJVNhcGWEq_10weavepy_vm4syncINtB5_7GilCellNtNtB7_6object10PyIteratorE10borrow_mutB7_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE7charsetB9_ +_RNCNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB7_7GcState18collect_generation0B9_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefNtNtBG_6object6ObjectEEBG_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace10root_debug0E0zEB1y_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16drain_gc_garbage +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockAbj80_E10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins17ascii_space_table0E0zE0E0B2r_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier217method_call_sites +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEEB1y_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218global_guards_hold +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20automatic_collection +_RNvMsl_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_6Finder13find_uncached +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace11stats_debug0E0zEB1y_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm16weakref_registry18sweep_dead_targets +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockAbj80_E10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins17ascii_space_table0E0zEB1D_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214entry_local_ok +_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBL_6object10PyFunctionEE14extend_trustedINtNtCsevLNFiNqfJP_4core6option8IntoIterBG_EEBL_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5trace21monitoring_union_mask0B5_ +_RNvMNtCs9NJVNhcGWEq_10weavepy_vm11weak_objectNtB2_10WeakObject12strong_count +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons24drain_pending_cext_drops +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace10root_debug0E0zE0E0B2m_ +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE5clearB7_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21core_local_attr_chain +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20specialized_for_iter +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215method_ret_infos_0B5_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower13method_kernel +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9method_kwNvB4_14str_replace_kwEs_0B6_ +_RNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_7GcState19sweep_deferred_from +_RNCNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB7_7GcState19sweep_deferred_from0B9_ +_RNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_7GcState18collect_generation +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace11stats_debug0E0zE0E0B2m_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins22sum_small_int_sequence +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter22instance_call_function +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17try_lean_for_iter +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance17laid_out_position +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215method_ret_info +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTmIBC_INtNtB4_6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEEEEB1E_ +_RINvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace13traverse_implKb1_NtB2_5TallyEB4_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace14intrusive_slot +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBI_16weakref_registry11WeakRefSlotENtNtBI_6object6ObjectEEBI_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215method_ret_infos9_0B5_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline16callee_never_rans0_0B7_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14str_replace_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1E_EEE4callB6_ +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellNtNtB1j_5trace15MonitoringToolsEuE16get_or_init_slowNvNvB1Y_16MONITORING_TOOLS27___rust_std_internal_init_fnEB1j_ +_RNvMse_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_8Registry5entry +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace13traverse_implKb0_DG_INtNtNtCsevLNFiNqfJP_4core3ops8function5FnMutTRL0_NtNtB6_6object6ObjectEEp6OutputuEL_Es5_0B6_ +_RNvMsi_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_5Graph9propagate +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace19clear_object_fields +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11do_sum_call +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE5countB9_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze14native_getitem +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7h_clone +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellNtNtB19_5trace15MonitoringToolsEEB19_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellNtNtBG_5trace15MonitoringToolsEEBG_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11direct_body +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB13_6object9BuiltinFnEIBC_NtB13_8LeafKindEbEEEB13_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit21run_switched_directly +_RNvCs9NJVNhcGWEq_10weavepy_vm17call_site_builtin +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3fop +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7h_store +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm7bitcast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_store_slow +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4bxor +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8h_copies +_RNvMs9_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_10DirectSite4fill +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit19run_pushed_directly +_RNvNtCsjIWZ3EBbJCG_15weavepy_codegen4fold4icmp +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13property_with +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s_0B7_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer22call_method_helper_sig +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTmNtNtCs1C1lLj4PWSY_5alloc6string6StringENtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_B1v_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0EB1z_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier28take_u32 +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5tier27CallCtxEBF_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainNtNtNtNtCsgHYyB3hU8Ec_3std4sync4mpmc5waker5EntryEECs9NJVNhcGWEq_10weavepy_vm +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline4PlanEBH_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter14lazy_pure_pair +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15core_seq_repeat +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter26kwonly_defaults_cover_slow +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18core_leaf_property +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter18try_inline_getitem0B7_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder7uextend +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze22resolve_list_container +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215attr_site_guard +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit19instance_class_read +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20kw_names_bind_cached +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types20install_type_dunders12type_doc_get +_RNvCs9NJVNhcGWEq_10weavepy_vm17iter_result_check +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBe_11collections4hash3map7HashMapPNtCshfZExtisgX1_16weavepy_compiler10CodeObjectTINtNtB1j_6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEbINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakB2w_EEINtNtB1j_4hash18BuildHasherDefaultNtNtB4u_5tier218CodeIdentityHasherEEEuE16get_or_init_slowNvNvB5I_14RET_LANE_CACHE27___rust_std_internal_init_fnEB4u_ +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm9leaf_planNtB8_11Interpreter12leaf_run_retKb0_Kb1_KB1f_EB8_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215attr_site_guard0B5_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer14emit_int_arith +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier27put_u64 +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_attr_local +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline4PlanE8grow_oneBS_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17lean_call_kw_fill +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9inst_dict16note_materialize0E0zE0E0B2m_ +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot10set_getter +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter24call_object_with_globals +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze15analyze_for_rets0_0B5_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort25insertion_sort_shift_leftNtNtCs4bqUF11K40R_11weavepy_jit2ir8OsrEntryNCINvMB8_SB1m_20sort_unstable_by_keymNCNvNtB1q_7analyze12analyze_oncesa_0E0EB1q_ +_RINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB6_11Interpreter9leaf_evalKb0_Kb1_EB6_ +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s3_0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier28take_u64 +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier27put_u32 +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtCshfZExtisgX1_16weavepy_compiler10CodeObjectEE8grow_oneBR_ +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower13inline_return +_RNvMNtCs4bqUF11K40R_11weavepy_jit7analyzeNtB2_9PathArena3seg +_RNvMsh_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtB5_8InstDict11materialize +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16property_payload +_RINvNtCs4bqUF11K40R_11weavepy_jit7analyze15exclude_span_pcNtNtB4_2ir14MethodSpanMetaEB4_ +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze15analyze_for_rets5_0B5_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTPNtCshfZExtisgX1_16weavepy_compiler10CodeObjectTINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEbINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakBR_EEEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_B1B_INtNtB1H_4hash18BuildHasherDefaultNtNtB34_5tier218CodeIdentityHasherEE0EB34_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze12infer_append +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit3runKb1_EB6_ +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtCs9NJVNhcGWEq_10weavepy_vm5tier27JitBufsEuE16get_or_init_slowNvNvB1R_8JIT_BUFS27___rust_std_internal_init_fnEB1T_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit18site_property_leaf +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_site_kernel +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower15inline_callable +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19kw_names_bind_check +_RINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB6_11Interpreter20kw_names_fill_localsNtNtB6_11frame_slots10FrameStackEB6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17core_call_forward +_RINvMNtCs9NJVNhcGWEq_10weavepy_vm8lazy_arcINtB3_7LazyArcINtNtB5_4sync7GilCellNtNtB5_6object8DictDataEE10initializeNCNvMsh_NtB5_9inst_dictNtB1W_8InstDict11materializes_0EB5_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object14int_like_value +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18deopt_call_generic +_RNvCsdtSMxSA38aw_7___rustc12___rust_alloc +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer13emit_attr_get +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15attr_local_slow +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9attr_miss +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline11InlineFrameE8grow_oneBS_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs4bqUF11K40R_11weavepy_jit7analyze2SEEINtB4_18SpecFromIterNestedB13_INtNtB6_5drain5DrainB13_EE9from_iterB17_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9inst_dict16note_materialize0E0zEB1y_ +_RNvMsb_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtB5_11SplitValues4take +_RNvCs9NJVNhcGWEq_10weavepy_vm14repeat_objects +_RINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB6_11Interpreter14core_fast_leafNCNvB2_19core_leaf_call_lane0EB6_ +_RINvNtCs4bqUF11K40R_11weavepy_jit7analyze15exclude_span_pcNtNtB4_2ir14CalleeSpanMetaEB4_ +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtCs9NJVNhcGWEq_10weavepy_vm5tier27JitBufsEEB1J_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13inline_finish +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14class_poly_hit +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB2_8FnLayout2of +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower11inline_body +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11method_call +_RNvYNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types22install_object_dunders19object_subclasshookINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins15property_setterINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter11cursor_pair +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter14lazy_pure_next +_RNvMNtCshfZExtisgX1_16weavepy_compiler4nameNtB2_4Name9to_string +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215callee_ret_lane +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCINvMs7_B28_NtB28_11Interpreter9leaf_evalKb0_Kb1_E0E0zEB28_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace11track_built +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit18inst_builtin_bound +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11h_container +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtNtNtBa_11collections4hash3map7HashMapPNtCshfZExtisgX1_16weavepy_compiler10CodeObjectTINtNtB19_6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEbINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakB2m_EEINtNtB19_4hash18BuildHasherDefaultNtNtB4k_5tier218CodeIdentityHasherEEEEB4k_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower8float_op +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14site_leaf_fits +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6NativeEBF_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower6binary +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower14float_operands +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit4left +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs6Aq91OXocfR_4libc4unix6pollfdE8grow_oneCs9NJVNhcGWEq_10weavepy_vm +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native9SlotNamesE10initializeNCINvB1a_11get_or_initNCNvB1I_5names0E0zE0E0B1M_ +_RNvXs8_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_10DirectSiteNtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4drop +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native9SlotNamesE10initializeNCINvB2_11get_or_initNCNvBV_5names0E0zEBZ_ +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionjE7inspectNCINvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11direct_callKb1_E0EBZ_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtBG_5boxed3BoxNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline10InlineSiteEEEB1w_ +_RNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10LayoutMemo4note +_RNvCs9NJVNhcGWEq_10weavepy_vm19builtin_method_site +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower12binary_plain +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6CachesEBF_ +_RNvNtCsjIWZ3EBbJCG_15weavepy_codegen4fold3alu +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11h_site_leaf +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20instance_call_native +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215method_ret_infos5_0B5_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215method_ret_infos2_0B5_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBX_6string6StringEB1p_EmEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_mNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs9NJVNhcGWEq_10weavepy_vm +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs9NJVNhcGWEq_10weavepy_vm5tier211MethodEntryE8grow_oneBQ_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214enter_compiled +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower16compare_fallback +_RNvMs1t_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyIterator10pure_ready +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter9src_ready +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm6object21dict_key_is_reentrantINtNtNtCsevLNFiNqfJP_4core3ops8function5FnMutTRNtB4_6ObjectEE8call_mutB6_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterINtNtB4_6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEEB1P_ +_RNvMNtCskibSv91bgl1_9hashbrown11rustc_entryINtNtB4_3map7HashMapmINtNtCs1C1lLj4PWSY_5alloc3vec3VecjEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE11rustc_entryCs4bqUF11K40R_11weavepy_jit +_RNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm9leaf_planNtB5_7Pending7release +_RNvCs9NJVNhcGWEq_10weavepy_vm16class_entry_fill +_RINvYINtNtNtCsevLNFiNqfJP_4core5slice4iter4IterNtNtCshfZExtisgX1_16weavepy_compiler8bytecode11InstructionENtNtNtNtBa_4iter6traits8iterator8Iterator8try_folduNCINvNvXs_NtNtB1M_8adapters9enumerateINtB2F_9EnumeratepEB1G_8try_fold9enumerateRBJ_uINtNtNtBa_3ops12control_flow11ControlFlowuENCINvNtB2H_6filter15filter_try_foldTjB3M_EuB3R_NCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212loop_headers0NCINvNtB2H_10filter_map19filter_map_try_foldB57_juB3R_NCB5l_s_0NCINvNtB2H_3map12map_try_foldjmuB3R_NCB5l_s0_0NCINvNvB1G_3all5checkmNCNvMs6_B5n_NtB5n_8JitState12get_compileds6_0E0E0E0E0E0B3R_EB5p_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer23emit_method_helper_call +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell4CellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm5tier23PinEEEB2e_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object11str_char_at +_RNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod8lru_type0s_0B9_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod15native_new_pure +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14lazy_iter_step +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB6_11Interpreter12seq_pull_all +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtB15_7dictmap4KeysNCNvMs7_B15_NtB15_11Interpreter14leaf_type_calls_0EE9from_iterB15_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object18native_scalar_repr +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB14_6string6StringENtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeIBC_TB1w_mEEbEEEB1X_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier216inline_fields_of +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier216arm_method_guard +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier211split_index +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer15inline_body_for +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14field_hit_slow +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11flush_local +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockANtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrj4_E10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib13functools_mod8lru_keys0E0zE0E0B1L_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real14proxy_referent +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14lazy_iter_next +_RNvMs1_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEE6resizeB1l_ +_RNvMs19_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB6_5EntrymINtNtCs1C1lLj4PWSY_5alloc3vec3VecjEE10or_defaultCs4bqUF11K40R_11weavepy_jit +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215method_ret_infos0_0B5_ +_RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB1M_6string6StringEB2e_EECs9NJVNhcGWEq_10weavepy_vm +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier220decompose_live_loops +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod8category +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter27try_inline_call_ex_keywords +_RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtNtBc_5slice4iter4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEBR_ENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvNvB24_3all5checkTRB1h_B38_ENCNvMs1v_B1j_B1h_8eq_value0E0INtNtNtBc_3ops12control_flow11ControlFlowuEEB1l_ +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance9dict_cell +_RNCNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB8_11Interpreter12seq_pull_all0B8_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer12emit_int_cmp +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze15analyze_for_ret0B5_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm5tier28SiteArgsEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2q_5slice4iter4IterTmIBU_INtNtB2q_6option6OptionNtNtB17_6object6ObjectEEEENCNvB15_18probe_method_entrys_0EE9from_iterB17_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5tier211MethodEntryEBF_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer20emit_push_global_obj +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215attr_chain_step +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12quiet_unwind +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace10is_tracked +_RNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_7GcState14is_tracked_obj +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod10native_new +_RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBJ_5types10TypeObjectEE15append_elementsBJ_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier216note_native_exit0B5_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14inst_dict_read +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod10count_core +_RNvMs0_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB7_11Interpreter14lazy_core_next +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE6searchB9_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215method_ret_infos3_0B5_ +_RNvMs1_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit2ir14MethodSiteMetaEE6resizeB1l_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter22leaf_pure_builtin_kind +_RNvNtCsjIWZ3EBbJCG_15weavepy_codegen4fold7is_bool +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower7compare +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockANtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrj4_E10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib13functools_mod8lru_keys0E0zEBY_ +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter16module_shadowings0_0B7_ +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB6_11Interpreter15seq_step_source +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze15analyze_for_rets8_0B5_ +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneB1s_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer15method_leaf_for +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15attr_miss_quicks0_0B5_ +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower12release_slot +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod10with_class +_RINvMsu_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapNtB6_6SetMap15insert_probe_ifNtNtB8_6object9LeafProbeNCNvMs7_B8_NtB8_11Interpreter17core_container_ops5_0NCB1z_s6_0EB8_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter8max_fast +_RNvMs1t_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyIterator9pure_peek +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter21core_local_attr_chains2_0B7_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215callee_ret_infos0_0B5_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215callee_ret_infos1_0B5_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_pop_checked +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13leaf_builtins7fast_kw +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10h_pop_slow +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower6int_op +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15raised_in_place +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11subscr_call +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower8ref_call +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10subscr_ref +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15class_poly_note +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10MethodSiteEBF_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer15emit_build_list +__divti3 +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native14deque_pure_new +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17leaf_instance_len +_RNvNtNtCs4d4ibTJ6dSQ_17compiler_builtins3int19specialized_div_rem12u128_div_rem +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14leaf_next_step +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer17emit_dyn_attr_get +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer14stage_elements +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter22core_leaf_next_resolve +_RINvMsp_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB6_11SlotStorage17from_layout_arrayKj4_EB8_ +_RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipINtNtNtBc_5slice4iter4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyEINtNtNtBc_5array4iter8IntoIterReKj4_EENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvNvB2D_3all5checkTRB1h_B2v_ENCNvNtNtB1l_6stdlib18collections_native14deque_pure_new0E0INtNtNtBc_3ops12control_flow11ControlFlowuEEB1l_ +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm6fsetcc +_RINvMsV_CshfZExtisgX1_16weavepy_compilerNtB6_8Compiler18with_attr_locationNCNvB2_18compile_stmt_inners_0EB6_ +_RNCNvMsV_CshfZExtisgX1_16weavepy_compilerNtB7_8Compiler18compile_stmt_inners_0B7_ +_RNvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB5_3MapNtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap4IterNCNvMs7_B10_NtB10_11Interpreter16core_new_mapping0ENtNtNtB9_6traits8iterator8Iterator9size_hintB10_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter28break_implicit_context_cycle +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native8tg_index +_RNvMso_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_10PyProperty3doc +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTyINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakNtNtB1t_16weakref_registry11WeakRefSlotEEEE14reserve_rehashNCINvNtB8_3map11make_hasheryBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtB1t_8fasthash14ObjectIdHasherEE0EB1t_ +_RNvMsV_CshfZExtisgX1_16weavepy_compilerNtB5_8Compiler15emit_super_attr +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real16wrapper_referent +_RNvCs9NJVNhcGWEq_10weavepy_vm17slot_member_unset +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types22install_object_dunders14object_setattr +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects14match_position +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer11emit_dyn_op +mi_arena_page_at_slice +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance12exc_tail_get +_RNvMs1t_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_10PyIterator9pure_skip +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12warnings_mod15default_filters +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real19find_cached_wrapper +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtB1J_12SliceStorageNtNtB1L_6object7DictKeyEEE10initializeNCINvB1a_11get_or_initNCNvNtB1L_16weakref_registry21fixed_wrapper_storage0E0zE0E0B1L_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter12machine_step +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_upperINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13str_translates0_0B5_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort12sort4_stableNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB19_NtNtBa_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215probe_cell_lane +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13dict_fromkeysINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11marshal_modNtB2_13MarshalWriter9write_int +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEEEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0EB1u_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjNtNtCs4bqUF11K40R_11weavepy_jit7analyze7PairSrcINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertBS_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_truth_local +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE6filterNCNvMs7_BM_NtBM_11Interpreter13cached_imports0_0EBM_ +_RNvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters3mapINtB5_3MapNtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap4IterNCNvMs7_B10_NtB10_11Interpreter16core_new_mapping0ENtNtNtB9_6traits8iterator8Iterator4nextB10_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectBG_EE8push_mutBK_ +_RNvYNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12warnings_mod5builds_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRSNtNtBa_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1R_EEE9call_onceBa_ +_RNvXs0_NtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB7_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB5_10SpecExtendBU_INtNtB7_9into_iter8IntoIterBU_EE11spec_extendBY_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict11od_pure_new +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict14is_odict_class +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14core_push_init +_RNvYNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types22install_object_dunders14object_setattrINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvCs9NJVNhcGWEq_10weavepy_vm19percent_format_with +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects10with_matchINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_14match_position0E0B8_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable9quicksort9quicksortjNvYjNtNtBa_3cmp10PartialOrd2ltECs4bqUF11K40R_11weavepy_jit +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtNtCs4bqUF11K40R_11weavepy_jit2ir9StrMethodE8grow_oneBQ_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215probe_py_callee +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17shared_cell_index +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyANtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyj5_EB19_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm5error11PyExceptionEEB1e_ +_RNvMs2_Cs9NJVNhcGWEq_10weavepy_vmNtB5_5Frame7exc_mut +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter15do_min_max_calls4_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native15tuplegetter_get +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real5b_dynNCNvB2_26make_ref_object_with_classs0_0EB6_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtBW_12SliceStorageNtNtBY_6object7DictKeyEEE10initializeNCINvB2_11get_or_initNCNvNtBY_16weakref_registry21fixed_wrapper_storage0E0zEBY_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19dispatch_inplace_op +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter9repr_fast +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort31small_sort_general_with_scratchNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1s_NtNtBa_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real26make_ref_object_with_classs0_0B7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtCs9NJVNhcGWEq_10weavepy_vm4sync6RefMutNtNtBH_6object8DictDataEBC_EEBH_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13dict_fromkeys +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4ishl +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCshfZExtisgX1_16weavepy_compiler8bytecode11InstructionENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218short_scalar_ranges1_0EB2C_ +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance12exc_tail_set +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10string_mod7builtin +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12warnings_mod5build +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12warnings_mod15default_filters0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_upper +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13str_translate +_RNvNtCs9NJVNhcGWEq_10weavepy_vm3gil15maybe_yield_gil +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6result6ResultINtNtCs9NJVNhcGWEq_10weavepy_vm4sync6RefMutINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB12_6object6ObjectEENtB10_14BorrowMutErrorEEB12_ +_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable7ipnsortjNvYjNtNtB8_3cmp10PartialOrd2ltECs4bqUF11K40R_11weavepy_jit +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit7analyze10CarveStateEBF_ +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object16tuple_from_exactINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1j_5slice4iter4IterBG_ENvB9_9clone_hotEEB9_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15do_min_max_call +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageANtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyj5_uE16get_or_init_slowNvNvNtB1j_16weakref_registry12WRAPPER_KEYS27___rust_std_internal_init_fnEB1j_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11do_len_call +_RNvNtNtNtCsevLNFiNqfJP_4core7unicode12unicode_data1n11lookup_slow +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrE10initializeNCINvB2_11get_or_initNCNvNtNtBX_6stdlib17collections_odict10order_name0E0zEBX_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict8order_of +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict10exact_keys +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze15analyze_for_rets1_0B5_ +_RINvMNtCs9NJVNhcGWEq_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterNtNtB5_11frame_slots10StackDrainEB5_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmTmINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertB1r_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer16split_field_addr +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8run_body +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19coerce_index_object +_RNvMNtCs9NJVNhcGWEq_10weavepy_vm8gen_fastNtB4_11Interpreter14gen_fast_drain +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedNtNtB15_7dictmap6ValuesEE9from_iterB15_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12warnings_mod10builtin_kw +_RNvMs3_NtCs9NJVNhcGWEq_10weavepy_vm16weakref_registryNtB5_15WeakRefRegistry14collect_strong +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter19itertools_pure_next +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrE10initializeNCINvB1a_11get_or_initNCNvNtNtB1K_6stdlib17collections_odict10order_name0E0zE0E0B1K_ +_RINvMNtCs9NJVNhcGWEq_10weavepy_vm13tuple_storageNtB3_12TupleStorage15from_exact_iterINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainNtNtB5_6object6ObjectEEB5_ +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s9_0B7_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE9req_holdsB9_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE21alternative_can_startB9_ +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs4bqUF11K40R_11weavepy_jit7analyze2SEENtNtNtNtBb_4iter6traits8iterator8Iterator3allNvMs5_BS_BQ_8is_plainEBU_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze13kw_call_names +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit2ir5TFuncECs9NJVNhcGWEq_10weavepy_vm +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer14emit_const_pin +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer13emit_attr_set +_RINvYINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterjENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator8try_folduNCINvNvBX_3any5checkRjNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12plan_rewrites0_0E0INtNtNtB15_3ops12control_flow11ControlFlowuEEB2u_ +_RNvMs6_NtCs1C1lLj4PWSY_5alloc2rcINtB5_2RcNtNtCs9NJVNhcGWEq_10weavepy_vm5tier211DirectEntryE9drop_slowBH_ +mi_arena_try_claim_abandoned +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower12field_guards +_RINvMNtCs9NJVNhcGWEq_10weavepy_vm13tuple_storageNtB3_12TupleStorage10from_arrayKj2_EB5_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real14module_getattr +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real26make_ref_object_with_class +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_coreKb0_Esb_0B8_ +_RNvMNtNtCsevLNFiNqfJP_4core4char7methodsc15is_alphanumeric +_RNvNtNtNtCsevLNFiNqfJP_4core7unicode12unicode_data10alphabetic11lookup_slow +_RNvNtCs9NJVNhcGWEq_10weavepy_vm16weakref_registry13wrapper_value +_RNvMs0_NtCs9NJVNhcGWEq_10weavepy_vm16weakref_registryNtB5_11WeakRefSlot7upgrade +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real13ref_type_call +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17rich_compare_rest +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter10cmp_method +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict15od_setitem_leaf +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjNtNtCs4bqUF11K40R_11weavepy_jit7analyze14CompHeaderPlanINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE12contains_keyjEBT_ +_RINvMs1_NtCs9NJVNhcGWEq_10weavepy_vm11frame_slotsNtB6_10FrameStack8with_vecuNCINvB2_6extendINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtB8_6object6ObjectEE0EB8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10string_mod5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real16supports_weakref +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13str_translateINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNCNvCs9NJVNhcGWEq_10weavepy_vm17slot_member_class0B3_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict10peek_order +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB2m_3rev3RevINtNtNtB2q_5slice4iter4IterNtNtB17_7analyze2SEEENCNvB3P_13step_abstracts6_0EE9from_iterB17_ +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0sb_0B7_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer10emit_truth +mi_bitmap_try_find_and_claim +_RINvCs9NJVNhcGWEq_10weavepy_vm9push_growNtNtB2_6object6ObjectEB2_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit19call_activation_out +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_subscr_ref +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15class_poly_notes_0B5_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower18dict_index_in_line +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline4PlanEEB1e_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower9build_map +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11method_slow +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14leaf_site_call +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14h_local_method +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit17fill_method_cache +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7recordsNtB5_9DirectRec9take_slot +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower9call_with +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native12deque_append +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBK_6object9BuiltinFnEE8push_mutBK_ +_RNvMs9_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_10DirectSite7promote +_RNvMs9_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_10DirectSite9fill_leaf +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real16new_rlock_object +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real13lock_instance +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins7b_bytesINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins15byte_item_value +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins29bytes_from_iterable_reentrant +_RNvCs9NJVNhcGWEq_10weavepy_vm12bytes_repeat +_RNvCs9NJVNhcGWEq_10weavepy_vm15dict_may_shadow +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB6_5TableNtNtB8_6object6ObjectE8get_fullNtBU_13LeafNameProbeEB8_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins21bytes_from_source_obj +_RNvYNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real10rlock_type00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRINtNtBc_2rc2RcNtNtBc_5types10TypeObjectERSNtNtBc_6object6ObjectEE9call_onceBc_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins15bytes_construct +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB1a_11get_or_initNCINvMs8_B2T_NtB2V_11Interpreter12leaf_run_retKb0_KB50_KB50_E0E0zE0E0B2V_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4math5build +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native5build0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects14pattern_search +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer13emit_call_dyn +_RNvXNtCsevLNFiNqfJP_4core3anyNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native5StateNtB2_3Any7type_idBx_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtB1J_12SliceStorageNtNtB1L_6object7DictKeyEEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib11thread_real11lock_layout0E0zE0E0B1L_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native7install +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtBW_12SliceStorageNtNtBY_6object7DictKeyEEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib11thread_real11lock_layout0E0zEBY_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10b_bytes_kw +_RNvMsi_Cs9NJVNhcGWEq_10weavepy_vmNtB5_8SumState6finish +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10os_process19register_at_fork_kw +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4math7builtin +_RNvCs9NJVNhcGWEq_10weavepy_vm20checked_repeat_count +_RNvMsN_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_8DictData16build_key_filter +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins20sum_numeric_sequence +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19sum_exact_int_range +_RNvMsi_Cs9NJVNhcGWEq_10weavepy_vmNtB5_8SumState7entered +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder8f64const +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot17note_builtin_type +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm4fimm +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower11inline_call +__udivti3 +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3div +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native9deque_len +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7imp_mod13imp_is_frozen +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod9pure_pool +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19property_dunder_getINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterNtNtCslbMUDoFrEqM_14weavepy_parser3ast8ConstantENvYNtCshfZExtisgX1_16weavepy_compiler8ConstantINtNtB1f_7convert4FromB2l_E4fromEB3a_EB3c_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod13identity_item +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecINtNtCsevLNFiNqfJP_4core6option6OptionTNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyNtB1G_6ObjectEEEINtB2_18SpecFromIterNestedB11_INtNtNtNtB16_4iter8adapters3map3MapNtNtB1I_7dictmap8IntoIterNcNtB11_4Some0EE9from_iterB1I_ +_RNCNvNvNtCs9NJVNhcGWEq_10weavepy_vm12type_surface21install_value_richcmp15richcmp_builtin0B7_ +_RNvXNtCsevLNFiNqfJP_4core3anyNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict9ViewTypesNtB2_3Any7type_idBx_ +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastNtNtB4_6object6ObjectEB4_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict9view_iter +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict10order_iter +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter4steps0_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects11group_index +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE20insert_unique_hashedB7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects11pattern_sub +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer12emit_pin_len +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit4h_is +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefIBC_NtNtB1z_6object6ObjectEEEEEB1z_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtBH_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBH_6object6ObjectEEEINtNtB4_6option6OptionINtNtB1D_5boxed3BoxB25_EEEEBH_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7imp_mod7builtin +_RNvXso_NtCs9NJVNhcGWEq_10weavepy_vm12shared_valueINtB5_7ThinArcINtB5_12SliceStoragehEEINtNtCsevLNFiNqfJP_4core7convert4FromRShE4fromB7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7imp_mod22imp_extension_suffixes +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10dict_clear +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod9pure_poolINtNtNtCsevLNFiNqfJP_4core3ops8function5FnMutTRNtNtB8_6object6ObjectEE8call_mutB8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod12product_core +_RNvNtCshfZExtisgX1_16weavepy_compiler7ast_opt5py_eq +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod12lru_make_key +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real13ref_type_hash +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod20scalar_lru_operation +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod20native_lru_tuple_key +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter17core_partial_calls0_0B7_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21deep_order_collection +_RNvMs1v_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6Object3cmp +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecTNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyNtB14_6ObjectEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapNtNtB16_7dictmap4IterNCNvNtB16_8builtins17namespace_replaces3_0EE9from_iterB16_ +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtNtB6_6object10PyFunctionE3newB6_ +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject9best_base +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11iter_dunder +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object6ObjectE9drop_lastB7_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17leaf_getattr_hook +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter37prune_globals_missing_hooks_sometimes +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects10with_matchINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_11match_group0E0B8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects10group_text +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objectsNtB4_4Sink9push_span +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objectsNtB4_4Sink8push_obj +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objectsNtB2_7Subject5group +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0sc_0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier221probe_stack_iter_lane +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer20emit_call_str_method +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower11list_append +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10str_lstrip +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter12fresh_result +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB12_6object10PyFunctionEEEB12_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14reentrant_call +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib3sys21sys_getrecursionlimit +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod18lru_flush_deferred +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18function_descr_getINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod19with_partial_fieldsINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB8_6object6ObjectENCINvB4_17with_partial_callB1R_NCNvMs7_B8_NtB8_11Interpreter17core_partial_calls_0E0E0B8_ +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm12type_surface21install_value_richcmp7fam_int +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter29register_globals_missing_hook +_RINvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTjINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBM_5types10PyInstanceEEE6retainNCNvMs7_BM_NtBM_11Interpreter27prune_globals_missing_hooks0EBM_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19mappingproxy_valuesINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects11match_group +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_stripINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects13pattern_split +_RNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects13pattern_split00B9_ +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze15analyze_for_rets2_0B5_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze14escape_verdict +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze15str_accumulator +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower8identity +_RNvCs9NJVNhcGWEq_10weavepy_vm11short_loops +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7ast_mod5build +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16set_from_vm_iter +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10dict_clearINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13classdict_get +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable9quicksort9quicksortNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB17_NtNtBa_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtCslbMUDoFrEqM_14weavepy_parser3ast8ConstantEECshfZExtisgX1_16weavepy_compiler +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject29invalidate_getattribute_cache +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod8lru_call +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16reentrant_interp +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object21bytearray_is_exported +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtB4_6option6OptionTNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyNtB1x_6ObjectEEEEB1z_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs9NJVNhcGWEq_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNvNtNtBY_6stdlib13functools_mod8lru_calls_0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types20install_type_dunders20type_dunder_dict_get +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter17core_partial_calls_0B7_ +_RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE15append_elementsBI_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6result6ResultQNtCs9NJVNhcGWEq_10weavepy_vm11InterpreterNtNtB10_5error12RuntimeErrorEEB10_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEE11extend_withB1l_ +_RNvMss_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10PyInstance7set_cls +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict8receiver +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict11values_iter +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects9match_end +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects7run_sub0B7_ +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_13pattern_split0E0B8_ +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12plan_rewrites6_0B5_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16templatelib_attr +_RNvXs8_NtNtCsevLNFiNqfJP_4core5slice5indexINtNtNtB9_3ops5range14RangeInclusivejEINtB5_10SliceIndexSNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE5indexB1D_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7imp_mod5build +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14leaf_py_setter +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB2l_5chain5ChainINtNtNtB2p_5slice4iter4IterB13_EB3v_EEE9from_iterB17_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod17permutations_core +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs9NJVNhcGWEq_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNvMs7_BY_NtBY_11Interpreter4stepsF_0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types20install_type_dunders17type_annotate_get +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19call_annotate_value +_RNvNtCslbMUDoFrEqM_14weavepy_parser6parser27validate_fstring_conversion +_RNvXse_NtNtCs1C1lLj4PWSY_5alloc3vec9into_iterINtB5_8IntoIterNtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap6BucketENtNtNtCsevLNFiNqfJP_4core3ops4drop4Drop4dropB10_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18function_descr_get +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyANtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrj4_E4withNCINvNtNtBZ_6stdlib13functools_mod19with_partial_fieldsINtNtCsevLNFiNqfJP_4core6option6OptionTNtNtBZ_6object6ObjectB3s_EENCNvB21_14partial_inline0E0IB2Q_B2P_EEBZ_ +_RNvCs9NJVNhcGWEq_10weavepy_vm10compare_op +_RNvCs9NJVNhcGWEq_10weavepy_vm12is_nan_value +_RNvXsk_NtCshfZExtisgX1_16weavepy_compiler4nameNtB5_4NameINtNtCsevLNFiNqfJP_4core7convert4FromNtNtCs1C1lLj4PWSY_5alloc6string6StringE4from +_RNCNvMNtCs9NJVNhcGWEq_10weavepy_vm13builtin_typesNtB4_12BuiltinTypes5buildsa_0B6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter23class_assign_compatible +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict14od_update_fast +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict11native_iter +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21percent_mod_left_slot +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecNtCsjIWZ3EBbJCG_15weavepy_codegen4CodeE8grow_oneCs9NJVNhcGWEq_10weavepy_vm +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13register_lazy +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18ensure_module_spec +_RNCNvMNtCs9NJVNhcGWEq_10weavepy_vm13builtin_typesNtB4_12BuiltinTypes5builds7_0B6_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13itertools_mod17native_new_interps_0B7_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter36parse_source_emitting_warnings_flags +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort18small_sort_generalNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB1f_NtNtBa_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18object_is_callable +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtBG_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VechEEEEBG_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17core_partial_call +_RNvCs9NJVNhcGWEq_10weavepy_vm8set_view +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB6_11Interpreter13seq_strict_kw +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject13adds_own_dict +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict9od_values +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object13push_hex_byte +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objectsNtB4_4Sink12finish_plain +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze17unary_result_type +_RNvMsx_Cs9NJVNhcGWEq_10weavepy_vmNtB5_8CallSlot8poly_hit +_RNvMs_NtCs4bqUF11K40R_11weavepy_jit7analyzeNtB4_4Plan18comp_lane_for_body +_RNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB5_8JitState19resolve_native_func +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower5is_op +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit17h_list_append_ref +_RNvMs_NtCs4bqUF11K40R_11weavepy_jit7analyzeNtB4_4Plan12in_loop_span +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10str_lstripINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object13int_from_i128 +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12tokenize_mod5build +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types20install_type_dunders20type_annotations_get +_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable7ipnsortNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYBT_NtNtB8_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RNvNtCskEmZ9gTcSHg_12weavepy_capi5types11live_tp_doc +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod9lru_parts +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20core_partial_builtin +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyANtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrj4_E4withNCINvNtNtBZ_6stdlib13functools_mod19with_partial_fieldsINtNtCsevLNFiNqfJP_4core6option6OptionINtNtBZ_2rc2RcNtNtBZ_6object10PyFunctionEENCINvB21_17with_partial_callB3r_NCNvMs7_BZ_NtBZ_11Interpreter17core_partial_calls0_0E0E0IB2Q_B2P_EEBZ_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15store_fast_step +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueANtNtCs9NJVNhcGWEq_10weavepy_vm6object6Objectj3_EBG_ +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject18layout_struct_base +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict9make_view +_RNvXsZ_NtCs1C1lLj4PWSY_5alloc6stringNtB5_6StringNtNtCsevLNFiNqfJP_4core3fmt5Write10write_char +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects8sub_fast +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects7run_sub +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm6extend +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze16settle_container +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtB7_5boxed3BoxNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline11MethodNotesEE8push_mutB13_ +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower10plain_call +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower11field_place +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze14check_dict_key +_RNvMs2_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_6Native3ran +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefNtNtB1d_6object10PyIteratorEEEB1d_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB2l_3rev3RevINtNtNtB2p_5slice4iter4IterB13_EEEE9from_iterB17_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12do_exec_call +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21normalize_hash_result +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_5slice4iter4IterNtNtCshfZExtisgX1_16weavepy_compiler4name4NameEINvMs1B_B15_B13_8from_strRB3v_EEE9from_iterB17_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter24function_annotation_dict +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB6_11Interpreter9seq_build +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject15solid_base_name +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19code_synthetic_attrs2_0B5_ +_RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectENCNvNtNtB1Y_6stdlib17collections_odict18exact_view_entriess_0EB1U_INtNtB6_6option6OptionNtNtB6_7convert10InfallibleENCINvXsI_B3K_IB3I_INtB1b_3VecB1U_EEINtNtNtB4_6traits7collect12FromIteratorIB3I_B1U_EE9from_iterBQ_E0B4N_EB1Y_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_strip +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze11infer_blocks2_0B5_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16settle_lazy_cold +_RINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB6_11Interpreter18lean_bind_keywordsINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB1d_7flatten7FlatMapINtNtB1h_6option4IterINtNtB6_4sync3RefNtNtB6_6object8DictDataEENtNtB6_7dictmap4IterNCNvB2_27try_inline_call_ex_keywords0ENCB3I_s_0EEB6_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSINtNtB4_6option6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtB13_4sync7GilCellNtNtB13_6object10PyIteratorEEEEB13_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16leaf_setter_eval +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15gen_ex_on_frame +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins17int_to_bytes_leaf +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_5slice4iter4IterjENCNvNtB17_7seqiter12machine_steps2_0EE9from_iterB17_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19property_dunder_get +_RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapINtNtNtB6_5slice4iter4IterNtCshfZExtisgX1_16weavepy_compiler8ConstantENvNtB1y_9flowgraph15to_ast_constantENtNtCslbMUDoFrEqM_14weavepy_parser3ast8ConstantINtNtB6_6option6OptionNtNtB6_7convert10InfallibleENCINvXsI_B3C_IB3A_INtNtCs1C1lLj4PWSY_5alloc3vec3VecB2O_EEINtNtNtB4_6traits7collect12FromIteratorIB3A_B2O_EE9from_iterBQ_E0B4F_EB1y_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod7lru_hit +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod9item_hash +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod9lru_count +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod9lru_store +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter20core_partial_builtins_0B7_ +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject19member_slots_sorted +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject16adds_own_weakref +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19mappingproxy_values +_RNvMsh_NtCs9NJVNhcGWEq_10weavepy_vm4syncINtB5_7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionReEE3getB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueTjINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBI_5types10PyInstanceEEEBI_ +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objectsNtB2_7Subject5slice +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneBJ_ +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower12operand_addr +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12pop_top_step +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower7call_kw +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11h_build_map +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs9NJVNhcGWEq_10weavepy_vm9InlineActEBD_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline5KwMapEEEB1C_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs9NJVNhcGWEq_10weavepy_vm9GetterRefEBD_ +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_nativeNtB4_4Fast7popleft +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fadd +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records11note_direct +_RNvCs9NJVNhcGWEq_10weavepy_vm15class_attr_site +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter23leaf_instance_subscript +mi_good_size +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9slot_note +mi_theap_malloc_zero_aligned_at_generic +_mi_bin_size +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9h_call_kw +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit8AttrSiteEBF_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native13deque_popleft +_RINvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_subscr_hotKm0_EB4_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib14datetime_accel11date_fields +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib14datetime_accel11time_fields +_RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRThReEECs9NJVNhcGWEq_10weavepy_vm +_RINvNtCsevLNFiNqfJP_4core5array11try_from_fnINtNtNtB4_3ops9try_trait17NeverShortCircuitINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtB1q_12SliceStorageNtNtB1s_6object7DictKeyEEEKj4_NCINvMBJ_BG_10wrap_mut_1jNCINvXsk_B2_B1n_NtB2_14SpecArrayClone5cloneKB30_E0E0EB1s_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecThNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrNtNtBL_6object6ObjectFG_RL0_SB1z_EINtNtCsevLNFiNqfJP_4core6option6OptionINtNtB2c_6result6ResultB1z_NtNtBL_5error12RuntimeErrorEEEE8push_mutBL_ +_RNvXs0_NtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_mapINtB5_9FilterMapINtNtNtBb_5slice4iter4IterThReEENCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native7installs5_0ENtNtNtB9_6traits8iterator8Iterator4nextB1O_ +_RNvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB2_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecThReNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEE10try_insertB1x_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter9hash_fast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object24bytearray_export_acquire +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15attr_stack_slow +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native7install +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockAINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtB1K_12SliceStorageNtNtB1M_6object7DictKeyEEj4_E10initializeNCINvB1a_11get_or_initNCNvNtNtB1M_6stdlib15datetime_native7layouts0E0zE0E0B1M_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2q_5slice4iter4IterReENCNCNCNvNtNtB17_6stdlib15datetime_native7layouts000EE9from_iterB17_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib14decimal_native8interned +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecThNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrNtNtB1w_6object6ObjectFG_RL0_SB2k_EINtNtCsevLNFiNqfJP_4core6option6OptionINtNtB2Y_6result6ResultB2k_NtNtB1w_5error12RuntimeErrorEEEEE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEB1w_ +_RNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_7GcState7untrack +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10struct_mod14install_struct +_RNvCs9NJVNhcGWEq_10weavepy_vm17coerce_len_result +_RNvXsG_NtNtCscdyiIoZL7b2_10num_bigint6bigint8divisionNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops5arith3DivRBP_E3div +_RNvCs9NJVNhcGWEq_10weavepy_vm11range_slice +_RNCNvCs9NJVNhcGWEq_10weavepy_vm11range_slices_0B3_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17make_seq_iterator +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_countINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_mi_os_alloc +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapThReENtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBW_ +_RNvMs2_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_nativeNtB5_5Names3new +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueAINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtBF_12SliceStorageNtNtBH_6object7DictKeyEEj1_EBH_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecThNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrNtNtB2j_6object6ObjectFG_RL0_SB37_EINtNtCsevLNFiNqfJP_4core6option6OptionINtNtB3L_6result6ResultB37_NtNtB2j_5error12RuntimeErrorEEEEE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0B2j_ +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10struct_mod14install_structINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object16range_len_bigint +_RNvXs0_NtNtCscdyiIoZL7b2_10num_bigint6bigint11subtractionNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops5arith3SubRBT_E3sub.1487 +_RNCNvCs9NJVNhcGWEq_10weavepy_vm11range_slice0B3_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter17is_stop_iteration +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10bytes_findINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakINtNtBX_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VechEEEjEEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EBX_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs9NJVNhcGWEq_10weavepy_vm4sync4CellbEE9drop_slowBL_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16leaf_eval_nested +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_truth_stack +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTThReENtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BV_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EBZ_ +_RNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_7GcState13untrack_young +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13str_split_sep +_RNvXNtNtCscdyiIoZL7b2_10num_bigint6bigint11subtractionRNtB4_6BigIntNtNtNtCsevLNFiNqfJP_4core3ops5arith3Sub3sub.1445 +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13str_partition +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19binary_subscr_basic +_RNvXs2_NtNtCscdyiIoZL7b2_10num_bigint7biguint11subtractionNtB7_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops5arith9SubAssignmE10sub_assign +_RNvXs4_NtCscdyiIoZL7b2_10num_bigint6bigintNtB5_6BigIntNtNtCsevLNFiNqfJP_4core3cmp3Ord3cmp +_RNvXsF_NtNtCscdyiIoZL7b2_10num_bigint6bigint8divisionNtB7_6BigIntNtNtNtCsevLNFiNqfJP_4core3ops5arith3Div3div +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexINtNtNtNtB7_11collections4hash3map7HashMapjTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakINtNtB29_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VechEEEjEEEE10initializeNCINvB2_11get_or_initNCNvNtB29_6object20bytearray_export_map0E0zEB29_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins12substr_count +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9list_copy +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan13new_container +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit17finished_in_place +mi_reserve_os_memory_ex2 +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib14datetime_accel15timedelta_parts +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtNtNtB6_6stdlib15datetime_native5StateE3newB6_ +_RNvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB2_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecThNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrNtNtB1v_6object6ObjectFG_RL0_SB2j_EINtNtCsevLNFiNqfJP_4core6option6OptionINtNtB2X_6result6ResultB2j_NtNtB1v_5error12RuntimeErrorEEEEE10try_insertB1v_ +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecThReNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters10filter_map9FilterMapINtNtNtB2s_5slice4iter4IterThB13_EENCNvNtNtB19_6stdlib15datetime_native7installs5_0EE9from_iterB19_ +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10struct_mod13b_native_packINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvXs_NtNtCscdyiIoZL7b2_10num_bigint6bigint8additionRNtB6_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops5arith3AddBP_E3add +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10bytes_find +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins20bytes_needle_guarded +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object24bytearray_export_release +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_count +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_attr_stack +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6h_call0B5_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10struct_mod5build +_RNvNtNtCscdyiIoZL7b2_10num_bigint7biguint8division11div_rem_ref +_RNvXs9_NtNtCscdyiIoZL7b2_10num_bigint7biguint8additionRNtB7_7BigUintNtNtNtCsevLNFiNqfJP_4core3ops5arith3Add3add.1444 +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10bytes_finds_0B5_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21deep_equal_collection +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit5StateEBF_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit20fused_function_attrs +_mi_arena_id_none +_RINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB7_6Object15new_tuple_arrayKj5_EB9_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecThReNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zEB1y_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13str_partitionINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10struct_mod13b_native_pack +_RNvXsf_NtNtCscdyiIoZL7b2_10num_bigint6bigint14multiplicationRNtB7_6BigIntNtNtNtCsevLNFiNqfJP_4core3ops5arith3Mul3mul +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16leaf_python_next +_RINvCs9NJVNhcGWEq_10weavepy_vm9push_growjEB2_ +_mi_os_has_virtual_reserve +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib14datetime_accel5build +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtNtBG_6stdlib15datetime_native5StateEEBG_ +_RNvXs_NtNtCscdyiIoZL7b2_10num_bigint7biguint11subtractionNtB6_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops5arith9SubAssignRBT_E10sub_assign +_RNvMst_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_5Range6bounds +_RNvXs3_NtNtCscdyiIoZL7b2_10num_bigint6bigint11subtractionNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops5arith3SubmE3sub.1488 +_RNvXsb_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecyENtNtCsevLNFiNqfJP_4core5clone5Clone5cloneCs9NJVNhcGWEq_10weavepy_vm +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCINvMs8_B26_NtB28_11Interpreter12leaf_run_retKb0_KB4c_KB4c_E0E0zEB28_ +__mi_stat_adjust_decrease_mt +mi_arena_id_from_arena +_mi_os_zalloc +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockAINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcINtBX_12SliceStorageNtNtBZ_6object7DictKeyEEj4_E10initializeNCINvB2_11get_or_initNCNvNtNtBZ_6stdlib15datetime_native7layouts0E0zEBZ_ +_RNvCs9NJVNhcGWEq_10weavepy_vm14core_bignum_op +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10struct_mod14install_struct0B7_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9list_copyINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTjIBw_NtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline4PlanEEE8push_mutBR_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline4PlanE8push_mutBL_ +_RNvMs2_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower18inline_python_call +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit16module_attr_note +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower13binary_helper +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjThjEINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertCs4bqUF11K40R_11weavepy_jit +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs4bqUF11K40R_11weavepy_jit2ir11GlobalGuardENtNtNtNtBb_4iter6traits8iterator8Iterator3anyNCNvNtBU_7analyze12plan_rewritesf_0EBU_ +_RINvYINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3set4IterjENtNtNtNtCsevLNFiNqfJP_4core4iter6traits8iterator8Iterator8try_folduNCINvNvBX_3any5checkRjNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12plan_rewritesd_0E0INtNtNtB15_3ops12control_flow11ControlFlowuEEB2u_ +_RINvYINtNtNtCsevLNFiNqfJP_4core3ops5range5RangejENtNtNtNtBa_4iter6traits8iterator8Iterator8try_folduNCINvNvBL_3any5checkjNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze12plan_rewritese_0E0INtNtB8_12control_flow11ControlFlowuEEB21_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2p_3ops5range5RangejENCNvNtB17_9frame_jit7h_builds_0EE9from_iterB17_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_binop_site +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real21lock_try_acquire_leaf +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real4heldNtNtB6_4sync8RealLockEB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real17thread_handle_new +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTyINtNtCs1C1lLj4PWSY_5alloc4sync3ArcNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real17ThreadHandleStateEEE14reserve_rehashNCINvNtB8_3map11make_hasheryBR_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EB1v_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterNtNtCs9NJVNhcGWEq_10weavepy_vm8builtins12SetInplaceOpEEB1t_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real25make_thread_handle_object0EBJ_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real13get_native_id +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline18inline_global_miss +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real25make_thread_handle_object +_RNvYNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real9lock_type00INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRINtNtBc_2rc2RcNtNtBc_5types10TypeObjectERSNtNtBc_6object6ObjectEE9call_onceBc_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real19is_main_interpreter +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterINtNtBI_4sync3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm15thread_registry11ThreadEntryEEEB1K_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins7set_add +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real20resolve_acquire_args +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterhENtNtNtNtBb_4iter6traits8iterator8Iterator8positionNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod4scanhNvB1L_8uni_wordE0EB1P_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real15thread_shutdown +_RNvNtCs9NJVNhcGWEq_10weavepy_vm3gil18before_gil_release +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNtCs9NJVNhcGWEq_10weavepy_vm15thread_registry14ThreadRegistryE10initializeNCINvB1a_11get_or_initNvMs0_B1I_B1G_3newE0zE0E0B1K_ +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakINtNtB2j_4sync7GilCellNtNtB2j_7dictmap6SetMapEENtNtB2j_8builtins12SetInplaceOpEEEEB2j_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12local_native5build +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real6keeperNtNtB8_4sync8RealLockE0B8_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs7UfkFU4le9s_8lock_api5mutex5MutexNtNtCs3pgaDf2SUin_11parking_lot9raw_mutex8RawMutexINtNtNtNtB7_11collections4hash3map7HashMapyINtNtCs1C1lLj4PWSY_5alloc4sync3ArcNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real17ThreadHandleStateEEEE10initializeNCINvB2_11get_or_initNCNvB3C_15handle_registry0E0zEB3G_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins17set_apply_inplace +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline16h_inline_builtin +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline9h_release +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real9get_ident +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real9lock_exit +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins21take_deferred_set_ops +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real25make_thread_handle_objects0_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real16make_lock_object +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject20forget_display_names +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real4heldNtNtB8_4sync9RealRLockE0B8_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real25make_thread_handle_object0B7_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins7set_addINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins20apply_set_inplace_op +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real13allocate_lock +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real4heldNtNtB8_4sync8RealLockE0B8_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs9NJVNhcGWEq_10weavepy_vm8builtins12SetInplaceOpEEB1c_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real18make_thread_handle +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real22rlock_try_acquire_leaf +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real4heldNtNtB6_4sync9RealRLockEB6_ +_RNvMs5_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_8ModCache4note +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower19field_store_in_line +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBV_5types10TypeObjectEENtNtNtNtBb_4iter6traits8iterator8Iterator3anyNCNvNtNtBV_6stdlib12weakref_real16supports_weakrefs_0EBV_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real12lock_acquire +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real21get_main_thread_ident +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real10rlock_exit +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline15h_inline_global +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNtCs9NJVNhcGWEq_10weavepy_vm15thread_registry14ThreadRegistryE10initializeNCINvB2_11get_or_initNvMs0_BV_BT_3newE0zEBX_ +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm6importNtB4_11ModuleCache6remove +_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable7ipnsortmNvYmNtNtB8_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable9quicksort9quicksortmNvYmNtNtBa_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4srem +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer11pinned_list +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer16emit_list_append +_RINvMNtCsevLNFiNqfJP_4core6resultINtB3_6ResultINtNtCs9NJVNhcGWEq_10weavepy_vm4sync3RefNtNtBN_6object8DictDataENtBL_11BorrowErrorE9is_ok_andNCNvMs7_BN_NtBN_11Interpreter19builtin_ex_on_frames0_0EBN_ +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6option6OptionINtNtB1b_6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorEENCNvB4_8sub_fast0E0B8_ +_RNvMs18_NtNtNtCsgHYyB3hU8Ec_3std11collections4hash3mapINtB6_5EntrymmE9or_insertCs4bqUF11K40R_11weavepy_jit +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer19emit_attr_get_chain +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier219deliver_call_result +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10k_str_join +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins12list_reverseINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir6TBlockEEB1c_ +_RNvMsK_Cs9NJVNhcGWEq_10weavepy_vmNtB5_8LeafSite8poly_hit +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer12emit_str_mod +_RNvMsi_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtNtB7_5types10PyInstance13attr_peek_has +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter24run_py_exact_nofree_with +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter19core_store_new_attr0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object20materialize_stack_at +_RNvCs9NJVNhcGWEq_10weavepy_vm22certain_miss_error_obj +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218finish_interp_call +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm7timsort10MergeStateNtNtBG_6object6ObjectNCINvMs7_BG_NtBG_11Interpreter10sort_keyedB1q_NCNvB1Q_13sort_with_keys_0Es2_0EEBG_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins12list_reverse +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_gen_return +_RINvMso_Cs9NJVNhcGWEq_10weavepy_vmNtB6_14SortKindScalar2ofINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterRNtNtB6_6object6ObjectEEB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier213pin_memo_note +_RINvNtCs9NJVNhcGWEq_10weavepy_vm5tier226call_with_activation_shellINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB4_6object6ObjectNtNtB4_5error12RuntimeErrorENCNvB2_23wpjit_call_method_inners6_0EB4_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7h_catch +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm7seqiterNtB6_11Interpreter11filter_next +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB5_7CallCtx14refresh_tables +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15attr_miss_raise +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter10sort_keyedNtNtB8_6object6ObjectNCNvB4_13sort_with_keys_0Es2_0B8_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16core_gen_call_ex +_RNvMNtCskibSv91bgl1_9hashbrown11rustc_entryINtNtB4_3map7HashMapmmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE11rustc_entryCs4bqUF11K40R_11weavepy_jit +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier217wpjit_call_method +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs9NJVNhcGWEq_10weavepy_vm13PolyLeafSitesEBD_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB12_6object11PyGeneratorEEEB12_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer17emit_dyn_attr_set +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs9NJVNhcGWEq_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_13gave_up_often0bEBZ_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared5pivot11median3_recjNvYjNtNtBa_3cmp10PartialOrd2ltECs4bqUF11K40R_11weavepy_jit +_RNvMs0_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_7PyFrame8set_back +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212pin_memo_hit +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17do_list_sort_call +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_inst_native +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib14operator_accel15itemgetter_fast0B7_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower16inst_native_call +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit20subscr_raise_missing +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionbE7or_elseNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6h_calls2_0EBY_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7abc_mod19abc_instance_cached +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records11finish_rest +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18do_isinstance_call +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjIBC_NtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline4PlanEEEEB1k_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13k_list_append +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7abc_mod19abc_instance_cacheds_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib14operator_accel15itemgetter_fast +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native7head_of +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecTbmEEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1L_5slice4iter4IterNtNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB2Z_5Lower13method_kernel3ArgENCNvMsc_B2Z_B3B_13method_kernel0EE9from_iterB31_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7abc_mod17abc_instancecheck +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11dict_remove +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records11ctor_direct +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14direct_call_kw +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native8receiver +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records10new_direct +_RNvCs9NJVNhcGWEq_10weavepy_vm24inst_builtin_method_site +_RINvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_subscr_hotKm3_EB4_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11str_isdigitINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11str_isdigit +_RNvYINtNtNtCsevLNFiNqfJP_4core3str7pattern18MultiCharEqPatternAcj2_ENtB5_7Pattern15strip_prefix_ofCs9NJVNhcGWEq_10weavepy_vm +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins21int_from_bytes_method +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14set_issuperset +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter14load_attr_types6_0B7_ +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject12recompute_c3 +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types8exc_init +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4math9sqrt_fast +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2io17stringio_new_pure +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile15mem_text_append +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm6object6PyFileEBF_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm6object11FileBackendEBF_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11str_isascii +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins21fromhex_wrap_subclass +_RNvXs_NtNtCscdyiIoZL7b2_10num_bigint7biguint4bitsNtB6_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops3bit6BitAndRBL_E6bitand.1447 +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types8exc_initINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot10set_static +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs9NJVNhcGWEq_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE8try_withNCNvB2n_19current_compile_gen0yEBZ_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19int_from_bytes_leaf +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter4calls0_0B7_ +_RNvMsn_NtCscdyiIoZL7b2_10num_bigint6bigintNtB5_6BigInt3pow +_RNvXs5_NtNtCscdyiIoZL7b2_10num_bigint6bigint4bitsNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops3bit12BitXorAssignRBL_E13bitxor_assign +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib13functools_mod16partial_pure_new +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17managed_dict_attr +_RNvMsi_Cs9NJVNhcGWEq_10weavepy_vmNtB5_8SumState3add +_RNvXsd_NtNtNtCsevLNFiNqfJP_4core3fmt3num3impyNtB9_7Display3fmt +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object11empty_cells +_RNvMNtCs9NJVNhcGWEq_10weavepy_vm8gen_fastNtB4_11Interpreter13gen_fast_step +_RINvMs8_NtCs9NJVNhcGWEq_10weavepy_vm9leaf_planNtB8_11Interpreter12leaf_run_retKb0_Kb1_KB1j_EB8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12binascii_mod11register_kw +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16check_int_result +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15deopt_binary_op +_RNvNtNtCscdyiIoZL7b2_10num_bigint7biguint14multiplication4mac3 +_RNvXNtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB4_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyEINtB2_18SpecFromIterNestedB11_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters6cloned6ClonedINtNtB15_7dictmap4KeysuEEE9from_iterB15_ +_RNvXs1_NtNtCscdyiIoZL7b2_10num_bigint7biguint4bitsNtB7_7BigUintINtNtNtCsevLNFiNqfJP_4core3ops3bit5BitOrRBM_E5bitor +_RNvXsE_NtNtCsevLNFiNqfJP_4core3fmt3numyNtB7_8UpperHex3fmt +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19format_template_str +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2io20stringio_newline_arg +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins15file_write_fast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214finish_deopted +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5tier212NativeCalleeEBF_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmTNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeBP_EINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertBT_ +_RNvMNtCs9NJVNhcGWEq_10weavepy_vm8gen_fastNtB4_11Interpreter15gen_resume_rest +_RINvMNtCsevLNFiNqfJP_4core3stre12trim_matchesNCNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter17builtin_ctor_arms0EBN_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins20b_int_from_bytes_cls +_RNvXNtNtCscdyiIoZL7b2_10num_bigint6bigint4bitsRNtB4_6BigIntNtNtNtCsevLNFiNqfJP_4core3ops3bit6BitAnd6bitand +_RNvMNtCs1C1lLj4PWSY_5alloc6stringNtB2_6String9from_utf8 +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins15bytes_maketrans +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10str_rsplitINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1A_EEE4callB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2io18wrap_memory_stream +_RNCNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB8_6PyFile15mem_text_appends1_0Ba_ +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile13unlist_writer +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects16pattern_sub_full +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18jump_backward_step +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer13emit_iter_new +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier213rebuild_stack +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCNvMs7_B28_NtB28_11Interpreter14leaf_init_eval0E0zEB28_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14truth_instance +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11str_isasciiINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14set_issupersetINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvXsv_NtNtCscdyiIoZL7b2_10num_bigint6bigint5shiftNtB7_6BigIntINtNtNtCsevLNFiNqfJP_4core3ops3bit3ShrjE3shr +_RNvNtNtCscdyiIoZL7b2_10num_bigint7biguint5shift12biguint_shr2 +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins15bytes_maketransINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9method_kwNvB4_10str_rsplitEs_0B6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15default_delattr +_RNvCs9NJVNhcGWEq_10weavepy_vm20inst_dict_attr_named +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16alloc_exc_native +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastNtNtB4_6object6PyFileEB4_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects7installs_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects8sub_full +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier211unpack_pins +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14leaf_init_eval +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10str_rsplit0B5_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCNvMNtCs9NJVNhcGWEq_10weavepy_vm13builtin_typesNtBG_12BuiltinTypes5buildsa_0EBI_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2io12stringio_new +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6object6PyFileE9drop_lastB7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects8dispatch +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier221finish_deopted_callee +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12binascii_mod5build +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap6BucketuEEEB1d_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17resolve_field_str +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects9class_ext +_RNvXs8_NtNtCsevLNFiNqfJP_4core5slice5indexINtNtNtB9_3ops5range14RangeInclusivejEINtB5_10SliceIndexSPNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE5indexB1E_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_9inst_dict10SharedKeysE9drop_lastB7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13byteorder_str +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14set_iter_items +_RINvXsz_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapNtB6_6SetMapINtNtNtNtCsevLNFiNqfJP_4core4iter6traits7collect12FromIteratorNtNtB8_6object7DictKeyE9from_iterINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterB1S_EEB8_ +_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE16extend_desugaredINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtBK_7dictmap4KeysuENCNvMs1v_BI_BG_9make_iters_0EEBK_ +_RINvNvMNtCsevLNFiNqfJP_4core5sliceSp7reverse7revswapNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEBS_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16core_delete_attr +_RNvMsi_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtNtB7_5types10PyInstance12split_remove +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects15pattern_findall +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_15pattern_findall0E0B8_ +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile11set_newline +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSNtNtCs9NJVNhcGWEq_10weavepy_vm5tier23PinEBG_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs9NJVNhcGWEq_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE8try_withNCNvB2n_22try_call_native_directs2_0uEBZ_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline13h_inline_call +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline13h_inline_exit +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline10leave_body +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline11bind_levels +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fsub +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records14left_uncleanly +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11direct_doneKb0_Es_0B6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15h_make_function +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline20h_inline_truth_local +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10k_list_pop +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7recordsNtB5_9DirectRec4grow +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel17json_make_encoders5_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel9json_kind +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel10EncoderCfgEBH_ +_RNvXNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accelhNtB2_8JsonChar3key +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter11quoted_utf8 +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastNtNtNtB4_6stdlib10json_accel10EncoderCfgEB4_ +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel9scan_oncehEB6_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStruNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE6insertBR_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel17encode_value_impl +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel11encode_list0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel10built_list +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fdiv +_RNvXs_NtCse5K8AiQ2P3E_4zmij7privatedNtB4_6Sealed20write_to_zmij_buffer +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel7KeyMemoEBH_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower7map_add +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel20write_encoded_string +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter6finish +_RNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel17json_make_scanners_00B9_ +_RNvXNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accelhNtB2_8JsonChar6string +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel5builds_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel12encode_value +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel13finish_object +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel17json_make_encoder +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter11push_object +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapjuNtNtCs9NJVNhcGWEq_10weavepy_vm8fasthash13FxBuildHasherE6removejEBU_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel17json_make_encoders5_0EBJ_ +_RINvYNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateNtNtCsevLNFiNqfJP_4core4hash11BuildHasher8hash_oneRNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrEB1J_ +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtNtNtB6_6stdlib10json_accel10EncoderCfgE3newB6_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accelNtB5_10JsonWriter8push_str +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtNtB7_6stdlib10json_accel10EncoderCfgE9drop_lastB7_ +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel12parse_objecthEB6_ +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel21scan_string_with_memohEB6_ +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel11parse_arrayhEB6_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStruEE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_uNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0EBU_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit7compile +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jitNtB5_5Lower5frame +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit6verify0E0zE0E0B2o_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6k_body +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jitNtB5_5Lower4call +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit6NativeEE10initializeNCINvB1a_11get_or_initNCINvB2k_3runKb0_E0E0zE0E0B2o_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13k_list_extend +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionNtNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit6NativeEE10initializeNCINvB2_11get_or_initNCINvB1x_3runKb0_E0E0zEB1B_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jitNtB5_5Lower4body +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11h_site_type +_RNvMs2_NtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jitNtB5_6Engine7release +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower10unpack_ref +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jitNtB5_5Lower2op +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit6verify0E0zEB1A_ +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10atexit_mod10a_registerINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1M_EEE4callB8_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218inline_method_bodys2_0B5_ +_RNvXs9_NtCs1C1lLj4PWSY_5alloc5boxedINtB5_3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10DirectSiteENtNtCsevLNFiNqfJP_4core7default7Default7defaultBL_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower16stack_store_attr +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastNtNtB4_16weakref_registry11WeakRefSlotEB4_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object14eq_is_identity +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real13rlock_release +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11list_remove +_mi_prim_decommit +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockbE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15builtin_counted0E0zEB1y_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod19code_range_has_mark +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10atexit_mod10a_register +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11list_removeINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11set_discardINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real26make_ref_object_with_classs0_0EBJ_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10atexit_mod14current_interp +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecINtNtB7_5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10DirectSiteEE8push_mutB11_ +_RNvMs3_NtCs9NJVNhcGWEq_10weavepy_vm16weakref_registryNtB5_15WeakRefRegistry13clear_entries +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real6keeperNtNtBK_4sync8RealLockE0EBK_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11set_discard +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time7time_ns +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2q_5slice4iter4IterTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueB13_EENCNvMNtB17_5lowerNtB4q_7Lowerer15inline_body_for0EE9from_iterB17_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower8contains +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower12setter_store +_RNvNtCs9NJVNhcGWEq_10weavepy_vm16weakref_registry13on_death_slow +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15class_attr_note +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10atexit_mod7builtin +_RNCNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s7_0Bb_ +_RNCNCNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB9_8JitState12get_compileds_0s8_0Bb_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm16weakref_registry15queue_callbacks +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons29push_pending_weakref_callback +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_16weakref_registry11WeakRefSlotE9drop_lastB7_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE20repeat_body_has_markB9_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10atexit_mod5build +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecINtNtCsevLNFiNqfJP_4core6option6OptionTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectINtNtB7_3vec3VecB1p_EIB28_TNtNtB7_6string6StringB1p_EEEEE8grow_oneB1t_ +_RNvMs3_NtCs9NJVNhcGWEq_10weavepy_vm16weakref_registryNtB5_15WeakRefRegistry12take_entries +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableuE17swap_remove_indexB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm16weakref_registry11WeakRefSlotEBF_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19leaf_attr_store_any +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockbE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15builtin_counted0E0zE0E0B2m_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE19max_until_recursiveB9_ +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types25install_import_error_init22import_error_init_impl +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib9fcntl_mod7builtin +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionlEE10initializeNCINvB2_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit20inst_deferred_offset0E0zEB2b_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib9fcntl_mod5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7grp_mod5build +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit16k_str_startswith +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types25install_import_error_inits_0B5_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2os24path_like_type_singleton0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11k_str_split +_RNvCs9NJVNhcGWEq_10weavepy_vm21lookup_exception_init +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7pwd_mod5build +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter17builtin_ctor_armss1_0B5_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7grp_mod7builtin +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionlEE10initializeNCINvB1a_11get_or_initNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit20inst_deferred_offset0E0zE0E0B2Z_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter20leaf_instance_dunder +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_titleINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_title +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier223try_borrowed_dyn_scalar +_RINvNtCs9NJVNhcGWEq_10weavepy_vm5tier226call_with_activation_shellINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB4_6object6ObjectNtNtB4_5error12RuntimeErrorENCNvB2_13call_dyn_impls2_0EB4_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier216wpjit_global_obj +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214wpjit_call_dyn +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215dyn_call_result +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer13emit_list_get +_RINvMs9_NtCs9NJVNhcGWEq_10weavepy_vm9leaf_planNtB8_11Interpreter11plan_getterKb1_EB8_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier27pin_any +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter19leaf_load_attr_with0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier221note_generic_dyn_call +_RINvXNvMNtCs1C1lLj4PWSY_5alloc5sliceSp9to_vec_inNtNtCslbMUDoFrEqM_14weavepy_parser3ast13ComprehensionNtB3_10ConvertVec6to_vecNtNtB8_5alloc6GlobalECshfZExtisgX1_16weavepy_compiler +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native18deque_getitem_leaf +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native13deque_getitem +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier217wpjit_list_append +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer13emit_list_len +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs4bqUF11K40R_11weavepy_jit7analyze5ESlotENtNtNtNtBb_4iter6traits8iterator8Iterator3allNvMs6_BS_BQ_8is_plainEBU_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapmNtNtCs4bqUF11K40R_11weavepy_jit2ir13CompSavedMetaINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE6insertBS_ +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTmNtNtCs4bqUF11K40R_11weavepy_jit2ir13CompSavedMetaEE14reserve_rehashNCINvNtB8_3map11make_hashermBR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE0EBV_ +_RNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecNtB5_11RawVecInner17try_reserve_exactCs9NJVNhcGWEq_10weavepy_vm +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10locale_mod5build +_RNvNtCs9NJVNhcGWEq_10weavepy_vm14descr_registry9module_of +_RNvCs9NJVNhcGWEq_10weavepy_vm11builtin_doc +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib7bz2_mod16compressor_class0E0zE0E0B1L_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib8lzma_mod18decompressor_class0E0zEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib8lzma_mod18decompressor_class0E0zE0E0B1L_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib8zstd_mod14zstddict_class0E0zE0E0B1L_ +ZSTD_versionNumber +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter11divmod_fast +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zstd_mod21m_set_parameter_typesINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11file_fileno +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile6fileno +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2os20struct_seq_method_kwNCNCNvB4_22struct_seq_type_layout0s_0Es_0B8_ +_RNCNvCs9NJVNhcGWEq_10weavepy_vm14percent_format0B3_ +_RNvMs0_NtCs9NJVNhcGWEq_10weavepy_vm16weakref_registryNtB5_11WeakRefSlot11target_died +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier217missed_call_entry +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecTRexEEE10initializeNCINvB1a_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10locale_mod18langinfo_constants0E0zE0E0B30_ +_RNvMsn_Cs9NJVNhcGWEq_10weavepy_vmNtB5_8SortKind6str_lt +_RNCNvCs9NJVNhcGWEq_10weavepy_vm18native_set_compares_0B3_ +_RNCNCNvCs9NJVNhcGWEq_10weavepy_vm18native_set_compares_00B5_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2os20os_get_terminal_size +_RNvNtNtNtNtCsgHYyB3hU8Ec_3std3sys2io5error4unix12error_string +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib16interpreters_mod10i_get_main +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12match_groups +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18dict_fromkeys_leaf +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib8zlib_mod16zlib_error_class0E0zEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib8zlib_mod16zlib_error_class0E0zE0E0B1L_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zlib_mod1b +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7bz2_mod12class_method +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib8lzma_mod16lzma_error_class0E0zEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib8lzma_mod16lzma_error_class0E0zE0E0B1L_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zstd_mod5build +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib8zstd_mod16zstd_error_class0E0zEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib8zstd_mod16zstd_error_class0E0zE0E0B1L_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7imp_mod18imp_create_builtin +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2os9os_isatty +_RNvYNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types22install_object_dunders11object_initINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215wpjit_list_next0B5_ +_mi_arenas_page_try_reabandon_to_mapped +_RNvNtCs9NJVNhcGWEq_10weavepy_vm14descr_registry20builtin_module_value +_RNvNtCs9NJVNhcGWEq_10weavepy_vm14descr_registry13live_c_doc_of +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zlib_mod4b_kw +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib7bz2_mod18decompressor_class0E0zEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib7bz2_mod18decompressor_class0E0zE0E0B1L_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zstd_mod15class_method_kw +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib8zstd_mod18decompressor_class0E0zEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib8zstd_mod18decompressor_class0E0zE0E0B1L_ +_RNvNtNtNtNtCsgHYyB3hU8Ec_3std3sys2io5error4unix17decode_error_kind.1275 +_RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters4takeINtB4_4TakeINtNtNtBa_5slice4iter4IterINtNtBa_6option6OptionReEEENtNtNtB8_6traits8iterator8Iterator3nthCs9NJVNhcGWEq_10weavepy_vm +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7imp_mod14imp_is_builtin +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter12core_dict_kw +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16dict_of_keywords +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapmmINtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtCsjIWZ3EBbJCG_15weavepy_codegen6fxhash8FxHasherEE3getmECs4bqUF11K40R_11weavepy_jit +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm9leaf_planNtB5_7Pending6latest +_RNvMsb_NtCs9NJVNhcGWEq_10weavepy_vm11frame_slotsNtB5_11FrameLocals6borrow +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc3vec3VecTRexEEE10initializeNCINvB2_11get_or_initNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10locale_mod18langinfo_constants0E0zEB2c_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10locale_mod7builtin +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib7bz2_mod16compressor_class0E0zEBY_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8lzma_mod15class_method_kw +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtNtB5_6poison5mutex5MutexNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zstd_mod14ParameterTypesEE10initializeNCINvB2_11get_or_initNCNvB1o_15parameter_types0E0zEB1s_ +_RNvMs_NtCs1C1lLj4PWSY_5alloc3vecINtB4_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE10insert_mutBI_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyNtNtCs9NJVNhcGWEq_10weavepy_vm6object18KeyComparisonStateE4withNCINvBW_13key_cmp_scopeINtNtCsevLNFiNqfJP_4core6option6OptionNtBW_6ObjectENCNvMs7_BY_NtBY_11Interpreter11instantiates0_0E0INtNtB2n_6result6ResultB2i_NtNtBY_5error12RuntimeErrorEEBY_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zstd_mod12class_method +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib8zstd_mod14zstddict_class0E0zEBY_ +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zstd_mod12class_getterNCNvB2_16zstddict_as_mode0EB6_ +ZSTD_versionString +ZSTD_defaultCLevel +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9method_kwNvB4_17str_expandtabs_kwEs_0B6_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBG_6object10FrameShellEEBG_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8gc_trace19clear_object_fields0B5_ +_RNvCs9NJVNhcGWEq_10weavepy_vm20builtin_display_name +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zlib_mod5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7bz2_mod5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7bz2_mod15class_method_kw +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib8zstd_mod16compressor_class0E0zEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib8zstd_mod16compressor_class0E0zE0E0B1L_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtNtBa_6poison5mutex5MutexNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zstd_mod14ParameterTypesEE10initializeNCINvB1a_11get_or_initNCNvB2b_15parameter_types0E0zE0E0B2f_ +_RNvYNCNvNvMNtNtCsgHYyB3hU8Ec_3std2io5errorNtNtNtCsevLNFiNqfJP_4core2io5error5Error17from_raw_os_error9FUNCTIONS0INtNtNtBK_3ops8function6FnOnceTlQNtNtBK_3fmt9FormatterEE9call_onceCs9NJVNhcGWEq_10weavepy_vm +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16str_removeprefix +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins17str_expandtabs_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1H_EEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215wpjit_list_next +__mi_stat_adjust_decrease +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8lzma_mod5build +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBY_5types10TypeObjectEE10initializeNCINvB2_11get_or_initNCNvNtNtBY_6stdlib8lzma_mod16compressor_class0E0zEBY_ +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1L_5types10TypeObjectEE10initializeNCINvB1a_11get_or_initNCNvNtNtB1L_6stdlib8lzma_mod16compressor_class0E0zE0E0B1L_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib8zstd_mod21m_set_parameter_types +_RNvCs9NJVNhcGWEq_10weavepy_vm12compare_sets +_RNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2os22struct_seq_type_layout0s_0B9_ +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects10with_matchINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_12match_groups0E0B8_ +_RINvYINtNtNtCsevLNFiNqfJP_4core5slice4iter4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectENtNtNtNtBa_4iter6traits8iterator8Iterator8try_folduNCINvNvXs_NtNtB1y_8adapters9enumerateINtB2r_9EnumeratepEB1s_8try_fold9enumerateRBJ_uINtNtNtBa_3ops12control_flow11ControlFlowuENCINvNvB1s_3all5checkTjB3y_ENCNvMs7_BN_NtBN_11Interpreter16dict_of_keywordss_0E0E0B3D_EBN_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16str_removeprefixINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21leaf_attr_store_ready +ZSTD_DStreamOutSize +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11file_filenoINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMs7_NtCs9NJVNhcGWEq_10weavepy_vm8lazy_arcINtB5_7OnceBoxNtNtB7_6object6ObjectE3setB7_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE12branch_firstB9_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE16branch_can_startB9_ +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_modINtB5_7MatcherhE12quick_assertB9_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict15od_popitem_leaf +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockNtNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native16chainmap_maps_of8MapsNameE10initializeNCINvB2_11get_or_initNCBV_0E0zEB11_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11h_container0B5_ +_RNvCs9NJVNhcGWEq_10weavepy_vm16builtin_recv_tag +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict19od_move_to_end_leaf +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvNtBU_7seqiter18dict_from_zip_pure0EBU_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11heapq_accel12heapify_impl +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native15dd_missing_pure +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockNtNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native16chainmap_maps_of8MapsNameE10initializeNCINvB1a_11get_or_initNCB1I_0E0zE0E0B1O_ +_RNvMsb_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtB5_11SplitValues8get_memo +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter17core_pure_kw_call0B7_ +_RNvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters4takeINtB4_4TakeINtNtB6_9enumerate9EnumerateINtNtNtBa_5slice4iter7IterMutPNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEENtNtNtB8_6traits8iterator8Iterator3nthB1X_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit18h_store_subscr_ref +_RNvYINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxShENtCshfZExtisgX1_16weavepy_compiler9CodeBytes4readBG_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records10enter_more +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_load_methods1_0B5_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native14count_elements +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native17deque_rotate_leaf +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native21chainmap_getitem_leaf +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6h_calls_0B5_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11heapq_accel5build +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11heapq_accel7heapifyINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_nativeNtB2_10DequeState10bump_state +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm5error14TracebackEntryEBF_ +_RINvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_subscr_hotKm1_EB4_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13global_len_of +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueATyINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakNtNtBJ_6object10PyFunctionEbEj3_EBJ_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native11dd_pure_new +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib17collections_odict11leaf_unlink +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native23namedtuple_replace_leaf +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native18namedtuple_replace +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit17store_subscr_fast +_RNvNtCshfZExtisgX1_16weavepy_compiler11native_code6decode +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native15new_named_tuple +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakNtNtBW_6object10PyFunctionEINtBU_2RcNtCshfZExtisgX1_16weavepy_compiler10CodeObjectEjEENtNtNtNtBb_4iter6traits8iterator8Iterator3anyNCNvNtNtBW_6stdlib18collections_native18namedtuple_replace0EBW_ +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower16store_subscr_ref +_RINvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_setitem_hotKm0_EB4_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter26instance_setitem_leaf_slow +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter17core_local_methodKb0_Es0_0B8_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18core_init_on_frame +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records11left_slowly +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native10tally_dict0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native9tally_one +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11heapq_accel6siftup +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native12deque_rotate +_RNvMs8_NtCs9NJVNhcGWEq_10weavepy_vm7dictmapINtB5_5TableNtNtB7_6object6ObjectE10move_indexB7_ +_RNvMsN_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_8DictData7reserve +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11class_lacks +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11heapq_accel7heap_lt +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11heapq_accel8siftdown +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native21builtin_factory_value +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_nativeNtB2_10DequeState8set_head +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter24cached_slot_name_matches +_RNvNvNtCshfZExtisgX1_16weavepy_compiler11native_code12check_nested14check_constant +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records14ctor_direct_kw +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit7records14h_direct_leave +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types22install_object_dunders14object_delattr +_RNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types30install_mutable_container_init9list_init +_RNvCs9NJVNhcGWEq_10weavepy_vm10bm_builtin +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter14lean_getter_ok +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12bisect_accel5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4math8log_fast +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile8getvalue +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile8readable +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile16unbridge_on_read +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter21leaf_fused_local_attr +_RNvCs9NJVNhcGWEq_10weavepy_vm20property_site_getter +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB13_6object10PyFunctionEIBZ_NtCshfZExtisgX1_16weavepy_compiler10CodeObjectEEEEB13_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze16has_native_cycle +_RNvMsg_NtCs9NJVNhcGWEq_10weavepy_vm8gc_traceNtB5_7GcState12untrack_slot +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter11str_payload +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16do_reversed_call +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins19bytes_splitlines_kwINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1J_EEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10bytes_join +_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE14extend_trustedINtNtCsevLNFiNqfJP_4core6option8IntoIterBG_EEBK_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9file_readINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9file_seekINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBG_6object6PyFileEEBG_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14file_readlinesINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18file_readline_fast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier216builtin_seq_step +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10h_property +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15direct_call_out +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18bytearray_byte_arg +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot12set_non_leaf +_RNvYNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types22install_object_dunders14object_delattrINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter24generic_delattr_instance +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16seq_dunder_binop0B5_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm12type_surface21list_reversed_builtin +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEB1e_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11random_core11random_init +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11random_core8store_mt +_RNvMsN_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_8DictData20track_deferred_owner +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter13core_gen_make0B7_ +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile11read_text_n +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile11decode_text +_RNvNvNtNtNtCs4H1No5ph5dL_6memchr4arch6x86_646memchr11memchr2_raw9find_avx2 +_RNvMsT_Cs9NJVNhcGWEq_10weavepy_vmNtB5_15NativeTruthPlan3run +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14set_isdisjointINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17str_payload_class +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4math8exp_fast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9file_read +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9file_seek +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object20memtext_byte_of_char +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14file_readlines +_RNCNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB8_6PyFile14next_line_pures_0Ba_ +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_coreKb1_EsD_0B8_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9attr_misss2_0B5_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16str_removesuffix +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14file_read_line +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer11emit_is_obj +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11h_gen_yield +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11list_append +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10bytes_data +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11random_core5build +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11random_core11random_seed +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16str_removesuffixINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile13utf8_identity +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13file_readline +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile14next_line_pure +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile15read_line_bytes +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object9line_take +_RNvNvNtNtNtCs4H1No5ph5dL_6memchr4arch6x86_646memchr11memchr2_raw6detect +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13file_truncate +_RNvNtCs9NJVNhcGWEq_10weavepy_vm10specialize15record_dispatch +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212wpjit_is_obj +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214wpjit_iter_new +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215wpjit_iter_next +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13property_call +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11list_appendINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RINvMs2_NtNtCsgHYyB3hU8Ec_3std6thread5localINtB6_8LocalKeyINtNtCs9NJVNhcGWEq_10weavepy_vm3gil15ReleaseUnderGilINtNtCsevLNFiNqfJP_4core4cell7RefCellNtNtBZ_5tier28JitStateEEE4withNCNvB2n_16try_enter_resume0INtNtB1P_6option6OptionNtB2n_13CompiledEntryEEBZ_ +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile23translate_newlines_read +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18stream_text_object +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile4seek +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile9text_plan +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins13file_truncateINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter15gen_method_send +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9descr_get +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit18site_property_note +_RNvNtCs9NJVNhcGWEq_10weavepy_vm12type_surface15obj_len_builtin +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16core_super_other +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14set_isdisjoint +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10bytes_join0B5_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm6object14GeneratorStateEBF_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter18start_generator_at +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile21text_incr_active_gate +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell10UnsafeCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTmmINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1F_9inst_dict10SharedKeysEEEEEB1F_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBG_6object11PyGeneratorEEBG_ +_RNvYNvNvNtCs9NJVNhcGWEq_10weavepy_vm13builtin_types30install_mutable_container_init9list_initINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins14set_isdisjoints1_0B5_ +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9method_kwNvB4_19bytes_splitlines_kwEs_0B6_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10bytes_joinINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13box_gen_frame +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5error19stop_iteration_with +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11random_core17seed_from_entropy +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins18file_getvalue_fast +_RNvMs1o_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB6_6PyFile8truncate +_RNCNvNtCs4bqUF11K40R_11weavepy_jit7analyze13step_abstractsa_0B5_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214iter_next_rest +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214pack_iter_elem +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit18property_leaf_here +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10h_property0B5_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_fold_yield +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastNtNtB4_9inst_dict10SharedKeysEB4_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13prologue_cell +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline14h_inline_deref +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14leaf_call_lane +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit21h_make_function_attrs +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inlineNtB7_5Lower17inline_load_deref +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_delete_fast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14h_load_closure +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecTjjINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcSbEEEEEB2l_ +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastSbEB4_ +_RNvMsn_NtCscdyiIoZL7b2_10num_bigint6bigintNtB5_6BigInt11parse_bytes +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16parse_int_strings_0B5_ +_RNvXs_NtNtCscdyiIoZL7b2_10num_bigint7biguint7convertNtB6_7BigUintNtCsiImLG5VQbrW_10num_traits3Num14from_str_radix +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_store_deref +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins16parse_int_string +_RINvNtCs9NJVNhcGWEq_10weavepy_vm5error11index_errorReEB4_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcSbE9drop_lastB7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12lane_outcome +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower12int_true_div +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable9quicksort9quicksortTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectB18_ENCINvMB8_SB17_16sort_unstable_byNCNvNtNtB1c_6stdlib10json_accel10sort_itemss_0E0EB1c_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel10sort_items +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort18small_sort_generalTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectB1g_ENCINvMB8_SB1f_16sort_unstable_byNCNvNtNtB1k_6stdlib10json_accel10sort_itemss_0E0EB1k_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort12sort4_stableTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectB1a_ENCINvMB8_SB19_16sort_unstable_byNCNvNtNtB1e_6stdlib10json_accel10sort_itemss_0E0EB1e_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core3num3imp7dec2flt6lemire13compute_floatdEBa_ +_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort8unstable7ipnsortTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectBU_ENCINvMB6_SBT_16sort_unstable_byNCNvNtNtBY_6stdlib10json_accel10sort_itemss_0E0EBY_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib10json_accel12write_indent +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline8kw_names +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer12emit_int_neg +_RNvXs0_NtCsjIWZ3EBbJCG_15weavepy_codegen3x64NtB5_3X64NtNtB7_3asm3Asm3neg +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit16native_body_here +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jitNtB5_5Lower7set_out +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter8all_fast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter8any_fast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13k_list_insert +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit3CtxEBH_ +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4fmul +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_call_native +_RNvMs_NtCsjIWZ3EBbJCG_15weavepy_codegen7builderNtB4_15FuncInstBuilder4ineg +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10list_index +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter12any_all_fast +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11list_insert +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10list_indexINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9h_map_add +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_site_native +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit7h_unary +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11list_insertINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15h_for_iter_pair +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15h_for_iter_view +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2os9os_getpid +_RNvMs2_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtB5_10SharedKeys12names_before +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtB1a_6option6OptionTINtNtCs1C1lLj4PWSY_5alloc3vec3VechENtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEEEB2H_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218inline_method_bodys1_0B5_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_7PyFrame14current_lineno +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time13time_strftime +floor +_RNvMsc_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_5Lower12load_special +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit16class_poly_prove +_RNvMs0_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_7PyFrame10back_frame +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time14time_localtime +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time8zone_str +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object21bigint_from_f64_trunc +_RNvCs9NJVNhcGWEq_10weavepy_vm27percent_format_leaf_mapping +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14h_contains_ref +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12weakref_real11ref_type_eq +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline14h_inline_store +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time8gettmarg +_RNvNtNtNtCs4d4ibTJ6dSQ_17compiler_builtins4math9libm_math4fmod4fmod +_RNvCs9NJVNhcGWEq_10weavepy_vm10format_int +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline19h_inline_attr_local +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object9member_eq +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtNtCsevLNFiNqfJP_4core4cell4once8OnceCellINtNtCs1C1lLj4PWSY_5alloc2rc2RcSNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyEEEB2o_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time14strftime_chunk +fmod +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline20h_inline_method_note +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14h_load_special +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time16strftime_bridged +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time7checktm +_RNvXs0_NvMs_NtNtCs1C1lLj4PWSY_5alloc3ffi5c_strNtBa_7CString3newReNtB5_11SpecNewImpl13spec_new_impl +_RINvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14h_contains_hotKm0_EB4_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecTmNtNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline9FieldMemoEE8grow_oneBU_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14h_compare_site +_RINvMNtNtCsevLNFiNqfJP_4core4cell4onceINtB3_8OnceCellINtNtCs1C1lLj4PWSY_5alloc2rc2RcSNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyEE8try_initNCINvB2_11get_or_initNCNCNvNtNtB1p_6stdlib4time16struct_time_keys00E0zEB1p_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4time8gettmargs0_0B7_ +_RINvMs3_NtCs1C1lLj4PWSY_5alloc3stre7replaceAcj2_ECs9NJVNhcGWEq_10weavepy_vm +_RNvMs4_CshfZExtisgX1_16weavepy_compilerNtB5_7JitHint9loop_free +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline17h_inline_for_iter +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17core_load_special +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit17h_attr_local_slot +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14type_name_site +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13spread_direct +_RNCNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB7_11Interpreter26leaf_cached_instance_fields0_0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_unpack_ref +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jitNtB5_5Lower12inline_field +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9h_call_ex +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib2os19path_splitroot_fast +_RNvMs3_NtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jitNtB5_5Lower17inline_class_attr +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15spread_on_frame +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit15call_ex_general +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_store_attr +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject20fully_qualified_name +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionTRNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyRNtBM_6ObjectEE6filterNCNvMs7_BO_NtBO_11Interpreter26leaf_cached_instance_field0EBO_ +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit7h_fieldKb0_EB6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit15laid_out_member +_RNvMsd_NtCs9NJVNhcGWEq_10weavepy_vm5typesNtB5_10TypeObject13display_names +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer16emit_build_tuple +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17quiet_native_step +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan3jit6h_attrKb0_EB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit12h_str_eq_ref +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit17type_attr_resolve +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit14k_str_endswith +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionRNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE7or_elseNCNvMs7_BN_NtBN_11Interpreter26leaf_cached_instance_fields0_0EBN_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11spread_ctor +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionTRNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyRNtBM_6ObjectEE6filterNCNvMs7_BO_NtBO_11Interpreter21specialized_load_attrs0_0EBO_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit9type_attr +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13spread_native +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12scanner_next +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12scanner_step +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit6inline17h_inline_defaults +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13h_iter_dunder +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcDNtNtB4_3any3AnyNtNtB4_6marker4SendNtB1u_4SyncEL_EEBG_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects15pattern_scanner +_RNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12with_patternINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB8_6object6ObjectNtNtB8_5error12RuntimeErrorENCNvB4_15pattern_scanner0E0B8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects11match_start +_RINvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objectsNtB3_7Subject4execTINtNtCsevLNFiNqfJP_4core6result6ResultNtNtB7_6object6ObjectNtNtB7_5error12RuntimeErrorEjjENCNvB3_12scanner_steps1_0EB7_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12scanner_step0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects16pattern_finditer +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtBW_6string6StringxEEEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_NtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs9NJVNhcGWEq_10weavepy_vm +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objectsNtB2_7Subject3new +_RNCINvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit11direct_doneKb1_Es0_0B6_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects15cached_template +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects12scanner_iter +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects7SubjectEBH_ +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterhENtNtNtNtBb_4iter6traits8iterator8Iterator8positionNCINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib7sre_mod4scanhNvB1L_9uni_spaceE0EB1P_ +_RNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11sre_objects15pattern_findall00B9_ +_RNvMs2_NtCs9NJVNhcGWEq_10weavepy_vm9frame_jitNtB5_6Native9note_fail +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_zfillINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10str_centerINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins9str_zfill +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11str_isalnumINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11str_isalnum +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10str_center +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins10pad_around +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit10k_str_find +_RNvNtCs9NJVNhcGWEq_10weavepy_vm9frame_jit13k_str_replace +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native10new_packed +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native12leaf_compare +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native16dt_fromisoformat +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native7installs4_0B7_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native10leaf_fields0_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native6dt_add +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native6td_mul +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_nativeNtB2_11PackedSlots11release_aux +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17core_native_field +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native11date_fields +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native9parse_hms +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native15construct_names +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native10leaf_binop +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native6td_cmp +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native7ymd2ord +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native5tz_of +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native15dt_shift_in_day +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter19core_native_compare +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native8push_ymd +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native6new_td +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native8verified +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native7recycle +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_nativeNtB2_11PackedSlots11free_values +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native10leaf_field +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native12date_weekday +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native9dt_fields +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter17core_native_binop +_RNvNtNtCsevLNFiNqfJP_4core4char7methods15encode_utf8_raw +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native8push_hms +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native16strftime_numeric +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native8date_sub +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native9td_fields +_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBL_5types10PyInstanceEE14extend_trustedINtNtCsevLNFiNqfJP_4core6option8IntoIterBG_EEBL_ +_RNvNvNtNtCsevLNFiNqfJP_4core5slice5ascii8is_ascii7runtime +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native11dt_strftime +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native11verify_slow +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native10valid_date +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native6new_dt +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxSINtNtNtCsevLNFiNqfJP_4core4sync6atomic6AtomicbEEE10initializeNCINvB2_11get_or_initNCNvCs9NJVNhcGWEq_10weavepy_vm16native_site_notes_0E0zEB2R_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native6dt_sub +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native9dt_packed +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native10leaf_fields1_0B7_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native14date_toordinal +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native12dt_isoformat +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native8push_num +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native13format_offset +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native11text_object +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native12date_replace +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib15datetime_native8new_date +_RINvXs_NtNtNtCsevLNFiNqfJP_4core4iter8adapters4skipINtB5_4SkipINtNtB7_9enumerate9EnumerateINtNtNtBb_5slice4iter4IterINtNtBb_6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEEEENtNtNtB9_6traits8iterator8Iterator8try_folduNCINvNvB2Z_3all5checkTjRB1Q_ENCNvMs_NtB2g_6engineNtB4h_12InlineMethod2ofs1_0E0INtNtNtBb_3ops12control_flow11ControlFlowuEEB2g_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214wpjit_attr_set +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs4bqUF11K40R_11weavepy_jit2ir5TStmtENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvMs_NtBU_6engineNtB2l_12InlineMethod2ofs5_0EBU_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecmEINtB4_18SpecFromIterNestedmINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB1F_5slice4iter4IterNtNtCs4bqUF11K40R_11weavepy_jit2ir12AttrSiteMetaENCNvMs_NtB2P_6engineNtB3F_12InlineMethod2ofs9_0EE9from_iterB2P_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218wpjit_dyn_attr_get +_RINvNtNtCsevLNFiNqfJP_4core4iter8adapters11try_processINtNtB2_3map3MapINtNtNtB6_5slice4iter4IterINtNtB6_6option6OptionNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEENCNvMs_NtB1W_6engineNtB2K_12InlineMethod2ofs4_0EB1S_IB1x_NtNtB6_7convert10InfallibleENCINvXsI_B1z_IB1x_INtNtCs1C1lLj4PWSY_5alloc3vec3VecB1S_EEINtNtNtB4_6traits7collect12FromIteratorB1w_E9from_iterBQ_E0B4i_EB1W_ +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_tinyKb0_Es0_0B8_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer14emit_unbox_int +_RNCINvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB8_11Interpreter9leaf_tinyKb0_Es_0B8_ +_RNvMs6_NtCs9NJVNhcGWEq_10weavepy_vm5tier2NtB5_8JitState21resolve_native_callee +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218callee_guards_hold +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs4bqUF11K40R_11weavepy_jit5value7JitTypeEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2q_5slice4iter4IterNtNtB17_2ir12AttrSiteMetaENCNvMs_NtB17_6engineNtB43_12InlineMethod2ofs8_0EE9from_iterB17_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214wpjit_list_get +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtCs4bqUF11K40R_11weavepy_jit2ir3TOpEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB2j_5slice4iter4IterNtB15_5TStmtENCNvMs_NtB17_6engineNtB3J_12InlineMethod2ofs6_0EE9from_iterB17_ +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCsevLNFiNqfJP_4core6option6OptionINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan8LeafPlanEEE10initializeNCINvB2_11get_or_initNCINvMs8_B26_NtB28_11Interpreter12leaf_run_retKb0_Kb1_KB4c_E0E0zEB28_ +_RNCNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier212warm_compile0s8_0B7_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier222note_callee_roundtrips +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer19inline_method_guard +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier232scalar_update_class_value_stable +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier216probe_ctor_field +_RINvXs_NtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elembNtB5_12SpecFromElem9from_elemNtNtB9_5alloc6GlobalECs4bqUF11K40R_11weavepy_jit +_RINvXNtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemNtNtCs4bqUF11K40R_11weavepy_jit6engine7FieldAtNtB3_12SpecFromElem9from_elemNtNtB7_5alloc6GlobalEBP_ +_RNvMsS_Cs9NJVNhcGWEq_10weavepy_vmNtB5_10MethodSlot12peek_unbound +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs4bqUF11K40R_11weavepy_jit6engine12InlineMethodEBF_ +_RNCNvNtCs9NJVNhcGWEq_10weavepy_vm5tier218wpjit_dyn_attr_get0B5_ +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter16leaf_site_getter +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer23emit_call_method_inline +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215wpjit_unbox_int +_RINvXs2J_NtNtCsevLNFiNqfJP_4core5slice4iterINtB7_4IterNtNtCs4bqUF11K40R_11weavepy_jit2ir12AttrSiteMetaENtNtNtNtBb_4iter6traits8iterator8Iterator3allNCNvMs_NtBU_6engineNtB2t_12InlineMethod2ofs3_0EBU_ +_RNvXs_NtNtCs1C1lLj4PWSY_5alloc3vec21spec_from_iter_nestedINtB6_3VecNtNtB8_6string6StringEINtB4_18SpecFromIterNestedB13_INtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtNtB22_5slice4iter4IterNtNtCs4bqUF11K40R_11weavepy_jit2ir12AttrSiteMetaENCNvMs_NtB3c_6engineNtB42_12InlineMethod2ofs7_0EE9from_iterB3c_ +_RINvXs_NtNtCs1C1lLj4PWSY_5alloc3vec14spec_from_elemyNtB5_12SpecFromElem9from_elemNtNtB9_5alloc6GlobalECs4bqUF11K40R_11weavepy_jit +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE7or_elseNCNvNtBM_5tier218wpjit_dyn_attr_gets_0EBM_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native15deque_make_iter +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native19deque_iterator_next +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5error14stop_iteration +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec6splice6SpliceINtNtNtNtB4_4iter7sources8repeat_n7RepeatNNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectEEEB24_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native10deque_next +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native16deque_appendleft +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18collections_native10deque_iter +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4math8cos_fast +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib4math8sin_fast +_RNvMNtCs9NJVNhcGWEq_10weavepy_vm8gen_fastNtB4_11Interpreter17gen_fast_for_iter +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214wpjit_list_len +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer13emit_list_set +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer20emit_list_from_range +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer15emit_list_slice +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable5drift4sortTmNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSBW_7sort_byNCNvMNtB12_7codegenINtB2w_3GenNtNtB12_3x643X64E11choose_pinss0_0E0EB12_ +_RNvNtCs4bqUF11K40R_11weavepy_jit7analyze15fuse_int_result +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable9quicksort9quicksortTmNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB15_7sort_byNCNvMNtB1b_7codegenINtB2G_3GenNtNtB1b_3x643X64E11choose_pinss0_0E0EB1b_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer21emit_list_append_keep +_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable14driftsort_mainTmNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSBZ_7sort_byNCNvMNtB15_7codegenINtB2z_3GenNtNtB15_3x643X64E11choose_pinss0_0E0INtNtB1S_3vec3VecBZ_EEB15_ +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared9smallsort12sort8_stableTmNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValueENCINvMNtCs1C1lLj4PWSY_5alloc5sliceSB19_7sort_byNCNvMNtB1f_7codegenINtB2K_3GenNtNtB1f_3x643X64E11choose_pinss0_0E0EB1f_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter14list_sort_fast +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer9list_elem +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapjTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc4WeakNtNtB1D_6object9BuiltinFnENtNtB1D_13leaf_builtins5EntryENtNtB1D_8fasthash13FxBuildHasherEEB1D_ +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real21start_joinable_threadINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1Y_EEE4callB8_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real19spawn_python_worker +_RNvMs1_NtCsDlJtCLYfsZ_16parking_lot_core11parking_lotNtB5_10ThreadData3new +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native12installed_as +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native16fire_switch_hook +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs9NJVNhcGWEq_10weavepy_vm11InterpreterEBD_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm6import11ModuleCacheEBF_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm6object9BuiltinFnE9drop_slowBK_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm15thread_registry11ThreadEntryE9drop_slowBK_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native8is_exact +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native8new_dict +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTyyEE14reserve_rehashNCINvNtB8_3map11make_hasheryyNtNtNtCsgHYyB3hU8Ec_3std4hash6random11RandomStateE0ECs9NJVNhcGWEq_10weavepy_vm +_RNvNtCs9NJVNhcGWEq_10weavepy_vm13vm_singletons26install_seed_builtin_types +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtB7_3vec3VecNtNtBL_6object6ObjectEEE9drop_slowBL_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapNtNtCs1C1lLj4PWSY_5alloc6string6StringyEEE9drop_lastB7_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real25make_thread_handle_objects_0B7_ +_RNvMs1_NtNtCsgHYyB3hU8Ec_3std6thread9lifecycleINtB5_9JoinInneruE4joinCs9NJVNhcGWEq_10weavepy_vm +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcDNtNtCsevLNFiNqfJP_4core3any3AnyNtNtBO_6marker4SendNtB1h_4SyncEL_E9drop_lastB7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapReFG_RL0_NtNtB7_6import11ModuleCacheEIBB_NtNtB7_6object8PyModuleEEEE9drop_lastB7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCsevLNFiNqfJP_4core6option6OptionTNtNtB7_6object6ObjectIB15_B2e_EIB15_TNtNtB19_6string6StringB2e_EEEEEEE9drop_lastB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value7ThinArcNtNtB1e_13tuple_storage12TupleStorageEEEB1e_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real12lock_release +_RNvMs_NtCs3pgaDf2SUin_11parking_lot7condvarNtB4_7Condvar15notify_one_slow +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native7ctx_run +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellNtNtNtB7_6stdlib10os_process14AtForkHandlersEE9drop_lastB7_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs7UfkFU4le9s_8lock_api5mutex5MutexNtNtCs3pgaDf2SUin_11parking_lot9raw_mutex8RawMutexINtNtCsevLNFiNqfJP_4core6option6OptionIBx_NtNtCs9NJVNhcGWEq_10weavepy_vm15thread_registry11ThreadEntryEEEE9drop_slowB2S_ +_RINvMsi_NtCs9NJVNhcGWEq_10weavepy_vm9inst_dictNtNtB8_5types10PyInstance14attr_index_mapINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB8_6object6ObjectENCNvMs7_B8_NtB8_11Interpreter21specialized_load_attr0EB8_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtB7_3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtB11_4sync7GilCellNtNtB11_6object6ObjectEEEE9drop_slowB11_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native5enter +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm6object5RangeE9drop_slowBK_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm6object10PyDictViewE9drop_slowBK_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellINtNtB7_3vec3VecINtNtBL_2rc2RcNtNtBL_6object10FrameShellEEEE9drop_slowBL_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm7seqiter9next_fast +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native4call +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazy7destroyNtNtCsDlJtCLYfsZ_16parking_lot_core11parking_lot10ThreadDataECs3pgaDf2SUin_11parking_lot +_RNvNtCsDlJtCLYfsZ_16parking_lot_core11parking_lot16create_hashtable +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellNtNtBL_6object8DictDataEE9drop_slowBL_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellDNtNtNtCsevLNFiNqfJP_4core2io5write5WriteNtNtB1b_6marker4SendNtB1L_4SyncEL_EE9drop_lastB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_4cell10UnsafeCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB1C_6object10FrameShellEEEEB1C_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCsgHYyB3hU8Ec_3std6thread9lifecycle6PacketuEECs9NJVNhcGWEq_10weavepy_vm +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native4exit +_RNvMsA_NtCs9NJVNhcGWEq_10weavepy_vm4syncNtB5_8RealLock9wait_free +_RNvMs_NtCs3pgaDf2SUin_11parking_lot7condvarNtB4_7Condvar19wait_until_internal +_RINvMs0_NtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native4lazyINtB6_7StorageNtNtCsDlJtCLYfsZ_16parking_lot_core11parking_lot10ThreadDatauE16get_or_init_slowNvNvNvB1g_16with_thread_data11THREAD_DATA27___rust_std_internal_init_fnECs3pgaDf2SUin_11parking_lot +_RNvMsf_NtCs9NJVNhcGWEq_10weavepy_vm4syncINtB5_7GilCellAjj3_E21try_borrow_mut_lockedB7_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm13tuple_storage12TupleStorageE9drop_slowBK_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native6run_in +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real20join_wait_collecting +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellNtNtBL_6object6ObjectEE9drop_slowBL_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs9NJVNhcGWEq_10weavepy_vm4sync7GilCellNtNtBL_6object10PyIteratorEE9drop_slowBL_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellINtNtCsevLNFiNqfJP_4core6option6OptionNtNtCs1C1lLj4PWSY_5alloc6string6StringEEE9drop_lastB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtCs9NJVNhcGWEq_10weavepy_vm7LeafFnsEBD_ +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell7RefCellINtNtB1a_6option6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtB28_5types10TypeObjectEEEEB28_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native11new_mapping +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm6object11BoundMethodE9drop_slowBK_ +_RNSNvYNCINvNtNtCsgHYyB3hU8Ec_3std6thread9lifecycle15spawn_uncheckedNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real19spawn_python_workers1_0uEs_0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceuE9call_once6vtableB1b_ +_RNvMsf_NtCs9NJVNhcGWEq_10weavepy_vm4syncINtB5_7GilCellAjj3_E17try_borrow_lockedB7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_13builtin_types12BuiltinTypesE9drop_lastB7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecIBB_NtNtB7_6object10FrameShellEEEE9drop_lastB7_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcINtNtB7_4sync7GilCellINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapyNtNtCs1C1lLj4PWSY_5alloc6string6StringEEE9drop_lastB7_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm6object10FrameShellE9drop_slowBK_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real12reap_workers +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value10StrStorageE9drop_slowBK_ +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native7ctx_runINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectRSTNtNtCs1C1lLj4PWSY_5alloc6string6StringB1Q_EEE4callB8_ +_RNCINvMs18_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB9_9BuiltinFn11with_kwargsNvNtNtBb_6stdlib11thread_real21start_joinable_threadEs_0Bb_ +_RINvNtNtCsgHYyB3hU8Ec_3std3sys9backtrace28___rust_begin_short_backtraceNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib11thread_real19spawn_python_workers1_0uEB1f_ +_RNvMsf_NtCs9NJVNhcGWEq_10weavepy_vm4syncINtB5_7GilCellINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtNtNtCsgHYyB3hU8Ec_3std11collections4hash3map7HashMapINtNtBV_5boxed3BoxeEINtNtCsevLNFiNqfJP_4core6option6OptionNtNtB7_6object6ObjectENtNtB7_8fasthash13FxBuildHasherEEE17try_borrow_lockedB7_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm15thread_registry11ThreadEntryEBF_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec9into_iter8IntoIterINtNtNtCsgHYyB3hU8Ec_3std6thread11join_handle10JoinHandleuEEECs9NJVNhcGWEq_10weavepy_vm +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value12SliceStorageNtNtBL_6object7DictKeyEE9drop_slowBL_ +_RNvMsA_NtCs9NJVNhcGWEq_10weavepy_vm4syncNtB5_8RealLock15acquire_timeout +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native12ctx_receiver +_RNvYNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib18contextvars_native10is_context0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceTRNtB6_5StateEE9call_onceBa_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm5types10PyInstanceE9drop_slowBK_ +_RNvMNtCsDlJtCLYfsZ_16parking_lot_core11parking_lotNtB2_9HashTable3new +_RNvNtCs9NJVNhcGWEq_10weavepy_vm4sync11revoke_bias +_RNvNtCsDlJtCLYfsZ_16parking_lot_core11parking_lot16lock_bucket_pair +_RNvMs7_Cs9NJVNhcGWEq_10weavepy_vmNtB5_11Interpreter13delete_subscr +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtB7_6import14FrozenRegistryE9drop_lastB7_ +_RINvMs_NtNtNtCs1C1lLj4PWSY_5alloc11collections5btree6removeINtNtB7_4node6HandleINtBY_7NodeRefNtNtBY_6marker3MutyINtNtBb_4sync3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm15thread_registry11ThreadEntryENtB1v_4LeafENtB1v_2KVE14remove_leaf_kvNCINvMsV_NtB7_3mapINtB3N_14ExtractIfInneryB1M_NtNtNtCsevLNFiNqfJP_4core3ops5range9RangeFullE4nextNCINvMsi_B3N_INtB3N_8BTreeMapyB1M_E6retainNCNvMs0_B25_NtB25_14ThreadRegistry21take_finished_handles0E0NtNtBb_5alloc6GlobalE0B6R_EB27_ +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcINtNtNtCsgHYyB3hU8Ec_3std6thread9lifecycle6PacketuEE9drop_slowCs9NJVNhcGWEq_10weavepy_vm +_RNvMs1_NtCs3pgaDf2SUin_11parking_lot9raw_mutexNtB5_8RawMutex9lock_slow +_RNvMsn_NtCs1C1lLj4PWSY_5alloc4syncINtB5_3ArcNtNtCs9NJVNhcGWEq_10weavepy_vm6object10PyFunctionE9drop_slowBK_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBG_6object7PyFrameEEBG_ +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel10make_loads +_RNvXNtNtCsevLNFiNqfJP_4core4iter8adaptersINtB2_12GenericShuntINtNtB2_3map3MapINtNtNtB6_5slice4iter4IterReENCNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB1N_20ModuleFunctionsGuard3new0EINtNtB6_6option6OptionNtNtB6_7convert10InfallibleEENtNtNtB4_6traits8iterator8Iterator4nextB1R_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel10make_loads0B7_ +_RNvMs4_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_14UnpicklerGuard5holds +_RNvMsb_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Scratch4keep +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB4_20ModuleFunctionsGuard5holds +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtB4_6option6OptionINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtNtNtB12_6stdlib12pickle_accel6encode9ClassPlanEEEB12_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectBD_EEBH_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtNtNtBG_6stdlib12pickle_accel6encode9ClassPlanEEBG_ +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6newobj +_RNvXs0_NtNtCs1C1lLj4PWSY_5alloc3vec11spec_extendINtB7_3VecTNtNtCs9NJVNhcGWEq_10weavepy_vm6object7DictKeyNtBX_6ObjectEEINtB5_10SpecExtendBU_INtNtB7_9into_iter8IntoIterBU_EE11spec_extendBZ_ +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6intern +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_7PyFrame14compute_locals +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable9quicksort9quicksortNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB15_NtNtBa_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RNvYNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11str_isupperINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB6_6object6ObjectEE4callB6_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm8builtins11str_isupper +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel10make_loadsINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNCNvMs4_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB7_14UnpicklerGuard3news_0Bb_ +_RNvNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel7classes8pure_get +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel10make_dumps +_RNvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB2_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxShEE10try_insertCs9NJVNhcGWEq_10weavepy_vm +_RNvMs_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB4_9MemoTable4grow +_RINvMsk_NtCs1C1lLj4PWSY_5alloc3vecINtB6_3VecNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE14extend_trustedINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB6_5drain5DrainTBG_yEENCNvMsc_NtNtBK_6stdlib12pickle_accelNtB32_7Decoder6extend0EEBK_ +_RNvMs0_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder13save_instance +_RNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel10make_loads00B9_ +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_7PyFrame22has_live_hidden_locals +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecNtNtB7_6string6StringE8push_mutCs9NJVNhcGWEq_10weavepy_vm +_RNvYNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel10make_dumpsINtNtNtCsevLNFiNqfJP_4core3ops8function2FnTRSNtNtB8_6object6ObjectEE4callB8_ +_RNvNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel7classes12plain_layout +_RINvNtCs9NJVNhcGWEq_10weavepy_vm2rc12release_lastNtNtNtNtB4_6stdlib12pickle_accel6encode9ClassPlanEB4_ +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectyEE8push_mutBK_ +_RINvNtNtCs1C1lLj4PWSY_5alloc3vec16in_place_collect18from_iter_in_placeINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3map3MapINtNtB4_9into_iter8IntoIterNtNtB6_6string6StringEINvMs1B_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB2P_6Object8from_strB2l_EEB3o_EB2R_ +_RNvMNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB2_6Framer4data +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder8setitems +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionTNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectyEE6filterNCNvMsc_NtNtBN_6stdlib12pickle_accelNtB1J_7Decoder5parses_0EBN_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel10PlainClassEEB1e_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcINtNtB1d_4sync7GilCellNtNtB1d_6object8DictDataEEEEB1d_ +_RNvNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel7classes14resolve_global +_RNvMsG_NtCs1C1lLj4PWSY_5alloc3vecINtB5_3VecTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBL_5types10TypeObjectEIBw_NtNtBL_6object6ObjectEEE8push_mutBL_ +_RNvNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel7classes14is_member_slot +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB5_2RcNtNtNtNtB7_6stdlib12pickle_accel6encode9ClassPlanE9drop_lastB7_ +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder10build_pair +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel7ScratchEBH_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm6object21materialize_stack_top +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6shared5pivot11median3_recNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYB14_NtNtBa_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB2_13FunctionGuard14holds_function +_RNvMs_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB4_20ModuleFunctionsGuard3new +_RNvXNtNtCsevLNFiNqfJP_4core4iter8adaptersINtB2_12GenericShuntINtNtB2_3map3MapNtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap4IterNCNvMs7_NtNtB1h_6stdlib12pickle_accelNtB22_12PicklerGuard3new0EINtNtB6_6option6OptionNtNtB6_7convert10InfallibleEENtNtNtB4_6traits8iterator8Iterator4nextB1h_ +_RNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel10make_dumps0B7_ +_RNvMs0_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder15save_dict_items +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder9push_memo +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder5tuple +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder7recycle +_RNvNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel7classes16benign_metaclass +_RNvMs_NtCs9NJVNhcGWEq_10weavepy_vm2rcINtB4_2RcNtNtNtNtB6_6stdlib12pickle_accel6encode9ClassPlanE3newB6_ +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder5build +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell4CellINtNtB1a_6option6OptionNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel7ScratchEEEB26_ +_RNvMNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB2_13FunctionGuard3new +_RNvMs5_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_19ClassFunctionsGuard3new +_RNCINvMs0_NtNtCsgHYyB3hU8Ec_3std4sync4onceNtB8_4Once15call_once_forceNCINvMNtBa_9once_lockINtB1b_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxShEE10initializeNCINvB1a_11get_or_initNCNvB1a_10try_insert0E0zE0E0Cs9NJVNhcGWEq_10weavepy_vm +_RINvYINtNtNtNtCsevLNFiNqfJP_4core4iter8adapters3zip3ZipNtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap4IterINtNtNtBc_5slice4iter4IterTINtNtBV_2rc4WeakNtNtBV_5types10TypeObjectENtNtNtBV_6stdlib12pickle_accel13FunctionGuardEEENtNtNtBa_6traits8iterator8Iterator8try_folduNCINvNvB3r_3all5checkTTRNtNtBV_6object7DictKeyRNtB4z_6ObjectERB1Y_ENCNvMs7_B2H_NtB2H_12PicklerGuard5holdss_0E0INtNtNtBc_3ops12control_flow11ControlFlowuEEBV_ +_RNvMs0_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder4save +_RNvMs0_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder18memoized_container +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder5parse +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6extend +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtNtCs1C1lLj4PWSY_5alloc3vec5drain5DrainINtNtCs9NJVNhcGWEq_10weavepy_vm7dictmap6BucketuEEEB1n_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueINtNtCs1C1lLj4PWSY_5alloc3vec3VecTNtNtCs9NJVNhcGWEq_10weavepy_vm12shared_value9SharedStrB19_EEEB1d_ +_RNvMs0_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_12BuiltinGuard5holds +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTjINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtNtNtBW_6stdlib12pickle_accel6encode9ClassPlanEEE14reserve_rehashNCINvNtB8_3map11make_hasherjBR_NtNtBW_8fasthash13FxBuildHasherE0EBW_ +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6global +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder16apply_dict_state +_RNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel5build +_RNvMs0_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder7integer +_RNvMs0_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder7memoize +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueSTINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtBI_5types10TypeObjectEINtNtCs1C1lLj4PWSY_5alloc3vec3VecNtNtBI_6object6ObjectEEEBI_ +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder7memoize +_RNvNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel7classes10slot_names +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapjINtNtCs9NJVNhcGWEq_10weavepy_vm2rc2RcNtNtNtNtBT_6stdlib12pickle_accel6encode9ClassPlanENtNtBT_8fasthash13FxBuildHasherE6insertBT_ +_RNvMs0_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder10save_items +_RNvMs4_NtCs9NJVNhcGWEq_10weavepy_vm6objectNtB5_7PyFrame15locals_snapshot +_RINvNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable14driftsort_mainNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYBZ_NtNtB8_3cmp10PartialOrd2ltINtNtB13_3vec3VecBZ_EECshfZExtisgX1_16weavepy_compiler +_RINvNtNtNtNtCsevLNFiNqfJP_4core5slice4sort6stable5drift4sortNtNtCs1C1lLj4PWSY_5alloc6string6StringNvYBW_NtNtBa_3cmp10PartialOrd2ltECshfZExtisgX1_16weavepy_compiler +_RNvNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encode6encode +_RNvMNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB2_6Framer4open +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionINtNtCs1C1lLj4PWSY_5alloc3vec3VechEE6map_orNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectNCNCNvNtNtB1t_6stdlib12pickle_accel10make_dumps0s_0EB1t_ +_RINvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6decodeNCNCNvB2_10make_loads0s0_0EB6_ +_RINvMNtCsevLNFiNqfJP_4core6optionINtB3_6OptionNtNtCs9NJVNhcGWEq_10weavepy_vm6object6ObjectE6map_orBI_NCNCNvNtNtBM_6stdlib12pickle_accel10make_loads0s1_0EBM_ +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_11ImportGuard7modules +_RNvMs0_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder17memoize_anonymous +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder10build_from +_RINvNtNtNtNtCsgHYyB3hU8Ec_3std3sys12thread_local6native5eager7destroyINtNtCsevLNFiNqfJP_4core4cell4CellINtNtB1a_6option6OptionNtNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encode9MemoTableEEEB28_ +_RINvNtCs1C1lLj4PWSY_5alloc5slice11stable_sortNtNtB4_6string6StringNvYBH_NtNtCsevLNFiNqfJP_4core3cmp10PartialOrd2ltECs9NJVNhcGWEq_10weavepy_vm +_RNvMs1_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_11ImportGuard3new +_RNvMs0_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_12BuiltinGuard3new +_RINvMNtNtCsgHYyB3hU8Ec_3std4sync9once_lockINtB3_8OnceLockINtNtCs1C1lLj4PWSY_5alloc5boxed3BoxShEE10initializeNCINvB2_11get_or_initNCNvB2_10try_insert0E0zECs9NJVNhcGWEq_10weavepy_vm +_RNvMs2_NtCs1C1lLj4PWSY_5alloc7raw_vecNtB5_11RawVecInner11try_reserveCs9NJVNhcGWEq_10weavepy_vm +_RNvMs0_NtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB5_7Encoder3get +_RNvMNtNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel6encodeNtB2_6Framer9end_frame +_RNvMsc_NtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accelNtB5_7Decoder6finish +_RNCNCNvNtNtCs9NJVNhcGWEq_10weavepy_vm6stdlib12pickle_accel10make_dumps00B9_ +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier220wpjit_iter_next_pair +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer14emit_bytes_get +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier215wpjit_bytes_get +_RNvNtCs9NJVNhcGWEq_10weavepy_vm5tier214try_dyn_native +_RNvYNCNvMNtCs4U5RMT44ivg_13weavepy_lexer7scannerNtB7_7Scanner11scan_number0INtNtNtCsevLNFiNqfJP_4core3ops8function6FnOnceThEE9call_onceB9_ +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueANtNtCs9NJVNhcGWEq_10weavepy_vm6object6Objectj4_EBG_ +_RINvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB6_7HashMapTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValuexEBP_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBT_6fxhash8FxHasherEE3getBO_EBT_ +_RNvMs4_NtCs1C1lLj4PWSY_5alloc7raw_vecINtB5_6RawVecyE8grow_oneCsjIWZ3EBbJCG_15weavepy_codegen +_RINvNtCsevLNFiNqfJP_4core3ptr9drop_glueNtNtCs9NJVNhcGWEq_10weavepy_vm9leaf_plan8LeafPlanEBF_ +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen4foldNtB2_4Emit4push +_RINvMs6_NtCskibSv91bgl1_9hashbrown3rawINtB6_8RawTableTTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValuexEBR_EE14reserve_rehashNCINvNtB8_3map11make_hasherBQ_BR_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBV_6fxhash8FxHasherEE0EBV_ +_RNvMs1_NtCskibSv91bgl1_9hashbrown3mapINtB5_7HashMapTNtNtCsjIWZ3EBbJCG_15weavepy_codegen2ir5ValuexEBO_INtNtCsevLNFiNqfJP_4core4hash18BuildHasherDefaultNtNtBS_6fxhash8FxHasherEE6insertBS_ +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer16emit_float_arith +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen4foldNtB2_4Emit4sdiv +_RNvMNtCs4bqUF11K40R_11weavepy_jit5lowerNtB2_7Lowerer17emit_int_to_float +_RNvMNtCsjIWZ3EBbJCG_15weavepy_codegen4foldNtB2_4Emit3imm diff --git a/crates/weavepy-codegen/src/builder.rs b/crates/weavepy-codegen/src/builder.rs index bdb1ee303..b3b0aed1b 100644 --- a/crates/weavepy-codegen/src/builder.rs +++ b/crates/weavepy-codegen/src/builder.rs @@ -24,6 +24,9 @@ pub struct FunctionBuilder<'a> { /// definition serves every use (code generation rematerializes a /// constant where it's used, whatever block defines it). consts: HashMap<(Type, i64), Value>, + /// How many call instructions have been built (see + /// [`Self::calls_emitted`]). + calls: u32, } impl<'a> FunctionBuilder<'a> { @@ -35,6 +38,7 @@ impl<'a> FunctionBuilder<'a> { defs: HashMap::default(), reads: Vec::new(), consts: HashMap::default(), + calls: 0, } } @@ -70,6 +74,12 @@ impl<'a> FunctionBuilder<'a> { FuncRef(self.func.dfg.funcs.len() as u32 - 1) } + /// The number of call instructions built so far: a front end that + /// keeps facts only until the next call compares two readings. + pub fn calls_emitted(&self) -> u32 { + self.calls + } + pub fn create_block(&mut self) -> Block { let b = Block(self.func.dfg.blocks.len() as u32); self.func.dfg.blocks.push(BlockData::default()); @@ -169,7 +179,12 @@ impl<'a> FunctionBuilder<'a> { results: (start, dfg.pool.len() as u32), ty: results.first().copied().unwrap_or(types::I64), }); - dfg.blocks[block.index()].insts.push(inst); + let insts = &mut dfg.blocks[block.index()].insts; + if insts.capacity() == 0 { + // (Most blocks hold a few instructions, many more than four.) + insts.reserve_exact(8); + } + insts.push(inst); inst } @@ -445,6 +460,7 @@ impl FuncInstBuilder<'_, '_> { .iter() .map(|r| r.value_type) .collect(); + self.b.calls += 1; self.b.push(Op::Call(f), args, &rets) } @@ -480,6 +496,7 @@ impl FuncInstBuilder<'_, '_> { let mut all = Vec::with_capacity(args.len() + 1); all.push(callee); all.extend_from_slice(args); + self.b.calls += 1; self.b.push(Op::CallIndirect(sig), &all, &rets) } diff --git a/crates/weavepy-codegen/src/codegen.rs b/crates/weavepy-codegen/src/codegen.rs index 025986cd3..1aa3fccd9 100644 --- a/crates/weavepy-codegen/src/codegen.rs +++ b/crates/weavepy-codegen/src/codegen.rs @@ -18,7 +18,7 @@ use crate::asm::{bit, is_float, Abi, Asm, Cond, Frame, Label, Opnd, Reg, NOREG}; use crate::ir::{condcodes::FloatCC, Alu, Block, Function, Inst, Op, Type, Value, ValueDef}; -use crate::liveness::{analyze, each_use, successors, Analysis, NO_BLOCK}; +use crate::liveness::{analyze, successors, Analysis, NO_BLOCK}; use crate::Error; const NONE: u32 = u32::MAX; @@ -432,12 +432,15 @@ impl Gen<'_, A> { } fn reset(&mut self) { - for v in std::mem::take(&mut self.live) { + // (The vector keeps its room: a reset comes at every block.) + let mut live = std::mem::take(&mut self.live); + for v in live.drain(..) { let i = v.index(); self.tracked[i] = false; self.reg_of[i] = NOREG; self.home_ok[i] = false; } + self.live = live; self.holds = [NONE; 64]; } @@ -649,8 +652,9 @@ impl Gen<'_, A> { fn consume(&mut self, inst: Inst, at: &mut usize) { let mut dead = std::mem::take(&mut self.tmp); dead.clear(); - let f = self.f; - each_use(f, inst, |v| { + let (s, e) = self.an.use_span[inst.index()]; + for j in s as usize..e as usize { + let v = self.an.use_vals[j]; let n = self.arg_next[*at]; *at += 1; if self.tracked[v.index()] { @@ -659,7 +663,7 @@ impl Gen<'_, A> { dead.push(v); } } - }); + } for &v in &dead { if self.tracked[v.index()] && self.next[v.index()] == NONE { self.untrack(v); @@ -779,10 +783,9 @@ impl Gen<'_, A> { } }); } - let mut nuses = 0; + let nuses = self.an.uses_in(b).len(); let mut nres = 0; for &inst in insts { - each_use(f, inst, |_| nuses += 1); nres += f.dfg.results(inst).len(); } self.arg_next.clear(); @@ -794,7 +797,6 @@ impl Gen<'_, A> { let mut at = nuses; let mut rat = nres; let mut call = NONE; - let mut occ = std::mem::take(&mut self.tmp2); for (k, &inst) in insts.iter().enumerate().rev() { let res = f.dfg.results(inst); rat -= res.len(); @@ -813,8 +815,7 @@ impl Gen<'_, A> { ) { call = k as u32; } - occ.clear(); - each_use(f, inst, |v| occ.push(v)); + let occ = self.an.uses_of(inst); at -= occ.len(); for (j, &v) in occ.iter().enumerate() { self.arg_next[at + j] = if self.nu_stamp[v.index()] == stamp { @@ -823,12 +824,11 @@ impl Gen<'_, A> { NONE }; } - for &v in &occ { + for &v in occ { self.nu[v.index()] = k as u32; self.nu_stamp[v.index()] = stamp; } } - self.tmp2 = occ; } /// The first use of `v` in the block `next_uses` ran over. @@ -1440,7 +1440,9 @@ impl Gen<'_, A> { // Take the uses: what dies here needn't survive the call. let mut dead = std::mem::take(&mut self.tmp); dead.clear(); - each_use(f, inst, |v| { + let (s, e) = self.an.use_span[inst.index()]; + for j in s as usize..e as usize { + let v = self.an.use_vals[j]; let n = self.arg_next[*at]; *at += 1; if self.tracked[v.index()] { @@ -1449,7 +1451,7 @@ impl Gen<'_, A> { dead.push(v); } } - }); + } // Save what lives on in the registers the call clobbers: in a free // callee-saved register, or in its slot. let mut survivors = std::mem::take(&mut self.tmp2); diff --git a/crates/weavepy-codegen/src/liveness.rs b/crates/weavepy-codegen/src/liveness.rs index ec2c79459..a76dee597 100644 --- a/crates/weavepy-codegen/src/liveness.rs +++ b/crates/weavepy-codegen/src/liveness.rs @@ -25,9 +25,29 @@ pub(crate) struct Analysis { pub words: usize, /// Values rematerialized where they're used, rather than kept. pub remat: Vec, + /// Every reachable instruction's uses (see [`each_use`]), flat, block + /// by block in emission order: an instruction's are + /// `use_vals[use_span[inst]]`, a block's `use_vals[block_uses[b]]`. + pub use_vals: Vec, + pub use_span: Vec<(u32, u32)>, + pub block_uses: Vec<(u32, u32)>, } impl Analysis { + /// The uses of `inst` (see [`each_use`]), which must be reachable. + #[inline] + pub(crate) fn uses_of(&self, inst: Inst) -> &[Value] { + let (s, e) = self.use_span[inst.index()]; + &self.use_vals[s as usize..e as usize] + } + + /// The uses of `b`'s instructions, in order. + #[inline] + pub(crate) fn uses_in(&self, b: Block) -> &[Value] { + let (s, e) = self.block_uses[b.index()]; + &self.use_vals[s as usize..e as usize] + } + pub(crate) fn live_in(&self, b: Block) -> &[u64] { let at = b.index() * self.words; &self.live_in[at..at + self.words] @@ -203,11 +223,19 @@ pub(crate) fn analyze(func: &Function) -> Analysis { let mut last_pred = vec![NO_BLOCK; nblocks]; let mut table_target = vec![false; nblocks]; let mut uses = vec![0u32; dfg.values.len()]; + // (Each instruction's uses, once: every later walk reads them flat.) + let mut use_span = vec![(0u32, 0u32); dfg.insts.len()]; + let mut use_vals: Vec = Vec::with_capacity(dfg.insts.len() * 2); + let mut block_uses = vec![(0u32, 0u32); nblocks]; for &b in &order { + let block_start = use_vals.len() as u32; for &inst in &dfg.blocks[b.index()].insts { inst_block[inst.index()] = b.0; - each_use(func, inst, |v| uses[v.index()] += 1); + let start = use_vals.len() as u32; + each_use(func, inst, |v| use_vals.push(v)); + use_span[inst.index()] = (start, use_vals.len() as u32); } + block_uses[b.index()] = (block_start, use_vals.len() as u32); if let Some(&last) = dfg.blocks[b.index()].insts.last() { let table = matches!(dfg.insts[last.index()].op, Op::BrTable(_)); successors(func, last, |s| { @@ -217,6 +245,9 @@ pub(crate) fn analyze(func: &Function) -> Analysis { }); } } + for &v in &use_vals { + uses[v.index()] += 1; + } // The function's entry is an edge of its own. preds[entry.index()] += 1; let single_pred: Vec = (0..nblocks) @@ -256,18 +287,17 @@ pub(crate) fn analyze(func: &Function) -> Analysis { for &b in &order { let start = ue.len(); ue_at.push(start as u32); - for &inst in &dfg.blocks[b.index()].insts { - each_use(func, inst, |v| { - if !remat[v.index()] && def_block(v) != b.0 { - let mut g = gidx[v.index()]; - if g == u32::MAX { - g = globals.len() as u32; - gidx[v.index()] = g; - globals.push(v); - } - ue.push(g); + let (s, e) = block_uses[b.index()]; + for &v in &use_vals[s as usize..e as usize] { + if !remat[v.index()] && def_block(v) != b.0 { + let mut g = gidx[v.index()]; + if g == u32::MAX { + g = globals.len() as u32; + gidx[v.index()] = g; + globals.push(v); } - }); + ue.push(g); + } } let list = &mut ue[start..]; list.sort_unstable(); @@ -357,5 +387,8 @@ pub(crate) fn analyze(func: &Function) -> Analysis { live_in, words, remat, + use_vals, + use_span, + block_uses, } } diff --git a/crates/weavepy-codegen/src/x64.rs b/crates/weavepy-codegen/src/x64.rs index 713e6aebd..e891aa85d 100644 --- a/crates/weavepy-codegen/src/x64.rs +++ b/crates/weavepy-codegen/src/x64.rs @@ -1164,6 +1164,13 @@ impl X64 { let j = sites.partition_point(|s| s.0 < o); o - saved[j] }; + // (The sites are in code order: a branch is the `j`th to start, and + // its target's place among them is found once.) + debug_assert!(sites.windows(2).all(|w| w[0].0 < w[1].0)); + let target_at: Vec = sites + .iter() + .map(|s| sites.partition_point(|t| t.0 < s.2)) + .collect(); loop { fill(&mut saved, &short); let mut changed = false; @@ -1171,8 +1178,8 @@ impl X64 { if !short[j] { continue; } - let from = i64::from(moved(&saved, sites[j].0)) + 2; - let to = i64::from(moved(&saved, sites[j].2)); + let from = i64::from(sites[j].0 - saved[j]) + 2; + let to = i64::from(sites[j].2 - saved[target_at[j]]); if !(-128..=127).contains(&(to - from)) { short[j] = false; changed = true; @@ -1197,8 +1204,8 @@ impl X64 { } else { 0xeb }; - let from = i64::from(moved(&saved, start)) + 2; - let rel = i64::from(moved(&saved, target)) - from; + let from = i64::from(start - saved[j]) + 2; + let rel = i64::from(target - saved[target_at[j]]) - from; out.push(op); out.push(rel as i8 as u8); prev = (start + len) as usize; diff --git a/crates/weavepy-compiler/src/lib.rs b/crates/weavepy-compiler/src/lib.rs index f72ff7798..f169758bc 100644 --- a/crates/weavepy-compiler/src/lib.rs +++ b/crates/weavepy-compiler/src/lib.rs @@ -374,6 +374,16 @@ impl JitHint { true } + /// Whether a back edge of the code's loops has been counted (by + /// [`Self::backedge_tick`] or [`Self::backedge_pending`]): the + /// countdown starts at zero and never returns to it. + #[inline] + pub fn backedges_seen(&self) -> bool { + self.backedge_countdown + .load(std::sync::atomic::Ordering::Relaxed) + != 0 + } + /// Whether the tier-2 state has no further interest in this code's /// back edges (see [`Self::set_backedge_quiet`]). #[inline] @@ -1090,7 +1100,13 @@ struct LazyTable { /// The encoding of a module in the code cache's native form (see /// `native_code`): its own bytes, or, say, a mapping of the cache file. -pub struct TableBuffer(Box, std::sync::atomic::AtomicU8); +pub struct TableBuffer( + Box, + std::sync::atomic::AtomicU8, + /// The module's identifiers as pooled names, by number, each made on + /// its first read (see [`TableBuffer::name`]). + std::sync::OnceLock]>>, +); /// Where a [`TableBuffer`] gets its bytes. pub trait CodeBytes: Send + Sync + 'static { @@ -1113,7 +1129,11 @@ impl CodeBytes for Box<[u8]> { impl TableBuffer { pub fn new(bytes: impl CodeBytes) -> Self { - TableBuffer(Box::new(bytes), std::sync::atomic::AtomicU8::new(0)) + TableBuffer( + Box::new(bytes), + std::sync::atomic::AtomicU8::new(0), + std::sync::OnceLock::new(), + ) } /// Whether the module's identifier text is UTF-8, as its first read @@ -1123,6 +1143,28 @@ impl TableBuffer { self.1.load(std::sync::atomic::Ordering::Relaxed) } + /// The pooled name for identifier `i` of the `count` the module has, + /// made from its `text` on its first read: a name the module's code objects + /// share (`self`, `append`) goes through the pool once. + pub(crate) fn name<'t>( + &self, + i: usize, + count: usize, + text: impl FnOnce() -> Option<&'t str>, + ) -> Option { + let memo = self + .2 + .get_or_init(|| (0..count).map(|_| std::sync::OnceLock::new()).collect()); + let Some(slot) = memo.get(i) else { + return Some(crate::name::Name::new(text()?)); + }; + if let Some(name) = slot.get() { + return Some(name.clone()); + } + let name = crate::name::Name::new(text()?); + Some(slot.get_or_init(|| name).clone()) + } + pub(crate) fn set_names_utf8(&self, ok: bool) { self.1 .store(if ok { 1 } else { 2 }, std::sync::atomic::Ordering::Relaxed); @@ -2001,6 +2043,103 @@ impl Drop for Pep563Guard { } } +/// A `def`'s place in the tree being compiled: the addresses of its +/// parameters and body, and the body's length. +type DefKey = (usize, usize, usize); + +fn def_key(args: &AstArguments, body: &[Stmt]) -> DefKey { + ( + std::ptr::from_ref(args) as usize, + body.as_ptr() as usize, + body.len(), + ) +} + +/// A nested `def`'s free names (see [`function_free_names`]) by its place +/// in the module's own tree, kept for one compilation: every enclosing +/// scope asks for them, and a function nested `d` deep was walked `d` +/// times at each of `d` levels (a module of 80 nested closures took 47 ms +/// to compile, CPython 2). +/// +/// Only the `def`s of the tree the compilation was given are remembered +/// (`own`, collected before it starts): that tree lives, unchanged, until +/// the compilation ends, so their addresses name them. The compiler also +/// analyzes copies of statements it makes along the way (a `finally` +/// body's, a class body's), which are freed while it runs: a later copy +/// can land where an earlier one was, and an entry kept under its address +/// would answer for another function (a module then held `__class__` as +/// a free name it has no cell for). +#[derive(Default)] +struct FreeNamesMemo { + own: fxhash::HashSet, + names: fxhash::HashMap>, +} + +thread_local! { + static FREE_NAMES_MEMO: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// Every `def` in `stmts`, at any depth of statements, into `out`. +fn own_defs(stmts: &[Stmt], out: &mut fxhash::HashSet) { + for s in stmts { + match &s.kind { + StmtKind::FunctionDef { args, body, .. } + | StmtKind::AsyncFunctionDef { args, body, .. } => { + out.insert(def_key(args, body)); + own_defs(body, out); + } + StmtKind::ClassDef { body, .. } + | StmtKind::With { body, .. } + | StmtKind::AsyncWith { body, .. } => own_defs(body, out), + StmtKind::If { body, orelse, .. } + | StmtKind::While { body, orelse, .. } + | StmtKind::For { body, orelse, .. } + | StmtKind::AsyncFor { body, orelse, .. } => { + own_defs(body, out); + own_defs(orelse, out); + } + StmtKind::Try { + body, + handlers, + orelse, + finalbody, + .. + } => { + own_defs(body, out); + for h in handlers { + own_defs(&h.body, out); + } + own_defs(orelse, out); + own_defs(finalbody, out); + } + StmtKind::Match { cases, .. } => { + for c in cases { + own_defs(&c.body, out); + } + } + _ => {} + } + } +} + +/// Installs the free-names memo for one compilation of a (folded, so no +/// longer changing) AST, and puts back what was there when it ends. +struct FreeNamesMemoGuard(Option); + +impl FreeNamesMemoGuard { + fn install(module: &Module) -> Self { + let mut memo = FreeNamesMemo::default(); + own_defs(&module.body, &mut memo.own); + FreeNamesMemoGuard(FREE_NAMES_MEMO.with(|m| m.replace(Some(memo)))) + } +} + +impl Drop for FreeNamesMemoGuard { + fn drop(&mut self) { + FREE_NAMES_MEMO.with(|m| *m.borrow_mut() = self.0.take()); + } +} + /// Build the shared per-compilation parameters from caller options + /// the module's own `__future__` imports. fn make_params(module: &Module, opts: CompileOptions) -> CompileParams { @@ -2351,6 +2490,7 @@ fn compile_module_cow( let _pep563 = Pep563Guard::install(params.future_annotations); validate::validate_module(&module, source, params.future_annotations)?; ast_opt::fold_module(module.to_mut(), params.future_annotations); + let _free_names = FreeNamesMemoGuard::install(&module); let line_index = LineIndex::new(source); let mut top = Compiler::new( "".to_owned(), @@ -2408,6 +2548,7 @@ fn compile_interactive_cow( let _pep563 = Pep563Guard::install(params.future_annotations); validate::validate_module(&module, source, params.future_annotations)?; ast_opt::fold_module(module.to_mut(), params.future_annotations); + let _free_names = FreeNamesMemoGuard::install(&module); let line_index = LineIndex::new(source); let mut top = Compiler::new( "".to_owned(), @@ -2496,6 +2637,7 @@ fn compile_eval_cow( let _pep563 = Pep563Guard::install(params.future_annotations); validate::validate_module(&module, source, params.future_annotations)?; ast_opt::fold_module(module.to_mut(), params.future_annotations); + let _free_names = FreeNamesMemoGuard::install(&module); let line_index = LineIndex::new(source); let mut top = Compiler::new( "".to_owned(), @@ -2641,6 +2783,10 @@ struct Compiler { co: CodeObject, constant_index: intern::InternIndex, name_index: intern::InternIndex, + /// The same for `co.varnames`: a function with many locals (generated + /// code, a `namedtuple`'s constructor of a few thousand fields) looks + /// each one up by name at every use. + var_index: intern::InternIndex, kind: CodeKind, /// Which comprehension form this scope lowers (`None` outside /// comprehensions). Drives CPython's "'yield' inside list @@ -3097,6 +3243,7 @@ impl Compiler { co, constant_index: intern::InternIndex::default(), name_index: intern::InternIndex::default(), + var_index: intern::InternIndex::default(), kind, comp_kind: None, bindings: IndexMap::default(), @@ -9968,11 +10115,7 @@ impl Compiler { } fn var_index_or_add(&mut self, name: &str) -> u32 { - if let Some(i) = self.co.varnames.iter().position(|n| n == name) { - return i as u32; - } - self.co.varnames.push(Name::from(name.to_owned())); - (self.co.varnames.len() - 1) as u32 + self.var_index.intern_name(&mut self.co.varnames, name) } fn classify_for_store(&mut self, name: &str) -> Binding { @@ -16545,6 +16688,28 @@ fn class_nested_scope_reads(body: &[Stmt], out: &mut HashSet) { /// reach up even when only written). Decorators, defaults and /// annotations are the enclosing scope's business. fn function_free_names(args: &AstArguments, body: &[Stmt]) -> HashSet { + let key = def_key(args, body); + // (A `def` of the module's own tree, or a copy the compiler made and + // will free: only the former is remembered, see `FreeNamesMemo`.) + let (own, hit) = FREE_NAMES_MEMO.with(|m| match m.borrow().as_ref() { + Some(m) if m.own.contains(&key) => (true, m.names.get(&key).cloned()), + _ => (false, None), + }); + if let Some(names) = hit { + return names; + } + let names = function_free_names_uncached(args, body); + if own { + FREE_NAMES_MEMO.with(|m| { + if let Some(m) = m.borrow_mut().as_mut() { + m.names.insert(key, names.clone()); + } + }); + } + names +} + +fn function_free_names_uncached(args: &AstArguments, body: &[Stmt]) -> HashSet { let mut nested_reads = HashSet::default(); for s in body { collect_reads_stmt_in(s, &mut nested_reads, true); @@ -17911,6 +18076,31 @@ mod tests { compile_module(&module).expect("compile") } + /// The free-names memo answers by address, so it may only keep the + /// `def`s of the tree being compiled: a copy the compiler makes (a + /// class body's, for name mangling) is freed while it runs, and an + /// entry under its address would answer for whatever lands there. + #[test] + fn free_names_memo_keeps_only_the_modules_own_defs() { + let module = parse_module("def f(a):\n return a + outer\n").expect("parse"); + let _guard = FreeNamesMemoGuard::install(&module); + let StmtKind::FunctionDef { args, body, .. } = &module.body[0].kind else { + panic!("expected a def"); + }; + let remembered = |key: DefKey| { + FREE_NAMES_MEMO.with(|m| m.borrow().as_ref().unwrap().names.contains_key(&key)) + }; + let names = function_free_names(args, body); + assert!(names.contains("outer") && !names.contains("a")); + assert!(remembered(def_key(args, body))); + let copy = module.body.clone(); + let StmtKind::FunctionDef { args, body, .. } = ©[0].kind else { + panic!("expected a def"); + }; + assert_eq!(function_free_names(args, body), names); + assert!(!remembered(def_key(args, body))); + } + #[test] fn empty_module_compiles_to_return_none() { let co = compile(""); diff --git a/crates/weavepy-compiler/src/name.rs b/crates/weavepy-compiler/src/name.rs index 71a19aa27..57da1553b 100644 --- a/crates/weavepy-compiler/src/name.rs +++ b/crates/weavepy-compiler/src/name.rs @@ -57,6 +57,13 @@ impl Name { pub fn ptr_eq(a: &Name, b: &Name) -> bool { Arc::ptr_eq(&a.0, &b.0) } + + /// The text's address: equal pooled names share it (a memo keyed by it + /// holds the name, so no other text comes to sit there). + #[inline] + pub fn addr(&self) -> usize { + Arc::as_ptr(&self.0).cast::() as usize + } } /// The pool's hasher (FxHash's): a rotate, an exclusive-or and a diff --git a/crates/weavepy-compiler/src/native_code.rs b/crates/weavepy-compiler/src/native_code.rs index ef8a4e0db..9d80b6172 100644 --- a/crates/weavepy-compiler/src/native_code.rs +++ b/crates/weavepy-compiler/src/native_code.rs @@ -278,6 +278,14 @@ impl<'a> Module<'a> { )) } + /// How many identifiers the module has (see the module docs). + fn identifier_count(&self) -> Option { + let b = self + .bytes + .get(self.names_at..self.names_at.checked_add(4)?)?; + Some(u32::from_le_bytes(b.try_into().ok()?) as usize) + } + /// The text of the identifier numbered `i` (see the module docs). fn identifier(&self, i: usize) -> Option<&'a str> { let bytes = self.bytes; @@ -681,7 +689,9 @@ impl Reader<'_> { /// An identifier [`Writer::name`] wrote. fn name(&mut self, module: &Module) -> Option { let i = usize::try_from(self.uint()?).ok()?; - Some(Name::new(module.identifier(i)?)) + module + .buffer + .name(i, module.identifier_count()?, || module.identifier(i)) } /// A name table [`Writer::names`] wrote. diff --git a/crates/weavepy-compiler/src/validate.rs b/crates/weavepy-compiler/src/validate.rs index e5ee0b3d9..3e154b9d3 100644 --- a/crates/weavepy-compiler/src/validate.rs +++ b/crates/weavepy-compiler/src/validate.rs @@ -249,6 +249,7 @@ impl Validator<'_> { self.visit_annotation(r)?; } let mut params: Vec<(&str, Span)> = Vec::new(); + let mut names: crate::fxhash::HashSet<&str> = crate::fxhash::HashSet::default(); for a in args .posonlyargs .iter() @@ -271,7 +272,7 @@ impl Validator<'_> { a.span, )); } - if params.iter().any(|(n, _)| *n == a.name) { + if !names.insert(a.name.as_str()) { return Err(CompileError::spanned( format!("duplicate argument '{}' in function definition", a.name), a.span, diff --git a/crates/weavepy-conformance/src/ecosystem.rs b/crates/weavepy-conformance/src/ecosystem.rs index 01e517ec8..f07b646d5 100644 --- a/crates/weavepy-conformance/src/ecosystem.rs +++ b/crates/weavepy-conformance/src/ecosystem.rs @@ -848,7 +848,7 @@ fn run_row( trim_reason(&format!("venv creation failed: {}", o.tail())), ) } - Err(TimedOut) => { + Err(TimedOut(_)) => { return RowOutcome::fail( FailStage::Timeout, "venv creation exceeded the wall budget".to_owned(), @@ -884,7 +884,7 @@ fn run_row( trim_reason(&format!("pip install failed: {}", o.tail())), ) } - Err(TimedOut) => { + Err(TimedOut(_)) => { return RowOutcome::fail( FailStage::Timeout, "pip install exceeded the wall budget".to_owned(), @@ -913,10 +913,10 @@ fn run_row( trim_reason(&format!("probe failed: {}", o.tail())), ) } - Err(TimedOut) => { + Err(TimedOut(tail)) => { return RowOutcome::fail( FailStage::Timeout, - "probe exceeded the wall budget".to_owned(), + format!("probe exceeded the wall budget: {tail}"), ) } } @@ -1014,7 +1014,7 @@ fn install_from_sdist( FailStage::Install, trim_reason(&format!("sdist install failed: {}", o.tail())), )), - Err(TimedOut) => Err(RowOutcome::fail( + Err(TimedOut(_)) => Err(RowOutcome::fail( FailStage::Timeout, "sdist install exceeded the wall budget".to_owned(), )), @@ -1116,7 +1116,7 @@ fn run_selftest_stage( match run_with_deadline(&mut cmd, deadline) { Ok(o) if o.success => {} Ok(o) => return fail(format!("selftest deps install failed: {}", o.tail())), - Err(TimedOut) => { + Err(TimedOut(_)) => { return fail("selftest deps install exceeded the selftest budget".to_owned()) } } @@ -1148,7 +1148,9 @@ fn run_selftest_stage( match run_with_deadline(&mut cmd, deadline) { Ok(o) if o.success => (RowStatus::Pass, None), Ok(o) => fail(format!("selftest failed: {}", o.tail_n(50))), - Err(TimedOut) => fail(format!("selftest exceeded the {budget}s selftest budget")), + Err(TimedOut(tail)) => fail(format!( + "selftest exceeded the {budget}s selftest budget: {tail}" + )), } } @@ -1179,7 +1181,7 @@ fn fetch_and_extract_sdist( match out { Ok(o) if o.success => {} Ok(o) => return Err(format!("sdist extract failed: {}", o.tail())), - Err(TimedOut) => return Err("sdist extract exceeded the selftest budget".to_owned()), + Err(TimedOut(_)) => return Err("sdist extract exceeded the selftest budget".to_owned()), } single_subdir(&extract_dir).ok_or_else(|| { format!( @@ -1215,7 +1217,7 @@ fn venv_purelib(python: &Path, deadline: Instant) -> std::result::Result Err(format!("sysconfig probe failed: {}", o.tail())), - Err(TimedOut) => Err("sysconfig probe exceeded the selftest budget".to_owned()), + Err(TimedOut(_)) => Err("sysconfig probe exceeded the selftest budget".to_owned()), } } @@ -1311,7 +1313,7 @@ fn obtain_sdist( Ok(path) } Ok(o) => Err(format!("sdist download failed: {}", o.tail())), - Err(TimedOut) => Err("sdist download exceeded the wall budget".to_owned()), + Err(TimedOut(_)) => Err("sdist download exceeded the wall budget".to_owned()), } } @@ -1357,7 +1359,10 @@ fn venv_python(venv_dir: &Path) -> PathBuf { } } -struct TimedOut; +/// A child killed at its deadline, with the tail of what it wrote (on +/// Unix, after a `SIGABRT` so a child with `faulthandler` enabled dumps +/// every thread's stack first). +struct TimedOut(String); struct CmdOutput { success: bool, @@ -1376,7 +1381,31 @@ impl CmdOutput { fn tail_n(&self, n: usize) -> String { let lines: Vec<&str> = self.combined.lines().collect(); let start = lines.len().saturating_sub(n); - let tail = lines[start..].join("\n"); + let mut tail = lines[start..].join("\n"); + // A Rust panic's own line (and its message, on the next line when + // the location ends it) names the cause; the backtrace and the + // abort after it can push it out of the tail. The first panic is + // the cause: a later one is the abort of a panic that reached a + // function that can't unwind ("panic in a function that cannot + // unwind"), kept too. + let panics: Vec = lines[..start] + .iter() + .enumerate() + .filter(|(_, l)| l.contains(" panicked at ")) + .map(|(i, _)| i) + .collect(); + if let (Some(&first), Some(&last)) = (panics.first(), panics.last()) { + let mut kept = lines[first..(first + 3).min(start)] + .iter() + .take_while(|l| !l.trim_start().starts_with("stack backtrace:")) + .copied() + .collect::>(); + if last != first { + kept.push("[…]"); + kept.extend(&lines[last..(last + 2).min(start)]); + } + tail = format!("{}\n[…]\n{tail}", kept.join("\n")); + } if tail.trim().is_empty() { // A silent nonzero exit (e.g. a crash) would otherwise // produce an empty, undebuggable reason. @@ -1449,12 +1478,25 @@ fn run_with_deadline(cmd: &mut Command, deadline: Instant) -> Result { if Instant::now() >= deadline { + abort_for_traceback(&mut child); let _ = child.kill(); let _ = child.wait(); - // Reap the drain threads so they don't leak. - let _ = join(out_thread); - let _ = join(err_thread); - return Err(TimedOut); + // A grandchild (a worker process) may still hold the + // pipes open: wait a few seconds for the drains, then + // leave them. + let out = join_within(out_thread, Duration::from_secs(5)); + let err = join_within(err_thread, Duration::from_secs(5)); + let o = CmdOutput { + success: false, + code: None, + combined: format!("{out}\n{err}"), + }; + let tail = o.tail_n(60); + let mut cut = tail.len().saturating_sub(1900); + while !tail.is_char_boundary(cut) { + cut += 1; + } + return Err(TimedOut(tail[cut..].to_owned())); } std::thread::sleep(Duration::from_millis(50)); } @@ -1473,6 +1515,37 @@ fn run_with_deadline(cmd: &mut Command, deadline: Instant) -> Result, wait: Duration) -> String { + let until = Instant::now() + wait; + while !t.is_finished() { + if Instant::now() >= until { + return "(output pipe still held open)".to_owned(); + } + std::thread::sleep(Duration::from_millis(50)); + } + t.join().unwrap_or_default() +} + fn trim_reason(s: &str) -> String { trim_reason_to(s, 2000) } @@ -1914,6 +1987,58 @@ mod simple_tables { mod tests { use super::*; + #[test] + fn tail_keeps_a_panic_line_above_it() { + let mut out = String::from("start\nthread '' panicked at src/x.rs:1:2:\nboom\n"); + for k in 0..30 { + out.push_str(&format!(" {k}: frame\n")); + } + out.push_str("Fatal Python error: Aborted\n"); + let o = CmdOutput { + success: false, + code: None, + combined: out, + }; + let t = o.tail(); + assert!( + t.starts_with("thread '' panicked at src/x.rs:1:2:\nboom\n 0: frame\n[…]\n") + ); + assert!(t.ends_with("Fatal Python error: Aborted")); + // A panic that reached a non-unwinding function: the first panic + // (the cause) and the abort's. + let mut out = String::from( + "thread '' panicked at src/gil.rs:5:9:\nalready borrowed\nstack backtrace:\n", + ); + for k in 0..20 { + out.push_str(&format!(" {k}: frame\n")); + } + out.push_str("thread '' panicked at library/core/src/panicking.rs:225:5:\npanic in a function that cannot unwind\n"); + for k in 0..20 { + out.push_str(&format!(" {k}: frame\n")); + } + out.push_str("thread caused non-unwinding panic. aborting.\n"); + let o = CmdOutput { + success: false, + code: None, + combined: out, + }; + let t = o.tail(); + assert!( + t.starts_with( + "thread '' panicked at src/gil.rs:5:9:\nalready borrowed\n[…]\n\ + thread '' panicked at library/core/src/panicking.rs:225:5:\n\ + panic in a function that cannot unwind\n[…]\n" + ), + "{t}" + ); + let quiet = CmdOutput { + success: false, + code: Some(1), + combined: "a\nb\n".to_owned(), + }; + assert_eq!(quiet.tail(), "a\nb"); + } + // -- manifest parsing --------------------------------------------------- const MANIFEST_BODY: &str = r#" diff --git a/crates/weavepy-jit/src/analyze.rs b/crates/weavepy-jit/src/analyze.rs index 42d18db6b..95fb98688 100644 --- a/crates/weavepy-jit/src/analyze.rs +++ b/crates/weavepy-jit/src/analyze.rs @@ -56,6 +56,10 @@ pub struct MethodResolution { /// arithmetic on it speculates the integer lane (see /// [`SE::num_hint`]). pub elem: bool, + /// The callee is a small pure leaf, which tier 2 calls through the + /// leaf evaluator where the frame JIT puts its body in line (see + /// [`TFunc::leaf_calls`]). + pub leaf: bool, } /// Maximum receiver path retained by analysis. The final attribute read adds @@ -245,6 +249,20 @@ pub struct Probes<'a> { /// *unbound* slot keeps the retriable probe-miss verdict, so a /// later training point can still specialize. pub obj: &'a mut dyn FnMut(u32) -> bool, + /// Whether local `slot` holds a plain Python function, or a method + /// bound to one, in the requesting activation: a dynamic call of it + /// runs Python through the generic call helper (see + /// [`TFunc::py_dyn_calls`]). + /// (A global's name index with [`PY_CALLEE_GLOBAL`] set asks the same + /// of the global that name resolves to.) + pub py_callee: &'a mut dyn FnMut(u32) -> bool, + /// Whether the `BINARY_SUBSCR` or `COMPARE_OP` at this pc has called a + /// plain Python method (`__getitem__`, `__lt__`) or seen instance + /// operands, whose method the frame JIT calls in line or directly where + /// tier 2 goes through the interpreter's subscript or comparison: such + /// an operation of the object lane counts as a dynamic Python call + /// (see [`TFunc::py_dyn_calls`]). + pub py_operator: &'a mut dyn FnMut(u32) -> bool, /// The observed lane of local `slot` in the requesting activation, /// graded like [`Self::param`] (scalars, `str`, `bytes`, and the /// object lane; lists and dicts stay `None` for their use-site @@ -630,6 +648,8 @@ pub fn analyze_with_probes( obj_global: &mut |_| None, cell: &mut |_| None, obj: &mut |_| false, + py_callee: &mut |_| false, + py_operator: &mut |_| false, local: &mut |_| None, stack_iter: &mut |_| None, pairs: &mut |_| None, @@ -664,6 +684,8 @@ pub fn analyze_for_ret( obj_global: &mut obj, cell: &mut |_| None, obj: &mut |_| false, + py_callee: &mut |_| false, + py_operator: &mut |_| false, local: &mut |_| None, stack_iter: &mut |_| None, pairs: &mut |_| None, @@ -689,6 +711,53 @@ thread_local! { /// The instruction the last failed inference/emission step stopped /// at (see `carve_step`). static FAIL_PC: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// The analysis work this thread may still do (see [`with_work_budget`]). + static WORK_LEFT: std::cell::Cell = const { std::cell::Cell::new(u64::MAX) }; + /// Whether an analysis stopped for want of work budget since the + /// budget was set (see [`with_work_budget`]). + static WORK_SHORT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The [`JitVerdict::ProbeMiss`] reason of an analysis that ran out of +/// its work budget (see [`with_work_budget`]). +pub const OVER_BUDGET: &str = "analysis budget"; + +/// Run `f` with at most `budget` units of analysis work: one unit is one +/// instruction of a code object passed over once, and an analysis passes +/// over its code once for each attempt (each carving step, each retry +/// with other assumptions) and over each callee it types the same way. +/// An analysis that would exceed the budget fails as a +/// [`JitVerdict::ProbeMiss`] of [`OVER_BUDGET`], as does every analysis +/// after it. Returns `f`'s result, the work done, and whether any +/// analysis stopped short: a result reached after one did (a callee left +/// untyped, say) reflects the budget, not the code, so the embedder +/// treats the whole attempt as out of budget. +pub fn with_work_budget(budget: u64, f: impl FnOnce() -> R) -> (R, u64, bool) { + let prev = (WORK_LEFT.replace(budget), WORK_SHORT.replace(false)); + let r = f(); + let left = WORK_LEFT.replace(prev.0); + let short = WORK_SHORT.replace(prev.1); + (r, budget - left, short) +} + +/// Whether an analysis has stopped for want of work budget since the +/// budget was set (see [`with_work_budget`]). +pub fn work_short() -> bool { + WORK_SHORT.get() +} + +/// Charge one pass over `code` to the work budget; `false` when the +/// budget doesn't cover it (see [`with_work_budget`]). +fn charge_pass(code: &CodeObject) -> bool { + let cost = code.instructions.len() as u64; + let left = WORK_LEFT.get(); + if left < cost { + WORK_LEFT.set(0); + WORK_SHORT.set(true); + return false; + } + WORK_LEFT.set(left - cost); + true } /// One loop of a code object's (structured) loop nest. @@ -773,6 +842,26 @@ fn innermost_loop(loops: &[LoopInfo], pc: usize) -> Option { .max_by_key(|&k| loops[k].head) } +/// [`innermost_loop`] of every pc below `n`, filled loop by loop over +/// each extent instead of searching the forest per pc. +fn innermost_loops(loops: &[LoopInfo], n: usize) -> Vec> { + let mut out: Vec> = vec![None; n]; + for (k, lp) in loops.iter().enumerate() { + if lp.head >= n { + continue; + } + for slot in &mut out[lp.head..=lp.end.min(n - 1)] { + // The innermost is the containing loop with the latest head + // (the later one on a tie, as `max_by_key` picks). + if slot.is_none_or(|j| loops[j].head <= lp.head) { + *slot = Some(k); + } + } + } + debug_assert!((0..n).all(|pc| out[pc] == innermost_loop(loops, pc))); + out +} + /// The start of the statement holding the top-level (loop-free) `p`: /// the first instruction of its source line (a statement's internal /// jumps, a comprehension's loop say, stay inside the cut). For a loop @@ -812,15 +901,28 @@ struct Carve { /// activation, so every one of those analyses would carve the same loops /// first: the embedder keeps this with the code object and each starts /// from it (see [`Probes::carved`]). Steps taken for what inference found -/// aren't kept, nor any step after one. +/// aren't kept, nor any step after one. Apart from that, it keeps the +/// headers of the loops carved out for an opcode tier 2 never compiles, +/// whatever the steps around them. #[derive(Debug, Default)] -pub struct Carved(Option>); +pub struct Carved(Option>, Vec); impl Carved { /// How many carving steps are kept. pub fn steps(&self) -> usize { self.0.as_ref().map_or(0, |state| state.steps) } + + /// Whether the loop headed at `head` was carved out for an opcode tier + /// 2 never compiles: no later analysis compiles it. + pub fn excludes_for_code(&self, head: usize) -> bool { + self.1.contains(&head) + } + + /// The headers [`Self::excludes_for_code`] answers for. + pub fn code_heads(&self) -> &[usize] { + &self.1 + } } /// Where a carving stands (see [`analyze_impl`]): the cold exits, the @@ -876,9 +978,7 @@ impl Region { let roots = (0..loops.len()) .filter(|&k| !stays[k] && loops[k].parent.is_some_and(|p| stays[p])) .collect(); - let innermost = (0..code.instructions.len()) - .map(|pc| innermost_loop(loops, pc)) - .collect(); + let innermost = innermost_loops(loops, code.instructions.len()); Region { stays, innermost, @@ -915,6 +1015,35 @@ impl Region { } } +/// The flag that marks a [`Probes::py_callee`] argument as a global's name +/// index rather than a local slot. +pub const PY_CALLEE_GLOBAL: u32 = 1 << 31; + +/// With [`PY_CALLEE_GLOBAL`], asks instead whether a guarded call of the +/// global (a `CallPy`) runs its callee through the embedder's frameless +/// evaluator: a short function that tier 2 hasn't compiled. Such a call +/// costs several hundred instructions, as a dynamic one does (see +/// [`crate::engine`]'s `call_bound`). +pub const PY_CALLEE_FRAMELESS: u32 = 1 << 30; + +/// Whether the callee of a dynamic call is a Python function: a local's +/// value the probe answers for, or (`f` from a `LOAD_GLOBAL` whose +/// self-or-null slot follows it) the global's. +fn dyn_callee_is_py( + ins: &[weavepy_compiler::Instruction], + src: Option, + null_pc: u32, + probes: &mut Probes<'_>, +) -> bool { + if let Some(slot) = src { + return (probes.py_callee)(slot); + } + let Some(load) = (null_pc as usize).checked_sub(1).and_then(|i| ins.get(i)) else { + return false; + }; + matches!(load.op, OpCode::LoadGlobal) && (probes.py_callee)(PY_CALLEE_GLOBAL | load.arg) +} + /// Whether tier 2 compiles code of this kind and signature at all. Sync /// generator bodies are admitted (RFC 0070 WS2: yields become `Yielded` /// side exits; entry is OSR-only); coroutines and async generators aren't. @@ -923,8 +1052,17 @@ fn signature_admitted(code: &CodeObject) -> bool { || code.is_async_generator || code.is_class_body || code.has_varargs - || code.has_varkeywords - || code.kwonly_count > 0) + || code.has_varkeywords) +} + +/// How many local slots the call binds before the body runs: the +/// positional parameters, then the keyword-only ones (`*args` and +/// `**kwargs` frames aren't admitted). Keyword-only parameters are plain +/// locals the caller's binding fills, so a frame entered with them bound +/// compiles like any other; a direct native call never takes them (see +/// the embedder's `py_callee_ok`). +fn param_slots(code: &CodeObject) -> u32 { + code.arg_count + code.kwonly_count } /// Whether a failure verdict depends on the activation the compile ran @@ -974,6 +1112,9 @@ fn analyze_impl( let mut num_slots = numeric_slots(code); let mut backoffs = 0usize; loop { + if !charge_pass(code) { + return Err(JitVerdict::ProbeMiss(OVER_BUDGET)); + } FAIL_PC.with(|c| c.set(None)); let mut in_plan = false; match analyze_once( @@ -1024,6 +1165,18 @@ fn analyze_impl( if steps < MAX_CARVE_STEPS && carve_step(code, &forest, &mut carve, &mut cold, &e, probes.carve_env) => { + if let (JitVerdict::UnsupportedOpcode(_), Some(carved), Some(p)) = ( + &e, + probes.carved.as_deref_mut(), + FAIL_PC.with(std::cell::Cell::get), + ) { + if let Some(k) = innermost_loop(&forest, p) { + let head = forest[k].head; + if !carve.env.contains(&head) && !carved.1.contains(&head) { + carved.1.push(head); + } + } + } steps += 1; planning &= in_plan; first_err.get_or_insert(e); @@ -1355,7 +1508,7 @@ fn analyze_once( // [`Probes::param`]). A seeded slot behaves exactly like one typed // by an assignment: conflicting evidence still rejects, and the // final `TFunc` entry-guards it. - for slot in 0..code.arg_count { + for slot in 0..param_slots(code) { if local_types[slot as usize].is_none() { if let Some(t) = (probes.param)(slot) { // RFC 0071 — `Str`/`Bytes` (WS6) and the nullable @@ -1524,6 +1677,8 @@ fn analyze_once( math_guards: Vec::new(), math_spans: Vec::new(), null_spans: Vec::new(), + py_dyn_calls: Vec::new(), + leaf_calls: Vec::new(), max_call_args: 0, loop_depths: HashMap::default(), comp_saved: HashMap::default(), @@ -1716,7 +1871,7 @@ fn analyze_once( // kernel first called with ints and later with a float would pack // the float as 0 and silently compute garbage.) let mut livein = livein; - for slot in 0..code.arg_count { + for slot in 0..param_slots(code) { if local_types.get(slot as usize).copied().flatten().is_some() { livein.insert(slot); } @@ -1848,6 +2003,18 @@ fn analyze_once( math_guards: out.math_guards, math_spans: out.math_spans, null_spans: out.null_spans, + py_dyn_calls: { + let mut v = out.py_dyn_calls; + v.sort_unstable(); + v.dedup(); + v + }, + leaf_calls: { + let mut v = out.leaf_calls; + v.sort_unstable(); + v.dedup(); + v + }, osr_entries, resume_entries, max_call_args: out.max_call_args, @@ -1976,6 +2143,36 @@ fn merge_entry( Ok(()) } +/// The jump-landing pcs of a code object ([`plan_rewrite`]'s), as a +/// bitmap: the planner asks about a few pcs around each candidate site, +/// once per analysis of every code tier 2 looks at. +struct JumpTargets(Vec); + +impl JumpTargets { + fn new(n: usize) -> Self { + Self(vec![false; n + 1]) + } + + /// (A target past the code's end lands on nothing the planner asks + /// about.) + fn insert(&mut self, pc: usize) { + if let Some(slot) = self.0.get_mut(pc) { + *slot = true; + } + } + + fn contains(&self, pc: usize) -> bool { + self.0.get(pc).copied().unwrap_or(false) + } + + /// Whether some target lies in `lo..=hi`, `except` aside (none when + /// `lo` wrapped below zero: the site is too near the code's start). + fn any_in(&self, lo: usize, hi: usize, except: usize) -> bool { + let hi = hi.min(self.0.len().saturating_sub(1)); + (lo..=hi).any(|pc| pc != except && self.0[pc]) + } +} + /// Recognize every `FOR_ITER` as the canonical counted `range` loop and /// build the rewrite [`Plan`]. Any `FOR_ITER` that doesn't match the /// shape disqualifies the whole frame (there is no generic iterator @@ -1997,7 +2194,7 @@ fn plan_rewrite( // All jump-landing pcs, to reject jumps into the middle of a // recognized `range(...)` prefix. - let mut targets: HashSet = HashSet::default(); + let mut targets = JumpTargets::new(n); for (i, item) in ins.iter().enumerate() { match item.op { OpCode::PopJumpIfFalse @@ -2090,7 +2287,7 @@ fn plan_rewrite( && matches!(ins[i + 2].op, OpCode::StoreFast) && matches!(ins[i + 3].op, OpCode::StoreFast) { - if targets.iter().any(|&t| i - 1 <= t && t <= i + 3 && t != i) { + if targets.any_in(i.wrapping_sub(1), i + 3, i) { return Err(bail()); } let seq_slot = n_real + plan.n_synth; @@ -2202,7 +2399,7 @@ fn plan_rewrite( if i >= 1 && matches!(ins[i - 1].op, OpCode::GetIter) { // No jump may land on the `GET_ITER` or the fused store — // the header itself is the only allowed landing point. - if targets.iter().any(|&t| i - 1 <= t && t <= i + 1 && t != i) { + if targets.any_in(i.wrapping_sub(1), i + 1, i) { return Err(bail()); } let seq_slot = n_real + plan.n_synth; @@ -2268,9 +2465,8 @@ fn plan_rewrite( // prologue, and nothing may land in the erased epilogue // (the `FOR_ITER`'s own exit target lands on `END_FOR`, // which starts a block of pure no-ops). - if targets - .iter() - .any(|&t| (i - 5 <= t && t <= i + 1 && t != i) || (exit < t && t <= exit + 3)) + if targets.any_in(i.wrapping_sub(5), i + 1, i) + || targets.any_in(exit + 1, exit + 3, usize::MAX) { return Err(bail()); } @@ -2439,8 +2635,8 @@ fn plan_rewrite( || !matches!(ins[i + 1].op, OpCode::LoadConst) || !matches!(ins[i + 2].op, OpCode::ListExtend) || ins[i + 2].arg != 1 - || targets.contains(&(i + 1)) - || targets.contains(&(i + 2)) + || targets.contains(i + 1) + || targets.contains(i + 2) { continue; } @@ -2486,7 +2682,7 @@ fn plan_rewrite( && !plan.const_list.contains_key(&(i - 1)) && !plan.nop.contains(&(i - 1)) && !plan.nop.contains(&i) - && !targets.contains(&i); + && !targets.contains(i); if lit { sites.entry(ins[i].arg).or_default().push(i - 1); } else { @@ -2569,7 +2765,7 @@ fn plan_rewrite( } // Nothing may land inside the erased window (the list load // itself starts the expression and may be a landing point). - if targets.iter().any(|&t| list_load < t && t <= c) + if targets.any_in(list_load + 1, c, usize::MAX) || (list_load..c).any(|p| plan.nop.contains(&p)) { continue; @@ -2670,8 +2866,8 @@ fn plan_rewrite( for i in 1..n { if !matches!(ins[i].op, OpCode::CallKw) || !matches!(ins[i - 1].op, OpCode::LoadConst) - || targets.contains(&i) - || targets.contains(&(i - 1)) + || targets.contains(i) + || targets.contains(i - 1) { continue; } @@ -2699,7 +2895,7 @@ fn plan_rewrite( fn range_prefix( code: &CodeObject, plan: &Plan, - targets: &HashSet, + targets: &JumpTargets, i: usize, ) -> Option<(usize, usize, Option, u8)> { let ins = &code.instructions; @@ -2770,7 +2966,7 @@ fn range_prefix( // No jump may land inside the prefix or on the fused store — the // header itself (a JUMP_BACKWARD target) is the only allowed // landing point. - if targets.iter().any(|&t| callee < t && t <= i + 1 && t != i) { + if targets.any_in(callee + 1, i + 1, i) { return None; } Some((callee, push_null, step_nop, pops)) @@ -3417,9 +3613,16 @@ fn compute_livein( reachable: &[usize], n_locals: u32, ) -> HashSet { - let width = slot_width(code, n_locals.max(code.arg_count)); - let assigned_in = - assigned_on_entry(code, raw, reachable, None, code.arg_count, n_locals, width); + let width = slot_width(code, n_locals.max(param_slots(code))); + let assigned_in = assigned_on_entry( + code, + raw, + reachable, + None, + param_slots(code), + n_locals, + width, + ); // Collect live-in: a load of a slot not definitely assigned yet. let mut livein = HashSet::default(); let mut cur = SlotBits::empty(width); @@ -3456,7 +3659,7 @@ fn root_livein( raw, reachable, Some(roots), - code.arg_count.min(n_real), + param_slots(code).min(n_real), n_real, width, ); @@ -3679,6 +3882,8 @@ struct MethodMark { native: bool, /// See [`MethodResolution::elem`]. elem: bool, + /// See [`MethodResolution::leaf`]. + leaf: bool, } /// RFC 0073 WS3 — a burned-in native `str` method riding on its @@ -4660,7 +4865,7 @@ fn step_abstract( // A plain local assigned in this body (a // comprehension result, say) may be typed by a // later fixpoint iteration: transient. - if v.src.is_some_and(|slot| slot >= code.arg_count) { + if v.src.is_some_and(|slot| slot >= param_slots(code)) { return Ok(()); } // The param probe is a no-op on the unseeded @@ -5164,6 +5369,7 @@ fn step_abstract( load_pc: i as u32, native: res.native, elem: res.elem, + leaf: res.leaf, }), ..recv }); @@ -5393,7 +5599,7 @@ fn step_abstract( } else if (probes.dict)(slot).is_some() { // RFC 0073 WS2 — `len(d)` on an exact dict. set_local(local_types, slot, JitType::Dict, changed)?; - } else if slot >= code.arg_count { + } else if slot >= param_slots(code) { // A plain local assigned in this body: a // later fixpoint iteration may type it. } else { @@ -7009,6 +7215,11 @@ struct EmitOut { /// RFC 0074 WS2 — self-or-null `Unbound` markers of opaque-call /// sites (`token` unused, `live_to` = the consuming `CALL` pc). null_spans: Vec, + /// The pcs of `CallDyn`s whose callee is a Python function (see + /// [`TFunc::py_dyn_calls`]). + py_dyn_calls: Vec, + /// See [`TFunc::leaf_calls`]. + leaf_calls: Vec, max_call_args: u32, /// RFC 0073 WS1 — per-loop interpreter depth of the erased /// iterator, keyed by the loop span's `live_from` pc (recorded at @@ -7753,6 +7964,17 @@ fn emit_instr( } OpCode::StoreFast => { let top = *stack.last().ok_or(JitVerdict::StackUnderflow)?; + // A store the fixpoint never typed (its value has no lane: an + // operation that only ever raised before it, say) has no + // managed variable to store into. + if local_types + .get(ins.arg as usize) + .copied() + .flatten() + .is_none() + { + return Err(JitVerdict::TypeUnknown); + } // RFC 0070 WS1 — `x = None` on an object-lane local: the // `None` constant never had a native slot, so materialize // it (machine value `-1`) and store it like any value. @@ -8026,6 +8248,9 @@ fn emit_instr( } } else if dyn_op_ok(a, b) { *max_call_args = (*max_call_args).max(2); + if (a == JitType::Obj || b == JitType::Obj) && (probes.py_operator)(pc) { + out.py_dyn_calls.push(pc); + } push( TOp::DynCompare { arg: ins.arg }, Some(dyn_compare_lane(ins.arg)), @@ -8235,6 +8460,8 @@ fn emit_instr( ctor: ctor_site, self_ctor: self_site, slot_member: false, + in_line: false, + position: None, }); push(TOp::AttrGet { site, out: lane }, Some(lane), stack, stmts); // RFC 0071 WS3 — extend the provenance chain on the result. @@ -8425,6 +8652,7 @@ fn emit_instr( load_pc: pc, native: res.native, elem: res.elem, + leaf: res.leaf, }); stack.push(ESlot { null: Some((pc, plan.hidden_at(i) + stack.len() as u32)), @@ -8470,6 +8698,8 @@ fn emit_instr( ctor: ctor_site, self_ctor: self_site, slot_member: false, + in_line: false, + position: None, }); push(TOp::AttrGet { site, out: lane }, Some(lane), stack, stmts); // RFC 0071 WS3 — extend the provenance chain on the result. @@ -8623,6 +8853,8 @@ fn emit_instr( ctor: ctor_site, self_ctor: None, slot_member: false, + in_line: false, + position: None, }); // Native stack order matches the interpreter: value below, // receiver on top. Lowering pops receiver then value. @@ -8714,6 +8946,9 @@ fn emit_instr( *max_call_args = (*max_call_args).max(argc as u32); // A native site whose arguments ran no code since the load // checks its guard at the call (one helper call, not two). + if m.leaf { + out.leaf_calls.push(pc); + } let mut token = m.token; if m.native { token |= crate::runtime::METHOD_NATIVE; @@ -8833,6 +9068,9 @@ fn emit_instr( if !f.ty.is_pinned() { return Err(JitVerdict::UnsupportedOpcode("CALL (callee lane)")); } + if dyn_callee_is_py(&code.instructions, f.src, null_pc, probes) { + out.py_dyn_calls.push(pc); + } for &ty in &arg_tys { // Any representable lane stages by tag — pins are // meaningful here (the marshal never leaves this @@ -8993,6 +9231,15 @@ fn emit_instr( interp_depth: mark.interp_depth, }); *max_call_args = (*max_call_args).max(argc as u32); + if mark.kind == MarkKind::Py && !mark.ctor && !mark.is_self { + let load = code.instructions.get(mark.load_pc as usize); + if load.is_some_and(|l| { + l.op == OpCode::LoadGlobal + && (probes.py_callee)(PY_CALLEE_GLOBAL | PY_CALLEE_FRAMELESS | l.arg) + }) { + out.py_dyn_calls.push(pc); + } + } push( TOp::CallPy { token: mark.token, @@ -9043,6 +9290,9 @@ fn emit_instr( if !f.ty.is_pinned() { return Err(JitVerdict::UnsupportedOpcode("CALL_KW (callee lane)")); } + if dyn_callee_is_py(&code.instructions, f.src, null_pc, probes) { + out.py_dyn_calls.push(pc); + } for &ty in &arg_tys { if !ty.is_representable() { return Err(JitVerdict::TypeUnknown); @@ -9585,6 +9835,9 @@ fn emit_instr( if !dyn_op_ok(cont, idx_slot.ty) { return Err(JitVerdict::TypeUnknown); } + if cont == JitType::Obj && (probes.py_operator)(pc) { + out.py_dyn_calls.push(pc); + } *max_call_args = (*max_call_args).max(2); push(TOp::DynGetItem, Some(JitType::Obj), stack, stmts); return Ok(()); diff --git a/crates/weavepy-jit/src/engine.rs b/crates/weavepy-jit/src/engine.rs index e5fab7cf8..f2c3fa83d 100644 --- a/crates/weavepy-jit/src/engine.rs +++ b/crates/weavepy-jit/src/engine.rs @@ -600,7 +600,7 @@ impl JitEngine { &mut |_| None, &mut |_| None, &mut |_, _, _| None, - &mut |_| false, + &mut |_| SiteLayout::default(), ) } @@ -614,7 +614,9 @@ impl JitEngine { /// arguments of those lanes, runs in line once its guard holds (see /// [`InlineMethod::of`]). `slot_member(site)` says whether an attribute /// site's receiver keeps the attribute in a laid-out member slot (see - /// [`AttrSiteMeta::slot_member`]). + /// [`AttrSiteMeta::slot_member`]), and whether the site has a position + /// compiled code reads or writes in line (see + /// [`AttrSiteMeta::in_line`]). #[allow(clippy::too_many_arguments)] pub fn compile_frame_direct( &mut self, @@ -624,7 +626,7 @@ impl JitEngine { direct: &mut dyn FnMut(u32) -> Option, direct_method: &mut dyn FnMut(u32) -> Option, inline_method: &mut dyn FnMut(u32, &[JitType], u32) -> Option, - slot_member: &mut dyn FnMut(&AttrSiteMeta) -> bool, + slot_member: &mut dyn FnMut(&AttrSiteMeta) -> SiteLayout, ) -> Result { let tfunc = analyze_admitted(code, resolve, probes, slot_member)?; self.compile_tfunc_methods(&tfunc, direct, direct_method, inline_method) @@ -644,7 +646,7 @@ impl JitEngine { direct: &mut dyn FnMut(u32) -> Option, direct_method: &mut dyn FnMut(u32) -> Option, inline_method: &mut dyn FnMut(u32, &[JitType], u32) -> Option, - slot_member: &mut dyn FnMut(&AttrSiteMeta) -> bool, + slot_member: &mut dyn FnMut(&AttrSiteMeta) -> SiteLayout, ) -> Result { let tfunc = analyze_admitted(code, resolve, probes, slot_member)?; if engine.is_none() { @@ -1086,6 +1088,16 @@ fn calls_dynamically(tfunc: &TFunc) -> bool { /// through a helper that redoes the lookups the interpreter's caches /// remember, while each typed one saves only a dispatch. A loop-free /// body is left alone: other compiled code calls it directly. +/// What the embedder knows of an attribute site's storage when its code +/// is compiled (see [`AttrSiteMeta::slot_member`], +/// [`AttrSiteMeta::in_line`] and [`AttrSiteMeta::position`]). +#[derive(Clone, Copy, Debug, Default)] +pub struct SiteLayout { + pub slot_member: bool, + pub in_line: bool, + pub position: Option<(u64, u32, usize)>, +} + /// The [`JitEngine::compile_frame_lazily`] verdict for a host the code /// generator can't target. pub const NO_HOST_ENGINE: &str = "no code generator for the host"; @@ -1096,9 +1108,20 @@ fn analyze_admitted( code: &CodeObject, resolve: &mut dyn FnMut(&str) -> ResolvedGlobal, probes: &mut Probes<'_>, - slot_member: &mut dyn FnMut(&AttrSiteMeta) -> bool, + slot_member: &mut dyn FnMut(&AttrSiteMeta) -> SiteLayout, ) -> Result { let mut tfunc = crate::analyze::analyze_frame(code, resolve, probes)?; + for site in &mut tfunc.attr_sites { + let layout = slot_member(site); + site.slot_member = layout.slot_member; + site.in_line = layout.in_line; + site.position = layout.position; + } + // A callee's analysis ran out of work budget: what this one made of + // the callee (an untyped call) reflects the budget, not the code. + if crate::analyze::work_short() { + return Err(JitVerdict::ProbeMiss(crate::analyze::OVER_BUDGET)); + } if calls_dynamically(&tfunc) { return Err(JitVerdict::UnsupportedOpcode("dynamic call (loop-free)")); } @@ -1108,15 +1131,135 @@ fn analyze_admitted( if attr_bound(&tfunc) { return Err(JitVerdict::UnsupportedOpcode("attribute-bound loop")); } + if call_bound(&tfunc) { + return Err(JitVerdict::UnsupportedOpcode("call-bound loop")); + } + if method_bound(&tfunc) { + return Err(JitVerdict::UnsupportedOpcode("method-bound loop")); + } if unpacks_pairs(&tfunc) { return Err(JitVerdict::UnsupportedOpcode("tuple-target loop")); } - for site in &mut tfunc.attr_sites { - site.slot_member = slot_member(site); + if steps_objects(&tfunc) { + return Err(JitVerdict::UnsupportedOpcode("object-element loop")); + } + if chases_pointers(&tfunc) { + return Err(JitVerdict::UnsupportedOpcode("pointer-chasing loop")); } Ok(tfunc) } +/// Whether `tfunc`'s loops walk a linked structure (`n = n.next`, `node = +/// node.left`) with too little typed work to repay the walk. Each new +/// object such a read yields pins (a table entry the activation holds +/// until it leaves, appended through the read's helper), about 270 +/// instructions a step where the frame JIT, which counts references +/// instead, reads the field in line: `while n is not None: t += n.v; n = +/// n.nxt` ran at 486 instructions a node in tier 2 against 185 in the +/// frame JIT. The frame JIT runs such code instead, unless the loops do +/// enough typed arithmetic or make a typed Python call (which tier 2 +/// makes natively, as for [`steps_objects`]: `richards`' scheduler walks +/// its task list by `t = t.link` between such calls). +fn chases_pointers(tfunc: &TFunc) -> bool { + use crate::ir::TOp; + use crate::value::JitType; + if GENERIC_LOOPS_ADMITTED.load(std::sync::atomic::Ordering::Relaxed) || !has_loop(tfunc) { + return false; + } + let (mut chases, mut typed) = (false, 0usize); + for b in loop_blocks(tfunc) { + for (k, st) in b.stmts.iter().enumerate() { + match st.op { + // `x = x.attr` of the object lane: a load of the local, the + // read, and the store back. + TOp::AttrGet { + out: JitType::Obj, .. + } => { + let before = k.checked_sub(1).map(|j| b.stmts[j].op); + let after = b.stmts.get(k + 1).map(|s| s.op); + if let (Some(TOp::LoadLocal(x)), Some(TOp::StoreLocal(y))) = (before, after) { + chases |= x == y; + } + } + TOp::CallPy { .. } | TOp::CallPyKw { .. } | TOp::CallMethod { .. } + if tfunc.py_dyn_calls.binary_search(&st.pc).is_err() + && tfunc.leaf_calls.binary_search(&st.pc).is_err() => + { + typed += call_weight(); + } + TOp::IntArith(_) + | TOp::FloatArith(_) + | TOp::IntTrueDiv + | TOp::IntCmp(_) + | TOp::FloatCmp(_) + | TOp::IntNeg + | TOp::FloatNeg + | TOp::IntInvert => typed += 1, + _ => {} + } + } + } + chases && typed < PAIR_LOOP_TYPED_WORK +} + +/// Whether `tfunc` runs a loop over a list of objects (instances, strings, +/// tuples) natively with too little typed work to repay its step. Each +/// element pins (a table entry the activation holds until it leaves), so +/// a step costs several times the frame JIT's, which counts references +/// instead: `for p in points: pass` stepped at 290 instructions an element +/// against the frame JIT's 39. The frame JIT runs such code instead, as it +/// does a tuple-target loop (see [`unpacks_pairs`]); a body with enough +/// typed arithmetic, or a typed Python call (which tier 2 makes natively: +/// `richards`' `for t in tasks: t.run()` ran half again as long in the +/// frame JIT), keeps tier 2. Only the loop's own blocks count: a call that +/// built the list (`[P(i) for i in range(n)]`) doesn't repay its steps, +/// nor does a call of a small pure leaf method, whose body the frame JIT +/// puts in line where tier 2 runs it in the leaf evaluator (`for o in +/// objs: t += o.pick()` ran at a third of tier 2's cost in the frame JIT). +fn steps_objects(tfunc: &TFunc) -> bool { + use crate::ir::{TOp, TTerm}; + use crate::value::JitType; + if GENERIC_LOOPS_ADMITTED.load(std::sync::atomic::Ordering::Relaxed) { + return false; + } + let typed_work = |blocks: &[crate::ir::TBlock]| -> usize { + blocks + .iter() + .flat_map(|b| &b.stmts) + .map(|s| match s.op { + TOp::CallPy { .. } | TOp::CallPyKw { .. } | TOp::CallMethod { .. } + if tfunc.py_dyn_calls.binary_search(&s.pc).is_err() + && tfunc.leaf_calls.binary_search(&s.pc).is_err() => + { + call_weight() + } + TOp::IntArith(_) + | TOp::FloatArith(_) + | TOp::IntTrueDiv + | TOp::IntCmp(_) + | TOp::FloatCmp(_) + | TOp::IntNeg + | TOp::FloatNeg + | TOp::IntInvert => 1, + _ => 0, + }) + .sum() + }; + // (Blocks are in instruction order: a loop's run from its header to + // its exit.) + tfunc.blocks.iter().enumerate().any(|(h, b)| match b.term { + TTerm::ForList { + elem: JitType::Obj, + exit, + .. + } => { + let end = if exit > h { exit } else { tfunc.blocks.len() }; + typed_work(&tfunc.blocks[h..end]) < PAIR_LOOP_TYPED_WORK + } + _ => false, + }) +} + /// Whether `tfunc` runs a tuple-target loop (`for a, b in pairs`) natively. /// Its step goes through a helper that pins each unpacked object, three /// times the frame JIT's step, and loops that iterate pairs (a graph's @@ -1217,12 +1360,16 @@ fn loop_blocks(tfunc: &TFunc) -> impl Iterator { } /// Whether `tfunc`'s loops access attributes more often than they do -/// typed arithmetic: each attribute read or write of a tier-2 loop goes -/// through a helper that redoes its guards (about 50 host instructions), -/// where the frame JIT reads or writes the field in line, so a loop of -/// attribute traffic runs faster in the frame JIT unless typed work in -/// registers repays it. (Calls don't count: a driver loop that calls -/// compiled functions keeps them native-to-native in tier 2.) +/// typed arithmetic: an attribute read or write of a tier-2 loop that +/// has no in-line position goes through a helper that redoes its guards +/// (about 50 host instructions), where the frame JIT reads or writes the +/// field in line, so a loop of such attribute traffic runs faster in the +/// frame JIT unless typed work in registers repays it. An access tier 2 +/// makes in line itself (a scalar field of a split-layout instance or a +/// laid-out member slot, see [`AttrSiteMeta::in_line`]) doesn't count: +/// a loop of those, and of the methods it then runs in line, took 1.45 +/// times as long in the frame JIT. (Calls don't count: a driver loop +/// that calls compiled functions keeps them native-to-native in tier 2.) /// `WEAVEPY_T2_ATTRS=0` turns the rule off, a tuning aid. fn attr_bound(tfunc: &TFunc) -> bool { use crate::ir::TOp; @@ -1237,6 +1384,11 @@ fn attr_bound(tfunc: &TFunc) -> bool { let (mut attrs, mut typed) = (0usize, 0usize); for st in loop_blocks(tfunc).flat_map(|b| &b.stmts) { match st.op { + TOp::AttrGet { site, .. } | TOp::AttrSet { site } + if tfunc + .attr_sites + .get(site as usize) + .is_some_and(|s| s.in_line) => {} TOp::AttrGet { .. } | TOp::AttrSet { .. } | TOp::DynAttrGet { .. } @@ -1255,6 +1407,129 @@ fn attr_bound(tfunc: &TFunc) -> bool { attrs > typed } +/// Whether `tfunc`'s loops make dynamic calls of Python functions that +/// outweigh what tier 2 does better: a Python callee called through tier +/// 2's generic call helper (one held in a local, say) costs about 800 +/// host instructions more than the frame JIT's call of it, which checks +/// and enters the callee directly or inlines it (`f(1, 2, 3)` of a local +/// `f`: 932 instructions against 114), where each typed operation saves +/// tier 2 only a few, and each guarded call (a global function's, a +/// method's) it makes native-to-native. So a loop with fewer than +/// [`call_weight`] typed operations, counting a guarded call as that +/// many, for each such dynamic call runs faster in the frame JIT. Calls +/// of builtins don't count: tier 2's helper runs those about as fast. A +/// loop-free body is left alone, as for [`attr_bound`]. +fn call_bound(tfunc: &TFunc) -> bool { + use crate::ir::TOp; + let weight = call_weight(); + if weight == 0 + || tfunc.py_dyn_calls.is_empty() + || GENERIC_LOOPS_ADMITTED.load(std::sync::atomic::Ordering::Relaxed) + || !has_loop(tfunc) + { + return false; + } + let (mut calls, mut typed) = (0usize, 0usize); + for st in loop_blocks(tfunc).flat_map(|b| &b.stmts) { + match st.op { + // (A guarded call the analysis marked runs its callee + // frameless, which costs as much as a dynamic call.) + TOp::CallDyn { .. } | TOp::CallPy { .. } | TOp::DynGetItem | TOp::DynCompare { .. } + if tfunc.py_dyn_calls.binary_search(&st.pc).is_ok() => + { + calls += 1; + } + TOp::CallPy { .. } | TOp::CallPyKw { .. } | TOp::CallMethod { .. } => typed += weight, + TOp::IntArith(_) + | TOp::FloatArith(_) + | TOp::IntTrueDiv + | TOp::IntCmp(_) + | TOp::FloatCmp(_) + | TOp::IntNeg + | TOp::FloatNeg + | TOp::IntInvert => typed += 1, + _ => {} + } + } + calls * weight > typed +} + +/// Whether `tfunc`'s loops call methods through the generic load and call +/// more than tier 2 repays: a method of a value whose class the compile +/// didn't resolve (`d.pop(k)`, `out.add(x)`, `line.split()`) is a generic +/// attribute load and a generic call, two helper round trips where the +/// frame JIT's method site makes one cached call (about 270 host +/// instructions more for a builtin value's method, more for others), and +/// each typed operation saves tier 2 only a few. So a loop with fewer +/// than [`method_weight`] typed operations for each such call runs +/// faster in the frame JIT. +fn method_bound(tfunc: &TFunc) -> bool { + use crate::ir::TOp; + let weight = method_weight(); + if weight == 0 + || tfunc.null_spans.is_empty() + || GENERIC_LOOPS_ADMITTED.load(std::sync::atomic::Ordering::Relaxed) + || !has_loop(tfunc) + { + return false; + } + let (mut methods, mut typed) = (0usize, 0usize); + for st in loop_blocks(tfunc).flat_map(|b| &b.stmts) { + match st.op { + // (A method-form load: the marker span of its call opens at it.) + TOp::DynAttrGet { .. } if tfunc.null_spans.iter().any(|s| s.live_from == st.pc) => { + methods += 1; + } + TOp::CallPy { .. } | TOp::CallPyKw { .. } | TOp::CallMethod { .. } => { + typed += call_weight(); + } + TOp::IntArith(_) + | TOp::FloatArith(_) + | TOp::IntTrueDiv + | TOp::IntCmp(_) + | TOp::FloatCmp(_) + | TOp::IntNeg + | TOp::FloatNeg + | TOp::IntInvert => typed += 1, + _ => {} + } + } + methods * weight > typed +} + +/// How many typed operations a loop needs for each generic method call +/// before tier 2 takes it (see [`method_bound`]): 4 unless +/// `WEAVEPY_T2_METHODS` says otherwise (`0` turns the rule off), a tuning +/// aid. (At 4 a dict's pop and re-insert loop went from 138 ns to the +/// frame JIT's 92 and a queue worker's loop ran 4% faster, while the +/// suite's loops that mix such calls with typed work, `chaos`, `go` and +/// `raytrace`, stayed within 1% either way; the instruction counts would +/// allow a larger weight, but nothing measured asks for one.) +fn method_weight() -> usize { + static WEIGHT: std::sync::OnceLock = std::sync::OnceLock::new(); + *WEIGHT.get_or_init(|| { + std::env::var("WEAVEPY_T2_METHODS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(4) + }) +} + +/// How many typed operations a loop needs for each dynamic call before +/// tier 2 takes it (see [`call_bound`]): 24 unless `WEAVEPY_T2_CALLS` +/// says otherwise (`0` turns the rule off), a tuning aid. (A float +/// operation saves tier 2 about 30 instructions over the frame JIT, so +/// some 27 of them repay one generic call; integer ones save less.) +fn call_weight() -> usize { + static WEIGHT: std::sync::OnceLock = std::sync::OnceLock::new(); + *WEIGHT.get_or_init(|| { + std::env::var("WEAVEPY_T2_CALLS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(24) + }) +} + /// The generic share [`mostly_generic`] admits, in percent, and whether it /// counts only loop bodies: 20% of the whole frame unless /// `WEAVEPY_T2_GENERIC` says otherwise (`off`, or a percent with an diff --git a/crates/weavepy-jit/src/engine/tests.rs b/crates/weavepy-jit/src/engine/tests.rs index 84cf00214..021a4c68b 100644 --- a/crates/weavepy-jit/src/engine/tests.rs +++ b/crates/weavepy-jit/src/engine/tests.rs @@ -33,6 +33,8 @@ fn function(ops: &[TOp]) -> TFunc { math_guards: vec![], math_spans: vec![], null_spans: vec![], + py_dyn_calls: vec![], + leaf_calls: vec![], osr_entries: vec![], max_call_args: 0, ret_lane: Some(JitType::Int), @@ -388,6 +390,8 @@ fn attribute_chains_keep_the_first_read_deopt_snapshot() { ctor: None, self_ctor: None, slot_member: false, + in_line: false, + position: None, }) .collect(); tfunc @@ -711,6 +715,8 @@ fn cached_attribute_chains_keep_native_fallback_and_exact_exits() { ctor: None, self_ctor: None, slot_member: false, + in_line: false, + position: None, }) .collect(); f @@ -986,6 +992,8 @@ fn adjacent_scalar_reads_share_only_a_guarded_value() { ctor: None, self_ctor: None, slot_member: false, + in_line: false, + position: None, }; 2 ]; diff --git a/crates/weavepy-jit/src/ir.rs b/crates/weavepy-jit/src/ir.rs index e23b42331..81d23cd09 100644 --- a/crates/weavepy-jit/src/ir.rs +++ b/crates/weavepy-jit/src/ir.rs @@ -1055,6 +1055,19 @@ pub struct AttrSiteMeta { /// and writes it there in line instead of in split values. Set by the /// embedder before lowering; the helpers decide any other shape. pub slot_member: bool, + /// Whether compiled code reads or writes the attribute in line (the + /// embedder's guard holds a position for it and the lane is a scalar + /// one), filled in beside [`Self::slot_member`]. An admission rule's + /// input only: the lowering decides per access. + pub in_line: bool, + /// The embedder's guard for the site, where it holds a position: the + /// receiver's class version, the split-values index (or, marked + /// [`crate::runtime::SLOT_FIELD`], the member slot's position) and + /// the slot layout's word (`0` for a split field). A guard never + /// changes once made, so compiled code compares and indexes with + /// these as constants instead of loading them from the guard table + /// at each access. + pub position: Option<(u64, u32, usize)>, } /// RFC 0073 WS1 — where one canonical constructor field's value comes @@ -1548,6 +1561,15 @@ pub struct TFunc { /// holds nothing. A deopt strictly inside `(live_from, live_to)` /// re-inserts it (the `token` field is unused). pub null_spans: Vec, + /// The pcs of `CallDyn`s whose callee was a Python function (or a + /// method bound to one) when the code compiled: tier 2 calls it + /// through the interpreter's generic call protocol, where the frame + /// JIT checks and enters the callee directly. + pub py_dyn_calls: Vec, + /// The pcs of `CallMethod`s whose callee was a small pure leaf when + /// the code compiled (see [`crate::analyze::MethodResolution::leaf`]): + /// such a call doesn't repay a loop's element steps. + pub leaf_calls: Vec, /// OSR entry points (RFC 0059 WS3b): backward-jump target blocks /// enterable via `entry_pc`. pub osr_entries: Vec, diff --git a/crates/weavepy-jit/src/lib.rs b/crates/weavepy-jit/src/lib.rs index 34b7e12b6..737ce7ef7 100644 --- a/crates/weavepy-jit/src/lib.rs +++ b/crates/weavepy-jit/src/lib.rs @@ -31,12 +31,13 @@ mod value; pub use analyze::{ analyze, analyze_for_ret, analyze_frame, analyze_with_probe, analyze_with_probes, - returns_none_syntactically, returns_self_syntactically, Carved, JitVerdict, MethodResolution, - PathArena, Probes, ELEM_SENTINEL, MIN_REGION_TRIPS, + returns_none_syntactically, returns_self_syntactically, with_work_budget, work_short, Carved, + JitVerdict, MethodResolution, PathArena, Probes, ELEM_SENTINEL, MIN_REGION_TRIPS, OVER_BUDGET, + PY_CALLEE_FRAMELESS, PY_CALLEE_GLOBAL, }; pub use engine::{ admit_attr_loops, admit_generic_loops, generic_loops_admitted, CompiledFrame, DirectLeaf, - FieldAt, InlineMethod, JitEngine, OpMix, NO_HOST_ENGINE, + FieldAt, InlineMethod, JitEngine, OpMix, SiteLayout, NO_HOST_ENGINE, }; pub use ir::{ ArithKind, AttrSiteMeta, BlockId, CalleeSpanMeta, CmpKind, CompSavedMeta, CtorFieldSrc, @@ -45,30 +46,30 @@ pub use ir::{ TOp, TStmt, TTerm, UNBOX_FLOAT_ARITH, UNBOX_FLOAT_CMP, UNBOX_FLOAT_EXACT, }; pub use runtime::{ - global_obj_list_elem, register_attr_get_chain_helper, register_attr_helpers, - register_build_map_helper, register_build_set_helper, register_cached_attr_chain_helper, - register_call_dyn_helper, register_call_dyn_int_helper, register_call_method_helper, - register_call_native_method_helper, register_call_py_helper, register_cell_helpers, - register_const_str_helper, register_contains_dyn_helper, register_dict_del_helper, - register_dict_helpers, register_dict_iter_helper, register_dyn_attr_helpers, - register_dyn_item_helpers, register_dyn_op_helpers, register_float_pow_helper, - register_global_obj_helper, register_guard_method_helper, register_is_obj_helper, - register_iter_helpers, register_iter_new_helper, register_iter_next_pair_helper, - register_list_extra_helpers, register_list_from_range_helper, register_list_helpers, - register_list_next_helper, register_math_helpers, register_method_enter_helper, - register_obj_getitem_helper, register_poll_helper, register_self_call_helpers, - register_str_format_helpers, register_str_helpers, register_str_method_helper, - register_str_write_helpers, register_truth_helper, register_tuple_read_helpers, - register_unbox_float_helper, register_unbox_int_helper, set_obj_layout, AttrGetChainHelper, - AttrGetHelper, AttrSetHelper, BuildListHelper, BuildTupleHelper, BytesGetHelper, - CachedAttrChainHelper, CallDynHelper, CallMethodHelper, CallPyHelper, CallStatus, - CellGetHelper, CellSetHelper, DictAccessHelper, DynAttrHelper, GetIterHelper, - GuardMethodHelper, IterNextHelper, IterNextPairHelper, JitFrame, JitStatus, ListAppendHelper, - ListFromRangeHelper, ListGetHelper, ListLenHelper, ListNextHelper, ListRepeatHelper, - ListSetHelper, ListSliceHelper, MathBinaryHelper, MathUnaryHelper, MethodEnterHelper, - ObjLayout, PollHelper, SelfEnterHelper, SelfExitHelper, SelfSlowHelper, SlotTag, StrEqHelper, - StrLenHelper, StrModHelper, CALL_GAPS, DICT_KEY_INT, DICT_KEY_STR, DICT_VAL_FLOAT, - DICT_VAL_INT, DICT_VAL_OBJ, ITER_ELEM_STR, JIT_POLL_STRIDE, MAX_ATTR_CHAIN_LEN, + global_obj_list_elem, obj_layout_published, register_attr_get_chain_helper, + register_attr_helpers, register_build_map_helper, register_build_set_helper, + register_cached_attr_chain_helper, register_call_dyn_helper, register_call_dyn_int_helper, + register_call_method_helper, register_call_native_method_helper, register_call_py_helper, + register_cell_helpers, register_const_str_helper, register_contains_dyn_helper, + register_dict_del_helper, register_dict_helpers, register_dict_iter_helper, + register_dyn_attr_helpers, register_dyn_item_helpers, register_dyn_op_helpers, + register_float_pow_helper, register_global_obj_helper, register_guard_method_helper, + register_is_obj_helper, register_iter_helpers, register_iter_new_helper, + register_iter_next_pair_helper, register_list_extra_helpers, register_list_from_range_helper, + register_list_helpers, register_list_next_helper, register_math_helpers, + register_method_enter_helper, register_obj_getitem_helper, register_poll_helper, + register_self_call_helpers, register_str_format_helpers, register_str_helpers, + register_str_method_helper, register_str_write_helpers, register_truth_helper, + register_tuple_read_helpers, register_unbox_float_helper, register_unbox_int_helper, + set_obj_layout, AttrGetChainHelper, AttrGetHelper, AttrSetHelper, BuildListHelper, + BuildTupleHelper, BytesGetHelper, CachedAttrChainHelper, CallDynHelper, CallMethodHelper, + CallPyHelper, CallStatus, CellGetHelper, CellSetHelper, DictAccessHelper, DynAttrHelper, + GetIterHelper, GuardMethodHelper, IterNextHelper, IterNextPairHelper, JitFrame, JitStatus, + ListAppendHelper, ListFromRangeHelper, ListGetHelper, ListLenHelper, ListNextHelper, + ListRepeatHelper, ListSetHelper, ListSliceHelper, MathBinaryHelper, MathUnaryHelper, + MethodEnterHelper, ObjLayout, PollHelper, SelfEnterHelper, SelfExitHelper, SelfSlowHelper, + SlotTag, StrEqHelper, StrLenHelper, StrModHelper, CALL_GAPS, DICT_KEY_INT, DICT_KEY_STR, + DICT_VAL_FLOAT, DICT_VAL_INT, DICT_VAL_OBJ, ITER_ELEM_STR, JIT_POLL_STRIDE, MAX_ATTR_CHAIN_LEN, MAX_CACHED_ATTR_CHAIN_LEN, METHOD_GUARD_AT_CALL, METHOD_NATIVE, SLOT_FIELD, }; pub use value::JitType; diff --git a/crates/weavepy-jit/src/lower.rs b/crates/weavepy-jit/src/lower.rs index 1479c7350..d9b3cd08f 100644 --- a/crates/weavepy-jit/src/lower.rs +++ b/crates/weavepy-jit/src/lower.rs @@ -21,6 +21,7 @@ use crate::engine::{FieldAt, InlineMethod}; use crate::ir::{ArithKind, CmpKind, MathFunc, MethodRet, SliceOrigin, TFunc, TOp, TStmt, TTerm}; use crate::runtime::{self, JitFrame, JitStatus, SlotTag}; use crate::value::JitType; +use std::collections::HashMap; const OFF_LOCALS: i32 = core::mem::offset_of!(JitFrame, locals) as i32; const OFF_ENTRY_PC: i32 = core::mem::offset_of!(JitFrame, entry_pc) as i32; @@ -155,8 +156,37 @@ struct Lowerer<'a, 'b> { /// `Some` only when the embedder registered a poll helper and the /// function has loop headers to instrument. poll_countdown: Option, + /// Each obj-global's pin index for this native run, by the helper's + /// argument ([`Self::emit_push_global_obj`]): `i64::MIN` until a + /// load asks the helper, which answers one pin per activation and + /// token, so later loads (a loop's every iteration) reuse it. + global_obj_vars: HashMap, /// The abstract operand stack: SSA value + lane. vstack: Vec<(Value, JitType)>, + /// The local each loaded value came from (see [`Self::recv_facts`]). + local_of: HashMap, + /// Receivers validated on the way here, by the local that holds + /// them: the instance's payload pointer and its split values' block + /// (null on a path that didn't validate), as [`Self::split_field_addr`] + /// established them. They hold until something could change the + /// instance's layout or the pin table under them: a call that can run + /// code or store, the local's rebinding, the end of the block. A + /// further access of the local's attribute skips the receiver half of + /// its guard chain (the pin, the published dictionary, the names' + /// identity: some 35 instructions of 55). + recv_facts: Vec<(u32, Value, Value)>, + /// What the last [`Self::split_field_addr`] established on its hit + /// path, for its caller to carry past the join with its miss path. + pending_facts: Option<(u32, Value, Value)>, + /// Set by a statement that carried [`Self::recv_facts`] past its own + /// join (an in-line store or field update, whose hit path changes no + /// layout and whose helper path nulls them): [`Self::emit_stmt`] + /// then leaves them be. + facts_kept: bool, + /// Set for the method call the statement loop lowers directly: only + /// that one's in-line update carries the facts on (a call lowered + /// under an in-line body or a direct leaf runs more than the update). + facts_through_update: bool, /// This function itself, for direct self calls (see /// `engine::self_direct_eligible`); `None` when it makes none. self_func: Option, @@ -263,7 +293,13 @@ impl<'a, 'b> Lowerer<'a, 'b> { quad_sig: None, poll_sig: None, poll_countdown: None, + global_obj_vars: HashMap::default(), vstack: Vec::new(), + local_of: HashMap::default(), + recv_facts: Vec::new(), + pending_facts: None, + facts_kept: false, + facts_through_update: false, self_func: None, self_slot: None, self_sig: None, @@ -406,6 +442,28 @@ impl<'a, 'b> Lowerer<'a, 'b> { self.poll_countdown = Some(var); } + // The obj-globals' pin registers, unknown until first asked. + let mut codes: Vec = self + .tfunc + .blocks + .iter() + .flat_map(|b| &b.stmts) + .filter_map(|st| match st.op { + TOp::PushGlobalObj { token, lane } => { + Some(runtime::global_obj_list_code(token, lane)) + } + _ => None, + }) + .collect(); + codes.sort_unstable(); + codes.dedup(); + for code in codes { + let var = self.b.declare_var(types::I64); + let unknown = self.b.ins().iconst(types::I64, i64::MIN); + self.b.def_var(var, unknown); + self.global_obj_vars.insert(code, var); + } + // Declare + initialise a variable per managed local. self.vars = vec![None; self.tfunc.n_locals as usize]; self.assignable = assigned_slots(self.tfunc); @@ -518,6 +576,7 @@ impl<'a, 'b> Lowerer<'a, 'b> { } } let block = self.tfunc.blocks[bi].clone(); + self.recv_facts.clear(); let chain_helper = runtime::attr_get_chain_helper_addr(); let cached_chain_helper = runtime::cached_attr_chain_helper_addr(); let mut i = 0; @@ -595,6 +654,7 @@ impl<'a, 'b> Lowerer<'a, 'b> { int_result, &block.stmts[i..resume], ); + self.recv_facts.clear(); i = resume; continue; } @@ -637,6 +697,7 @@ impl<'a, 'b> Lowerer<'a, 'b> { out, stmt.pc, ); + self.recv_facts.clear(); i = end; continue; } @@ -1082,7 +1143,105 @@ impl<'a, 'b> Lowerer<'a, 'b> { }) } + /// Lower one statement, and drop the validated receivers (see + /// [`Self::recv_facts`]) it may have invalidated: anything but + /// loads, constants, arithmetic that built no call, and the + /// attribute reads, which carry them on themselves. fn emit_stmt(&mut self, stmt: TStmt) { + let calls = self.b.calls_emitted(); + self.facts_kept = false; + self.emit_stmt_inner(stmt); + let keeps = match stmt.op { + // (A read's helper stores nothing and runs no code. A store + // or a field update keeps them on its in-line path and says + // so.) + TOp::AttrGet { .. } => true, + TOp::AttrSet { .. } | TOp::CallMethod { .. } => std::mem::take(&mut self.facts_kept), + TOp::StoreLocal(slot) => { + self.recv_facts.retain(|f| f.0 != slot); + true + } + TOp::PushConstInt(_) + | TOp::PushConstBool(_) + | TOp::PushConstFloat(_) + | TOp::LoadLocal(_) + | TOp::IntArith(_) + | TOp::FloatArith(_) + | TOp::IntCmp(_) + | TOp::FloatCmp(_) + | TOp::IntNeg + | TOp::FloatNeg => self.b.calls_emitted() == calls, + _ => false, + }; + if !keeps { + self.recv_facts.clear(); + } + } + + /// The validated receiver in local `slot`, if any. + fn recv_fact(&self, slot: Option) -> Option<(Value, Value)> { + let slot = slot?; + self.recv_facts + .iter() + .find(|f| f.0 == slot) + .map(|f| (f.1, f.2)) + } + + /// Two block arguments for a receiver's facts: `fact`'s, or nulls. + fn fact_args(&mut self, fact: Option<(Value, Value)>) -> [BlockArg; 2] { + match fact { + Some((inst, block)) => [BlockArg::from(inst), BlockArg::from(block)], + None => { + let null = self.b.ins().iconst(self.ptr_ty, 0); + [BlockArg::from(null), BlockArg::from(null)] + } + } + } + + /// After the join `done` of a read's hit and miss paths, whose last + /// two parameters carry local `slot`'s facts: record them. + fn take_fact_params(&mut self, slot: u32, done: Block) { + let params = self.b.block_params(done); + let (inst, block) = (params[params.len() - 2], params[params.len() - 1]); + self.recv_facts.retain(|f| f.0 != slot); + self.recv_facts.push((slot, inst, block)); + } + + /// Parameters on `join` for every validated receiver's facts, after + /// the ones it has: an edge into it passes [`Self::fact_keep_args`] + /// (nothing on that path could invalidate them) or + /// [`Self::fact_null_args`], and [`Self::fact_rebind`] reads them back. + /// Returns the first one's position. + fn fact_params(&mut self, join: Block) -> usize { + let first = self.b.block_params(join).len(); + for _ in 0..self.recv_facts.len() * 2 { + self.b.append_block_param(join, self.ptr_ty); + } + first + } + + fn fact_keep_args(&self) -> Vec { + self.recv_facts + .iter() + .flat_map(|f| [BlockArg::from(f.1), BlockArg::from(f.2)]) + .collect() + } + + fn fact_null_args(&mut self) -> Vec { + let null = self.b.ins().iconst(self.ptr_ty, 0); + vec![BlockArg::from(null); self.recv_facts.len() * 2] + } + + fn fact_rebind(&mut self, join: Block, first: usize) { + let params = self.b.block_params(join).to_vec(); + for (k, f) in self.recv_facts.iter_mut().enumerate() { + f.1 = params[first + 2 * k]; + f.2 = params[first + 2 * k + 1]; + } + self.facts_kept = true; + } + + fn emit_stmt_inner(&mut self, stmt: TStmt) { match stmt.op { TOp::PushConstInt(v) => { let val = self.b.ins().iconst(types::I64, v); @@ -1100,6 +1259,7 @@ impl<'a, 'b> Lowerer<'a, 'b> { let ty = self.tfunc.local_types[slot as usize].unwrap_or(JitType::Int); let var = self.vars[slot as usize].expect("managed local"); let v = self.b.use_var(var); + self.local_of.insert(v, slot); self.vstack.push((v, ty)); } TOp::StoreLocal(slot) => { @@ -1243,7 +1403,9 @@ impl<'a, 'b> Lowerer<'a, 'b> { } else if let Some(ix) = self.method_leaf_for(token, argc, ret) { self.emit_call_method_leaf(ix, token, argc, ret, stmt.pc); } else { + self.facts_through_update = true; self.emit_call_method(token, argc, ret, stmt.pc); + self.facts_through_update = false; } } TOp::GuardMethod { token } => { @@ -1382,15 +1544,27 @@ impl<'a, 'b> Lowerer<'a, 'b> { /// interpreter re-executes the `LOAD_GLOBAL`. fn emit_push_global_obj(&mut self, token: u32, lane: JitType, pc: u32) { let snapshot = self.vstack.clone(); + let code = runtime::global_obj_list_code(token, lane); + // A load after the first in this run reads the pin it got. + let known = self.global_obj_vars.get(&code).copied(); + let join = known.map(|var| { + let cached = self.b.use_var(var); + let miss = self.b.ins().icmp_imm(IntCC::Equal, cached, i64::MIN); + let ask = self.b.create_block(); + let join = self.b.create_block(); + self.b.append_block_param(join, types::I64); + self.b + .ins() + .brif(miss, ask, &[], join, &[BlockArg::from(cached)]); + self.b.switch_to_block(ask); + (var, join) + }); let sig = self.pin_helper_sig(); let helper = self .b .ins() .iconst(self.ptr_ty, runtime::global_obj_helper_addr() as i64); - let tokenv = self - .b - .ins() - .iconst(types::I64, runtime::global_obj_list_code(token, lane)); + let tokenv = self.b.ins().iconst(types::I64, code); let call = self .b .ins() @@ -1399,6 +1573,15 @@ impl<'a, 'b> Lowerer<'a, 'b> { let bad = self.b.ins().icmp_imm(IntCC::SignedLessThan, res, -1); let cont = self.guard(bad, pc, &snapshot); self.b.switch_to_block(cont); + let res = match join { + Some((var, join)) => { + self.b.def_var(var, res); + self.b.ins().jump(join, &[BlockArg::from(res)]); + self.b.switch_to_block(join); + self.b.block_params(join)[0] + } + None => res, + }; self.vstack.push((res, lane)); } @@ -3006,12 +3189,22 @@ impl<'a, 'b> Lowerer<'a, 'b> { _ => None, }; let mut join = None; + // (The update's own path stores a field's value in place and + // calls nothing: validated receivers stay so past it.) + let carry = std::mem::take(&mut self.facts_through_update) && inline.is_some(); if let Some((l, arg)) = inline { let miss = self.b.create_block(); let done = self.b.create_block(); self.b.append_block_param(done, types::I64); + if carry { + self.fact_params(done); + } let v = self.inline_method_update(&l, pin, token, arg, miss); - self.b.ins().jump(done, &[BlockArg::from(v)]); + let mut args = vec![BlockArg::from(v)]; + if carry { + args.extend(self.fact_keep_args()); + } + self.b.ins().jump(done, &args); self.b.switch_to_block(miss); join = Some(done); } @@ -3068,8 +3261,15 @@ impl<'a, 'b> Lowerer<'a, 'b> { .load(Self::cl_ty(t), trusted, self.frame_ptr, OFF_RET_BITS); let res = match join { Some(done) => { - self.b.ins().jump(done, &[BlockArg::from(res)]); + let mut args = vec![BlockArg::from(res)]; + if carry { + args.extend(self.fact_null_args()); + } + self.b.ins().jump(done, &args); self.b.switch_to_block(done); + if carry { + self.fact_rebind(done, 1); + } self.b.block_params(done)[0] } None => res, @@ -3163,12 +3363,35 @@ impl<'a, 'b> Lowerer<'a, 'b> { let ver = self.b.ins().load(types::I64, t, e, l.method_ver); let cls = self.b.ins().load(ptr, t, inst, l.inst_class); let cver = self.b.ins().load(types::I64, t, cls, l.type_attr_version); - let lazy = self.b.ins().load(ptr, t, inst, l.inst_dict_lazy); let flag = self.b.ins().iconst(ptr, l.cells_unguarded as i64); let shared = self.b.ins().uload8(types::I64, t, flag, 0); + let stale = self.b.ins().icmp(IntCC::NotEqual, cver, ver); + // A `__slots__` member (the index says which form the helper + // armed): the slot at its position in the entry's layout. Its + // class's instances have no dictionary to shadow the method in. + let field = self.b.create_block(); + self.b.append_block_param(field, ptr); + if l.slots_ok { + let member = self.b.create_block(); + let split = self.b.create_block(); + let kind = self.b.ins().band_imm(idx, i64::from(runtime::SLOT_FIELD)); + self.b.ins().brif(kind, member, &[], split, &[]); + self.b.switch_to_block(member); + let shared_now = self.b.ins().icmp_imm(IntCC::NotEqual, shared, 0); + let bad = self.b.ins().bor(stale, shared_now); + self.miss_if(bad, miss); + let layout = self.b.ins().load(ptr, t, e, l.method_upd_layout); + let (vals, bad) = self.laid_out_slots(l, inst, layout, false); + self.miss_if(bad, miss); + let i = self.b.ins().band_imm(idx, i64::from(!runtime::SLOT_FIELD)); + let off = self.b.ins().ishl_imm(i, 4); + let at = self.b.ins().iadd(vals, off); + self.b.ins().jump(field, &[BlockArg::from(at)]); + self.b.switch_to_block(split); + } + let lazy = self.b.ins().load(ptr, t, inst, l.inst_dict_lazy); let borrow = self.b.ins().sload32(t, inst, l.inst_split_borrow); let block = self.b.ins().load(ptr, t, inst, l.inst_split_block); - let stale = self.b.ins().icmp(IntCC::NotEqual, cver, ver); let busy = self.b.ins().icmp_imm(IntCC::NotEqual, borrow, 0); let empty = self.b.ins().icmp_imm(IntCC::Equal, block, 0); let other = self.b.ins().bor(lazy, shared); @@ -3194,6 +3417,9 @@ impl<'a, 'b> Lowerer<'a, 'b> { let off = self.b.ins().ishl_imm(idx, 4); let at = self.b.ins().iadd(block, off); let at = self.b.ins().iadd_imm(at, i64::from(l.split_values)); + self.b.ins().jump(field, &[BlockArg::from(at)]); + self.b.switch_to_block(field); + let at = self.b.block_params(field)[0]; // An `int` field, plus the increment without overflow. let tag = self.b.ins().uload8(types::I32, t, at, 0); let not_int = self @@ -3452,6 +3678,16 @@ impl<'a, 'b> Lowerer<'a, 'b> { let trusted = MemFlags::trusted(); let snapshot = self.vstack.clone(); let (pin, _) = self.pop(); + // The receiver's local, when the read can carry its validation + // on (see `recv_facts`): the read helper stores nothing and runs + // no code, so what held before the read holds after it on + // either path, and the hit path may have established more. + let fact_slot = if runtime::obj_layout().is_some() { + self.local_of.get(&pin).copied() + } else { + None + }; + let prev_fact = self.recv_fact(fact_slot); // A scalar field of a split-layout instance, read in line; any // other shape takes the helper below. let inline = match (runtime::obj_layout(), out) { @@ -3459,11 +3695,82 @@ impl<'a, 'b> Lowerer<'a, 'b> { _ => None, }; let mut join = None; + // An object, `str` or `bytes` field that still holds the value + // the site read last: the pin that value got then, found again + // in line (the helper's own first answer, without the call). A + // field with another value, or of another type, takes the helper. + let pinned = match (runtime::obj_layout(), out) { + (Some(l), JitType::Obj) => Some((*l, l.tag_instance)), + (Some(l), JitType::Str) => Some((*l, l.tag_str)), + (Some(l), JitType::Bytes) => Some((*l, l.tag_bytes)), + _ => None, + }; + if let Some((l, want)) = pinned { + let ptr = self.ptr_ty; + let miss = self.b.create_block(); + let done = self.b.create_block(); + self.b.append_block_param(done, Self::cl_ty(out)); + if fact_slot.is_some() { + self.b.append_block_param(done, ptr); + self.b.append_block_param(done, ptr); + } + let addr = self.split_field_addr(&l, pin, site, miss, true); + let hit_fact = self.pending_facts.take().map(|f| (f.1, f.2)).or(prev_fact); + let tag = self.b.ins().uload8(types::I32, trusted, addr, 0); + let other = self.b.ins().icmp_imm(IntCC::NotEqual, tag, i64::from(want)); + self.miss_if(other, miss); + let value = self.b.ins().load(types::I64, trusted, addr, 8); + // The guard's hint, and the pin it names. + let ctx = self.b.ins().load(ptr, trusted, self.frame_ptr, OFF_CTX); + let guards = self.b.ins().load(ptr, trusted, ctx, l.ctx_guards); + let gbuf = self.b.ins().load(ptr, trusted, guards, l.guards_buf); + let g = self + .b + .ins() + .iadd_imm(gbuf, i64::from(site) * i64::from(l.guard_size)); + let hint = self.b.ins().load(types::I64, trusted, g, l.guard_last_pin); + let n = self.b.ins().load(types::I64, trusted, ctx, l.ctx_pins_len); + let gone = self + .b + .ins() + .icmp(IntCC::UnsignedGreaterThanOrEqual, hint, n); + self.miss_if(gone, miss); + let buf = self.b.ins().load(ptr, trusted, ctx, l.ctx_pins_ptr); + let off = self.b.ins().imul_imm(hint, i64::from(l.pin_size)); + let p = self.b.ins().iadd(buf, off); + let ptag = self.b.ins().uload8(types::I32, trusted, p, l.pin_tag); + let otag = self.b.ins().uload8(types::I32, trusted, p, l.pin_obj); + let held = self.b.ins().load(types::I64, trusted, p, l.pin_obj + 8); + let not_obj = self + .b + .ins() + .icmp_imm(IntCC::NotEqual, ptag, i64::from(l.pin_obj_tag)); + let not_kind = self + .b + .ins() + .icmp_imm(IntCC::NotEqual, otag, i64::from(want)); + let not_same = self.b.ins().icmp(IntCC::NotEqual, held, value); + let bad = self.b.ins().bor(not_obj, not_kind); + let bad = self.b.ins().bor(bad, not_same); + self.miss_if(bad, miss); + let mut args = vec![BlockArg::from(hint)]; + if fact_slot.is_some() { + args.extend(self.fact_args(hit_fact)); + } + self.b.ins().jump(done, &args); + self.b.switch_to_block(miss); + join = Some(done); + } if let Some(l) = inline { let miss = self.b.create_block(); let done = self.b.create_block(); self.b.append_block_param(done, Self::cl_ty(out)); + if fact_slot.is_some() { + self.b.append_block_param(done, self.ptr_ty); + self.b.append_block_param(done, self.ptr_ty); + } let addr = self.split_field_addr(&l, pin, site, miss, true); + let hit_fact = self.pending_facts.take().map(|f| (f.1, f.2)).or(prev_fact); let (want, off, ty) = match out { JitType::Int => (l.tag_int, 8, types::I64), JitType::Float => (l.tag_float, 8, types::F64), @@ -3478,7 +3785,11 @@ impl<'a, 'b> Lowerer<'a, 'b> { } else { v }; - self.b.ins().jump(done, &[BlockArg::from(v)]); + let mut args = vec![BlockArg::from(v)]; + if fact_slot.is_some() { + args.extend(self.fact_args(hit_fact)); + } + self.b.ins().jump(done, &args); self.b.switch_to_block(miss); join = Some(done); } @@ -3502,8 +3813,15 @@ impl<'a, 'b> Lowerer<'a, 'b> { .load(Self::cl_ty(out), trusted, self.frame_ptr, OFF_RET_BITS); let res = match join { Some(done) => { - self.b.ins().jump(done, &[BlockArg::from(res)]); + let mut args = vec![BlockArg::from(res)]; + if fact_slot.is_some() { + args.extend(self.fact_args(prev_fact)); + } + self.b.ins().jump(done, &args); self.b.switch_to_block(done); + if let Some(slot) = fact_slot { + self.take_fact_params(slot, done); + } self.b.block_params(done)[0] } None => res, @@ -3543,95 +3861,168 @@ impl<'a, 'b> Lowerer<'a, 'b> { .attr_sites .get(site as usize) .is_some_and(|s| s.slot_member); + self.pending_facts = None; + let slot = self.local_of.get(&pin).copied(); let ctx = self.b.ins().load(ptr, t, self.frame_ptr, OFF_CTX); - // The guard first: a site whose field has no position of this kind - // leaves straight away. - let guards = self.b.ins().load(ptr, t, ctx, l.ctx_guards); - let gbuf = self.b.ins().load(ptr, t, guards, l.guards_buf); - let g = self - .b - .ins() - .iadd_imm(gbuf, i64::from(site) * i64::from(l.guard_size)); - let idx = self.b.ins().uload32(t, g, l.guard_split_idx); - let none = if slot_member { - let kind = self.b.ins().band_imm(idx, i64::from(runtime::SLOT_FIELD)); - self.b.ins().icmp_imm(IntCC::Equal, kind, 0) - } else { - self.b - .ins() - .icmp_imm(IntCC::Equal, idx, i64::from(u32::MAX)) + // The site's guard: its index, class version and (for a member + // slot) layout word, as constants when the embedder gave them + // (a guard doesn't change once made), read from the guard table + // otherwise. + let burned = self + .tfunc + .attr_sites + .get(site as usize) + .and_then(|s| s.position); + let (idx, ver, layout) = match burned { + Some((ver, idx, layout)) => ( + self.b.ins().iconst(types::I64, i64::from(idx)), + self.b.ins().iconst(types::I64, ver as i64), + self.b.ins().iconst(ptr, layout as i64), + ), + None => { + let guards = self.b.ins().load(ptr, t, ctx, l.ctx_guards); + let gbuf = self.b.ins().load(ptr, t, guards, l.guards_buf); + let g = self + .b + .ins() + .iadd_imm(gbuf, i64::from(site) * i64::from(l.guard_size)); + let idx = self.b.ins().uload32(t, g, l.guard_split_idx); + let ver = self.b.ins().load(types::I64, t, g, l.guard_ver); + let layout = if slot_member { + self.b.ins().load(ptr, t, g, l.guard_slot_layout) + } else { + self.b.ins().iconst(ptr, 0) + }; + (idx, ver, layout) + } }; - // The pin. - let n = self.b.ins().load(types::I64, t, ctx, l.ctx_pins_len); - let out = self.b.ins().icmp(IntCC::UnsignedGreaterThanOrEqual, pin, n); - let bad = self.b.ins().bor(none, out); - self.miss_if(bad, miss); - let buf = self.b.ins().load(ptr, t, ctx, l.ctx_pins_ptr); - let off = self.b.ins().imul_imm(pin, i64::from(l.pin_size)); - let p = self.b.ins().iadd(buf, off); - let ptag = self.b.ins().uload8(types::I32, t, p, l.pin_tag); - let otag = self.b.ins().uload8(types::I32, t, p, l.pin_obj); - let not_obj = self - .b - .ins() - .icmp_imm(IntCC::NotEqual, ptag, i64::from(l.pin_obj_tag)); - let not_inst = self - .b - .ins() - .icmp_imm(IntCC::NotEqual, otag, i64::from(l.tag_instance)); - let bad = self.b.ins().bor(not_obj, not_inst); - self.miss_if(bad, miss); - let inst = self.b.ins().load(ptr, t, p, l.pin_obj + 8); - let ver = self.b.ins().load(types::I64, t, g, l.guard_ver); - let cls = self.b.ins().load(ptr, t, inst, l.inst_class); - let cver = self.b.ins().load(types::I64, t, cls, l.type_attr_version); - let flag = self.b.ins().iconst(ptr, l.cells_unguarded as i64); - let shared = self.b.ins().uload8(types::I64, t, flag, 0); - let stale = self.b.ins().icmp(IntCC::NotEqual, cver, ver); if slot_member { - // The member slot at its position in the guard's layout. + // The pin, then the member slot at its position in the + // guard's layout. + let kind = self.b.ins().band_imm(idx, i64::from(runtime::SLOT_FIELD)); + let none = self.b.ins().icmp_imm(IntCC::Equal, kind, 0); + let n = self.b.ins().load(types::I64, t, ctx, l.ctx_pins_len); + let out = self.b.ins().icmp(IntCC::UnsignedGreaterThanOrEqual, pin, n); + let bad = self.b.ins().bor(none, out); + self.miss_if(bad, miss); + let inst = self.pinned_instance(l, ctx, pin, miss); + let cls = self.b.ins().load(ptr, t, inst, l.inst_class); + let cver = self.b.ins().load(types::I64, t, cls, l.type_attr_version); + let flag = self.b.ins().iconst(ptr, l.cells_unguarded as i64); + let shared = self.b.ins().uload8(types::I64, t, flag, 0); + let stale = self.b.ins().icmp(IntCC::NotEqual, cver, ver); let shared = self.b.ins().icmp_imm(IntCC::NotEqual, shared, 0); let bad = self.b.ins().bor(stale, shared); self.miss_if(bad, miss); - let layout = self.b.ins().load(ptr, t, g, l.guard_slot_layout); let (vals, bad) = self.laid_out_slots(l, inst, layout, read); self.miss_if(bad, miss); let i = self.b.ins().band_imm(idx, i64::from(!runtime::SLOT_FIELD)); let off = self.b.ins().ishl_imm(i, 4); return self.b.ins().iadd(vals, off); } - // The split values (grouped by what each group's loads need proven: - // fewer blocks compile faster). + // The receiver: validated already on the way here (see + // `recv_facts`), or now: an instance pin with no published + // dictionary, whose values are split over its class's names, + // while cells are read without guards. + let have = self.b.create_block(); + self.b.append_block_param(have, ptr); + self.b.append_block_param(have, ptr); + if let Some((inst, block)) = self.recv_fact(slot) { + let full = self.b.create_block(); + self.b.ins().brif( + block, + have, + &[BlockArg::from(inst), BlockArg::from(block)], + full, + &[], + ); + self.b.switch_to_block(full); + } + let n = self.b.ins().load(types::I64, t, ctx, l.ctx_pins_len); + let out = self.b.ins().icmp(IntCC::UnsignedGreaterThanOrEqual, pin, n); + self.miss_if(out, miss); + let inst = self.pinned_instance(l, ctx, pin, miss); + let cls = self.b.ins().load(ptr, t, inst, l.inst_class); let lazy = self.b.ins().load(ptr, t, inst, l.inst_dict_lazy); - let borrow = self.b.ins().sload32(t, inst, l.inst_split_borrow); + let flag = self.b.ins().iconst(ptr, l.cells_unguarded as i64); + let shared = self.b.ins().uload8(types::I64, t, flag, 0); let block = self.b.ins().load(ptr, t, inst, l.inst_split_block); - let busy = if read { - self.b.ins().icmp_imm(IntCC::SignedLessThan, borrow, 0) - } else { - self.b.ins().icmp_imm(IntCC::NotEqual, borrow, 0) - }; let empty = self.b.ins().icmp_imm(IntCC::Equal, block, 0); let other = self.b.ins().bor(lazy, shared); let other = self.b.ins().icmp_imm(IntCC::NotEqual, other, 0); - let bad = self.b.ins().bor(stale, busy); - let bad = self.b.ins().bor(bad, empty); - let bad = self.b.ins().bor(bad, other); + let bad = self.b.ins().bor(empty, other); self.miss_if(bad, miss); let keys = self.b.ins().load(ptr, t, block, l.split_keys); let ckeys = self.b.ins().load(ptr, t, cls, l.type_shared_keys); - let len = self.b.ins().uload32(t, block, l.split_len); let foreign = self.b.ins().icmp(IntCC::NotEqual, keys, ckeys); + self.miss_if(foreign, miss); + self.b + .ins() + .jump(have, &[BlockArg::from(inst), BlockArg::from(block)]); + self.b.switch_to_block(have); + let (inst, block) = { + let p = self.b.block_params(have); + (p[0], p[1]) + }; + // The split values. The receiver half was done above; what is + // left is the site's: its class version, the borrow rule for + // this access, and its index within the block. + let cls = self.b.ins().load(ptr, t, inst, l.inst_class); + let cver = self.b.ins().load(types::I64, t, cls, l.type_attr_version); + let borrow = self.b.ins().sload32(t, inst, l.inst_split_borrow); + let len = self.b.ins().uload32(t, block, l.split_len); + let stale = self.b.ins().icmp(IntCC::NotEqual, cver, ver); + let busy = if read { + self.b.ins().icmp_imm(IntCC::SignedLessThan, borrow, 0) + } else { + self.b.ins().icmp_imm(IntCC::NotEqual, borrow, 0) + }; + // (An index of `u32::MAX`, a site with no position, is past any + // length.) let absent = self .b .ins() .icmp(IntCC::UnsignedGreaterThanOrEqual, idx, len); - let bad = self.b.ins().bor(foreign, absent); + let bad = self.b.ins().bor(stale, busy); + let bad = self.b.ins().bor(bad, absent); self.miss_if(bad, miss); + if let Some(slot) = slot { + self.pending_facts = Some((slot, inst, block)); + } let off = self.b.ins().ishl_imm(idx, 4); let at = self.b.ins().iadd(block, off); self.b.ins().iadd_imm(at, i64::from(l.split_values)) } + /// The payload pointer of the instance the pin at index `pin` (in + /// range) holds; a pin of another kind branches to `miss`. + fn pinned_instance( + &mut self, + l: &runtime::ObjLayout, + ctx: Value, + pin: Value, + miss: Block, + ) -> Value { + let t = MemFlags::trusted(); + let ptr = self.ptr_ty; + let buf = self.b.ins().load(ptr, t, ctx, l.ctx_pins_ptr); + let off = self.b.ins().imul_imm(pin, i64::from(l.pin_size)); + let p = self.b.ins().iadd(buf, off); + let ptag = self.b.ins().uload8(types::I32, t, p, l.pin_tag); + let otag = self.b.ins().uload8(types::I32, t, p, l.pin_obj); + let not_obj = self + .b + .ins() + .icmp_imm(IntCC::NotEqual, ptag, i64::from(l.pin_obj_tag)); + let not_inst = self + .b + .ins() + .icmp_imm(IntCC::NotEqual, otag, i64::from(l.tag_instance)); + let bad = self.b.ins().bor(not_obj, not_inst); + self.miss_if(bad, miss); + self.b.ins().load(ptr, t, p, l.pin_obj + 8) + } + /// The address the new-key store at `site` appends its field to, in /// the pinned instance `pin`'s split values (see /// [`runtime::ObjLayout`]), having counted it in: an ordinary instance @@ -3970,6 +4361,7 @@ impl<'a, 'b> Lowerer<'a, 'b> { // The constructor pattern: a fresh instance's next field. let miss = self.b.create_block(); let stored = self.b.create_block(); + self.fact_params(stored); let addr = self.split_append_addr(&l, pin, site, miss); let (tag, off, v) = match lane { JitType::Int => (l.tag_int, 8, val), @@ -3979,12 +4371,15 @@ impl<'a, 'b> Lowerer<'a, 'b> { let tagv = self.b.ins().iconst(types::I8, i64::from(tag)); self.b.ins().store(trusted, tagv, addr, 0); self.b.ins().store(trusted, v, addr, off); - self.b.ins().jump(stored, &[]); + // (A scalar stored in place: no layout changed, nothing ran.) + let keep = self.fact_keep_args(); + self.b.ins().jump(stored, &keep); self.b.switch_to_block(miss); done = Some(stored); } else if let Some(l) = inline { let miss = self.b.create_block(); let stored = self.b.create_block(); + self.fact_params(stored); let addr = self.split_field_addr(&l, pin, site, miss, false); let old = self.b.ins().uload8(types::I64, trusted, addr, 0); let one = self.b.ins().iconst(types::I64, 1); @@ -4006,7 +4401,9 @@ impl<'a, 'b> Lowerer<'a, 'b> { let tagv = self.b.ins().iconst(types::I8, i64::from(tag)); self.b.ins().store(trusted, tagv, addr, 0); self.b.ins().store(trusted, v, addr, off); - self.b.ins().jump(stored, &[]); + // (A scalar stored in place: no layout changed, nothing ran.) + let keep = self.fact_keep_args(); + self.b.ins().jump(stored, &keep); self.b.switch_to_block(miss); done = Some(stored); } @@ -4038,8 +4435,12 @@ impl<'a, 'b> Lowerer<'a, 'b> { let cont = self.guard(bad, pc, &snapshot); self.b.switch_to_block(cont); if let Some(stored) = done { - self.b.ins().jump(stored, &[]); + // (The helper may have reshaped the receiver: nothing + // validated before it is taken on trust after.) + let nulls = self.fact_null_args(); + self.b.ins().jump(stored, &nulls); self.b.switch_to_block(stored); + self.fact_rebind(stored, 0); } } diff --git a/crates/weavepy-jit/src/runtime.rs b/crates/weavepy-jit/src/runtime.rs index e0e576fd6..3c5ed55a0 100644 --- a/crates/weavepy-jit/src/runtime.rs +++ b/crates/weavepy-jit/src/runtime.rs @@ -196,6 +196,10 @@ pub struct ObjLayout { pub guard_ver: i32, pub guard_split_idx: i32, pub guard_slot_layout: i32, + /// A guard's hint (a word): the pin that held the value its site last + /// read into the object, `str` or `bytes` lane. A read that finds the + /// same value in the field takes that pin again in line. + pub guard_last_pin: i32, /// Object tags (the first byte of a value); a word payload is at 8, a /// `bool`'s at 1. pub tag_instance: u8, @@ -203,6 +207,8 @@ pub struct ObjLayout { pub tag_float: u8, pub tag_bool: u8, pub tag_none: u8, + pub tag_str: u8, + pub tag_bytes: u8, /// A class value's tag (its payload pointer is the class pointer). pub tag_type: u8, /// An instance value's payload pointer → the instance's class pointer, @@ -260,6 +266,10 @@ pub struct ObjLayout { pub method_upd_inc: i32, pub method_upd_code_at: i32, pub method_upd_code: i32, + /// The slot layout's word (a word) of an update whose field is a + /// `__slots__` member: its index then carries [`SLOT_FIELD`] and is + /// the member's position in that layout, as an attribute guard's. + pub method_upd_layout: i32, /// Words (or a byte, for `dict_watchers`) that are nonzero while a /// call can't be skipped: an observer may be active, a dict watcher /// is, or a class may hold an exotic key. @@ -304,6 +314,14 @@ pub(crate) fn obj_layout() -> Option<&'static ObjLayout> { OBJ_LAYOUT.get() } +/// Whether an object layout is published, and if so whether it covers +/// member slots (see [`ObjLayout::slots_ok`]): what an embedder needs to +/// tell which attribute sites compiled code handles in line. +#[must_use] +pub fn obj_layout_published() -> Option { + OBJ_LAYOUT.get().map(|l| l.slots_ok) +} + /// The exchange buffer the VM passes to a compiled frame. /// /// The VM owns the backing storage (`Vec` / `Vec`); this diff --git a/crates/weavepy-jit/tests/frame_coverage.rs b/crates/weavepy-jit/tests/frame_coverage.rs index edad821da..51af9c15a 100644 --- a/crates/weavepy-jit/tests/frame_coverage.rs +++ b/crates/weavepy-jit/tests/frame_coverage.rs @@ -121,6 +121,8 @@ fn analyze_code_carved( obj_global: &mut obj_global, cell: &mut |_| None, obj: &mut |_| false, + py_callee: &mut |_| false, + py_operator: &mut |_| false, local: &mut |_| None, stack_iter: &mut |_| None, pairs: &mut |_| None, @@ -784,6 +786,8 @@ fn shadowed_enumerate_gets_no_trained_lanes() { obj_global: &mut obj_global, cell: &mut |_| None, obj: &mut |_| false, + py_callee: &mut |_| false, + py_operator: &mut |_| false, local: &mut |_| None, stack_iter: &mut |_| None, pairs: &mut |_| None, diff --git a/crates/weavepy-jit/tests/helper_registration.rs b/crates/weavepy-jit/tests/helper_registration.rs index 54993311c..35382f384 100644 --- a/crates/weavepy-jit/tests/helper_registration.rs +++ b/crates/weavepy-jit/tests/helper_registration.rs @@ -33,6 +33,8 @@ fn function(ops: &[TOp]) -> TFunc { math_guards: vec![], math_spans: vec![], null_spans: vec![], + py_dyn_calls: vec![], + leaf_calls: vec![], osr_entries: vec![], max_call_args: 1, ret_lane: None, diff --git a/crates/weavepy-jit/tests/numeric.rs b/crates/weavepy-jit/tests/numeric.rs index a0e10c7a5..d6d484e3a 100644 --- a/crates/weavepy-jit/tests/numeric.rs +++ b/crates/weavepy-jit/tests/numeric.rs @@ -90,6 +90,8 @@ fn integer_binary(kind: ArithKind) -> TFunc { math_guards: vec![], math_spans: vec![], null_spans: vec![], + py_dyn_calls: vec![], + leaf_calls: vec![], osr_entries: vec![], max_call_args: 0, ret_lane: None, @@ -238,6 +240,8 @@ fn add_overflow_deopts_with_operands_spilled() { math_guards: vec![], math_spans: vec![], null_spans: vec![], + py_dyn_calls: vec![], + leaf_calls: vec![], osr_entries: vec![], max_call_args: 0, ret_lane: None, @@ -292,6 +296,8 @@ fn sum_loop() -> TFunc { math_guards: vec![], math_spans: vec![], null_spans: vec![], + py_dyn_calls: vec![], + leaf_calls: vec![], osr_entries: vec![], max_call_args: 0, ret_lane: None, @@ -395,6 +401,8 @@ fn binop_fn(op: ArithKind) -> TFunc { math_guards: vec![], math_spans: vec![], null_spans: vec![], + py_dyn_calls: vec![], + leaf_calls: vec![], osr_entries: vec![], max_call_args: 0, ret_lane: None, @@ -481,6 +489,8 @@ fn int_truediv_returns_float() { math_guards: vec![], math_spans: vec![], null_spans: vec![], + py_dyn_calls: vec![], + leaf_calls: vec![], osr_entries: vec![], max_call_args: 0, ret_lane: None, diff --git a/crates/weavepy-jit/tests/range_loops.rs b/crates/weavepy-jit/tests/range_loops.rs index 236d8a69f..ea03abc71 100644 --- a/crates/weavepy-jit/tests/range_loops.rs +++ b/crates/weavepy-jit/tests/range_loops.rs @@ -180,3 +180,50 @@ fn params_are_entry_guarded() { tfunc.livein_locals ); } + +const KERNEL: &str = + "def kernel(n):\n total = 0\n for i in range(n):\n total = total + i * 2\n return total\n"; + +#[test] +fn work_budget_counts_passes_over_the_code() { + let code = compile_first_fn(KERNEL); + let len = code.instructions.len() as u64; + let (res, spent, short) = + weavepy_jit::with_work_budget(len * 100, || analyze(&code, &mut range_only)); + assert!(res.is_ok()); + assert!(!short); + // One unit an instruction for each pass, and the kernel needs few. + assert!( + spent >= len && spent % len == 0 && spent <= len * 4, + "{spent} units for {len}" + ); + // The budget is restored: an analysis outside one is unlimited. + assert!(!weavepy_jit::work_short()); + assert!(analyze(&code, &mut range_only).is_ok()); +} + +#[test] +fn work_budget_too_small_fails_as_a_retriable_miss() { + let code = compile_first_fn(KERNEL); + let len = code.instructions.len() as u64; + let (res, spent, short) = + weavepy_jit::with_work_budget(len - 1, || analyze(&code, &mut range_only)); + assert_eq!( + res.err(), + Some(JitVerdict::ProbeMiss(weavepy_jit::OVER_BUDGET)) + ); + assert!(short); + assert_eq!(spent, len - 1); + // Every analysis after it in the same budget fails the same way, so + // one that reads the result of a callee's doesn't finish on it. + let (res, _, short) = weavepy_jit::with_work_budget(len + len / 2, || { + let first = analyze(&code, &mut range_only); + assert!(first.is_ok()); + analyze(&code, &mut range_only) + }); + assert_eq!( + res.err(), + Some(JitVerdict::ProbeMiss(weavepy_jit::OVER_BUDGET)) + ); + assert!(short); +} diff --git a/crates/weavepy-parser/src/parser.rs b/crates/weavepy-parser/src/parser.rs index b47868712..4c6cc94c9 100644 --- a/crates/weavepy-parser/src/parser.rs +++ b/crates/weavepy-parser/src/parser.rs @@ -2453,7 +2453,8 @@ impl<'src> Parser<'src> { // (positional-only, positional-or-keyword, `*args`, keyword-only, // `**kwargs`) — CPython raises "duplicate argument '' in // function definition". - let mut seen: Vec<&str> = Vec::new(); + // (A set: generated signatures run to thousands of parameters.) + let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new(); let dup_span = |span: Span, name: &str| ParseError::Unexpected { span, message: format!("duplicate argument '{name}' in function definition"), @@ -2466,10 +2467,9 @@ impl<'src> Parser<'src> { .chain(args.kwonlyargs.iter()) .chain(args.kwarg.iter()) { - if seen.contains(&a.name.as_str()) { + if !seen.insert(a.name.as_str()) { return Err(dup_span(a.span, &a.name)); } - seen.push(a.name.as_str()); } Ok(args) } diff --git a/crates/weavepy-vm/Cargo.toml b/crates/weavepy-vm/Cargo.toml index 0730ec720..a43785917 100644 --- a/crates/weavepy-vm/Cargo.toml +++ b/crates/weavepy-vm/Cargo.toml @@ -63,6 +63,7 @@ memmap2 = { workspace = true } memchr = { workspace = true } libc = { workspace = true } rustls = { workspace = true } +ring = { workspace = true } rustls-pki-types = { workspace = true } pkcs8 = { workspace = true } rustls-pemfile = { workspace = true } diff --git a/crates/weavepy-vm/src/builtin_types.rs b/crates/weavepy-vm/src/builtin_types.rs index 696ac1853..82a82637e 100644 --- a/crates/weavepy-vm/src/builtin_types.rs +++ b/crates/weavepy-vm/src/builtin_types.rs @@ -58,6 +58,10 @@ pub struct BuiltinTypes { pub map_: Rc, pub filter_: Rc, pub zip_: Rc, + /// `callable_iterator`, the type of `iter(callable, sentinel)`: no + /// constructor of its own, its instances native adapters (see + /// `crate::seqiter`). + pub callable_iterator_: Rc, pub none_type: Rc, pub ellipsis_: Rc, pub not_implemented_type_: Rc, @@ -219,6 +223,11 @@ impl BuiltinTypes { TypeObject::new_exception(name, base).expect("built-in exception must linearise") }; let object_ = mk("object", vec![]); + // `object()`: a bare instance (as `b_object` builds it). + object_.pure_new.set(Some(|cls, args| { + args.is_empty() + .then(|| Object::Instance(Rc::new(crate::types::PyInstance::new(cls.clone())))) + })); // `object()` instances carry no `__dict__` (tp_dictoffset 0 in // CPython): attribute writes on a plain object raise // AttributeError, and weak references to one are refused. @@ -250,6 +259,22 @@ impl BuiltinTypes { let float_ = mk("float", vec![object_.clone()]); let bool_ = mk("bool", vec![int_.clone()]); let complex_ = mk("complex", vec![object_.clone()]); + // `complex()`, `complex(x)` and `complex(x, y)` of plain numbers. + complex_.pure_new.set(Some(|_, args| { + let num = |o: &Object| match o { + Object::Int(i) => Some(*i as f64), + Object::Float(f) => Some(*f), + Object::Bool(b) => Some(f64::from(u8::from(*b))), + _ => None, + }; + let (re, im) = match args { + [] => (0.0, 0.0), + [a] => (num(a)?, 0.0), + [a, b] => (num(a)?, num(b)?), + _ => return None, + }; + Some(Object::new_complex(re, im)) + })); let str_ = mk("str", vec![object_.clone()]); let bytes_ = mk("bytes", vec![object_.clone()]); let bytearray_ = mk("bytearray", vec![object_.clone()]); @@ -261,6 +286,11 @@ impl BuiltinTypes { let range_ = mk("range", vec![object_.clone()]); let slice_ = mk("slice", vec![object_.clone()]); let memoryview_ = mk("memoryview", vec![object_.clone()]); + // `memoryview(b)` of a `bytes` or `bytearray`. + memoryview_.pure_new.set(Some(|_, args| match args { + [Object::Bytes(_) | Object::ByteArray(_)] => crate::builtins::b_memoryview(args).ok(), + _ => None, + })); let mappingproxy_ = mk("mappingproxy", vec![object_.clone()]); // `types.MappingProxyType(mapping)` is a live read-only *view*: // wrapping a dict shares the underlying storage (CPython's @@ -380,6 +410,7 @@ impl BuiltinTypes { let map_ = mk("map", vec![object_.clone()]); let filter_ = mk("filter", vec![object_.clone()]); let zip_ = mk("zip", vec![object_.clone()]); + let callable_iterator_ = mk("callable_iterator", vec![object_.clone()]); let none_type = mk("NoneType", vec![object_.clone()]); let ellipsis_ = mk("ellipsis", vec![object_.clone()]); let not_implemented_type_ = mk("NotImplementedType", vec![object_.clone()]); @@ -961,6 +992,33 @@ impl BuiltinTypes { } } + // The builtin types `seqiter::builtin_ctor_arms` builds for some + // arguments, and the lazy adapters: their constructors' pure halves + // (any other builtin type's call skips them at a load). + for ty in [ + &bool_, + &bytearray_, + &bytes_, + &dict_, + &enumerate_, + &float_, + &frozenset_, + &int_, + &list_, + &method_, + &reversed_, + &set_, + &slice_, + &str_, + &super_, + &tuple_, + &type_, + ] { + ty.pure_new.set(Some(crate::seqiter::builtin_ctor_arms)); + } + for ty in [&map_, &filter_, &zip_] { + ty.pure_new.set(Some(crate::seqiter::seq_ctor_pure)); + } let bt = BuiltinTypes { object_: object_.clone(), type_: type_.clone(), @@ -992,6 +1050,7 @@ impl BuiltinTypes { map_, filter_, zip_, + callable_iterator_, none_type, ellipsis_, not_implemented_type_, @@ -1354,10 +1413,8 @@ impl BuiltinTypes { thread_local! { // The registry handles are local to this thread; only the referenced // type objects are shared. Borrowing a handle needs no object lock. - static BUILTIN_TYPES: std::cell::RefCell>> = - const { std::cell::RefCell::new(None) }; - static PROPERTY_CLASS: std::cell::RefCell>> = - const { std::cell::RefCell::new(None) }; + static BUILTIN_TYPES: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(None)) }; + static PROPERTY_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(None)) }; /// The adopted registry behind [`builtin_types`]'s fast path. static BUILTIN_TYPES_PTR: std::cell::Cell<*const BuiltinTypes> = const { std::cell::Cell::new(std::ptr::null()) }; @@ -1660,7 +1717,7 @@ pub fn make_unicode_decode_error( .unwrap_or_else(|| bt.value_error.clone()); let inst = PyInstance::new(class); let enc = Object::from_str(encoding); - let obj = Object::new_bytes(object.to_vec()); + let obj = Object::new_bytes(object); let start_o = Object::Int(start as i64); let end_o = Object::Int(end as i64); let reason_o = Object::from_str(reason); @@ -1725,6 +1782,77 @@ fn any_elements(obj: &Object) -> Option> { concrete_elements(obj).or_else(|| elements_via_interp(obj)) } +/// What `object.__new__` asks of a user class's bases, from one walk of its +/// MRO: the position in `kinds` (see [`native_seed_for_new`]) of the value or +/// container type it derives from, and whether it derives from `module`, +/// `type` or `types.GenericAlias`. Memoized by the class's version, which is +/// unique across classes and moves with any reshaping of its MRO. +#[derive(Clone, Copy)] +struct BaseFacts { + seed: Option, + module: bool, + type_: bool, + alias: bool, +} + +fn base_facts(cls: &Rc, kinds: &[&Rc; 11]) -> BaseFacts { + thread_local! { + static SEEN: [std::cell::Cell<(u64, u8)>; 64] = + const { [const { std::cell::Cell::new((0, 0)) }; 64] }; + } + const NONE: u8 = 0x0f; + let ver = cls.attr_version.get(); + let slot = (ver as usize ^ (ver >> 6) as usize) & 63; + let unpack = |tag: u8| BaseFacts { + seed: (tag & NONE != NONE).then_some(usize::from(tag & NONE)), + module: tag & 0x10 != 0, + type_: tag & 0x20 != 0, + alias: tag & 0x40 != 0, + }; + let memo = SEEN.with(|s| s[slot].get()); + if ver != 0 && memo.0 == ver { + return unpack(memo.1); + } + let bt = builtin_types(); + let mut tag = NONE; + for t in cls.mro.borrow().iter().skip(1) { + if tag & NONE == NONE { + if let Some(i) = kinds.iter().position(|k| Rc::ptr_eq(t, k)) { + tag = (tag & !NONE) | i as u8; + } + } + if Rc::ptr_eq(t, &bt.module_) { + tag |= 0x10; + } else if Rc::ptr_eq(t, &bt.type_) { + tag |= 0x20; + } else if Rc::ptr_eq(t, &bt.generic_alias_) { + tag |= 0x40; + } + } + if ver != 0 { + SEEN.with(|s| s[slot].set((ver, tag))); + } + unpack(tag) +} + +/// The value or container kinds [`native_seed_for_new`] seeds, in the order +/// [`BaseFacts::seed`] numbers them. +fn seed_kinds(bt: &BuiltinTypes) -> [&Rc; 11] { + [ + &bt.int_, + &bt.float_, + &bt.complex_, + &bt.str_, + &bt.bytearray_, + &bt.bytes_, + &bt.tuple_, + &bt.frozenset_, + &bt.list_, + &bt.set_, + &bt.dict_, + ] +} + /// Build the native payload `object.__new__(cls, value?)` should stash /// on an instance of a value/container built-in subclass, or `None` for /// an ordinary `object` subclass. Mutable containers (`list`/`dict`/ @@ -1737,7 +1865,14 @@ fn native_seed_for_new(cls: &Rc, value: Option<&Object>) -> Option| cls.is_subclass_of(base) && !Rc::ptr_eq(cls, base); + // The one value or container type among these the class derives from + // (no class derives from two: their layouts conflict), found in one + // walk of its MRO instead of a subclass test per kind. + let kinds = seed_kinds(bt); + let found = base_facts(cls, &kinds).seed; + let is_strict = |base: &Rc| { + found.is_some_and(|i| Rc::ptr_eq(kinds[i], base)) && !Rc::ptr_eq(cls, base) + }; if is_strict(&bt.int_) { return Some(match value { None => Object::Int(0), @@ -1848,7 +1983,7 @@ pub(crate) fn object_new(args: &[Object]) -> Result { // `.args` but never runs `__init__` (CPython `BaseException_new`). // `UnicodeDecodeError.__new__(UnicodeDecodeError)` must succeed // with zero constructor arguments. - if cls.mro.borrow().iter().any(|t| t.name == "BaseException") { + if cls.flags.is_exception && cls.mro.borrow().iter().any(|t| t.name == "BaseException") { let new_args = if args.len() > 1 { &args[1..] } else { &[][..] }; if let Some(ptr) = crate::vm_singletons::current_interpreter_ptr() { // SAFETY: published by an enclosing VM frame still live on @@ -1859,7 +1994,7 @@ pub(crate) fn object_new(args: &[Object]) -> Result { let inst = Rc::new(PyInstance::new(cls)); inst.dict_cell().borrow_mut().insert( DictKey(Object::from_static("args")), - Object::new_tuple(new_args.to_vec()), + Object::tuple_from_slice(new_args), ); let obj = Object::Instance(inst); crate::gc_trace::track(&obj); @@ -1872,7 +2007,8 @@ pub(crate) fn object_new(args: &[Object]) -> Result { // `module.__new__(module)` allocates an *uninitialized* module — // empty dict, no `__name__` — exactly CPython's `module_new` (the // name/doc seeding lives in `module.__init__` only). - if cls.is_subclass_of(&builtin_types().module_) { + let facts = base_facts(&cls, &seed_kinds(builtin_types())); + if facts.module || Rc::ptr_eq(&cls, &builtin_types().module_) { let inst = Object::Instance(Rc::new(PyInstance::new(cls))); crate::gc_trace::track(&inst); return Ok(inst); @@ -1882,7 +2018,7 @@ pub(crate) fn object_new(args: &[Object]) -> Result { // intercepted upstream (the 4-arg `__new__` route / `Meta(name, // bases, ns)`), so e.g. `type(typing.Any)()` must raise like // CPython's `type_new` ("takes exactly 3 arguments (0 given)"). - if cls.is_subclass_of(&builtin_types().type_) && args.len() != 4 { + if (facts.type_ || Rc::ptr_eq(&cls, &builtin_types().type_)) && args.len() != 4 { return Err(crate::error::type_error(format!( "type.__new__() takes exactly 3 arguments ({} given)", args.len() - 1 @@ -1906,11 +2042,7 @@ pub(crate) fn object_new(args: &[Object]) -> Result { // duck-typed generic alias. (numpy's `_array_like` builds // `collections.abc.Callable[..., Any]` exactly this way during import.) { - let bt = builtin_types(); - if args.len() == 3 - && !Rc::ptr_eq(&cls, &bt.generic_alias_) - && cls.is_subclass_of(&bt.generic_alias_) - { + if args.len() == 3 && facts.alias { let alias = crate::make_generic_alias_public(args[1].clone(), args[2].clone()); // CPython `ga_new` allocates through `cls`, so the instance // reports the subclass as its type (test_dataclasses @@ -2052,27 +2184,19 @@ pub(crate) fn overrides_dunder_new(cls: &Rc) -> bool { /// Does `cls` (or a non-`object` base) define a *user* `__init__`? pub(crate) fn overrides_dunder_init(cls: &Rc) -> bool { - for ty in cls.mro.borrow().iter() { - if let Some(init) = ty - .dict - .borrow() - .get(&DictKey(Object::from_static("__init__"))) - { - // Surface-only default-`__init__` mirrors (RFC 0056 WS4) - // are not overrides. - if crate::descr_registry::is_surface_only(init) { - continue; - } - // `object.__init__` itself stored on a subclass (`typing`'s - // protocol init does `cls.__init__ = object.__init__`) leaves - // CPython's `tp_init` at `object_init`: not an override. - if matches!(init, Object::Builtin(b) if crate::is_object_init(b)) { - return false; - } - return ty.name != "object"; - } + // (Through the class's type cache: the first `__init__` along the MRO, + // past the surface-only default mirrors of RFC 0056 WS4, which aren't + // overrides.) + let Some((init, owner)) = cls.lookup_with_owner("__init__") else { + return false; + }; + // `object.__init__` itself stored on a subclass (`typing`'s protocol + // init does `cls.__init__ = object.__init__`) leaves CPython's + // `tp_init` at `object_init`: not an override. + if matches!(&init, Object::Builtin(b) if crate::is_object_init(b)) { + return false; } - false + owner.name != "object" } /// A fresh `Object::Builtin("__new__")` wrapping [`object_new`]. Each @@ -2900,7 +3024,7 @@ fn install_object_dunders(object_: &Rc) { )); } let name = match &args[1] { - Object::Str(s) => s.to_string(), + Object::Str(s) => s.clone(), _ => return Err(crate::error::type_error("attribute name must be str")), }; match &args[0] { @@ -2909,7 +3033,12 @@ fn install_object_dunders(object_: &Rc) { // SAFETY: published by an enclosing VM frame still // live on this thread; the GIL keeps access exclusive. let interp = unsafe { &mut *ptr }; - interp.generic_setattr_instance(inst, &args[0], &name, args[2].clone())?; + interp.generic_setattr_instance_shared( + inst, + &args[0], + &name, + args[2].clone(), + )?; } else if matches!(inst.cls().lookup(&name), Some(Object::SlotDescriptor(_))) { // No VM frame on this thread (e.g. a bare C-API embed): // we can't run a Python property setter, but a @@ -3054,14 +3183,75 @@ fn install_object_dunders(object_: &Rc) { call_kw: None, })), ); + /// `object.__setattr__(obj, name, value)`'s leaf half (see + /// `leaf_builtins::register_fast`), for the stores the default + /// `__setattr__` makes without running any code: a plain instance's + /// own attribute in its split dict (where the class holds nothing that + /// would intercept the name) or a writable `__slots__` member. What a + /// frozen dataclass's `__init__` pays per field. `None` leaves the + /// rest to the full store. + fn object_setattr_fast(args: &[Object]) -> Option> { + let [Object::Instance(inst), Object::Str(name), value] = args else { + return None; + }; + let n: &str = name; + let cls = inst.cls_raw(); + // (Dunders and `args` have stores of their own; a bound method + // value is tracked first.) + if n.starts_with("__") + || n == "args" + || inst.native.get().is_some() + || inst.c_body.get() != 0 + || cls.native_kind.get() != 0 + || cls.is_super_proxy_type() + || matches!(value, Object::BoundMethod(_)) + || crate::object::exotic_str_keys_possible() + || crate::capi_watchers::dicts_active() + { + return None; + } + match cls.lookup(n) { + Some(Object::SlotDescriptor(sd)) if sd.name == n && !sd.readonly => { + inst.note_slot_store(value); + let old = inst + .slots + .try_borrow_mut() + .ok()? + .insert_shared(name, value.clone()); + drop(old); + Some(Ok(Object::None)) + } + None + | Some( + Object::Function(_) + | Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Str(_), + ) if !cls.forbids_dict => { + let key = crate::stdlib::sys::intern_shared_memo(name); + match inst.split_store(&key, value.clone()) { + Ok(old) => { + drop(old); + Some(Ok(Object::None)) + } + Err(_) => None, + } + } + _ => None, + } + } + let setattr = Rc::new(BuiltinFn { + name: "__setattr__", + binds_instance: true, + call: Box::new(object_setattr), + call_kw: None, + }); + crate::leaf_builtins::register_fast(&setattr, object_setattr_fast); dict.insert( DictKey(Object::from_static("__setattr__")), - Object::Builtin(Rc::new(BuiltinFn { - name: "__setattr__", - binds_instance: true, - call: Box::new(object_setattr), - call_kw: None, - })), + Object::Builtin(setattr), ); dict.insert( DictKey(Object::from_static("__delattr__")), @@ -3902,7 +4092,7 @@ fn install_import_error_init(import_error: &Rc) { } } } - inst_rc.slot_set("args", Object::new_tuple(rest.to_vec())); + inst_rc.slot_set("args", Object::tuple_from_slice(rest)); inst_rc.slot_set( "msg", if rest.len() == 1 { @@ -3931,6 +4121,17 @@ fn install_import_error_init(import_error: &Rc) { ); } +/// The address of `OSError.__init__`'s builtin (see [`is_os_error_init`]). +static OS_ERROR_INIT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Whether `init` is `OSError`'s own `__init__`, whose work a built +/// exception instance already holds (`Interpreter::build_exception_instance` +/// sets the same fields). +pub(crate) fn is_os_error_init(init: &Object) -> bool { + matches!(init, Object::Builtin(b) + if Rc::as_ptr(b) as usize == OS_ERROR_INIT.load(std::sync::atomic::Ordering::Relaxed)) +} + fn install_os_error_init(os_error: &Rc) { use crate::object::BuiltinFn; fn oserror_init(args: &[Object]) -> Result { @@ -3981,7 +4182,7 @@ fn install_os_error_init(os_error: &Rc) { .is_subclass_of(&builtin_types().blocking_io_error); if is_blocking && rest.len() == 3 && matches!(rest[2], Object::Int(_) | Object::Long(_)) { - inst_rc.slot_set("args", Object::new_tuple(rest.to_vec())); + inst_rc.slot_set("args", Object::tuple_from_slice(rest)); inst_rc.slot_set("errno", rest[0].clone()); inst_rc.slot_set("strerror", rest[1].clone()); inst_rc.slot_set("characters_written", rest[2].clone()); @@ -3993,9 +4194,9 @@ fn install_os_error_init(os_error: &Rc) { // tuple is stored and the fields stay None. let populated = (2..=5).contains(&rest.len()); let args_tuple = if populated { - Object::new_tuple(rest[..2].to_vec()) + Object::tuple_from_slice(&rest[..2]) } else { - Object::new_tuple(rest.to_vec()) + Object::tuple_from_slice(rest) }; inst_rc.slot_set("args", args_tuple); let pick = |i: usize| { @@ -4060,14 +4261,19 @@ fn install_os_error_init(os_error: &Rc) { } } let mut dict = os_error.dict.borrow_mut(); + let init = Rc::new(BuiltinFn { + name: "__init__", + binds_instance: true, + call: Box::new(oserror_init), + call_kw: None, + }); + OS_ERROR_INIT.store( + Rc::as_ptr(&init) as usize, + std::sync::atomic::Ordering::Relaxed, + ); dict.insert( DictKey(Object::from_static("__init__")), - Object::Builtin(Rc::new(BuiltinFn { - name: "__init__", - binds_instance: true, - call: Box::new(oserror_init), - call_kw: None, - })), + Object::Builtin(init), ); dict.insert( DictKey(Object::from_static("__str__")), @@ -4202,7 +4408,7 @@ fn install_unicode_error_dunders(ty: &Rc, kind: UnicodeErrorKind) { check(is_str(&rest[3]), 3, "str", &rest[3])?; } } - inst_rc.slot_set("args", Object::new_tuple(rest.to_vec())); + inst_rc.slot_set("args", Object::tuple_from_slice(rest)); let mut i = 0; if kind != UnicodeErrorKind::Translate { inst_rc.slot_set("encoding", rest[i].clone()); @@ -4422,7 +4628,7 @@ fn install_syntax_error_dunders(syntax_error: &Rc) { return Ok(Object::None); }; let rest = if args.len() > 1 { &args[1..] } else { &[][..] }; - inst_rc.slot_set("args", Object::new_tuple(rest.to_vec())); + inst_rc.slot_set("args", Object::tuple_from_slice(rest)); // Defaults — CPython always defines these slots. for name in [ "msg", @@ -4578,6 +4784,16 @@ fn syntax_basename(filename: &Object) -> String { /// on the instance so every subclass — built-in or user-defined /// — exposes `e.args` automatically. Module-scope so the docs surface /// pass (RFC 0056 WS4) can mint per-exception-type mirrors of it. +/// The address of `BaseException.__init__`'s builtin (see [`exc_init`]), +/// for compiled code's lane (`frame_jit::h_call_native`). +static EXC_INIT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Whether `f` is `BaseException.__init__`'s builtin. +#[inline] +pub(crate) fn is_exc_init(f: *const crate::BuiltinFn) -> bool { + f as usize == EXC_INIT.load(std::sync::atomic::Ordering::Relaxed) +} + pub(crate) fn exc_init(args: &[Object]) -> Result { { let inst = args @@ -4600,71 +4816,157 @@ pub(crate) fn exc_init(args: &[Object]) -> Result { let old = inst_rc .slots .borrow_mut() - .insert("args", Object::tuple_from_exact(rest.iter().cloned())); + .insert("args", Object::tuple_from_slice(rest)); drop(old); } Ok(Object::None) } } +/// [`exc_init`] called with keywords: the fields CPython's `*_init` slots +/// take by keyword (`AttributeError(name=, obj=)`, `NameError(name=)`, +/// `ImportError(name=, path=, name_from=)`), for a subclass constructed +/// through the inherited `__init__` or one that passes them on to +/// `super().__init__`. Any other keyword is refused as CPython refuses it. +fn exc_init_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result { + if !kwargs.is_empty() { + let Some(Object::Instance(inst)) = args.first() else { + return Err(crate::error::type_error( + "BaseException() takes no keyword arguments".to_owned(), + )); + }; + let bt = builtin_types(); + let cls = inst.cls(); + let (family, allowed): (&str, &[&str]) = if cls.is_subclass_of(&bt.import_error) { + ("ImportError", &["name", "path", "name_from"]) + } else if cls.is_subclass_of(&bt.attribute_error) { + ("AttributeError", &["name", "obj"]) + } else if cls.is_subclass_of(&bt.name_error) { + ("NameError", &["name"]) + } else { + return Err(crate::error::type_error(format!( + "{}() takes no keyword arguments", + cls.name + ))); + }; + if let Some((k, _)) = kwargs.iter().find(|(k, _)| !allowed.contains(&k.as_str())) { + return Err(crate::error::type_error(format!( + "{family}() got an unexpected keyword argument '{k}'" + ))); + } + // (Exception pseudo-slots: the class's slot descriptors read them.) + for (k, v) in kwargs { + inst.slot_set(k, v.clone()); + } + } + exc_init(args) +} + /// CPython's `BaseException.__str__` — `str(args[0])` for a single /// argument, tuple repr for several. Module-scope for the docs surface /// pass (see [`exc_init`]). fn exc_str(args: &[Object]) -> Result { - { - let inst = args - .first() - .ok_or_else(|| crate::error::type_error("expected exception instance".to_owned()))?; - if let Object::Instance(inst_rc) = inst { + let inst = args + .first() + .ok_or_else(|| crate::error::type_error("expected exception instance".to_owned()))?; + match inst { + Object::Instance(inst_rc) => { + exc_str_text(inst_rc, false).unwrap_or_else(|| Ok(Object::from_static(""))) + } + _ => Ok(Object::from_static("")), + } +} + +/// The address of `BaseException.__str__`'s function (see +/// [`is_base_exception_str`]). +static BASE_EXC_STR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Whether `f` is `BaseException.__str__`. +pub(crate) fn is_base_exception_str(f: &crate::object::BuiltinFn) -> bool { + std::ptr::from_ref(f) as usize == BASE_EXC_STR.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Whether `o`'s `str` and `repr` are native text, running no code of +/// anyone's (a container's could reach an instance's `__repr__`). +fn native_text_item(o: &Object) -> bool { + matches!( + o, + Object::Str(_) + | Object::WStr(_) + | Object::Int(_) + | Object::Bool(_) + | Object::None + | Object::Float(_) + | Object::Bytes(_) + ) +} + +/// `BaseException.__str__(inst)`'s text, or the error a lone argument's +/// own `__str__` raised. With `leaf`, `None` unless every argument's +/// text is native (see [`native_text_item`]) and `args` is a tuple, for +/// the caller's full path. +pub(crate) fn exc_str_text( + inst_rc: &Rc, + leaf: bool, +) -> Option> { + let args = inst_rc + .exc_args_get() + .or_else(|| inst_rc.attr_get_str("args")); + let Some(Object::Tuple(items)) = args else { + return if leaf { + None + } else { + Some(Ok(Object::from_static(""))) + }; + }; + Some(Ok(match &items[..] { + [] => Object::from_static(""), + _ if leaf && !items.iter().all(native_text_item) => return None, + [single] => { // CPython's ``KeyError.__str__`` overrides the default to // render the key via ``repr`` — so ``str(KeyError('x'))`` // is ``"'x'"`` not ``'x'``. We special-case KeyError here // because the runtime constructs them from Rust and we // can't easily install a per-subclass ``__str__``. - let is_key_error = is_subclass_by_name(&inst_rc.cls(), "KeyError"); - if let Some(Object::Tuple(items)) = exc_attr(inst_rc, "args") { - return Ok(match &items[..] { - [] => Object::from_static(""), - [single] => { - if is_key_error { - Object::from_str(single.repr()) - } else if matches!(single, Object::Str(_) | Object::WStr(_)) { - // `str(args[0])` of a str IS args[0] — round- - // tripping through a Rust String would mangle - // lone surrogates (test_getargs's surrogate - // keyword message). - single.clone() - } else if matches!(single, Object::Instance(_) | Object::Foreign(_)) { - // A nested exception, other instance, or a - // *foreign* extension object (e.g. a numpy - // scalar) needs its own `__str__`/`tp_str` - // dispatched: CPython's `BaseException.__str__` - // is `str(args[0])`, not `repr`. Without this a - // `OutOfBoundsTimedelta(np.timedelta64(...))` - // stringified to its repr - // (`np.timedelta64(...,'h')`) instead of - // `"... hours"`. - Object::from_str( - crate::builtins::str_reentrant(single) - .unwrap_or_else(|| single.to_str()), - ) - } else { - Object::from_str(single.to_str()) - } - } - _ => Object::from_str(format!( - "({})", - items - .iter() - .map(|x| x.repr()) - .collect::>() - .join(", ") - )), - }); + let cls = inst_rc.cls_raw(); + if cls.memo_verdict(crate::types::Verdict::ExcBaseStr, "k", || { + cls.is_subclass_of(&builtin_types().key_error) + }) { + Object::from_str(single.repr()) + } else if matches!(single, Object::Str(_) | Object::WStr(_)) { + // `str(args[0])` of a str IS args[0] — round- + // tripping through a Rust String would mangle + // lone surrogates (test_getargs's surrogate + // keyword message). + single.clone() + } else if matches!(single, Object::Instance(_) | Object::Foreign(_)) { + // A nested exception, other instance, or a + // *foreign* extension object (e.g. a numpy + // scalar) needs its own `__str__`/`tp_str` + // dispatched: CPython's `BaseException.__str__` + // is `str(args[0])`, not `repr`. Without this a + // `OutOfBoundsTimedelta(np.timedelta64(...))` + // stringified to its repr + // (`np.timedelta64(...,'h')`) instead of + // `"... hours"`. + match crate::builtins::str_reentrant_result(single) { + Some(Ok(text)) => Object::from_str(text), + Some(Err(e)) => return Some(Err(e)), + None => Object::from_str(single.to_str()), + } + } else { + Object::from_str(single.to_str()) } } - Ok(Object::from_static("")) - } + _ => Object::from_str(format!( + "({})", + items + .iter() + .map(|x| x.repr()) + .collect::>() + .join(", ") + )), + })) } /// CPython's `BaseException.__repr__` — `ClsName(arg_reprs…)`. @@ -4907,14 +5209,19 @@ fn install_exception_str_repr(base_exception: &Rc) { }) } let mut dict = base_exception.dict.borrow_mut(); + let init = Rc::new(BuiltinFn { + name: "__init__", + binds_instance: true, + call: Box::new(exc_init), + call_kw: Some(Box::new(exc_init_kw)), + }); + EXC_INIT.store( + Rc::as_ptr(&init) as usize, + std::sync::atomic::Ordering::Relaxed, + ); dict.insert( DictKey(Object::from_static("__init__")), - Object::Builtin(Rc::new(BuiltinFn { - name: "__init__", - binds_instance: true, - call: Box::new(exc_init), - call_kw: None, - })), + Object::Builtin(init), ); dict.insert( DictKey(Object::from_static("__setstate__")), @@ -4934,14 +5241,19 @@ fn install_exception_str_repr(base_exception: &Rc) { call_kw: None, })), ); + let str_fn = Rc::new(BuiltinFn { + name: "__str__", + binds_instance: true, + call: Box::new(exc_str), + call_kw: None, + }); + BASE_EXC_STR.store( + Rc::as_ptr(&str_fn) as usize, + std::sync::atomic::Ordering::Relaxed, + ); dict.insert( DictKey(Object::from_static("__str__")), - Object::Builtin(Rc::new(BuiltinFn { - name: "__str__", - binds_instance: true, - call: Box::new(exc_str), - call_kw: None, - })), + Object::Builtin(str_fn), ); dict.insert( DictKey(Object::from_static("__repr__")), @@ -5073,7 +5385,7 @@ fn install_exception_group_init(base: &Rc) { .first() .ok_or_else(|| crate::error::type_error("expected exception instance"))?; if let Object::Instance(inst_rc) = inst { - inst_rc.slot_set("args", Object::new_tuple(args[1..].to_vec())); + inst_rc.slot_set("args", Object::tuple_from_slice(&args[1..])); } Ok(Object::None) } @@ -5776,7 +6088,7 @@ fn exception_matches_type(exc: &Object, type_pred: &Object) -> bool { } } -fn is_subclass_by_name(class: &Rc, ancestor: &str) -> bool { +fn is_subclass_by_name(class: &TypeObject, ancestor: &str) -> bool { for t in class.mro.borrow().iter() { if t.name == ancestor { return true; @@ -5874,6 +6186,32 @@ fn install_value_type_new(bt: &BuiltinTypes) { make_default_new() }; register_new_metadata(&wrapper, ty); + // `str.__new__(cls, s)`, `tuple.__new__(cls, t)` and + // `int.__new__(cls, n)` of a value already of the type (a + // subclass's `super().__new__(cls, value)`, as `email`'s `Terminal` + // tokens make): the allocation, which runs no code for these. + if let Object::Builtin(b) = &wrapper { + if Rc::ptr_eq(ty, &bt.str_) { + crate::leaf_builtins::register_fast(b, |args| match args { + [Object::Type(_), Object::Str(_)] => Some(object_new(args)), + _ => None, + }); + } else if Rc::ptr_eq(ty, &bt.tuple_) { + crate::leaf_builtins::register_fast(b, |args| match args { + [Object::Type(_), Object::Tuple(_)] => Some(object_new(args)), + _ => None, + }); + } else if Rc::ptr_eq(ty, &bt.int_) { + crate::leaf_builtins::register_fast(b, |args| match args { + [Object::Type(cls), Object::Int(_)] + if !(cls.flags.is_builtin && cls.name == "bool") => + { + Some(object_new(args)) + } + _ => None, + }); + } + } ty.dict .borrow_mut() .insert(DictKey(Object::from_static("__new__")), wrapper); @@ -6052,7 +6390,25 @@ fn install_mutable_container_init(bt: &BuiltinTypes) { args.len() - 1 ))); } - if let Some(src) = args.get(1) { + // An exact dict into an empty one (`MyDict(d)`, what a dict + // subclass's construction from a dict comes to): its table copied + // whole, as `dict(d)` copies it, the keys hashed and told apart + // when they were stored. + let mut copied = false; + if let Some(Object::Dict(from)) = args.get(1) { + if !Rc::ptr_eq(from, target) { + let copy = from.try_borrow().ok().map(|from| from.clone()); + if let (Some(copy), Ok(mut t)) = (copy, target.try_borrow_mut()) { + if t.is_empty() { + let old = std::mem::replace(&mut *t, copy); + drop(t); + drop(old); + copied = true; + } + } + } + } + if let Some(src) = args.get(1).filter(|_| !copied) { let interp = reenter()?; let globals = interp.builtins_dict(); let merged: Vec<(DictKey, Object)> = @@ -6114,6 +6470,33 @@ fn install_mutable_container_init(bt: &BuiltinTypes) { args.len() - 1 ))); } + // Another set (`S(s)`, `S(other_s)`; a subclass's instance too, + // whatever its `__iter__`, as CPython's `set_update_internal` + // reads any set's table): the table copied whole, its elements + // hashed and told apart when they were stored. + let whole = match args.get(1) { + Some(Object::Set(s)) => Some(s), + Some(Object::Instance(inst)) => match inst.native.get() { + Some(Object::Set(s)) => { + let cls = inst.cls_raw(); + (cls.native_kind.get() == 0 && cls.c_ext_ptr.get() == 0).then_some(s) + } + _ => None, + }, + _ => None, + }; + if let Some(from) = whole.filter(|from| !Rc::ptr_eq(from, target)) { + let copy = from.try_borrow().ok().map(|from| from.clone()); + if let Some(copy) = copy { + if let Ok(mut t) = target.try_borrow_mut() { + let old = std::mem::replace(&mut *t, copy); + drop(t); + // (The old elements go with no borrow held.) + drop(old); + return Ok(Object::None); + } + } + } let items = match args.get(1) { Some(src) => { let interp = reenter()?; diff --git a/crates/weavepy-vm/src/builtins.rs b/crates/weavepy-vm/src/builtins.rs index 294cd0ace..a4b8c1647 100644 --- a/crates/weavepy-vm/src/builtins.rs +++ b/crates/weavepy-vm/src/builtins.rs @@ -58,6 +58,26 @@ pub fn build_class_builtin() -> BuiltinFn { /// `builtins.set is set` (a type) while `set(...)` still constructs through /// the native helper. pub(crate) fn builtin_type_constructor(name: &str) -> Option> { + thread_local! { + /// The constructors built so far, by type name: a type call that + /// reaches here (`reversed(s)`, `int(x, 16)`) reuses one instead + /// of allocating it and releasing it again. + static CTORS: crate::gil::ReleaseUnderGil)>>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(Vec::new())) }; + } + if let Some(hit) = CTORS.with(|c| { + c.borrow() + .iter() + .find(|(n, _)| *n == name) + .map(|(_, f)| f.clone()) + }) { + return Some(hit); + } + let f = make_builtin_type_constructor(name)?; + CTORS.with(|c| c.borrow_mut().push((f.name, f.clone()))); + Some(f) +} + +fn make_builtin_type_constructor(name: &str) -> Option> { macro_rules! ctor { ($n:literal, $body:expr) => { Some(Rc::new(BuiltinFn { @@ -460,13 +480,64 @@ pub fn lookup_method(obj: &Object, name: &str) -> Option { let Some(tag) = method_memo_tag(obj) else { return lookup_method_uncached(obj, name); }; + // A call site's name sits at one address: its last answer, checked by + // the name's text (another string may come to sit there). + let slot = ((name.as_ptr() as usize >> 3) ^ usize::from(tag)) % RECENT_METHODS; + if let Ok(Some(hit)) = RECENT_METHOD.try_with(|r| { + // SAFETY: a thread-local array no code reaches while this reads. + let e = unsafe { &(*r.get())[slot] }; + (e.0 == tag && *e.1 == *name).then(|| e.2.clone()) + }) { + return hit; + } + let found = lookup_method_memo(obj, name, tag); + let _ = RECENT_METHOD.try_with(|r| { + // SAFETY: as above; the replaced entry drops after the write. + let old = std::mem::replace( + unsafe { &mut (*r.get())[slot] }, + (tag, name.into(), found.clone()), + ); + drop(old); + }); + found +} + +/// Entries of [`RECENT_METHOD`]. +const RECENT_METHODS: usize = 64; + +std::thread_local! { + /// The last few `(receiver kind, name)` answers of [`lookup_method`], + /// direct-mapped by the name's address. + static RECENT_METHOD: crate::gil::ReleaseUnderGil, Option); RECENT_METHODS]>> = crate::gil::ReleaseUnderGil::new(std::cell::UnsafeCell::new(std::array::from_fn(|_| (u8::MAX, Box::from(""), None)))); +} + +/// [`lookup_method`] through the per-kind memo. +/// The fast half of a native iterator's `__next__`: the next item when the +/// step runs no code; an exhausted iterator (whose `StopIteration` is the +/// full call's) and any other step decline. +fn iter_next_fast(args: &[Object]) -> Option> { + let [Object::Iter(it)] = args else { + return None; + }; + // SAFETY: nothing below runs code; the view ends with this call. + let c = unsafe { it.peek_mut() }?; + if !c.pure_ready() { + return None; + } + c.next_value().map(Ok) +} + +fn lookup_method_memo(obj: &Object, name: &str, tag: u8) -> Option { let memo = METHOD_MEMO.get_or_init(|| RefCell::new(Vec::new())); - if let Some(hit) = memo - .borrow() - .get(usize::from(tag)) - .and_then(|names| names.get(name)) - { - return hit.clone(); + // (The memo is one cache for the process: a lookup that finds it in + // use, by another thread's lookup between GIL switches, goes without + // it rather than panicking.) + if let Some(hit) = memo.try_borrow().ok().and_then(|memo| { + memo.get(usize::from(tag)) + .and_then(|names| names.get(name)) + .cloned() + }) { + return hit; } // (Built without the memo borrowed: nothing here reaches it, but a // builder is free to.) @@ -477,16 +548,75 @@ pub fn lookup_method(obj: &Object, name: &str) -> Option { match name { "write" => crate::leaf_builtins::register_fast(b, file_write_fast), "readline" => crate::leaf_builtins::register_fast(b, file_readline_fast), + "getvalue" => crate::leaf_builtins::register_fast(b, file_getvalue_fast), + "read" => crate::leaf_builtins::register_fast(b, file_read_fast), + "readinto" => crate::leaf_builtins::register_fast(b, file_readinto_fast), + "tell" => crate::leaf_builtins::register_fast(b, file_tell_fast), + "seek" => crate::leaf_builtins::register_fast(b, file_seek_fast), + _ => {} + } + } + // A native iterator's step that runs no code (`it.__next__()`, `nx()` + // of a bound `__next__`). + if let (Object::Iter(_), Some(Object::Builtin(b))) = (obj, &found) { + if name == "__next__" { + crate::leaf_builtins::register_fast(b, iter_next_fast); + } + } + // A set's `add` and `update` of values that hash and compare natively. + if let (Object::Set(_), Some(Object::Builtin(b))) = (obj, &found) { + match name { + "add" => crate::leaf_builtins::register_fast(b, set_add_fast), + "update" => crate::leaf_builtins::register_fast(b, set_update_fast), + _ => {} + } + } + // A set's or frozenset's tests and algebra with other sets. + if let (Object::Set(_) | Object::FrozenSet(_), Some(Object::Builtin(b))) = (obj, &found) { + let fast: Option = match name { + "issubset" => Some(set_issubset_fast), + "issuperset" => Some(set_issuperset_fast), + "isdisjoint" => Some(set_isdisjoint_fast), + "union" => Some(set_union_fast), + "intersection" => Some(set_intersection_fast), + "difference" => Some(set_difference_fast), + "symmetric_difference" => Some(set_symmetric_difference_fast), + _ => None, + }; + if let Some(fast) = fast { + crate::leaf_builtins::register_fast(b, fast); + } + } + // `startswith`/`endswith` of one `bytes` or `bytearray` affix. + if let (Object::Bytes(_) | Object::ByteArray(_), Some(Object::Builtin(b))) = (obj, &found) { + match name { + "startswith" => crate::leaf_builtins::register_fast(b, bytes_startswith_fast), + "endswith" => crate::leaf_builtins::register_fast(b, bytes_endswith_fast), + "join" if matches!(obj, Object::Bytes(_)) => { + crate::leaf_builtins::register_fast(b, bytes_join_fast) + } + _ => {} + } + } + // A dict's `update` from another plain dict whose keys run no code. + if let (Object::Dict(_), Some(Object::Builtin(b))) = (obj, &found) { + match name { + "update" => crate::leaf_builtins::register_fast(b, dict_update_fast), + "copy" => crate::leaf_builtins::register_fast(b, dict_copy_fast), _ => {} } } - let mut memo = memo.borrow_mut(); + let Ok(mut memo) = memo.try_borrow_mut() else { + return found; + }; if memo.len() <= usize::from(tag) { memo.resize_with(usize::from(tag) + 1, Default::default); } let names = &mut memo[usize::from(tag)]; // Arbitrary names (`getattr(s, text)`) mustn't grow it without bound. - if names.len() < METHOD_MEMO_CAP { + // (An entry another lookup stored meanwhile stays: nothing is dropped + // while the memo is borrowed.) + if names.len() < METHOD_MEMO_CAP && !names.contains_key(name) { names.insert(name.into(), found.clone()); } found @@ -523,13 +653,18 @@ pub(crate) fn method_memo_tag(obj: &Object) -> Option { // A native stream's methods follow from its layer and backing (see // `lookup_method_uncached`), unless the stream carries attributes // of its own, which shadow them. - Object::File(f) if f.extra_attrs.borrow().is_empty() => { + // SAFETY: the length is read and the view dropped at once. + Object::File(f) + if unsafe { f.extra_attrs.peek() } + .map_or_else(|| f.extra_attrs.borrow().is_empty(), Vec::is_empty) => + { 16 + (f.io_kind.get() as u8) * 4 + u8::from(f.binary) * 2 + u8::from(f.is_memory()) } // A class's `__dict__` view (`cls.__dict__.get(name)`, as enum and // `inspect` read it). A view over another mapping // (`MappingProxyObj`) calls that mapping's own methods instead. Object::MappingProxy(_) => 120, + Object::MemoryView(_) => 121, _ => return None, }; Some(tag) @@ -1094,7 +1229,7 @@ fn lookup_method_uncached(obj: &Object, name: &str) -> Option { )); } let out = mv.shallow_clone(); - *out.format.borrow_mut() = fmt.to_string(); + *out.format.borrow_mut() = fmt.clone(); out.itemsize.set(itemsize); let dims = vec![nbytes / itemsize]; *out.strides.borrow_mut() = crate::object::c_contiguous_strides(&dims, itemsize); @@ -1505,8 +1640,8 @@ fn seq_getitem(args: &[Object]) -> Result { .ok_or_else(|| type_error("__getitem__() takes exactly one argument (0 given)"))?; let as_seq = |v: &Object| -> Vec { match v { - Object::List(items) => items.borrow().clone(), - Object::Tuple(items) => items.to_vec(), + Object::List(items) => crate::object::cloned_vec(&items.borrow()), + Object::Tuple(items) => crate::object::cloned_vec(items), Object::Str(s) => s.chars().map(|c| Object::from_str(c.to_string())).collect(), Object::Bytes(b) => b.iter().map(|x| Object::Int(i64::from(*x))).collect(), Object::ByteArray(b) => b @@ -1606,6 +1741,11 @@ fn obj_contains(args: &[Object]) -> Result { let item = args .get(1) .ok_or_else(|| type_error("__contains__() takes exactly one argument (0 given)"))?; + // (A bound method's call, `frozenset(words).__contains__(w)`: the probe + // `x in s` takes when it runs no code, first.) + if let Some(found) = crate::Interpreter::leaf_contains_table(recv, item) { + return Ok(Object::Bool(found)); + } Ok(Object::Bool(recv.contains(item)?)) } @@ -1619,6 +1759,24 @@ fn slice_indices_method(args: &[Object]) -> Result { Some(Object::Slice(s)) => s.clone(), _ => return Err(type_error("descriptor 'indices' requires a 'slice' object")), }; + // Machine ints well inside the machine range (the usual slice): the + // same clamping at machine width. + const SMALL: std::ops::Range = -(1 << 62)..(1 << 62); + if let [_, Object::Int(length @ 0..)] = args { + let small = |o: &Object| match o { + Object::None => true, + Object::Int(v) => SMALL.contains(v), + _ => false, + }; + if SMALL.contains(length) && small(&s.start) && small(&s.stop) && small(&s.step) { + let (start, stop, step, _) = crate::adjust_slice(*length, &s)?; + return Ok(Object::new_tuple(vec![ + Object::Int(start), + Object::Int(stop), + Object::Int(step), + ])); + } + } // CPython's `_PySlice_GetLongIndices`: everything is arbitrary- // precision integer arithmetic — start/stop/step/length beyond // `sys.maxsize` clamp exactly, never overflow (issue #14794; @@ -2201,6 +2359,83 @@ fn arg_or_kw<'a>( /// `float.fromhex`, `bytes.maketrans`). Returns an unbound builtin /// so the call site supplies the arguments unchanged. pub fn builtin_classmethod(type_name: &str, attr: &str) -> Option { + // `int.from_bytes` is read on every `int.from_bytes(data)` call: one + // builtin per thread, registered with a leaf half (see + // `int_from_bytes_fast`), rather than a fresh one each read. + if (type_name, attr) == ("int", "from_bytes") { + thread_local! { + static FROM_BYTES: crate::gil::ReleaseUnderGil = crate::gil::ReleaseUnderGil::new({ + let mut f = method_kw("from_bytes", int_from_bytes_method); + f.binds_instance = false; + let b = Rc::new(f); + crate::leaf_builtins::register_fast(&b, int_from_bytes_fast); + crate::leaf_builtins::register_fast_kw( + &b, + &["bytes", "?byteorder", "*signed"], + int_from_bytes_kw_fast, + ); + Object::Builtin(b) + }); + } + if let Ok(f) = FROM_BYTES.try_with(|f| Object::clone(f)) { + return Some(f); + } + } + builtin_classmethod_fresh(type_name, attr) +} + +/// `int.from_bytes(data[, byteorder])` of a `bytes` or `bytearray` with a +/// `str` byte order: the full body, which then runs no code. `None` +/// for any other shape (an iterable's or buffer's items, keywords). +fn int_from_bytes_fast(args: &[Object]) -> Option> { + let rest = match args { + [Object::Type(_), rest @ ..] => rest, + _ => args, + }; + match rest { + [Object::Bytes(_) | Object::ByteArray(_)] + | [Object::Bytes(_) | Object::ByteArray(_), Object::Str(_)] => { + Some(int_from_bytes_method(args, &[])) + } + _ => None, + } +} + +/// `int.from_bytes(bytes, byteorder='big', *, signed=False)`'s keyword +/// half: `bytes` or `bytearray` data, a `str` order and a `bool` or `int` +/// flag, each taking its default where the call left it out. +pub(crate) fn int_from_bytes_kw_fast(args: &[Object]) -> Option> { + // (A subclass's result goes through `cls(result)`: the full body's.) + let (cls, rest) = match args { + [c @ Object::Type(t), rest @ ..] if Rc::ptr_eq(t, &builtin_types().int_) => (Some(c), rest), + [Object::Type(_), ..] => return None, + _ => (None, args), + }; + let [data @ (Object::Bytes(_) | Object::ByteArray(_)), order, signed] = rest else { + return None; + }; + let order = match order { + Object::Unbound => Object::from_static("big"), + Object::Str(_) => order.clone(), + _ => return None, + }; + let signed = match signed { + Object::Unbound => Object::Bool(false), + Object::Bool(_) | Object::Int(_) => signed.clone(), + _ => return None, + }; + let mut full = [const { Object::None }; 4]; + let offset = usize::from(cls.is_some()); + if let Some(c) = cls { + full[0] = c.clone(); + } + full[offset] = data.clone(); + full[offset + 1] = order; + full[offset + 2] = signed; + Some(int_from_bytes_body(&full[..offset + 3], &[], offset)) +} + +fn builtin_classmethod_fresh(type_name: &str, attr: &str) -> Option { let f = match (type_name, attr) { ("str", "maketrans") => Some(method("maketrans", str_maketrans)), ("bytes", "fromhex") | ("bytearray", "fromhex") => Some(method("fromhex", bytes_fromhex)), @@ -2541,9 +2776,9 @@ pub fn builtin_type_dunder(base_name: &str, name: &str) -> Option { // `Enum.__format__`, which only works when `int.__format__` is one // stable object rather than a fresh wrapper per access. thread_local! { - static DUNDER_CACHE: std::cell::RefCell< + static DUNDER_CACHE: crate::gil::ReleaseUnderGil>, - > = std::cell::RefCell::new(std::collections::HashMap::new()); + >> = crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(std::collections::HashMap::new())); } let key = format!("{base_name}.{name}"); if let Some(hit) = DUNDER_CACHE.with(|c| c.borrow().get(&key).cloned()) { @@ -2827,6 +3062,21 @@ fn slot_getstate(args: &[Object]) -> Result { // ---------- free builtins ---------- +/// The receiver of a method that takes no arguments (`float.hex()`), +/// rejecting any extra argument as CPython does. +fn self_only<'a>(args: &'a [Object], qual: &str) -> Result<&'a Object, RuntimeError> { + match args { + [v] => Ok(v), + [] => Err(type_error(format!( + "unbound method {qual}() needs an argument" + ))), + _ => Err(type_error(format!( + "{qual}() takes no arguments ({} given)", + args.len() - 1 + ))), + } +} + fn one<'a>(args: &'a [Object], name: &str) -> Result<&'a Object, RuntimeError> { args.first() .ok_or_else(|| type_error(format!("{name}() takes 1 argument (0 given)"))) @@ -2885,14 +3135,34 @@ pub(crate) fn coerce_index_object(o: &Object) -> Result { })?; // SAFETY: published by an enclosing VM frame still live on this thread. let interp = unsafe { &mut *ptr }; - let Ok(method) = interp.load_attr_public(o, "__index__") else { - return Err(type_error(format!( - "'{}' object cannot be interpreted as an integer", - o.type_name() - ))); + // (A plain instance's class's Python `__index__` through the class's + // cache, in place when a pure leaf, as `try_coerce_index_i64` calls it.) + let direct = match o { + Object::Instance(inst) if inst.native.get().is_none() => { + crate::Interpreter::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::INDEX_FN), + "__index__", + ) + } + _ => None, + }; + let r = match direct { + Some(f) => match interp.call_pure_leaf_with(&f, Some(o), &[]) { + Some(r) => r, + None => interp.call_dunder_function(f, std::slice::from_ref(o))?, + }, + None => { + let Ok(method) = interp.load_attr_public(o, "__index__") else { + return Err(type_error(format!( + "'{}' object cannot be interpreted as an integer", + o.type_name() + ))); + }; + let globals = interp.builtins_dict(); + interp.call_object_with_globals(&method, &[], &[], &globals)? + } }; - let globals = interp.builtins_dict(); - let r = interp.call_object_with_globals(&method, &[], &[], &globals)?; match r { Object::Int(_) | Object::Long(_) => Ok(r), Object::Bool(b) => Ok(Object::Int(i64::from(b))), @@ -2932,12 +3202,35 @@ pub(crate) fn try_coerce_index_i64(o: &Object) -> Option { + crate::Interpreter::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::INDEX_FN), + "__index__", + ) + } + _ => None, + }; + let method = match direct { + Some(_) => Object::None, + None => match interp.load_attr_public(o, "__index__") { + Ok(m) => m, + Err(_) => return None, + }, }; let globals = interp.builtins_dict(); Some((|| { - let r = interp.call_object_with_globals(&method, &[], &[], &globals)?; + let r = match direct { + Some(f) => match interp.call_pure_leaf_with(&f, Some(o), &[]) { + Some(r) => r, + None => interp.call_dunder_function(f, std::slice::from_ref(o))?, + }, + None => interp.call_object_with_globals(&method, &[], &[], &globals)?, + }; if let Some(v) = r.as_i64() { return Ok(v); } @@ -3146,7 +3439,7 @@ fn b_str(args: &[Object]) -> Result { }; // Any buffer decodes (`str(memoryview(b'…'), 'utf-8')`, // test_str.test_constructor). - let data = match args[0].as_bytes_view() { + let data = match args[0].bytes_cow() { Some(v) => v, None => { return Err(type_error(format!( @@ -3263,7 +3556,17 @@ fn b_format(args: &[Object]) -> Result { .unwrap_or_else(|| Object::from_static("")); let spec_str = match &spec { Object::Str(s) => s.to_string(), - _ => return Err(type_error("format() spec must be a string")), + other => { + // (`_PyArg_BadArgument` names `None` itself.) + let name = if matches!(other, Object::None) { + "None".to_owned() + } else { + other.type_name().to_string() + }; + return Err(type_error(format!( + "format() argument 2 must be str, not {name}" + ))); + } }; let s = crate::format_via_spec(value, &spec_str)?; Ok(Object::from_str(s)) @@ -3642,15 +3945,15 @@ fn property_deleter(args: &[Object]) -> Result { /// (`property.__get__` / `__set__` / `__delete__`), whose accessors are /// ordinary Python functions. /// `str(obj)` through the running interpreter (so user `__str__` / -/// nested-exception rendering dispatches). `None` when no interpreter -/// is live on this thread. -pub(crate) fn str_reentrant(obj: &Object) -> Option { +/// nested-exception rendering dispatches), its error kept. `None` when no +/// interpreter is live on this thread. +pub(crate) fn str_reentrant_result(obj: &Object) -> Option> { let ptr = crate::vm_singletons::current_interpreter_ptr()?; // SAFETY: the pointer was published by an enclosing VM frame still // live on this thread; the GIL keeps the access exclusive. let interp = unsafe { &mut *ptr }; let globals = interp.builtins_dict(); - interp.stringify_public(obj, &globals).ok() + Some(interp.stringify_public(obj, &globals)) } pub(crate) fn reentrant_call(callable: &Object, args: &[Object]) -> Result { @@ -3923,6 +4226,18 @@ pub(crate) fn wstr_attr_dict(obj: &Object) -> Option Option>> { + match name { + Object::WStr(_) => wstr_attr_dict(obj), + _ => None, + } +} + pub(crate) fn wstr_attr_get(obj: &Object, name: &Object) -> Option { let d = wstr_attr_dict(obj)?; let hit = d.borrow().get(&DictKey(name.clone())).cloned(); @@ -3977,7 +4292,7 @@ fn b_setattr(args: &[Object]) -> Result { ))) } }; - if let (Object::WStr(_), Some(d)) = (&args[1], wstr_attr_dict(&args[0])) { + if let Some(d) = wstr_name_dict(&args[1], &args[0]) { d.borrow_mut() .insert(DictKey(args[1].clone()), args[2].clone()); return Ok(Object::None); @@ -4001,7 +4316,7 @@ fn b_delattr(args: &[Object]) -> Result { ))) } }; - if let (Object::WStr(_), Some(d)) = (&args[1], wstr_attr_dict(&args[0])) { + if let Some(d) = wstr_name_dict(&args[1], &args[0]) { if d.borrow_mut() .shift_remove(&DictKey(args[1].clone())) .is_some() @@ -4090,9 +4405,10 @@ pub(crate) fn object_is_callable(v: &Object) -> bool { if intrinsic { return true; } - // Instances are callable when their class exposes `__call__`. + // Instances are callable when their class exposes `__call__` (the + // class's memoized answer, kept under its attribute version). if let Object::Instance(inst) = v { - return inst.cls().lookup("__call__").is_some(); + return inst.cls_raw().dunder(crate::types::Dunder::Call).present(); } false } @@ -4102,7 +4418,10 @@ fn b_callable(args: &[Object]) -> Result { Ok(Object::Bool(object_is_callable(v))) } -fn b_object(_args: &[Object]) -> Result { +fn b_object(args: &[Object]) -> Result { + if !args.is_empty() { + return Err(type_error("object() takes no arguments")); + } let cls = crate::builtin_types::builtin_types().object_.clone(); let inst = crate::types::PyInstance::new(cls); Ok(Object::Instance(Rc::new(inst))) @@ -4240,7 +4559,7 @@ fn attr_get(obj: &Object, name: &str) -> Option { if f.defaults.is_empty() { Some(Object::None) } else { - Some(Object::new_tuple(f.defaults.to_vec())) + Some(Object::tuple_from_slice(&f.defaults)) } } "__kwdefaults__" => { @@ -4258,7 +4577,7 @@ fn attr_get(obj: &Object, name: &str) -> Option { if f.closure.is_empty() { Some(Object::None) } else { - Some(Object::new_tuple(f.closure.to_vec())) + Some(Object::tuple_from_slice(&f.closure)) } } _ => None, @@ -5309,8 +5628,10 @@ thread_local! { /// repeated `f.__doc__` reads return the *same* `str` object (CPython /// stores the docstring once on the function; `update_wrapper` tests /// `assertIs(wrapper.__doc__, wrapped.__doc__)`). - static DOCSTRING_CACHE: std::cell::RefCell> = - std::cell::RefCell::new(std::collections::HashMap::new()); + /// (Released under the GIL at its thread's exit: it holds objects.) + static DOCSTRING_CACHE: crate::gil::ReleaseUnderGil< + std::cell::RefCell>, + > = crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(std::collections::HashMap::new())); } /// Return a function code object's docstring: CPython 3.14's @@ -5392,6 +5713,7 @@ fn attr_set(obj: &Object, name: &str, value: Object) -> Result<(), RuntimeError> } f.kwonly_memo.set(0); crate::frame_jit::retire_code(f.code.replace(c)); + crate::rare_events::note_func_edit(); f.names_kept.set(0); } else if crate::object::is_function_slot(name) { f.set_slot(name, value); @@ -5580,6 +5902,15 @@ fn parse_int_string( )) }; + // Plain hexadecimal digits and nothing else (a UUID's or a digest's + // text, base 16 given): the value straight from the digits, with no + // normalising pass, staging string or general radix parse. + if base == 16 { + if let Some(v) = int_from_plain_hex(raw.as_bytes()) { + return Ok(v); + } + } + // Normalise Unicode decimal digits / whitespace to ASCII, then strip the // surrounding whitespace CPython ignores. let transformed = transform_decimal_and_space(raw); @@ -5680,10 +6011,70 @@ fn parse_int_string( Ok(Object::int_from_bigint(big)) } +/// The integer `digits` spell in base 16 when they are ASCII hex digits +/// and nothing else (no sign, prefix, underscore or space; at least one +/// digit, at most 128): `None` leaves anything else to the general +/// parser. +pub(crate) fn int_from_plain_hex(digits: &[u8]) -> Option { + const MAX: usize = 128; + if digits.is_empty() || digits.len() > MAX { + return None; + } + /// Each byte's hex digit value, `0xff` for a byte that isn't one. + const NIBBLE: [u8; 256] = { + let mut t = [0xffu8; 256]; + let mut c = 0; + while c < 256 { + t[c] = match c as u8 { + b'0'..=b'9' => c as u8 - b'0', + b'a'..=b'f' => c as u8 - b'a' + 10, + b'A'..=b'F' => c as u8 - b'A' + 10, + _ => 0xff, + }; + c += 1; + } + t + }; + let nibble = |c: u8| -> Option { + let v = NIBBLE[usize::from(c)]; + (v != 0xff).then_some(v) + }; + if digits.len() <= 15 { + let mut v = 0i64; + for &c in digits { + v = (v << 4) | i64::from(nibble(c)?); + } + return Some(Object::Int(v)); + } + // Sixteen digits a 64-bit limb, the least significant last. + let mut limbs = [0u64; MAX / 16]; + let n = digits.len().div_ceil(16); + for (k, chunk) in digits.rchunks(16).enumerate() { + let mut v = 0u64; + for &c in chunk { + v = (v << 4) | u64::from(nibble(c)?); + } + limbs[k] = v; + } + if n == 1 || limbs[1..n].iter().all(|&l| l == 0) { + if let Ok(v) = i64::try_from(limbs[0]) { + return Some(Object::Int(v)); + } + } + let mut words = Vec::with_capacity(2 * n); + for &l in &limbs[..n] { + words.push(l as u32); + words.push((l >> 32) as u32); + } + Some(Object::int_from_bigint(BigInt::from( + num_bigint::BigUint::new(words), + ))) +} + // ---------- int methods (RFC 0019) ---------- fn int_bit_length(args: &[Object]) -> Result { - let v = one(args, "bit_length")?; + let v = self_only(args, "int.bit_length")?; match v { Object::Int(i) => { return Ok(Object::Int(i64::from( @@ -5691,6 +6082,8 @@ fn int_bit_length(args: &[Object]) -> Result { ))) } Object::Bool(b) => return Ok(Object::Int(i64::from(*b))), + // (Read in place: no copy of the value to count its bits.) + Object::Long(n) => return Ok(Object::Int(n.bits() as i64)), _ => {} } let n = v.as_bigint().ok_or_else(|| { @@ -5704,7 +6097,7 @@ fn int_bit_length(args: &[Object]) -> Result { } fn int_bit_count(args: &[Object]) -> Result { - let v = one(args, "bit_count")?; + let v = self_only(args, "int.bit_count")?; match v { Object::Int(i) => return Ok(Object::Int(i64::from(i.unsigned_abs().count_ones()))), Object::Bool(b) => return Ok(Object::Int(i64::from(*b))), @@ -5724,17 +6117,17 @@ fn int_bit_count(args: &[Object]) -> Result { } fn int_conjugate(args: &[Object]) -> Result { - let v = one(args, "conjugate")?; + let v = self_only(args, "int.conjugate")?; Ok(v.clone()) } fn int_is_integer(args: &[Object]) -> Result { - let _ = one(args, "is_integer")?; + let _ = self_only(args, "int.is_integer")?; Ok(Object::Bool(true)) } fn int_as_integer_ratio(args: &[Object]) -> Result { - let v = one(args, "as_integer_ratio")?; + let v = self_only(args, "int.as_integer_ratio")?; // The numerator is a *plain* int even when self is a bool or an int // subclass (CPython's long_as_integer_ratio calls _PyLong_Copy; // test_long asserts `type(True.as_integer_ratio()[0]) is int`). @@ -5755,18 +6148,37 @@ fn int_as_integer_ratio(args: &[Object]) -> Result { // keyword-only, so this must accept keywords (pandas' offsets / hypothesis // call `n.to_bytes(length, byteorder, signed=...)` by keyword). fn int_to_bytes(args: &[Object], kwargs: &[(String, Object)]) -> Result { + // (`signed` is keyword-only.) + if args.len() > 3 { + return Err(type_error(format!( + "to_bytes() takes at most 2 positional arguments ({} given)", + args.len() - 1 + ))); + } + int_to_bytes_body(args, kwargs) +} + +/// [`int_to_bytes`] past its arity check: a keyword half passes `signed` +/// fourth. +fn int_to_bytes_body(args: &[Object], kwargs: &[(String, Object)]) -> Result { let n_obj = args .first() .ok_or_else(|| type_error("to_bytes() requires self"))?; - // (A machine int converts only if its fast path below declines.) - let big = match n_obj { - Object::Int(_) => None, - other => Some( - other - .as_bigint() - .ok_or_else(|| type_error("to_bytes(): self is not an integer"))?, - ), - }; + // (Converted to a big integer only if the direct paths below + // decline.) + if !matches!(n_obj, Object::Int(_) | Object::Long(_) | Object::Bool(_)) + && n_obj.as_bigint().is_none() + { + return Err(type_error("to_bytes(): self is not an integer")); + } + if !kwargs.is_empty() { + check_kw_names( + "to_bytes", + &["length", "byteorder", "signed"], + args.len() - 1, + kwargs, + )?; + } let length = match arg_or_kw(args, 1, kwargs, "length") { Some(Object::Int(i)) if *i >= 0 => *i as usize, Some(Object::Bool(b)) => usize::from(*b), @@ -5780,14 +6192,36 @@ fn int_to_bytes(args: &[Object], kwargs: &[(String, Object)]) -> Result byteorder_str(o)?, - None => "big".to_owned(), - }; + let order_arg = arg_or_kw(args, 2, kwargs, "byteorder"); let signed = match arg_or_kw(args, 3, kwargs, "signed") { Some(o) => o.is_truthy(), None => false, }; + // A non-negative value in an unsigned buffer of any length, in either + // plain byte order (a UUID's sixteen bytes, a digest's thirty-two): + // its magnitude's bytes written once into the result, with no byte + // order string, big-integer copy or staging vector. An overflow, a + // negative value and any other order take the general path below. + if !signed { + let little = match order_arg { + None => Some(false), + Some(Object::Str(o)) => match o.as_bytes() { + b"big" => Some(false), + b"little" => Some(true), + _ => None, + }, + _ => None, + }; + if let Some(little) = little { + if let Some(out) = unsigned_to_bytes(n_obj, length, little) { + return Ok(Object::new_bytes(out)); + } + } + } + let byteorder = match order_arg { + Some(o) => byteorder_str(o)?, + None => "big".to_owned(), + }; // A machine int that fits the length: its two's-complement bytes, // without the big-integer conversion (anything else, an overflow // included, takes it). @@ -5808,16 +6242,43 @@ fn int_to_bytes(args: &[Object], kwargs: &[(String, Object)]) -> Result n, - None => n_obj.as_bigint().expect("a machine int"), - }; + let n = n_obj + .as_bigint() + .ok_or_else(|| type_error("to_bytes(): self is not an integer"))?; let bytes = bigint_to_bytes(&n, length, &byteorder, signed)?; Ok(Object::new_bytes(bytes)) } // CPython signature: `int.from_bytes(bytes, byteorder='big', *, signed=False)`. // `byteorder` is positional-or-keyword, `signed` keyword-only. +/// A keyword call's names against a method's parameters `names`, the +/// first `npos` of which the positionals filled: CPython's errors for an +/// unknown name and for one the positionals already gave. +fn check_kw_names( + fname: &str, + names: &[&str], + npos: usize, + kwargs: &[(String, Object)], +) -> Result<(), RuntimeError> { + for (k, _) in kwargs { + match names.iter().position(|n| n == k) { + Some(i) if i < npos => { + return Err(type_error(format!( + "argument for {fname}() given by name ('{k}') and position ({})", + i + 1 + ))) + } + Some(_) => {} + None => { + return Err(type_error(format!( + "{fname}() got an unexpected keyword argument '{k}'" + ))) + } + } + } + Ok(()) +} + fn int_from_bytes_method( args: &[Object], kwargs: &[(String, Object)], @@ -5830,10 +6291,40 @@ fn int_from_bytes_method( .map(|o| o.is_int_like() || matches!(o, Object::Type(_))) .unwrap_or(false), ); + // (`signed` is keyword-only.) + if args.len() - offset > 2 { + return Err(type_error(format!( + "from_bytes() takes at most 2 positional arguments ({} given)", + args.len() - offset + ))); + } + if !kwargs.is_empty() { + check_kw_names( + "from_bytes", + &["bytes", "byteorder", "signed"], + args.len() - offset, + kwargs, + )?; + } + int_from_bytes_body(args, kwargs, offset) +} + +/// [`int_from_bytes_method`] past its argument checks, the data at +/// `offset`: a keyword half passes `signed` third. +fn int_from_bytes_body( + args: &[Object], + kwargs: &[(String, Object)], + offset: usize, +) -> Result { let data_obj = args .get(offset) .ok_or_else(|| type_error("from_bytes() missing data"))?; - let data = match data_obj.as_bytes_view() { + if matches!(data_obj, Object::MemoryView(mv) if mv.released.get()) { + return Err(value_error( + "operation forbidden on released memoryview object", + )); + } + let data = match data_obj.bytes_cow() { Some(v) => v, // A str is iterable but is *not* an acceptable byte source // (int.from_bytes("", 'big') is a TypeError, test_long). @@ -5863,7 +6354,7 @@ fn int_from_bytes_method( } } } - out + std::borrow::Cow::Owned(out) } }; let byteorder = match arg_or_kw(args, offset + 1, kwargs, "byteorder") { @@ -5915,6 +6406,40 @@ fn byteorder_str(o: &Object) -> Result { } } +/// A non-negative `int`'s magnitude as `length` bytes in the given order, +/// zero-padded; `None` for a negative value, one that doesn't fit, or a +/// value that isn't a plain `int`. +fn unsigned_to_bytes(n: &Object, length: usize, little: bool) -> Option> { + // The magnitude's bytes, least significant first, into a zeroed + // result, a word at a time; then turned for big-endian. + let mut out; + match n { + Object::Int(v) if *v >= 0 => { + let v = *v as u64; + if (64 - v.leading_zeros() as usize).div_ceil(8) > length { + return None; + } + out = vec![0u8; length]; + let n = length.min(8); + out[..n].copy_from_slice(&v.to_le_bytes()[..n]); + } + Object::Long(b) if !b.is_negative() => { + if (b.bits() as usize).div_ceil(8) > length { + return None; + } + out = vec![0u8; length]; + for (chunk, digit) in out.chunks_mut(8).zip(b.iter_u64_digits()) { + chunk.copy_from_slice(&digit.to_le_bytes()[..chunk.len()]); + } + } + _ => return None, + } + if !little { + out.reverse(); + } + Some(out) +} + fn bigint_to_bytes( n: &BigInt, length: usize, @@ -6032,7 +6557,7 @@ fn float_receiver(v: &Object) -> Option { } fn float_is_integer(args: &[Object]) -> Result { - let v = one(args, "is_integer")?; + let v = self_only(args, "float.is_integer")?; match float_receiver(v) { Some(f) => Ok(Object::Bool(f.is_finite() && f.fract() == 0.0)), None => Err(type_error("is_integer: float expected")), @@ -6040,7 +6565,7 @@ fn float_is_integer(args: &[Object]) -> Result { } fn float_hex(args: &[Object]) -> Result { - let v = one(args, "hex")?; + let v = self_only(args, "float.hex")?; match float_receiver(v) { Some(f) => Ok(Object::from_str(format_float_hex(f))), None => Err(type_error("hex: float expected")), @@ -6085,7 +6610,7 @@ fn float_fromhex_wrap(cls: Option<&Object>, x: f64) -> Result Result { - let v = one(args, "as_integer_ratio")?; + let v = self_only(args, "float.as_integer_ratio")?; let Some(f) = float_receiver(v) else { return Err(type_error("as_integer_ratio: float expected")); }; @@ -6159,7 +6684,7 @@ fn float_as_integer_ratio(args: &[Object]) -> Result { } fn float_conjugate(args: &[Object]) -> Result { - Ok(one(args, "conjugate")?.clone()) + Ok(self_only(args, "float.conjugate")?.clone()) } fn float_trunc(args: &[Object]) -> Result { @@ -6743,6 +7268,51 @@ pub(crate) fn b_float_from_number_cls(args: &[Object]) -> Result Option> { + const BAD: u8 = 0xFF; + const DIGIT: [u8; 256] = { + let mut t = [BAD; 256]; + let mut c = 0; + while c < 256 { + t[c] = match c as u8 { + b'0'..=b'9' => c as u8 - b'0', + b'a'..=b'f' => c as u8 - b'a' + 10, + b'A'..=b'F' => c as u8 - b'A' + 10, + _ => BAD, + }; + c += 1; + } + t + }; + let mut out = Vec::with_capacity(text.len() / 2); + let mut rest = text; + loop { + // A run of whole pairs, up to the first pair that isn't two + // digits (a bad digit's high bits are set). + let pairs = rest.as_chunks::<2>().0; + let mut taken = 0; + for pair in pairs { + let (hi, lo) = (DIGIT[usize::from(pair[0])], DIGIT[usize::from(pair[1])]); + if (hi | lo) & 0xF0 != 0 { + break; + } + out.push(hi << 4 | lo); + taken += 2; + } + rest = &rest[taken..]; + // Then whitespace between pairs, or the end; anything else (a + // non-digit, a lone digit) is the slow parse's to report. + match rest.first() { + None => return Some(out), + Some(b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r') => rest = &rest[1..], + Some(_) => return None, + } + } +} + fn parse_hex_bytes(s: &str) -> Result, RuntimeError> { // CPython's `_PyBytes_FromHex`: pairs of hex digits, with *ASCII* // whitespace permitted only between pairs. Error positions are @@ -6752,6 +7322,13 @@ fn parse_hex_bytes(s: &str) -> Result, RuntimeError> { "non-hexadecimal number found in fromhex() arg at position {pos}" )) }; + // (ASCII text, the usual input, is read by its bytes, a table lookup + // per digit; anything else, and every error, by characters below.) + if s.is_ascii() { + if let Some(bytes) = hex_pairs_ascii(s.as_bytes()) { + return Ok(bytes); + } + } let chars: Vec = s.chars().collect(); let mut bytes = Vec::with_capacity(chars.len() / 2); let mut i = 0usize; @@ -7311,22 +7888,95 @@ fn b_tuple(args: &[Object]) -> Result { Ok(Object::new_tuple(out)) } -fn b_dict(args: &[Object]) -> Result { - if args.is_empty() { - let obj = Object::new_dict(); - crate::gc_trace::track(&obj); - return Ok(obj); - } - if args.len() > 1 { - return Err(type_error(format!( - "dict expected at most 1 argument, got {}", - args.len() - ))); +/// The key and value of an exact two-item tuple or list, read in place (as +/// CPython's `PySequence_Fast` reads a pair of `dict.update`'s). +pub(crate) fn exact_pair(pair: &Object) -> Option<(Object, Object)> { + match pair { + Object::Tuple(t) if t.len() == 2 => Some((t[0].clone(), t[1].clone())), + Object::List(l) => match l.try_borrow().ok()?.as_slice() { + [k, v] => Some((k.clone(), v.clone())), + _ => None, + }, + _ => None, } - // Fast path: another built-in dict copies entry-for-entry. Avoids - // re-iterating as a sequence of pairs (which would fail, since - // iter(dict) yields keys, not items). - if let Object::Dict(src) = &args[0] { +} + +/// `m[key] = value` for a key that settles by native equality (see +/// [`dict_insert_exact`]), with no notification: whether a stored value +/// was replaced by a different object, or the key and value handed back. +fn table_store_exact( + m: &mut DictData, + key: Object, + value: Object, +) -> Result { + let Some(probe) = crate::object::LeafProbe::new(&key) else { + return Err((key, value)); + }; + let vacancy = match m.probe_entry(&probe) { + crate::dictmap::ProbeEntry::Occupied(e) => { + let slot = e.into_mut(); + let changed = !slot.is_same(&value); + *slot = value; + return Ok(changed); + } + crate::dictmap::ProbeEntry::Vacant(e) => e, + }; + if !probe.miss_is_exact() { + return Err((key, value)); + } + vacancy.insert(DictKey(key), value); + Ok(false) +} + +/// The pairs at the front of `pairs` stored into `m` (with no +/// notification), while each is an exact two-item tuple or list whose key +/// settles natively: how many were stored, and whether a stored value was +/// replaced by a different object. +pub(crate) fn table_store_pairs(m: &mut DictData, pairs: &[Object]) -> (usize, bool) { + // An empty table is sized once for the pairs (up to a bound), and + // trimmed afterwards if the pairs mostly repeated their keys. + const ROOM_MAX: usize = 4096; + let room = if m.is_empty() { + pairs.len().min(ROOM_MAX) + } else { + 0 + }; + if room > 8 { + m.reserve(room); + } + let (mut stored, mut changed) = (0, false); + for pair in pairs { + let Some((k, v)) = exact_pair(pair) else { + break; + }; + match table_store_exact(m, k, v) { + Ok(replaced) => changed |= replaced, + Err(_) => break, + } + stored += 1; + } + if room > 64 && m.len() * 4 < room { + m.shrink_to_fit(); + } + (stored, changed) +} + +pub(crate) fn b_dict(args: &[Object]) -> Result { + if args.is_empty() { + let obj = Object::new_dict(); + crate::gc_trace::track(&obj); + return Ok(obj); + } + if args.len() > 1 { + return Err(type_error(format!( + "dict expected at most 1 argument, got {}", + args.len() + ))); + } + // Fast path: another built-in dict copies entry-for-entry. Avoids + // re-iterating as a sequence of pairs (which would fail, since + // iter(dict) yields keys, not items). + if let Object::Dict(src) = &args[0] { // Clone the stored table so copying never rehashes user keys. let d = src.borrow().clone(); let obj = Object::Dict(Rc::new(RefCell::new(d))); @@ -7336,10 +7986,50 @@ fn b_dict(args: &[Object]) -> Result { // Mapping path for user-defined classes (`__keys__` style) is // handled by the VM before dispatching here — see // `Vm::do_dict_call`. Anything left over is an iterable of pairs. - let mut it = args[0].make_iter()?; + // (An items view of a dict holds that dict's entries: its table, hashes + // and all.) + if let Object::DictView(view) = &args[0] { + if matches!(view.kind, crate::object::DictViewKind::Items) { + let d = view.dict.borrow().clone(); + let obj = Object::Dict(Rc::new(RefCell::new(d))); + crate::gc_trace::track(&obj); + return Ok(obj); + } + } let mut d = DictData::default(); + // A list's or tuple's leading pairs are walked in place (see + // `table_store_pairs`); the iterator below passes over them. + let (walked, all) = match &args[0] { + Object::Tuple(t) => (table_store_pairs(&mut d, t).0, t.len()), + Object::List(l) => l.try_borrow().map_or((0, usize::MAX), |l| { + (table_store_pairs(&mut d, &l).0, l.len()) + }), + _ => (0, usize::MAX), + }; + if walked == all { + let obj = Object::Dict(Rc::new(RefCell::new(d))); + crate::gc_trace::track(&obj); + return Ok(obj); + } + let mut it = args[0].make_iter()?; let mut i = 0usize; + while i < walked { + if it.next_value().is_none() { + break; + } + i += 1; + } while let Some(pair) = it.next_value() { + // An exact two-item tuple or list is read in place, and a key that + // settles natively stored with one probe. + if let Some((key, value)) = exact_pair(&pair) { + if let Err((key, value)) = table_store_exact(&mut d, key, value) { + ensure_dict_key(&key)?; + crate::object::key_cmp_scope(|| d.insert(DictKey(key), value))?; + } + i += 1; + continue; + } // CPython `PyDict_MergeFromSeq2`: each element must itself be a // sequence of exactly two items (a 2-char string works too). // User instances iterate through the live interpreter (their @@ -7415,7 +8105,9 @@ pub(crate) fn b_set(args: &[Object]) -> Result { // construction (test_badcmp `set([BadCmp(), BadCmp()])`). let mut it = args[0].make_iter()?; let mut out = crate::object::SetData::default(); - while let Some(v) = it.next_value() { + // (A list's, tuple's or range's cursor steps in place; its end, and + // every other iterator, take the full step.) + while let Some(v) = it.pure_next().or_else(|| it.next_value()) { let key = set_insert_key(&v)?; crate::object::key_cmp_scope(|| out.insert(key))?; } @@ -7430,7 +8122,9 @@ pub(crate) fn b_set(args: &[Object]) -> Result { /// The set of a list's or tuple's items when every item is an `int`, /// `str`, `float`, `bool` or `None` (whose hashing and comparison run no /// Python and can't fail): sized once and filled without the per-insert -/// error scope. `None` leaves the general path to it. +/// error scope. Likewise the set of another set's or a frozenset's +/// elements, or of a dict's keys, taken with their stored hashes. `None` +/// leaves the general path to it. fn simple_key_set(src: &Object) -> Option { fn build(items: &[Object]) -> Option { let simple = |v: &Object| { @@ -7454,6 +8148,26 @@ fn simple_key_set(src: &Object) -> Option { match src { Object::List(l) => build(&l.try_borrow().ok()?), Object::Tuple(t) => build(t), + // A short `str`'s characters (`set(word)`). + Object::Str(s) if s.len() <= 256 => { + build(&s.chars().map(Object::from_char).collect::>()) + } + // A set's or frozenset's own table, hashes and all; a dict's keys + // with their stored hashes (each differs from the rest, so none is + // hashed or compared). + Object::Set(s) => Some(crate::object::SetData::clone(&*s.try_borrow().ok()?)), + Object::FrozenSet(s) => Some(crate::object::SetData::clone(s)), + Object::Dict(d) => { + let d = d.try_borrow().ok()?; + let mut out = crate::object::SetData::with_capacity_and_hasher( + d.len(), + crate::fasthash::FxBuildHasher, + ); + for (hash, key) in d.hashed_keys() { + out.insert_unique_hashed(hash, key.clone()); + } + Some(out) + } _ => None, } } @@ -7478,6 +8192,11 @@ pub(crate) fn b_frozenset(args: &[Object]) -> Result { if let Object::FrozenSet(_) = &args[0] { return Ok(args[0].clone()); } + if let Some(out) = simple_key_set(&args[0]) { + return Ok(Object::FrozenSet(Rc::new( + crate::object::FrozenSetObj::new(out), + ))); + } let mut it = args[0].make_iter()?; let mut out = crate::object::SetData::default(); while let Some(v) = it.next_value() { @@ -7516,7 +8235,56 @@ fn byte_item_value(o: &Object) -> Result { /// `bytearray(x)` — CPython's `PyBytes_FromObject` / /// `bytearray_init` tail: index-sized count, buffer copy, or /// iterable of byte values. +/// The bytes of a list or tuple whose items are all plain ints in +/// `range(256)`, read in place; `None` for anything else (the general path +/// converts or refuses each item, and reports the first it can't take). +fn bytes_of_plain_ints(src: &Object) -> Option> { + fn pack(items: &[Object]) -> Option> { + let mut out = Vec::with_capacity(items.len()); + for item in items { + match item { + Object::Int(v @ 0..=255) => out.push(*v as u8), + _ => return None, + } + } + Some(out) + } + match src { + Object::List(l) => pack(&l.try_borrow().ok()?), + Object::Tuple(t) => pack(t), + // A range of byte values (`bytes(range(256))`), computed in place: + // at most 256 steps before a value leaves the byte range. + Object::Range(r) if r.big.is_none() => { + let (start, stop, step) = ( + i64::try_from(r.start).ok()?, + i64::try_from(r.stop).ok()?, + i64::try_from(r.step).ok()?, + ); + let span = if step > 0 { + i128::from(stop) - i128::from(start) + } else { + i128::from(start) - i128::from(stop) + }; + let len = (span.max(0) + i128::from(step).abs() - 1) / i128::from(step).abs().max(1); + let mut out = Vec::with_capacity(len.clamp(0, 256) as usize); + let mut v = start; + while (step > 0 && v < stop) || (step < 0 && v > stop) { + if !(0..=255).contains(&v) { + return None; + } + out.push(v as u8); + v = v.checked_add(step)?; + } + Some(out) + } + _ => None, + } +} + fn bytes_from_source_obj(src: &Object, type_name: &str) -> Result, RuntimeError> { + if let Some(bytes) = bytes_of_plain_ints(src) { + return Ok(bytes); + } let zero_fill = |n: i64| -> Result, RuntimeError> { if n < 0 { return Err(value_error("negative count")); @@ -8350,6 +9118,48 @@ pub(crate) fn sum_small_int_sequence(iterable: &Object, start: &Object) -> Optio match iterable { Object::List(items) => accumulate(&items.borrow()), Object::Tuple(items) => accumulate(items), + // A dict's values or keys, read in place. + Object::DictView(v) => { + let d = v.dict.try_borrow().ok()?; + let mut total = i128::from(*start); + for (k, val) in d.iter() { + let item = match v.kind { + crate::object::DictViewKind::Values => val, + crate::object::DictViewKind::Keys => &k.0, + crate::object::DictViewKind::Items => return None, + }; + total = total.checked_add(match item { + Object::Int(value) => i128::from(*value), + Object::Bool(value) => i128::from(*value), + _ => return None, + })?; + } + Some(crate::object::int_from_i128(total)) + } + // `sum(reversed(xs))` of ints (whose order doesn't matter): the rest + // of the reversed snapshot at once, the iterator then exhausted and + // detached as its last step leaves it. + Object::Iter(it) => { + let mut cursor = it.try_borrow_mut().ok()?; + let PyIterator::Reversed { + items, + index, + owner, + } = &mut *cursor + else { + return None; + }; + let total = { + let v = items.try_borrow().ok()?; + let i = usize::try_from(*index).ok()?; + accumulate(v.get(..=i)?)? + }; + let detached = (std::mem::take(items), owner.take()); + *index = -1; + drop(cursor); + drop(detached); + Some(total) + } _ => None, } } @@ -8395,11 +9205,16 @@ pub(crate) fn sum_numeric_sequence( // CPython leaves its integer loop permanently on overflow. // If this addition yields a float, its float loop follows; // later floats reached through generic arithmetic don't. - total = crate::binary_op( - &Object::Int(integer), - item, - weavepy_compiler::BinOpKind::Add, - )?; + // (A float's is `float(integer) + item`, the machine + // int rounded to the nearest double.) + total = match item { + Object::Float(value) => Object::Float(integer as f64 + *value), + _ => crate::binary_op( + &Object::Int(integer), + item, + weavepy_compiler::BinOpKind::Add, + )?, + }; break; } } @@ -8445,6 +9260,20 @@ pub(crate) fn sum_numeric_sequence( match iterable { Object::List(items) => accumulate(&items.borrow()), Object::Tuple(items) => accumulate(items), + // A dict's values or keys, copied out first (the sum may run a + // float's arithmetic, never Python code, but the dict stays free). + Object::DictView(v) if !matches!(v.kind, crate::object::DictViewKind::Items) => { + let items: Vec = { + let d = v.dict.try_borrow().ok()?; + d.iter() + .map(|(k, val)| match v.kind { + crate::object::DictViewKind::Keys => k.0.clone(), + _ => val.clone(), + }) + .collect() + }; + accumulate(&items) + } _ => None, } } @@ -8667,15 +9496,50 @@ pub(crate) fn b_reversed(args: &[Object]) -> Result { owner: None, })))); } + // An iterator, a native adapter (an endless `itertools.count()` + // among them), a generator or a set isn't a sequence: CPython's + // `reversed` wants `__reversed__` or `__len__` and `__getitem__`. + let sequence = match iterable { + Object::Str(_) | Object::Bytes(_) | Object::ByteArray(_) => true, + Object::Instance(_) => crate::instance_method(iterable, "__getitem__").is_some(), + Object::Iter(_) + | Object::LazyIter(_) + | Object::Generator(_) + | Object::Coroutine(_) + | Object::AsyncGenerator(_) + | Object::Set(_) + | Object::FrozenSet(_) => false, + _ => lookup_method(iterable, "__getitem__").is_some(), + }; + if !sequence { + return Err(type_error(format!( + "'{}' object is not reversible", + iterable.type_name() + ))); + } // Otherwise materialize the source in *forward* order; the Reversed // iterator walks it back-to-front. (CPython's `reversed` uses // `__reversed__` or `__len__`+`__getitem__`; a forward snapshot // reproduces the same sequence for the finite iterables handled here.) - let mut it = iterable.make_iter()?; - let mut buf = Vec::new(); - while let Some(v) = it.next_value() { - buf.push(v); - } + let buf: Vec = if let Object::Str(text) = iterable { + // (A `str`'s characters, read directly: an ASCII one's are the + // shared one-character strings, sized exactly.) + if text.is_ascii() { + text.as_bytes() + .iter() + .map(|&c| Object::Str(crate::shared_value::SharedStr::ascii_char(c))) + .collect() + } else { + text.chars().map(Object::from_char).collect() + } + } else { + let mut it = iterable.make_iter()?; + let mut buf = Vec::new(); + while let Some(v) = it.next_value() { + buf.push(v); + } + buf + }; let index = buf.len() as i64 - 1; Ok(Object::Iter(Rc::new(RefCell::new(PyIterator::Reversed { items: Rc::new(RefCell::new(buf)), @@ -8900,28 +9764,31 @@ pub(crate) fn build_super_proxy( receiver: Object, receiver_class: Rc, ) -> Object { + thread_local! { + /// The proxy's keys, in the order its dict holds them, with their + /// hashes. + static KEYS: crate::gil::ReleaseUnderGil<[(i64, DictKey); 3]> = crate::gil::ReleaseUnderGil::new(["__self__", "__thisclass__", "__self_class__"] + .map(|name| { + let key = DictKey(Object::from_static(name)); + (crate::object::dict_key_hash(&key.0), key) + })); + } + // `__self_class__` is CPython's `su->obj_type` — the class whose MRO is + // walked, passed as `owner` to descriptor `__get__`s. Also used to + // detect the class-bound form (`su->obj == starttype`), where + // descriptors get a NULL instance (so plain functions come back + // *unbound*: `super().__new__(cls, v)` must not prepend a second + // `cls`). + let mut values = [receiver, Object::Type(class), Object::Type(receiver_class)].into_iter(); + let map = KEYS.with(|keys| { + crate::dictmap::DictMap::from_unique_hashed(3, |i| { + let (hash, key) = &keys[i]; + (*hash, key.clone(), values.next().expect("three values")) + }) + }); let inst = crate::types::PyInstance { class: RefCell::new(proxy_type), - dict: Rc::new(RefCell::new({ - let mut d = DictData::default(); - d.insert(DictKey(Object::from_static("__self__")), receiver); - d.insert( - DictKey(Object::from_static("__thisclass__")), - Object::Type(class), - ); - // CPython's `su->obj_type` — the class whose MRO is walked, - // passed as `owner` to descriptor `__get__`s. Also used to - // detect the class-bound form (`su->obj == starttype`), - // where descriptors get a NULL instance (so plain functions - // come back *unbound*: `super().__new__(cls, v)` must not - // prepend a second `cls`). - d.insert( - DictKey(Object::from_static("__self_class__")), - Object::Type(receiver_class), - ); - d - })) - .into(), + dict: Rc::new(RefCell::new(DictData::from(map))).into(), native: crate::sync::OnceBox::new(), inline_values: crate::sync::Cell::new(true), slots: crate::sync::RefCell::new(crate::types::SlotStorage::default()), @@ -9304,6 +10171,7 @@ pub fn class_of(obj: &Object) -> crate::sync::Rc { Ok(K::Filter { .. }) => bt.filter_.clone(), Ok(K::Zip { .. }) => bt.zip_.clone(), Ok(K::Enumerate { .. }) => bt.enumerate_.clone(), + Ok(K::CallIter { .. }) => bt.callable_iterator_.clone(), _ => bt.iterator_.clone(), } } @@ -9761,8 +10629,14 @@ const CODE_ATTR_NAMES: &[&str] = &[ /// this loose because runtime helpers (typing, dataclasses, abc) /// only need it to enumerate user attributes. pub fn b_dir(args: &[Object]) -> Result { - use std::collections::BTreeSet; - let mut names: BTreeSet = BTreeSet::new(); + // (The list is the caller's to fill and keep: a tracked one.) + let out = b_dir_names(args)?; + crate::gc_trace::track_built(&out); + Ok(out) +} + +fn b_dir_names(args: &[Object]) -> Result { + let mut names = DirNames(Vec::new()); let obj = one(args, "dir")?; // Set when `getattr(obj, '__class__')` would fail — an *unset* // `__class__` slot (`__slots__ = ['__class__', …]`) hides the type @@ -9781,11 +10655,11 @@ pub fn b_dir(args: &[Object]) -> Result { } match obj { Object::Instance(inst) => { - for k in inst.dict_cell().borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } - } + // (The names alone: a split instance keeps its layout, whose + // attribute reads compiled code takes in line.) + inst.for_each_attr(|k, _| { + names.key(&k.0); + }); class_hidden = matches!( inst.cls().lookup("__class__"), Some(Object::SlotDescriptor(_)) @@ -9793,9 +10667,7 @@ pub fn b_dir(args: &[Object]) -> Result { if !class_hidden { for t in inst.cls().mro.borrow().iter() { for k in t.dict.borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } + names.key(&k.0); } } } @@ -9803,9 +10675,7 @@ pub fn b_dir(args: &[Object]) -> Result { Object::Type(t) => { for cls in t.mro.borrow().iter() { for k in cls.dict.borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } + names.key(&k.0); } } // `types.CodeType`'s getsets are synthesized in `load_attr` @@ -9816,7 +10686,7 @@ pub fn b_dir(args: &[Object]) -> Result { // `co_flags`/`co_argcount` on it. if t.name == "code" && t.flags.is_builtin { for n in CODE_ATTR_NAMES { - names.insert((*n).to_string()); + names.name(n); } } } @@ -9836,13 +10706,11 @@ pub fn b_dir(args: &[Object]) -> Result { .borrow() .contains_key(&crate::object::DictKey(Object::from_static("__spec__"))); if missing_spec { - names.insert("__spec__".to_owned()); - names.insert("__loader__".to_owned()); + names.name("__spec__"); + names.name("__loader__"); } for k in m.dict.borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } + names.key(&k.0); } } Object::Function(f) => { @@ -9854,9 +10722,7 @@ pub fn b_dir(args: &[Object]) -> Result { // `@pytest.mark.parametrize` stacked under `@given`. if let Some(attrs) = f.attrs.borrow().as_ref() { for k in attrs.borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } + names.key(&k.0); } } for n in [ @@ -9876,13 +10742,11 @@ pub fn b_dir(args: &[Object]) -> Result { "__qualname__", "__type_params__", ] { - names.insert(n.to_string()); + names.name(n); } for t in class_of(obj).mro.borrow().iter() { for k in t.dict.borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } + names.key(&k.0); } } } @@ -9894,18 +10758,14 @@ pub fn b_dir(args: &[Object]) -> Result { // `dir(obj.f)` too (test_funcattrs). if let Object::List(items) = b_dir(&[bm.function.clone()])? { for it in items.borrow().iter() { - if let Object::Str(s) = it { - names.insert(s.to_string()); - } + names.key(it); } } - names.insert("__func__".to_string()); - names.insert("__self__".to_string()); + names.name("__func__"); + names.name("__self__"); for t in class_of(obj).mro.borrow().iter() { for k in t.dict.borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } + names.key(&k.0); } } } @@ -9913,9 +10773,7 @@ pub fn b_dir(args: &[Object]) -> Result { // Generic objects: `object.__dir__` ≈ the type's attributes. for t in class_of(other).mro.borrow().iter() { for k in t.dict.borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } + names.key(&k.0); } } // A namespace-shaped object (PEP 585 GenericAlias, @@ -9924,9 +10782,7 @@ pub fn b_dir(args: &[Object]) -> Result { // (`'__origin__' in dir(list[int])`). if let Object::SimpleNamespace(d) = other { for k in d.borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } + names.key(&k.0); } // A PEP 604 union (3.14 `types.UnionType`) exposes its // getsets -- `__args__`, `__parameters__`, `__origin__`, @@ -9937,7 +10793,7 @@ pub fn b_dir(args: &[Object]) -> Result { names.remove("__is_pep604_union__"); names.remove("__weave_unhashable_args__"); for n in ["__origin__", "__name__", "__qualname__"] { - names.insert(n.to_string()); + names.name(n); } } // CPython `ga_dir`: a generic alias reports `dir(origin)` @@ -9950,9 +10806,7 @@ pub fn b_dir(args: &[Object]) -> Result { if let Some(Object::Type(t)) = origin { for cls in t.mro.borrow().iter() { for k in cls.dict.borrow().keys() { - if let Object::Str(s) = &k.0 { - names.insert(s.to_string()); - } + names.key(&k.0); } } } @@ -9962,7 +10816,7 @@ pub fn b_dir(args: &[Object]) -> Result { // dicts; surface the same names CPython's type dicts hold. if matches!(other, Object::Code(_)) { for n in CODE_ATTR_NAMES { - names.insert((*n).to_string()); + names.name(n); } } let extra: &[&str] = match other { @@ -10049,7 +10903,7 @@ pub fn b_dir(args: &[Object]) -> Result { _ => &[], }; for n in extra { - names.insert((*n).to_string()); + names.name(n); } } } @@ -10068,23 +10922,105 @@ pub fn b_dir(args: &[Object]) -> Result { "__sizeof__", "__str__", ] { - names.insert(n.to_string()); + names.name(n); } } - Ok(Object::new_list( - names.into_iter().map(Object::from_str).collect(), - )) + Ok(Object::new_list(names.sorted())) } -fn b_hex(args: &[Object]) -> Result { - match one(args, "hex")? { - Object::Int(i) => { - if *i < 0 { - Ok(Object::from_str(format!("-0x{:x}", (i.unsigned_abs())))) - } else { - Ok(Object::from_str(format!("0x{i:x}"))) +/// `dir()`'s names as it collects them: the dict keys' own `str` objects +/// (a reference each, nothing copied), sorted and deduplicated once at +/// the end. +struct DirNames(Vec); + +impl DirNames { + /// A dict key, if it's a `str`. + fn key(&mut self, k: &Object) { + if matches!(k, Object::Str(_)) { + self.0.push(k.clone()); + } + } + + fn name(&mut self, n: &'static str) { + self.0.push(Object::from_static(n)); + } + + /// Drop `n` from the names collected so far. + fn remove(&mut self, n: &str) { + self.0 + .retain(|k| !matches!(k, Object::Str(s) if s.as_ref() == n)); + } + + fn sorted(mut self) -> Vec { + fn as_str(o: &Object) -> &str { + match o { + Object::Str(s) => s.as_ref(), + _ => "", } } + self.0.sort_unstable_by(|a, b| as_str(a).cmp(as_str(b))); + self.0.dedup_by(|a, b| as_str(a) == as_str(b)); + self.0 + } +} + +/// `hex`/`oct`/`bin` of a machine int: the prefix (`0x`, `0o`, `0b`, after a +/// sign) and the digits of the magnitude in base `1 << shift`, built in a +/// stack buffer as an ASCII string. +fn radix_str(i: i64, letter: u8, shift: u32) -> Object { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut buf = [0u8; 67]; + let mut at = buf.len(); + let mut m = i.unsigned_abs(); + let mask = (1u64 << shift) - 1; + loop { + at -= 1; + buf[at] = DIGITS[(m & mask) as usize]; + m >>= shift; + if m == 0 { + break; + } + } + at -= 2; + buf[at] = b'0'; + buf[at + 1] = letter; + if i < 0 { + at -= 1; + buf[at] = b'-'; + } + // SAFETY: only ASCII digits, letters and signs were written. + let text = unsafe { std::str::from_utf8_unchecked(&buf[at..]) }; + Object::Str(SharedStr::from_ascii(text)) +} + +/// `hex(i)`, `oct(i)` and `bin(i)`'s leaf halves: an exact int, big int +/// or bool, formatted in place. Anything else (`__index__` may run code) +/// takes the full path. +fn radix_fast( + args: &[Object], + f: fn(&[Object]) -> Result, +) -> Option> { + match args { + [Object::Int(_) | Object::Bool(_) | Object::Long(_)] => Some(f(args)), + _ => None, + } +} + +pub(crate) fn hex_fast(args: &[Object]) -> Option> { + radix_fast(args, b_hex) +} + +pub(crate) fn oct_fast(args: &[Object]) -> Option> { + radix_fast(args, b_oct) +} + +pub(crate) fn bin_fast(args: &[Object]) -> Option> { + radix_fast(args, b_bin) +} + +fn b_hex(args: &[Object]) -> Result { + match one(args, "hex")? { + Object::Int(i) => Ok(radix_str(*i, b'x', 4)), Object::Long(b) => { let inner = (**b).clone(); if inner.is_negative() { @@ -10102,13 +11038,7 @@ fn b_hex(args: &[Object]) -> Result { fn b_oct(args: &[Object]) -> Result { match one(args, "oct")? { - Object::Int(i) => { - if *i < 0 { - Ok(Object::from_str(format!("-0o{:o}", i.unsigned_abs()))) - } else { - Ok(Object::from_str(format!("0o{i:o}"))) - } - } + Object::Int(i) => Ok(radix_str(*i, b'o', 3)), Object::Long(b) => { let inner = (**b).clone(); if inner.is_negative() { @@ -10125,13 +11055,7 @@ fn b_oct(args: &[Object]) -> Result { fn b_bin(args: &[Object]) -> Result { match one(args, "bin")? { - Object::Int(i) => { - if *i < 0 { - Ok(Object::from_str(format!("-0b{:b}", i.unsigned_abs()))) - } else { - Ok(Object::from_str(format!("0b{i:b}"))) - } - } + Object::Int(i) => Ok(radix_str(*i, b'b', 1)), Object::Long(b) => { let inner = (**b).clone(); if inner.is_negative() { @@ -10285,7 +11209,7 @@ pub fn vm_intrinsic(name: &str) -> Option { t } thread_local! { - static TABLE: Table = build(); + static TABLE: crate::gil::ReleaseUnderGil = crate::gil::ReleaseUnderGil::new(build()); } TABLE.with(|t| t.get(name).cloned()) } @@ -10483,20 +11407,42 @@ fn pow_simple(base: &Object, exp: &Object) -> Result { } fn pow_modular(base: &Object, exp: &Object, m: &Object) -> Result { + // (Borrowed where they're already big: no copy of a long operand.) let (b, e, mm) = ( - bigint_from(base, "pow")?, - bigint_from(exp, "pow")?, - bigint_from(m, "pow")?, + bigint_ref(base, "pow")?, + bigint_ref(exp, "pow")?, + bigint_ref(m, "pow")?, ); + let (b, e, mm): (&BigInt, &BigInt, &BigInt) = (&b, &e, &mm); if mm.is_zero() { return Err(value_error("pow() 3rd argument cannot be 0")); } use num_bigint::BigInt; use num_traits::One; + // A non-negative exponent: a word-size modulus works in machine + // integers, any other through num-bigint's `modpow` (Montgomery + // reduction for an odd modulus), the result taking `m`'s sign below. + if !e.is_negative() { + let result: BigInt = match u64::try_from(mm.magnitude()) { + Ok(m) => BigInt::from(pow_mod_word(b, e, m)), + Err(_) => { + let m_abs = mm.magnitude(); + let mut base = b.magnitude() % m_abs; + if b.is_negative() && !base.is_zero() { + base = m_abs - base; + } + BigInt::from(base.modpow(e.magnitude(), m_abs)) + } + }; + if mm.is_negative() && !result.is_zero() { + return Ok(Object::int_from_bigint(result + mm)); + } + return Ok(Object::int_from_bigint(result)); + } // Work modulo |m|; CPython gives the result the *sign* of `m` at the end. let m_abs: BigInt = mm.abs(); // Reduce the base into [0, |m|). - let mut base_mod: BigInt = ((&b % &m_abs) + &m_abs) % &m_abs; + let mut base_mod: BigInt = ((b % &m_abs) + &m_abs) % &m_abs; let mut exp_val: BigInt = e.clone(); // A negative exponent means `pow(base, -e, m) == pow(base**-1, e, m)`, // where `base**-1` is the modular inverse (CPython 3.8+). The inverse only @@ -10524,11 +11470,46 @@ fn pow_modular(base: &Object, exp: &Object, m: &Object) -> Result 0`, by square and multiply in 128-bit integers: the base +/// reduced limb by limb (`2**64` folded in as a shift), then the +/// exponent's bits from the lowest. +fn pow_mod_word(b: &num_bigint::BigInt, e: &num_bigint::BigInt, m: u64) -> u64 { + let m128 = u128::from(m); + let mut base: u64 = 0; + for d in b.magnitude().iter_u64_digits().rev() { + base = (((u128::from(base)) << 64 | u128::from(d)) % m128) as u64; + } + if b.is_negative() && base != 0 { + base = m - base; + } + let mut result: u64 = (1 % m128) as u64; + let mut sq = base; + let digits: Vec = e.magnitude().iter_u64_digits().collect(); + for (i, &d) in digits.iter().enumerate() { + let mut d = d; + // (The top digit stops at its highest set bit.) + let bits = if i + 1 == digits.len() { + 64 - d.leading_zeros() + } else { + 64 + }; + for _ in 0..bits { + if d & 1 == 1 { + result = (u128::from(result) * u128::from(sq) % m128) as u64; + } + d >>= 1; + sq = (u128::from(sq) * u128::from(sq) % m128) as u64; + } + } + result +} + /// Modular inverse of `a` (already reduced into `[0, m)`) modulo `m > 0`, via /// the iterative extended Euclidean algorithm. Returns `None` when `a` and `m` /// are not coprime (no inverse exists). Result is normalised into `[0, m)`. @@ -10550,6 +11531,17 @@ fn mod_inverse(a: &num_bigint::BigInt, m: &num_bigint::BigInt) -> Option( + o: &'a Object, + fn_name: &str, +) -> Result, RuntimeError> { + match o { + Object::Long(b) => Ok(std::borrow::Cow::Borrowed(&**b)), + other => bigint_from(other, fn_name).map(std::borrow::Cow::Owned), + } +} + fn bigint_from(o: &Object, fn_name: &str) -> Result { match o { Object::Int(i) => Ok(BigInt::from(*i)), @@ -10786,7 +11778,25 @@ pub(crate) fn b_divmod(args: &[Object]) -> Result { ])); } } - let q = crate::binary_op(&args[0], &args[1], weavepy_compiler::BinOpKind::FloorDiv)?; + let q = match crate::binary_op(&args[0], &args[1], weavepy_compiler::BinOpKind::FloorDiv) { + Ok(q) => q, + // (Operands `//` doesn't take: the error names `divmod()`.) + Err(_) + if !args.iter().all(|a| { + matches!( + a, + Object::Int(_) | Object::Long(_) | Object::Float(_) | Object::Bool(_) + ) + }) => + { + return Err(type_error(format!( + "unsupported operand type(s) for divmod(): '{}' and '{}'", + args[0].type_name_owned(), + args[1].type_name_owned() + ))); + } + Err(e) => return Err(e), + }; let r = crate::binary_op(&args[0], &args[1], weavepy_compiler::BinOpKind::Mod)?; Ok(Object::new_tuple_array([q, r])) } @@ -10897,8 +11907,13 @@ fn float_to_int_obj(r: f64) -> Object { /// unchanged; negative `ndigits` round to a power of ten (ties-to-even). fn round_int(value: &Object, ndigits: Option) -> Result { let n = match ndigits { - None => return Ok(value.clone()), - Some(n) if n >= 0 => return Ok(value.clone()), + // `bool.__round__` is `int.__round__`: the result is a plain `int`. + None | Some(0..) => { + return Ok(match value { + Object::Bool(b) => Object::Int(i64::from(*b)), + _ => value.clone(), + }); + } Some(n) => n, }; // Negative ndigits: round to 10^(-n) via BigInt to stay exact. @@ -11074,21 +12089,29 @@ fn str_result(args: &[Object], result: String) -> Object { /// CPython parity: enforce positional arity on native `str` methods the /// way the C argument clinic / `METH_NOARGS` do. `args[0]` is the /// receiver; `min`/`max` bound the *user-visible* argument count. +#[inline] fn str_arity(name: &str, args: &[Object], min: usize, max: usize) -> Result<(), RuntimeError> { let given = args.len().saturating_sub(1); + if given > max || given < min { + return Err(str_arity_error(name, given, min, max)); + } + Ok(()) +} + +/// [`str_arity`]'s `TypeError`, out of line. +#[cold] +#[inline(never)] +fn str_arity_error(name: &str, given: usize, min: usize, max: usize) -> RuntimeError { if given > max { - return Err(type_error(if max == 0 { + return type_error(if max == 0 { format!("str.{name}() takes no arguments ({given} given)") } else { format!("{name} expected at most {max} arguments, got {given}") - })); - } - if given < min { - return Err(type_error(format!( - "{name} expected at least {min} arguments, got {given}" - ))); + }); } - Ok(()) + type_error(format!( + "{name} expected at least {min} arguments, got {given}" + )) } /// An ASCII `str` receiver's case mapping, written straight into the @@ -11101,6 +12124,16 @@ fn ascii_case_result(args: &[Object], case: crate::unicode_case::AsciiCase) -> O if !SharedStr::is_ascii(s) { return None; } + // (An exact `str` already in the case `lower()` or `upper()` maps to: + // itself, as CPython may return it, with nothing built.) + let unchanged = match case { + crate::unicode_case::AsciiCase::Lower => !s.as_bytes().iter().any(u8::is_ascii_uppercase), + crate::unicode_case::AsciiCase::Upper => !s.as_bytes().iter().any(u8::is_ascii_lowercase), + _ => false, + }; + if unchanged { + return Some(args[0].clone()); + } // SAFETY: an ASCII case mapping of ASCII text is ASCII of the same // length, all of it written (see `ascii_case_into`). Some(Object::Str(unsafe { @@ -11201,7 +12234,7 @@ fn str_strip(args: &[Object]) -> Result { None | Some(Object::None) => s.trim_matches(crate::unicode_case::is_space).to_owned(), Some(arg) => { let chars = - str_arg_bridged(arg).ok_or_else(|| type_error("strip() argument must be str"))?; + str_arg_bridged(arg).ok_or_else(|| type_error("strip arg must be None or str"))?; let set: Vec = chars.chars().collect(); s.trim_matches(|c| set.contains(&c)).to_owned() } @@ -11251,7 +12284,14 @@ fn str_split_whitespace(s: &str, ascii: bool, maxsplit: i64) -> Vec { // Presized: `collect()` over a filtered split carries no size hint. // English prose averages under five letters a word, so a quarter of // the length covers a sentence without growing (each growth copies). - let mut out = Vec::with_capacity((s.len() / 4).min(256) + 1); + // (A short string's fields can't outnumber half its length, rounded + // up: `"a b c d"` takes four slots, not two and then a regrowth.) + let cap = if s.len() <= 16 { + s.len().div_ceil(2) + } else { + (s.len() / 4).min(256) + 1 + }; + let mut out = Vec::with_capacity(cap); let limit = if maxsplit < 0 { i64::MAX } else { maxsplit }; let mut splits = 0i64; if ascii { @@ -11277,7 +12317,12 @@ fn str_split_whitespace(s: &str, ascii: bool, maxsplit: i64) -> Vec { while i < b.len() && !is_space(b[i]) { i += 1; } - out.push(Object::Str(SharedStr::from_ascii(&s[start..i]))); + // (A one-character field is the shared string, as CPython's.) + out.push(Object::Str(if i - start == 1 { + SharedStr::ascii_char(b[start]) + } else { + SharedStr::from_ascii(&s[start..i]) + })); splits += 1; } return out; @@ -11316,18 +12361,134 @@ fn new_str_split_list(items: Vec) -> Object { } /// `str.split`'s and `str.rsplit`'s keywords: `sep` and `maxsplit` only. -fn split_keywords(name: &str, kwargs: &[(String, Object)]) -> Result<(), RuntimeError> { - match kwargs.iter().find(|(k, _)| k != "sep" && k != "maxsplit") { - Some((k, _)) => Err(type_error(format!( - "{name}() got an unexpected keyword argument '{k}'" - ))), - None => Ok(()), +fn split_keywords( + name: &str, + args: &[Object], + kwargs: &[(String, Object)], +) -> Result<(), RuntimeError> { + if kwargs.is_empty() { + return Ok(()); } -} - + // (CPython's argument parser counts first, then names.) + let positional = args.len().saturating_sub(1); + let total = positional + kwargs.len(); + if total > 2 { + let what = if positional == 0 { + "keyword arguments" + } else { + "arguments" + }; + return Err(type_error(format!( + "{name}() takes at most 2 {what} ({total} given)" + ))); + } + for (k, _) in kwargs { + // (`args` holds the receiver first: `sep` is argument 1.) + let pos = match k.as_str() { + "sep" => 1, + "maxsplit" => 2, + _ => { + return Err(type_error(format!( + "{name}() got an unexpected keyword argument '{k}'" + ))) + } + }; + if args.len() > pos { + return Err(type_error(format!( + "argument for {name}() given by name ('{k}') and position ({pos})" + ))); + } + } + Ok(()) +} + +/// `s.split(sep=None, maxsplit=-1)`'s keyword half (see +/// `leaf_builtins::register_fast_kw`): the receiver, then `sep` and +/// `maxsplit`, each `Unbound` when the call left it out. A `str` or `None` +/// separator and an `int` count split as the full method does, running no +/// code. +pub(crate) fn str_split_kw_fast(args: &[Object]) -> Option> { + let [recv @ Object::Str(_), sep, maxsplit] = args else { + return None; + }; + let sep = match sep { + Object::Unbound => Object::None, + Object::None | Object::Str(_) => sep.clone(), + _ => return None, + }; + let maxsplit = match maxsplit { + Object::Unbound => Object::Int(-1), + Object::Int(_) => maxsplit.clone(), + _ => return None, + }; + Some(str_split(&[recv.clone(), sep, maxsplit], &[])) +} + +/// `s.rsplit(sep=None, maxsplit=-1)`'s keyword half, as +/// [`str_split_kw_fast`] is `split`'s. +pub(crate) fn str_rsplit_kw_fast(args: &[Object]) -> Option> { + let [recv @ Object::Str(_), sep, maxsplit] = args else { + return None; + }; + let sep = match sep { + Object::Unbound => Object::None, + Object::None | Object::Str(_) => sep.clone(), + _ => return None, + }; + let maxsplit = match maxsplit { + Object::Unbound => Object::Int(-1), + Object::Int(_) => maxsplit.clone(), + _ => return None, + }; + Some(str_rsplit(&[recv.clone(), sep, maxsplit], &[])) +} + +/// `s.splitlines(keepends=False)`'s keyword half: a `bool` or `int` flag +/// (whose truth runs no code). +pub(crate) fn str_splitlines_kw_fast(args: &[Object]) -> Option> { + let [recv @ Object::Str(_), keepends] = args else { + return None; + }; + let keepends = match keepends { + Object::Unbound => Object::Bool(false), + Object::Bool(_) | Object::Int(_) => keepends.clone(), + _ => return None, + }; + Some(str_splitlines(&[recv.clone(), keepends], &[])) +} + +/// `n.to_bytes(length=1, byteorder='big', *, signed=False)`'s keyword +/// half: an `int` length, a `str` order and a `bool` or `int` flag, each +/// taking its default where the call left it out. +pub(crate) fn int_to_bytes_kw_fast(args: &[Object]) -> Option> { + let [recv @ (Object::Int(_) | Object::Bool(_) | Object::Long(_)), length, order, signed] = args + else { + return None; + }; + let length = match length { + Object::Unbound => Object::Int(1), + Object::Int(_) => length.clone(), + _ => return None, + }; + let order = match order { + Object::Unbound => Object::from_static("big"), + Object::Str(_) => order.clone(), + _ => return None, + }; + let signed = match signed { + Object::Unbound => Object::Bool(false), + Object::Bool(_) | Object::Int(_) => signed.clone(), + _ => return None, + }; + Some(int_to_bytes_body( + &[recv.clone(), length, order, signed], + &[], + )) +} + fn str_split(args: &[Object], kwargs: &[(String, Object)]) -> Result { str_arity("split", args, 0, 2)?; - split_keywords("split", kwargs)?; + split_keywords("split", args, kwargs)?; let s = str_self(args)?; let sep = arg_or_kw(args, 1, kwargs, "sep"); let maxsplit = split_maxsplit(arg_or_kw(args, 2, kwargs, "maxsplit"))?; @@ -11374,6 +12535,12 @@ fn str_split(args: &[Object], kwargs: &[(String, Object)]) -> Result Vec { let piece = |text: &str| { + // (A one-character field is the shared string.) + if let [c] = text.as_bytes() { + if c.is_ascii() { + return str_piece(text); + } + } Object::Str(if ascii { SharedStr::from_ascii(text) } else { @@ -11384,6 +12551,22 @@ fn str_split_sep(s: &str, ascii: bool, sep: &str, maxsplit: i64) -> Vec if let [byte] = *sep.as_bytes() { let mut out = Vec::new(); let mut start = 0; + // (A short line by byte: `memchr`'s vector setup costs more there. + // Room for a few fields at once, past the vector's growth steps.) + if s.len() <= 32 { + out.reserve_exact(4); + for (at, &b) in s.as_bytes().iter().enumerate() { + if b == byte { + if out.len() == limit { + break; + } + out.push(piece(&s[start..at])); + start = at + 1; + } + } + out.push(piece(&s[start..])); + return out; + } for at in memchr::memchr_iter(byte, s.as_bytes()) { if out.len() == limit { break; @@ -11394,6 +12577,35 @@ fn str_split_sep(s: &str, ascii: bool, sep: &str, maxsplit: i64) -> Vec out.push(piece(&s[start..])); return out; } + // A short separator (`", "`, `"\r\n"`) by a `memchr` scan for its + // first byte, as `str.replace` finds a short needle: the two-way + // searcher's setup cost more than a short line's whole split. (The + // first byte starts a character, so every hit is a boundary.) + if (2..=16).contains(&sep.len()) { + let (h, n) = (s.as_bytes(), sep.as_bytes()); + let mut out = Vec::with_capacity(4); + let (mut start, mut i) = (0, 0); + if let Some(last_start) = h.len().checked_sub(n.len()) { + while i <= last_start { + let Some(off) = memchr::memchr(n[0], &h[i..=last_start]) else { + break; + }; + let at = i + off; + if short_bytes_eq(&h[at + 1..at + n.len()], &n[1..]) { + if out.len() == limit { + break; + } + out.push(piece(&s[start..at])); + start = at + n.len(); + i = start; + } else { + i = at + 1; + } + } + } + out.push(piece(&s[start..])); + return out; + } s.splitn(limit.saturating_add(1), sep).map(piece).collect() } @@ -11416,6 +12628,45 @@ fn str_join(args: &[Object]) -> Result { if let Some(joined) = joined { return Ok(joined); } + // `"".join(reversed(xs))`: the rest of the reversed snapshot read + // back to front at once, the iterator left exhausted and detached + // as its last step leaves it (as `list(reversed(xs))` drains it). + if let Object::Iter(it) = &args[1] { + if let Ok(mut cursor) = it.try_borrow_mut() { + if let PyIterator::Reversed { + items, + index, + owner, + } = &mut *cursor + { + let rest: Option> = + items + .try_borrow() + .ok() + .map(|v| match usize::try_from(*index) { + Ok(i) if i < v.len() => v[..=i].iter().rev().cloned().collect(), + _ => Vec::new(), + }); + if let Some(joined) = rest.as_deref().and_then(|r| { + if r.is_empty() { + Some(Object::from_static("")) + } else { + join_exact_strings(r, sep) + } + }) { + let detached = ( + std::mem::replace(items, crate::object::detached_store()), + owner.take(), + ); + *index = -1; + drop(cursor); + drop(detached); + drop(rest); + return Ok(joined); + } + } + } + } } let mut it = args[1].make_iter()?; let mut items = Vec::new(); @@ -11430,7 +12681,7 @@ fn str_join(args: &[Object]) -> Result { } let mut parts: Vec> = Vec::with_capacity(items.len()); let mut saw_surrogate = matches!(args.first(), Some(Object::WStr(_))); - for v in &items { + for (index, v) in items.iter().enumerate() { match v { Object::Str(s) => parts.push(Cow::Borrowed(s)), Object::WStr(cps) => { @@ -11448,7 +12699,7 @@ fn str_join(args: &[Object]) -> Result { } _ => { return Err(type_error(format!( - "sequence item: expected str instance, {} found", + "sequence item {index}: expected str instance, {} found", other.type_name() ))) } @@ -11466,35 +12717,53 @@ fn str_join(args: &[Object]) -> Result { /// Return `None` for shapes that need the general Unicode/iterator path. /// The result is written straight into its final allocation, and knows its /// code-point count when every part (and the separator) already does. +/// The text `str.join` reads from `item`: an exact `str`, or a `str` +/// subclass's payload (CPython's `PyUnicode_Join` reads any `str`'s data +/// directly, calling no `__str__`). `None` for anything else. +#[inline] +pub(crate) fn join_item_str(item: &Object) -> Option<&SharedStr> { + match item { + Object::Str(s) => Some(s), + Object::Instance(i) => match i.native.get() { + Some(Object::Str(s)) => Some(s), + _ => None, + }, + _ => None, + } +} + fn join_exact_strings(items: &[Object], sep: &SharedStr) -> Option { let gaps = items.len().saturating_sub(1); let mut size = sep.len().checked_mul(gaps)?; // The separator is usually a constant: counting it once memoises it. let mut chars = SharedStr::char_count(sep).checked_mul(gaps); for item in items { - let Object::Str(s) = item else { - return None; - }; + let s = join_item_str(item)?; size = size.checked_add(s.len())?; chars = chars.and_then(|n| Some(n + SharedStr::known_char_count(s)?)); } if items.len() == 1 { - return Some(items[0].clone()); + // (An exact `str` is the result itself; a subclass's, its text.) + return join_item_str(&items[0]).map(|s| Object::Str(s.clone())); } let fill = |out: &mut crate::shared_value::TextWriter<'_>| { - let mut items = items.iter().filter_map(|item| match item { - Object::Str(s) => Some(s.as_bytes()), - _ => None, - }); + let mut items = items + .iter() + .filter_map(|item| join_item_str(item).map(|s| s.as_bytes())); if let Some(first) = items.next() { out.push(first); } - // The usual one-byte separator (`" "`, `","`) is stored directly. + // The usual one-byte separator (`" "`, `","`) is stored directly, + // and an empty one (`"".join(parts)`) not at all. if let [byte] = *sep.as_bytes() { for item in items { out.push_byte(byte); out.push(item); } + } else if sep.is_empty() { + for item in items { + out.push(item); + } } else { for item in items { out.push(sep.as_bytes()); @@ -11654,17 +12923,21 @@ fn str_match_prefix_suffix( } } None => { - return Err(type_error( - "startswith/endswith first arg must be str or tuple of str", - )); + return Err(type_error(format!( + "tuple for {} must only contain str, not {}", + if prefix { "startswith" } else { "endswith" }, + item.type_name() + ))); } } } Ok(false) } - _ => Err(type_error( - "startswith/endswith first arg must be str or tuple of str", - )), + _ => Err(type_error(format!( + "{} first arg must be str or a tuple of str, not {}", + if prefix { "startswith" } else { "endswith" }, + target.type_name() + ))), } } @@ -11702,6 +12975,52 @@ fn str_replace_exact(recv: &SharedStr, from: &str, to: &str, limit: usize) -> Op } } let (h, n) = (recv.as_bytes(), from.as_bytes()); + // One ASCII byte for another (`s.replace("o", "0")`): the text copied + // once and each match changed in place, as CPython's + // `replace_1char_inplace` does (an ASCII byte is never inside a + // multibyte character, so the result is the same characters). + if let ([f], [t]) = (n, to.as_bytes()) { + if f.is_ascii() && t.is_ascii() { + let (f, t) = (*f, *t); + let first = match memchr::memchr(f, h) { + Some(at) if limit > 0 => at, + _ => return Some(Object::Str(recv.clone())), + }; + let size = h.len(); + let chars = SharedStr::is_ascii(recv).then_some(size); + let fill = |out: &mut crate::shared_value::TextWriter<'_>| { + // SAFETY: all `size` bytes are written: the copy first. + unsafe { + out.push_with(size, |buf| { + std::ptr::copy_nonoverlapping( + h.as_ptr(), + buf.as_mut_ptr().cast::(), + size, + ); + let out = + std::slice::from_raw_parts_mut(buf.as_mut_ptr().cast::(), size); + let (mut at, mut done) = (first, 0); + loop { + out[at] = t; + done += 1; + if done == limit { + break; + } + match memchr::memchr(f, &h[at + 1..]) { + Some(off) => at += 1 + off, + None => break, + } + } + }); + } + }; + // SAFETY: the same characters, an ASCII byte for an ASCII + // byte; `chars` given only when every byte is ASCII. + return Some(Object::Str(unsafe { + SharedStr::build_unchecked(size, chars, fill) + })); + } + } let mut hits = Hits { inline: [0; 32], len: 0, @@ -11903,7 +13222,11 @@ pub(crate) fn substr_find(hay: &str, needle: &str) -> Option { // hit is a character boundary: scan the bytes directly (no char // searcher) and compare the short rest inline (no `memcmp` call). let mut i = 0; - let mut budget = h.len() / n.len() + 32; + // (A first byte that keeps turning up without the rest, `"ab"`s + // searched for `"abd"`: each restart of the byte scan costs more + // than the bytes it skips, so the substring searcher, which looks + // for the needle's rarest bytes, takes the rest.) + let mut budget = 8; while i <= last_start { let at = i + memchr::memchr(n[0], &h[i..=last_start])?; if short_bytes_eq(&h[at + 1..at + n.len()], &n[1..]) { @@ -11911,7 +13234,7 @@ pub(crate) fn substr_find(hay: &str, needle: &str) -> Option { } budget -= 1; if budget == 0 { - return hay[at + 1..].find(needle).map(|k| k + at + 1); + return memchr::memmem::find(&h[at + 1..], n).map(|k| k + at + 1); } i = at + 1; } @@ -11948,34 +13271,80 @@ pub(crate) fn substr_find(hay: &str, needle: &str) -> Option { /// `a == b` for the short needle tails the substring scans compare, inline /// (a `memcmp` call costs more than comparing a few bytes). #[inline(always)] +/// The first `n` in `h`, as [`substr_find`] scans bytes: a short needle +/// by its first byte's `memchr` and an in-line compare of the rest (a +/// `memmem` searcher's set-up costs more than a short haystack's whole +/// scan), anything else through `memmem`. +pub(crate) fn bytes_search(h: &[u8], n: &[u8]) -> Option { + if n.is_empty() { + return Some(0); + } + if n.len() > 16 || h.len() < n.len() || h.len() > 256 { + return memchr::memmem::find(h, n); + } + let last_start = h.len() - n.len(); + let mut i = 0; + let mut budget = h.len() / n.len() + 32; + while i <= last_start { + let at = i + memchr::memchr(n[0], &h[i..=last_start])?; + if short_bytes_eq(&h[at + 1..at + n.len()], &n[1..]) { + return Some(at); + } + budget -= 1; + if budget == 0 { + return memchr::memmem::find(&h[at + 1..], n).map(|k| k + at + 1); + } + i = at + 1; + } + None +} + fn short_bytes_eq(a: &[u8], b: &[u8]) -> bool { a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x == y) } /// [`substr_find`] from the right. pub(crate) fn substr_rfind(hay: &str, needle: &str) -> Option { + // The rightmost start, at a byte offset (for a match of whole UTF-8 + // text, a character's). let (h, n) = (hay.as_bytes(), needle.as_bytes()); - if n.is_empty() { - return Some(h.len()); - } - if n.len() > 16 || h.len() < n.len() { - return hay.rfind(needle); - } - let first = n[0]; - let mut end = h.len() - n.len(); - let mut budget = h.len() / n.len() + 32; + match n { + [] => Some(h.len()), + // (One byte: an ASCII byte, never inside a multibyte character.) + [b] => memchr::memrchr(*b, h), + // A short haystack costs less to scan than a searcher to build. + _ if h.len() <= 64 => hay.rfind(needle), + _ => bytes_rfind_windows(h, n), + } +} + +/// The rightmost start of `n` (two bytes or more) in `h`, by the forward +/// searcher (its vector prefilter is far faster than the reverse one's +/// scan) over windows taken from the end, each four times the last (a +/// frequent needle is found in the first, a rare one costs a forward scan +/// of the rest). Windows overlap by `n.len() - 1` bytes, so a match across +/// a boundary is in the earlier one, and matches are found overlapping. +fn bytes_rfind_windows(h: &[u8], n: &[u8]) -> Option { + let finder = memchr::memmem::Finder::new(n); + let mut hi = h.len(); + let mut size = 256usize; loop { - let at = h[..=end].iter().rposition(|&b| b == first)?; - if at + n.len() <= h.len() && h[at..at + n.len()] == *n { - return Some(at); + let lo = hi.saturating_sub(size + n.len() - 1); + let window = &h[lo..hi]; + let mut last = None; + let mut i = 0; + while let Some(k) = finder.find(&window[i..]) { + last = Some(i + k); + i += k + 1; } - budget -= 1; - if budget == 0 || at == 0 { - // Everything right of `at` has been ruled out, so the - // rightmost match overall is the rightmost below it. - return hay.rfind(needle); + if let Some(at) = last { + return Some(lo + at); } - end = at - 1; + if lo == 0 { + return None; + } + hi = lo + n.len() - 1; + size = (size * 4).min(1 << 16); } } @@ -11988,16 +13357,30 @@ pub(crate) fn substr_count(hay: &str, needle: &str) -> usize { if n.is_empty() || n.len() > 16 || h.len() < n.len() { return hay.matches(needle).count(); } + // One byte: counted a vector at a time (a call of the byte scan per + // hit cost ten times CPython's count in text full of the character). + if let [byte] = *n { + return memchr::memchr_iter(byte, h).count(); + } let last_start = h.len() - n.len(); if n[0].is_ascii() { - // As `substr_find`'s ASCII scan (every hit is a boundary). + // As `substr_find`'s ASCII scan (every hit is a boundary). The + // next candidate is looked for a byte at a time first: where the + // first byte is frequent (`"ab"` in text full of it), restarting + // the vector scan at each one costs several times the bytes it + // skips. let mut count = 0; let mut i = 0; while i <= last_start { - let Some(off) = memchr::memchr(n[0], &h[i..=last_start]) else { - break; + let near = (i + 16).min(last_start + 1); + let at = match h[i..near].iter().position(|c| *c == n[0]) { + Some(off) => i + off, + None if near > last_start => break, + None => match memchr::memchr(n[0], &h[near..=last_start]) { + Some(off) => near + off, + None => break, + }, }; - let at = i + off; if short_bytes_eq(&h[at + 1..at + n.len()], &n[1..]) { count += 1; i = at + n.len(); @@ -12031,13 +13414,32 @@ pub(crate) fn substr_count(hay: &str, needle: &str) -> usize { count } +/// CPython's argument error for a search method `name` of `str` whose +/// substring `arg` isn't a `str` (`None` is named as itself). +#[cold] +fn str_arg1_error(name: &str, arg: Option<&Object>) -> RuntimeError { + type_error(format!( + "{name}() argument 1 must be str, not {}", + match arg { + None | Some(Object::None) => "None".to_owned(), + Some(arg) => arg.type_name_owned(), + } + )) +} + fn str_find(args: &[Object]) -> Result { str_arity("find", args, 1, 3)?; + str_find_as(args, "find") +} + +/// `str.find`'s search for the method `name` (`find`, or `index`, which +/// names itself in the argument error), its arity checked. +fn str_find_as(args: &[Object], name: &str) -> Result { let s = str_self(args)?; let s = s.as_ref(); let sub = match args.get(1).and_then(str_arg_bridged) { Some(p) => p, - None => return Err(type_error("find() expected str")), + None => return Err(str_arg1_error(name, args.get(1))), }; // One ASCII probe for the whole call, O(1) from the receiver's // memoised count. @@ -12158,7 +13560,7 @@ fn str_lstrip(args: &[Object]) -> Result { .to_owned(), Some(arg) => { let chars = - str_arg_bridged(arg).ok_or_else(|| type_error("lstrip() argument must be str"))?; + str_arg_bridged(arg).ok_or_else(|| type_error("lstrip arg must be None or str"))?; let set: Vec = chars.chars().collect(); s.trim_start_matches(|c| set.contains(&c)).to_owned() } @@ -12179,7 +13581,7 @@ fn str_rstrip(args: &[Object]) -> Result { None | Some(Object::None) => s.trim_end_matches(crate::unicode_case::is_space).to_owned(), Some(arg) => { let chars = - str_arg_bridged(arg).ok_or_else(|| type_error("rstrip() argument must be str"))?; + str_arg_bridged(arg).ok_or_else(|| type_error("rstrip arg must be None or str"))?; let set: Vec = chars.chars().collect(); s.trim_end_matches(|c| set.contains(&c)).to_owned() } @@ -12227,7 +13629,7 @@ fn str_rsplit_whitespace(s: &str, maxsplit: i64) -> Vec { fn str_rsplit(args: &[Object], kwargs: &[(String, Object)]) -> Result { str_arity("rsplit", args, 0, 2)?; - split_keywords("rsplit", kwargs)?; + split_keywords("rsplit", args, kwargs)?; let s = str_self(args)?; let s = s.as_ref(); let sep = arg_or_kw(args, 1, kwargs, "sep"); @@ -12253,6 +13655,25 @@ fn str_rsplit(args: &[Object], kwargs: &[(String, Object)]) -> Result = Vec::new(); + let mut end = b.len(); + let mut at = b.len(); + while at > 0 && out.len() < limit { + at -= 1; + if b[at] == byte { + out.push(str_piece(&s[at + 1..end])); + end = at; + } + } + out.push(str_piece(&s[..end])); + out.reverse(); + return Ok(new_str_split_list(wrap(out))); + } // Always scan right-to-left: with overlapping separators the // match positions differ from a left scan ('aaa'.rsplit('aa') // is ['a', ''], not ['', 'a'] — test_userstring). @@ -12273,6 +13694,28 @@ fn str_rsplit(args: &[Object], kwargs: &[(String, Object)]) -> Result usize { + const ONES: u64 = 0x0101_0101_0101_0101; + const HIGH: u64 = 0x8080_8080_8080_8080; + while let Some(w) = b.get(i..i + 8) { + let x = u64::from_le_bytes(w.try_into().expect("eight bytes")); + // (A byte below `0x20` borrows into its high bit; ASCII text has + // none set otherwise.) + if x.wrapping_sub(0x20 * ONES) & HIGH != 0 { + break; + } + i += 8; + } + while i < b.len() && b[i] >= 0x20 { + i += 1; + } + i +} + fn str_splitlines(args: &[Object], kwargs: &[(String, Object)]) -> Result { str_arity("splitlines", args, 0, 1)?; let s = str_self(args)?; @@ -12297,6 +13740,39 @@ fn str_splitlines(args: &[Object], kwargs: &[(String, Object)]) -> Result = Vec::new(); let mut start = 0; + // An exact ASCII string's lines, by byte, each piece built in place. + if matches!(args.first(), Some(Object::Str(_))) + && !args.iter().any(|o| matches!(o, Object::WStr(_))) + && s.is_ascii() + { + let b = s.as_bytes(); + // (Every line break is a control byte: the runs between them are + // skipped a word at a time.) + let mut i = below_space(b, 0); + // One line and no break: the string itself, as CPython gives it. + if i == b.len() && !b.is_empty() { + if let Some(whole @ Object::Str(_)) = args.first() { + return Ok(new_str_split_list(vec![whole.clone()])); + } + } + while i < b.len() { + if matches!(b[i], b'\n' | b'\r' | 0x0b | 0x0c | 0x1c | 0x1d | 0x1e) { + let mut end = i + 1; + if b[i] == b'\r' && b.get(i + 1) == Some(&b'\n') { + end = i + 2; + } + out.push(str_piece(&s[start..if keepends { end } else { i }])); + start = end; + i = below_space(b, end); + } else { + i = below_space(b, i + 1); + } + } + if start < s.len() { + out.push(str_piece(&s[start..])); + } + return Ok(new_str_split_list(out)); + } let mut iter = s.char_indices().peekable(); while let Some((i, c)) = iter.next() { if is_break(c) { @@ -12325,11 +13801,16 @@ fn str_splitlines(args: &[Object], kwargs: &[(String, Object)]) -> Result Result { str_arity("rfind", args, 1, 3)?; + str_rfind_as(args, "rfind") +} + +/// `str.rfind`'s search for the method `name` (see [`str_find_as`]). +fn str_rfind_as(args: &[Object], name: &str) -> Result { let s = str_self(args)?; let s = s.as_ref(); let sub = match args.get(1).and_then(str_arg_bridged) { Some(p) => p, - None => return Err(type_error("rfind() expected str")), + None => return Err(str_arg1_error(name, args.get(1))), }; let (total_chars, ascii) = recv_char_len(args, s); let Some((start, end)) = str_search_window(args, total_chars as i64) else { @@ -12362,7 +13843,7 @@ fn str_index(args: &[Object]) -> Result { // test_userstring.test_find_etc_raise_correct_error_messages) // before delegating to the `find` engine. str_arity("index", args, 1, 3)?; - let pos = str_find(args)?; + let pos = str_find_as(args, "index")?; match pos { Object::Int(-1) => Err(value_error("substring not found")), other => Ok(other), @@ -12371,7 +13852,7 @@ fn str_index(args: &[Object]) -> Result { fn str_rindex(args: &[Object]) -> Result { str_arity("rindex", args, 1, 3)?; - let pos = str_rfind(args)?; + let pos = str_rfind_as(args, "rindex")?; match pos { Object::Int(-1) => Err(value_error("substring not found")), other => Ok(other), @@ -12384,7 +13865,7 @@ fn str_count(args: &[Object]) -> Result { let s = s.as_ref(); let sub = match args.get(1).and_then(str_arg_bridged) { Some(p) => p, - None => return Err(type_error("count() expected str")), + None => return Err(str_arg1_error("count", args.get(1))), }; // One ASCII probe for the whole call, as `str.find` does. let (total_chars, ascii) = recv_char_len(args, s); @@ -12408,7 +13889,60 @@ fn str_count(args: &[Object]) -> Result { )) } +/// A piece of a `str` method's result: the shared one-character string for +/// an ASCII character, else a new string of `t`. +#[inline] +fn str_piece(t: &str) -> Object { + match t.as_bytes() { + [] => Object::from_static(""), + [c] if c.is_ascii() => crate::shared_value::SharedStr::ascii_char_built(*c).map_or_else( + || Object::Str(crate::shared_value::SharedStr::from(t)), + Object::Str, + ), + _ => Object::Str(crate::shared_value::SharedStr::from(t)), + } +} + +/// `s.partition(sep)` and `s.rpartition(sep)` of an exact `str` by an +/// exact `str`, as CPython builds them: the separator object itself, and +/// the string itself when the separator isn't found. `None` for anything +/// else. +fn str_partition_exact(args: &[Object], from_right: bool) -> Option { + let [Object::Str(recv), sep_obj @ Object::Str(sep)] = args else { + return None; + }; + let (s, sep) = (&**recv, &**sep); + if sep.is_empty() { + return None; + } + let found = if from_right { + s.rfind(sep) + } else { + substr_find(s, sep) + }; + Some(match found { + Some(i) => Object::new_tuple_array([ + str_piece(&s[..i]), + sep_obj.clone(), + str_piece(&s[i + sep.len()..]), + ]), + None if from_right => Object::new_tuple_array([ + Object::from_static(""), + Object::from_static(""), + args[0].clone(), + ]), + None => Object::new_tuple_array([ + args[0].clone(), + Object::from_static(""), + Object::from_static(""), + ]), + }) +} + fn str_partition(args: &[Object]) -> Result { + if let Some(r) = str_partition_exact(args, false) { + return Ok(r); + } let s = str_self(args)?; let s = s.as_ref(); let sep = match args.get(1).and_then(str_arg_bridged) { @@ -12436,6 +13970,9 @@ fn str_partition(args: &[Object]) -> Result { } fn str_rpartition(args: &[Object]) -> Result { + if let Some(r) = str_partition_exact(args, true) { + return Ok(r); + } let s = str_self(args)?; let s = s.as_ref(); let sep = match args.get(1).and_then(str_arg_bridged) { @@ -12465,6 +14002,10 @@ fn str_rpartition(args: &[Object]) -> Result { fn str_isdigit(args: &[Object]) -> Result { str_arity("isdigit", args, 0, 0)?; let s = str_self(args)?; + // (ASCII's only digits, decimals and numerics are `0` to `9`.) + if let Some(all) = ascii_all(&s, u8::is_ascii_digit) { + return Ok(Object::Bool(all)); + } Ok(Object::Bool( !s.is_empty() && s.chars().all(crate::unicode_numeric::is_digit_char), )) @@ -12473,6 +14014,10 @@ fn str_isdigit(args: &[Object]) -> Result { fn str_isnumeric(args: &[Object]) -> Result { str_arity("isnumeric", args, 0, 0)?; let s = str_self(args)?; + // (ASCII's only digits, decimals and numerics are `0` to `9`.) + if let Some(all) = ascii_all(&s, u8::is_ascii_digit) { + return Ok(Object::Bool(all)); + } Ok(Object::Bool( !s.is_empty() && s.chars().all(crate::unicode_numeric::is_numeric_char), )) @@ -12481,14 +14026,38 @@ fn str_isnumeric(args: &[Object]) -> Result { fn str_isdecimal(args: &[Object]) -> Result { str_arity("isdecimal", args, 0, 0)?; let s = str_self(args)?; + // (ASCII's only digits, decimals and numerics are `0` to `9`.) + if let Some(all) = ascii_all(&s, u8::is_ascii_digit) { + return Ok(Object::Bool(all)); + } Ok(Object::Bool( !s.is_empty() && s.chars().all(crate::unicode_numeric::is_decimal_char), )) } +/// A `str.is...()` predicate that holds for every character of a +/// non-empty `s`, decided by its bytes while they're ASCII: an ASCII byte +/// that fails `f` settles it (`false`, whatever follows), and `None` at the +/// first non-ASCII byte leaves the rest to the Unicode tables. +#[inline] +fn ascii_all(s: &str, f: impl Fn(&u8) -> bool) -> Option { + for b in s.as_bytes() { + if !b.is_ascii() { + return None; + } + if !f(b) { + return Some(false); + } + } + Some(!s.is_empty()) +} + fn str_isalpha(args: &[Object]) -> Result { str_arity("isalpha", args, 0, 0)?; let s = str_self(args)?; + if let Some(all) = ascii_all(&s, u8::is_ascii_alphabetic) { + return Ok(Object::Bool(all)); + } Ok(Object::Bool( !s.is_empty() && s.chars().all(crate::unicode_case::is_alpha), )) @@ -12497,6 +14066,9 @@ fn str_isalpha(args: &[Object]) -> Result { fn str_isalnum(args: &[Object]) -> Result { str_arity("isalnum", args, 0, 0)?; let s = str_self(args)?; + if let Some(all) = ascii_all(&s, u8::is_ascii_alphanumeric) { + return Ok(Object::Bool(all)); + } Ok(Object::Bool( !s.is_empty() && s.chars().all(crate::unicode_case::is_alnum), )) @@ -12505,6 +14077,12 @@ fn str_isalnum(args: &[Object]) -> Result { fn str_isspace(args: &[Object]) -> Result { str_arity("isspace", args, 0, 0)?; let s = str_self(args)?; + if let Some(all) = ascii_all( + &s, + |b: &u8| matches!(b, b'\t'..=b'\r' | b'\x1c'..=b'\x1f' | b' '), + ) { + return Ok(Object::Bool(all)); + } Ok(Object::Bool( !s.is_empty() && s.chars().all(crate::unicode_case::is_space), )) @@ -12575,6 +14153,9 @@ fn str_zfill(args: &[Object]) -> Result { }; let len = s.chars().count(); if len >= width { + if let Some(o @ Object::Str(_)) = args.first() { + return Ok(o.clone()); + } return Ok(str_result(args, s.to_owned())); } let pad = width - len; @@ -12583,7 +14164,12 @@ fn str_zfill(args: &[Object]) -> Result { } else { ("", s) }; - Ok(str_result(args, format!("{sign}{}{rest}", "0".repeat(pad)))) + let mut out = String::with_capacity(s.len() + pad); + out.push_str(sign); + // SAFETY: ASCII zeros are valid UTF-8. + unsafe { out.as_mut_vec() }.resize(sign.len() + pad, b'0'); + out.push_str(rest); + Ok(str_result(args, out)) } fn str_ljust(args: &[Object]) -> Result { @@ -12612,17 +14198,35 @@ fn pad_str(args: &[Object], right_align: bool) -> Result { }; let len = s.chars().count(); if len >= width { + // (An exact `str` comes back as itself, as CPython's does.) + if let Some(o @ Object::Str(_)) = args.first() { + return Ok(o.clone()); + } return Ok(str_result(args, s.into_owned())); } - let pad: String = std::iter::repeat_n(fill, width - len).collect(); - Ok(str_result( - args, - if right_align { - format!("{pad}{s}") + let pad = width - len; + let (left, right) = if right_align { (pad, 0) } else { (0, pad) }; + Ok(str_result(args, pad_around(&s, left, right, fill))) +} + +/// `s` with `left` copies of `fill` before it and `right` after, built in +/// one allocation of the exact size (`str.center`, `ljust`, `rjust`). +fn pad_around(s: &str, left: usize, right: usize, fill: char) -> String { + let unit = fill.len_utf8(); + let mut out = String::with_capacity(s.len() + (left + right) * unit); + let push_fill = |out: &mut String, n: usize| { + if fill.is_ascii() { + // SAFETY: an ASCII byte repeated is valid UTF-8. + let to = out.len() + n; + unsafe { out.as_mut_vec() }.resize(to, fill as u8); } else { - format!("{s}{pad}") - }, - )) + out.extend(std::iter::repeat_n(fill, n)); + } + }; + push_fill(&mut out, left); + out.push_str(s); + push_fill(&mut out, right); + out } fn str_center(args: &[Object]) -> Result { @@ -12647,6 +14251,10 @@ fn str_center(args: &[Object]) -> Result { }; let len = s.chars().count(); if len >= width { + // (An exact `str` comes back as itself, as CPython's does.) + if let Some(o @ Object::Str(_)) = args.first() { + return Ok(o.clone()); + } return Ok(str_result(args, s.into_owned())); } let total = width - len; @@ -12655,14 +14263,15 @@ fn str_center(args: &[Object]) -> Result { // is `' Monday '`, not `' Monday '`. let left = total / 2 + (total & width & 1); let right = total - left; - let lpad: String = std::iter::repeat_n(fill, left).collect(); - let rpad: String = std::iter::repeat_n(fill, right).collect(); - Ok(str_result(args, format!("{lpad}{s}{rpad}"))) + Ok(str_result(args, pad_around(&s, left, right, fill))) } /// `str.expandtabs(tabsize=8)` — `tabsize` is positional-or-keyword in /// CPython's clinic signature (test/string_tests.py passes it by name). fn str_expandtabs_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result { + if kwargs.is_empty() { + return str_expandtabs(args); + } let mut full = args.to_vec(); for (k, v) in kwargs { if k != "tabsize" { @@ -12707,7 +14316,7 @@ fn str_expandtabs(args: &[Object]) -> Result { ))); } }; - let mut out = String::new(); + let mut out = String::with_capacity(s.len() + tabsize.min(64) * 2); let mut col = 0usize; for ch in s.chars() { match ch { @@ -12717,9 +14326,7 @@ fn str_expandtabs(args: &[Object]) -> Result { } else { tabsize - (col % tabsize) }; - for _ in 0..pad { - out.push(' '); - } + out.extend(std::iter::repeat_n(' ', pad)); col += pad; } '\n' | '\r' => { @@ -12747,23 +14354,40 @@ fn str_encode(args: &[Object], kwargs: &[(String, Object)]) -> Result 1, + "errors" => 2, + _ => { + return Err(type_error(format!( + "encode() got an unexpected keyword argument '{k}'" + ))) + } + }; + if args.len() > pos { + return Err(type_error(format!( + "argument for encode() given by name ('{k}') and position ({pos})" + ))); + } + } // UTF-8 with no error handler, the common call: a `str` holds valid // UTF-8 (lone surrogates live in `WStr`), so its bytes are the answer, // as CPython's C fast path for the codec gives them. if let Object::Str(text) = recv { - let utf8 = kwargs.is_empty() - && match args { - [_] => true, - [_, Object::Str(enc)] => { - matches!(&**enc, "utf-8" | "utf8" | "UTF-8" | "UTF8" | "utf_8") - } - [_, Object::Str(enc), errors] if is_builtin_error_handler(errors) => { + // (Keywords too.) + // (The names were checked above.) + let utf8 = kwargs.len() <= 2 + && args.len() <= 3 + && match arg_or_kw(args, 1, kwargs, "encoding") { + None => true, + Some(Object::Str(enc)) => { matches!(&**enc, "utf-8" | "utf8" | "UTF-8" | "UTF8" | "utf_8") } - _ => false, - }; + Some(_) => false, + } + && arg_or_kw(args, 2, kwargs, "errors").is_none_or(is_builtin_error_handler); if utf8 { - return Ok(Object::new_bytes(text.as_bytes().to_vec())); + return Ok(Object::new_bytes(text.as_bytes())); } } // The names accept any str-shaped object, not just `Object::Str`: @@ -12774,7 +14398,12 @@ fn str_encode(args: &[Object], kwargs: &[(String, Object)]) -> Result match str_arg_bridged(o) { Some(e) => e.into_owned(), - None => return Err(type_error("encode() expected str")), + None => { + return Err(type_error(format!( + "encode() argument 'encoding' must be str, not {}", + o.type_name() + ))) + } }, None => "utf-8".to_owned(), }; @@ -12835,6 +14464,36 @@ fn str_format_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result Option> { + let [Object::Str(template), Object::Dict(d)] = args else { + return None; + }; + // SAFETY: a read that runs no code, ended before the engine borrows. + let plain = unsafe { d.peek() }.is_some_and(|m| { + m.len() <= 32 + && m.values().all(|v| { + matches!( + v, + Object::Str(_) + | Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + ) + }) + }); + if !plain { + return None; + } + let out = crate::str_format_map_impl(template, d).ok()?; + Some(Ok(Object::from_str(out))) +} + fn str_format_map(args: &[Object]) -> Result { let template = str_self(args)?.into_owned(); let mapping = match args.get(1) { @@ -13252,13 +14911,12 @@ fn list_extend(args: &[Object]) -> Result { // instead grow without bound (a hang that the OOM killer ends). match &args[1] { Object::List(src) => { - let items: Vec = src.borrow().clone(); + let items: Vec = crate::object::cloned_vec(&src.borrow()); l.borrow_mut().extend(items); return Ok(Object::None); } Object::Tuple(src) => { - let items: Vec = src.iter().cloned().collect(); - l.borrow_mut().extend(items); + crate::object::extend_cloned(&mut l.borrow_mut(), src); return Ok(Object::None); } _ => {} @@ -13351,6 +15009,21 @@ fn list_remove(args: &[Object]) -> Result { return Err(type_error("list.remove() expected 1 argument")); } let l = list_self(args)?; + // Items that compare natively: one scan, no clones. + let mut at = None; + if list_scan_native(&args[0], &args[1], |i| { + at = Some(i); + false + }) + .is_some() + { + let Some(i) = at else { + return Err(value_error("list.remove(x): x not in list")); + }; + let removed = l.borrow_mut().remove(i); + drop(removed); + return Ok(Object::None); + } // CPython `list.remove` walks the *live* list by index with // `PyObject_RichCompareBool` (identity-first, then Python `__eq__`), // so `ALWAYS_EQ` matches the first element and a mutating `__eq__` @@ -13384,10 +15057,83 @@ fn list_remove(args: &[Object]) -> Result { Err(value_error("list.remove(x): x not in list")) } +/// The positions of `list` whose items equal `needle` by a comparison +/// that runs no code (identity first, as `PyObject_RichCompareBool` +/// compares): `f` sees each match in order and may stop the scan. `None` +/// when an item needs the full comparison (the caller then discards what +/// `f` saw and takes the full path, as nothing has run). +pub(crate) fn list_scan_native( + list: &Object, + needle: &Object, + f: impl FnMut(usize) -> bool, +) -> Option<()> { + list_scan_native_in(list, needle, None, f) +} + +/// [`list_scan_native`] over the items from `bounds`' start (inclusive) +/// to its stop (exclusive), as `list.index(x, start, stop)` adjusts them +/// (negative counts from the end, both clamped to the list): ints only. +fn list_scan_native_in( + list: &Object, + needle: &Object, + bounds: Option<(&Object, Option<&Object>)>, + mut f: impl FnMut(usize) -> bool, +) -> Option<()> { + let Object::List(l) = list else { + return None; + }; + let items = l.try_borrow().ok()?; + let len = items.len() as i64; + let adjust = |v: i64| if v < 0 { (v + len).max(0) } else { v.min(len) }; + let (start, stop) = match bounds { + None => (0, items.len()), + Some((Object::Int(a), None)) => (adjust(*a) as usize, items.len()), + Some((Object::Int(a), Some(Object::Int(b)))) => (adjust(*a) as usize, adjust(*b) as usize), + Some(_) => return None, + }; + for (i, x) in items.iter().enumerate().take(stop).skip(start) { + let eq = match (x, needle) { + (Object::Int(a), Object::Int(b)) => a == b, + (Object::Str(a), Object::Str(b)) => a == b, + _ => x.is_same(needle) || crate::Interpreter::leaf_contains_eq(x, needle)?, + }; + if eq && !f(i) { + break; + } + } + Some(()) +} + fn list_index(args: &[Object]) -> Result { if args.len() < 2 { return Err(type_error("list.index() expected at least 1 argument")); } + if args.len() > 4 { + return Err(type_error(format!( + "index expected at most 3 arguments, got {}", + args.len() - 1 + ))); + } + let native = match args { + [list, needle] => Some((list, needle, None)), + [list, needle, a] => Some((list, needle, Some((a, None)))), + [list, needle, a, b] => Some((list, needle, Some((a, Some(b))))), + _ => None, + }; + if let Some((list, needle, bounds)) = native { + let mut found = None; + if list_scan_native_in(list, needle, bounds, |i| { + found = Some(i); + false + }) + .is_some() + { + return match found { + Some(i) => Ok(Object::Int(i as i64)), + None => Err(value_error("list.index(x): x not in list")), + }; + } + } // Snapshot strong refs: CPython `list.index` re-reads by index because a // user `__eq__` can mutate the list mid-scan; cloning the handles keeps us // panic-free without holding the borrow across the comparison. @@ -13419,13 +15165,22 @@ fn list_index(args: &[Object]) -> Result { } i += 1; } - Err(value_error(format!("{} is not in list", args[1].repr()))) + Err(value_error("list.index(x): x not in list")) } fn list_count(args: &[Object]) -> Result { if args.len() != 2 { return Err(type_error("list.count() expected 1 argument")); } + let mut n = 0i64; + if list_scan_native(&args[0], &args[1], |_| { + n += 1; + true + }) + .is_some() + { + return Ok(Object::Int(n)); + } // Snapshot strong refs (a user `__eq__` may mutate the list mid-scan). // CPython compares with `PyObject_RichCompareBool`: identity-first (so // `[nan].count(nan)` for the same nan is 1), then Python `__eq__` both @@ -13540,6 +15295,11 @@ fn range_getitem(args: &[Object]) -> Result { let index = args .get(1) .ok_or_else(|| type_error("__getitem__() takes exactly one argument (0 given)"))?; + if let Object::Slice(slc) = index { + if let Some(sliced) = crate::range_slice_small(&r, slc) { + return Ok(sliced); + } + } let len = crate::object::range_len_bigint(&r); if let Object::Slice(slc) = index { return crate::range_slice(&r, len, slc); @@ -13628,6 +15388,32 @@ fn list_reverse(args: &[Object]) -> Result { Ok(Object::None) } +/// `xs.clear()`'s leaf half: an exact list whose items are all plain +/// scalars, strings or bytes (their release runs no code). `None` for +/// anything else, which the full call clears. +pub(crate) fn list_clear_leaf(args: &[Object]) -> Option> { + let [Object::List(l)] = args else { + return None; + }; + let mut items = l.try_borrow_mut().ok()?; + let plain = items.iter().all(|x| { + matches!( + x, + Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Str(_) + | Object::Bytes(_) + ) + }); + if !plain { + return None; + } + items.clear(); + Some(Ok(Object::None)) +} + fn list_clear(args: &[Object]) -> Result { if args.len() != 1 { return Err(type_error("clear() takes no arguments (1 given)")); @@ -13644,8 +15430,10 @@ fn list_copy(args: &[Object]) -> Result { return Err(type_error("copy() takes no arguments (1 given)")); } let l = list_self(args)?; - let v = l.borrow().clone(); - Ok(Object::new_list(v)) + let v = crate::object::cloned_vec(&l.borrow()); + let out = Object::new_list(v); + crate::gc_trace::track_built(&out); + Ok(out) } // ---------- dict methods ---------- @@ -13857,9 +15645,8 @@ pub(crate) fn dict_remove( // comparison scope (see `dict_lookup`). if let Some(probe) = crate::object::LeafProbe::new(key) { if let Ok(mut m) = d.try_borrow_mut() { - match m.get_index_of(&probe) { - Some(i) => { - let (k, v) = m.shift_remove_index(i).expect("found above"); + match m.lazy_remove_entry(&probe) { + Some((k, v)) => { drop(m); crate::object::dict_watch_bump(d); crate::object::dict_mutation_event(d); @@ -13879,7 +15666,7 @@ pub(crate) fn dict_remove( let (removed, deferred) = crate::object::with_key_eq_deferred(|| { crate::object::key_cmp_scope(|| { d.borrow_mut() - .shift_remove_entry(&DictKey(key.clone())) + .lazy_remove_entry(&DictKey(key.clone())) .map(|(k, v)| (k.0, v)) }) }); @@ -13935,7 +15722,7 @@ fn dict_getitem(args: &[Object]) -> Result { /// The dict a `dict.__getitem__`/`__setitem__` leaf half serves: an exact /// dict, or the native payload of a dict-subclass instance. #[inline] -fn leaf_dict_of(recv: &Object) -> Option<&Rc>> { +pub(crate) fn leaf_dict_of(recv: &Object) -> Option<&Rc>> { match recv { Object::Dict(d) => Some(d), Object::Instance(inst) => match inst.native.get()? { @@ -14007,14 +15794,40 @@ fn is_builtin_error_handler(o: &Object) -> bool { /// `s.encode([encoding])` with a plain codec, when every character /// encodes (an unencodable one raises on the full path). pub(crate) fn str_encode_leaf(args: &[Object]) -> Option> { - let (Object::Str(s), rest) = args.split_first()? else { - return None; + let (recv, rest) = args.split_first()?; + // (A `str` subclass's instance, `str.encode` itself being the method + // called: its text, as the full method encodes it.) + let s = match recv { + Object::Str(s) => s, + Object::Instance(inst) => match inst.native.get() { + Some(Object::Str(s)) => s, + _ => return None, + }, + _ => return None, }; if rest.len() > 1 && !(rest.len() == 2 && is_builtin_error_handler(&rest[1])) { return None; } let ascii = crate::shared_value::SharedStr::is_ascii(s); let s: &str = s; + // UTF-16 and UTF-32 by the spellings code writes (CPython's encoder + // shortcuts them too): a `str` has no lone surrogate, so every + // character encodes and no handler is consulted. + if let Some(Object::Str(name)) = rest.first() { + use crate::stdlib::codecs_engine::{utf16_encode_str, utf32_encode_str}; + let wide = match &**name { + "utf-16" | "utf_16" | "utf16" => Some(utf16_encode_str(s, 0)), + "utf-16-le" | "utf-16le" | "utf_16_le" => Some(utf16_encode_str(s, -1)), + "utf-16-be" | "utf-16be" | "utf_16_be" => Some(utf16_encode_str(s, 1)), + "utf-32" | "utf_32" | "utf32" => Some(utf32_encode_str(s, 0)), + "utf-32-le" | "utf-32le" | "utf_32_le" => Some(utf32_encode_str(s, -1)), + "utf-32-be" | "utf-32be" | "utf_32_be" => Some(utf32_encode_str(s, 1)), + _ => None, + }; + if let Some(bytes) = wide { + return Some(Ok(Object::new_bytes(bytes))); + } + } // (The text's own bytes are copied once, straight into the result.) let bytes = match plain_codec(rest.first())? { PlainCodec::Utf8 => return Some(Ok(bytes_from_slice(s.as_bytes()))), @@ -14040,13 +15853,69 @@ fn bytes_from_slice(data: &[u8]) -> Object { /// `b.decode([encoding])` with a plain codec, when the bytes decode (an /// undecodable one raises on the full path). -pub(crate) fn bytes_decode_leaf(args: &[Object]) -> Option> { - let (Object::Bytes(b), rest) = args.split_first()? else { +/// `b.decode(encoding="utf-8", errors="strict")`'s keyword half (see +/// `leaf_builtins::register_fast_kw`): the receiver, then the two, each +/// `Unbound` when the call left it out, decoded as [`bytes_decode_leaf`] +/// decodes them positionally. +pub(crate) fn bytes_decode_kw_fast(args: &[Object]) -> Option> { + let [recv, encoding, errors] = args else { return None; }; + let encoding = match encoding { + Object::Unbound => Object::from_static("utf-8"), + Object::Str(_) => encoding.clone(), + _ => return None, + }; + match errors { + Object::Unbound => bytes_decode_leaf(&[recv.clone(), encoding]), + Object::Str(_) => bytes_decode_leaf(&[recv.clone(), encoding, errors.clone()]), + _ => None, + } +} + +/// `b.find(sub[, start[, end]])` of `bytes` with a `bytes` or `int` +/// needle and `int` bounds: the full body, which then runs no code. +pub(crate) fn bytes_find_leaf(args: &[Object]) -> Option> { + match args { + [Object::Bytes(_), Object::Bytes(_) | Object::Int(_), rest @ ..] + if rest.len() <= 2 && rest.iter().all(|a| matches!(a, Object::Int(_))) => + { + Some(bytes_find(args)) + } + _ => None, + } +} + +/// `b.hex([sep[, bytes_per_sep]])` of `bytes` with an exact `str` or +/// `bytes` separator and an `int` group size: the full body, which then +/// runs no code (only a separator's own `__len__` could). +pub(crate) fn bytes_hex_leaf(args: &[Object]) -> Option> { + match args { + [Object::Bytes(_)] + | [Object::Bytes(_), Object::Str(_) | Object::Bytes(_)] + | [Object::Bytes(_), Object::Str(_) | Object::Bytes(_), Object::Int(_)] => { + Some(bytes_hex_kw(args, &[])) + } + _ => None, + } +} + +pub(crate) fn bytes_decode_leaf(args: &[Object]) -> Option> { + let (recv, rest) = args.split_first()?; if rest.len() > 1 && !(rest.len() == 2 && is_builtin_error_handler(&rest[1])) { return None; } + // (A `bytearray`'s bytes are read where they are: nothing below runs + // code.) + let held; + let b: &[u8] = match recv { + Object::Bytes(b) => b, + Object::ByteArray(b) => { + held = b.try_borrow().ok()?; + &held + } + _ => return None, + }; // (ASCII text is copied once, straight into the result, which is born // knowing its length in characters.) let ascii = |b: &[u8]| { @@ -14127,8 +15996,43 @@ pub(crate) fn dict_fromkeys_leaf(args: &[Object]) -> Option return None, }; let keys: Vec = match keys { - Object::List(l) => l.try_borrow().ok()?.clone(), - Object::Tuple(t) => t.to_vec(), + Object::List(l) => crate::object::cloned_vec(&l.try_borrow().ok()?), + Object::Tuple(t) => crate::object::cloned_vec(t), + // An ASCII string's characters (`dict.fromkeys("abc")`), the + // shared one-character strings. + Object::Str(s) if s.is_ascii() && s.len() <= 64 => s + .bytes() + .map(|c| Object::Str(crate::shared_value::SharedStr::ascii_char(c))) + .collect(), + // Another mapping's or set's keys, in their order. + Object::Dict(m) if m.try_borrow().ok()?.len() <= 64 => { + m.try_borrow().ok()?.keys().map(|k| k.0.clone()).collect() + } + Object::Set(m) if m.try_borrow().ok()?.len() <= 64 => { + m.try_borrow().ok()?.iter().map(|k| k.0.clone()).collect() + } + Object::FrozenSet(m) if m.len() <= 64 => m.iter().map(|k| k.0.clone()).collect(), + // A short range of machine ints (`dict.fromkeys(range(n))`). + Object::Range(r) if r.big.is_none() => { + let (start, stop, step) = ( + i128::from(i64::try_from(r.start).ok()?), + i128::from(i64::try_from(r.stop).ok()?), + i128::from(i64::try_from(r.step).ok()?), + ); + let n = if step > 0 && start < stop { + (stop - start + step - 1) / step + } else if step < 0 && start > stop { + (start - stop - step - 1) / -step + } else { + 0 + }; + if n > 64 { + return None; + } + (0..n) + .map(|k| Object::Int((start + k * step) as i64)) + .collect() + } _ => return None, }; let mut d = DictData::default(); @@ -14142,13 +16046,21 @@ pub(crate) fn dict_fromkeys_leaf(args: &[Object]) -> Option return None, } } - Some(Ok(Object::Dict(Rc::new(RefCell::new(d))))) + // (Registered with the collector, as the full path's: a value may + // refer back to it.) + let out = Object::Dict(Rc::new(RefCell::new(d))); + crate::gc_trace::track_built(&out); + Some(Ok(out)) } pub(crate) fn int_from_bytes_leaf(args: &[Object]) -> Option> { // One to seven bytes in either order: the machine int, with no byte // order string or copy of the data built. - if let [Object::Type(t), Object::Bytes(data), rest @ ..] = args { + // (A `bytearray`'s or a live `memoryview`'s bytes are read in place, + // as `bytes(view)` would read them.) + if let [Object::Type(t), src @ (Object::Bytes(_) | Object::ByteArray(_) | Object::MemoryView(_)), rest @ ..] = + args + { let little = match rest { [] => Some(false), [Object::Str(order)] => match order.as_bytes() { @@ -14158,15 +16070,23 @@ pub(crate) fn int_from_bytes_leaf(args: &[Object]) -> Option None, }; - if let (Some(little), 1..=7) = (little, data.len()) { - if crate::sync::Rc::ptr_eq(t, &builtin_types().int_) { - let v = data.iter().enumerate().fold(0u64, |v, (i, &b)| { - if little { - v | u64::from(b) << (8 * i) - } else { - v << 8 | u64::from(b) - } - }); + let live = !matches!(src, Object::MemoryView(mv) if mv.released.get()); + if let (Some(little), true) = ( + little, + live && crate::sync::Rc::ptr_eq(t, &builtin_types().int_), + ) { + let v = src.with_bytes_view(|data| { + (1..=7).contains(&data.len()).then(|| { + data.iter().enumerate().fold(0u64, |v, (i, &b)| { + if little { + v | u64::from(b) << (8 * i) + } else { + v << 8 | u64::from(b) + } + }) + }) + }); + if let Some(Some(v)) = v { return Some(Ok(Object::Int(v as i64))); } } @@ -14201,6 +16121,56 @@ pub(crate) fn dict_getitem_leaf(args: &[Object]) -> Option Option> { + let (recv, key, default) = match args { + [recv, key] => (recv, key, None), + [recv, key, default] => (recv, key, Some(default)), + _ => return None, + }; + if crate::capi_watchers::dicts_active() { + return None; + } + let probe = crate::object::LeafProbe::new(key)?; + let cell = leaf_dict_of(recv)?; + let mut m = cell.try_borrow_mut().ok()?; + match m.lazy_remove_entry(&probe) { + Some((k, v)) => { + drop(m); + crate::object::dict_watch_bump(cell); + crate::object::dict_mutation_event(cell); + drop(k); + Some(Ok(v)) + } + None if probe.miss_is_exact() => Some(match default { + Some(d) => Ok(d.clone()), + None => Err(crate::error::key_error_object(key.clone())), + }), + None => None, + } +} + +/// `dict.popitem()`'s leaf half: the last entry of a non-empty dict as a +/// pair (nothing is released, so nothing could finalize). An empty dict, +/// which raises, and a dict watcher take the full path. +pub(crate) fn dict_popitem_leaf(args: &[Object]) -> Option> { + let [recv] = args else { + return None; + }; + if crate::capi_watchers::dicts_active() { + return None; + } + let cell = leaf_dict_of(recv)?; + let (k, v) = cell.try_borrow_mut().ok()?.pop()?; + crate::object::dict_watch_bump(cell); + crate::object::dict_mutation_event(cell); + Some(Ok(Object::new_tuple_array([k.0, v]))) +} + /// `dict.__setitem__`'s leaf half: a `str`/`int` key replacing an /// exact-key entry, or inserting one no stored key could equal. Anything /// that could run Python (an exotic stored key, a dict watcher) takes the @@ -14322,7 +16292,7 @@ fn dict_delitem(args: &[Object]) -> Result { fn dict_view_no_args(args: &[Object], name: &str) -> Result<(), RuntimeError> { if args.len() > 1 { return Err(type_error(format!( - "{name}() takes no arguments ({} given)", + "dict.{name}() takes no arguments ({} given)", args.len() - 1 ))); } @@ -14380,7 +16350,7 @@ fn dict_pop(args: &[Object]) -> Result { } let key = args .get(1) - .ok_or_else(|| type_error("dict.pop() expected at least 1 argument"))?; + .ok_or_else(|| type_error("pop expected at least 1 argument, got 0"))?; ensure_dict_key(key)?; let removed = dict_remove(&d, key)?; if let Some((k, v)) = removed { @@ -14395,6 +16365,24 @@ fn dict_pop(args: &[Object]) -> Result { } } +/// `d.update(other)`'s leaf half: a plain dict merged from another whose +/// keys' hashing and equality run no code (see +/// `Interpreter::dict_merge_plain`), `None` for anything else. +fn dict_update_fast(args: &[Object]) -> Option> { + let [Object::Dict(d), Object::Dict(src)] = args else { + return None; + }; + // (A dict updated from itself is left as it is, as CPython's + // `dict_merge` leaves it.) + if Rc::ptr_eq(d, src) { + return Some(Ok(Object::None)); + } + if crate::capi_watchers::dicts_active() { + return None; + } + crate::Interpreter::dict_merge_plain(d, src).then_some(Ok(Object::None)) +} + fn dict_update(args: &[Object]) -> Result { let d = dict_self(args)?; if let Some(other) = args.get(1) { @@ -14488,13 +16476,24 @@ fn tuple_count(args: &[Object]) -> Result { // directions), propagating any exception the comparison raises. let mut n: i64 = 0; for x in t.iter() { - if crate::object::member_eq(x, &args[1])? { + if seq_item_eq(x, &args[1])? { n += 1; } } Ok(Object::Int(n)) } +/// `PyObject_RichCompareBool(x, value)` for a sequence scan: ints and +/// strings compared directly, anything else through [`member_eq`]. +#[inline] +fn seq_item_eq(x: &Object, value: &Object) -> Result { + match (x, value) { + (Object::Int(a), Object::Int(b)) => Ok(a == b), + (Object::Str(a), Object::Str(b)) => Ok(a == b), + _ => crate::object::member_eq(x, value), + } +} + fn tuple_index(args: &[Object]) -> Result { if args.len() < 2 { return Err(type_error("tuple.index() expected at least 1 argument")); @@ -14523,7 +16522,7 @@ fn tuple_index(args: &[Object]) -> Result { }; let mut i = start; while i < stop { - if crate::object::member_eq(&t[i as usize], &args[1])? { + if seq_item_eq(&t[i as usize], &args[1])? { return Ok(Object::Int(i)); } i += 1; @@ -14579,15 +16578,23 @@ pub(crate) fn dict_setdefault(args: &[Object]) -> Result { Ok(value) } +/// `d.copy()`'s leaf half: a plain dict's copy runs no code. +fn dict_copy_fast(args: &[Object]) -> Option> { + let [Object::Dict(_)] = args else { + return None; + }; + Some(dict_copy(args)) +} + fn dict_copy(args: &[Object]) -> Result { let d = dict_self(args)?; dict_view_no_args(args, "copy")?; let cloned = d.borrow().clone(); let out = Object::Dict(Rc::new(RefCell::new(cloned))); - // Tracked by its contents, as any new dict is: a copy of scalars stays - // deferred, and one that could close a cycle is registered. + // Deferred without scanning its values: every collection promotes the + // deferred containers that could close a cycle before it marks. // (`gc.is_tracked` answers for a dict as CPython does either way.) - crate::gc_trace::track(&out); + crate::gc_trace::track_built(&out); Ok(out) } @@ -14634,7 +16641,9 @@ fn dict_fromkeys(args: &[Object]) -> Result { dict_insert(&d, k, value.clone())?; } } - return Ok(Object::Dict(d)); + let out = Object::Dict(d); + crate::gc_trace::track_built(&out); + return Ok(out); } // A dict subclass: CPython's `dict_fromkeys` calls `cls()` — running // `__new__`/`__init__`, either of which may raise or return a foreign @@ -14825,40 +16834,95 @@ thread_local! { /// `test_hash_collision_concurrent_add`, where a hash-colliding /// `__eq__` calls `s.add(...)` during another `s.add`). Rather than /// panic on the re-entrant `borrow_mut`, the inner call records its op - /// here keyed by the set's identity; the outer frame replays it once - /// its own mutation completes, so the final contents match CPython. - static SET_DEFERRED_OPS: std::cell::RefCell> = + /// here against the set; the outer frame replays it once its own + /// mutation completes, so the final contents match CPython. An op whose + /// outer frame was some other operation (a comparison, `remove`) waits + /// for the set's next in-place mutation, which replays it first. + /// + /// Each entry holds a weak handle, which keeps the set's allocation (and + /// so its address) from being reused while the op waits: a set that dies + /// with ops pending drops them, and a new set never inherits them. + static SET_DEFERRED_OPS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } +type DeferredSet = crate::sync::Weak>; + +/// Queue `op` against `set` (see `SET_DEFERRED_OPS`). +fn defer_set_op(set: &Rc>, op: SetInplaceOp) { + let dead = SET_DEFERRED_OPS.with(|q| { + let mut q = q.borrow_mut(); + let dead = take_dead_set_ops(&mut q); + q.push((Rc::downgrade(set), op)); + dead + }); + // (Released with the queue free: their drop glue can run code.) + drop(dead); +} + +/// Remove the entries whose set has died. +fn take_dead_set_ops(q: &mut Vec<(DeferredSet, SetInplaceOp)>) -> Vec { + let mut dead = Vec::new(); + let mut i = 0; + while i < q.len() { + if q[i].0.strong_count() == 0 { + dead.push(q.remove(i).1); + } else { + i += 1; + } + } + dead +} + /// Drain and return any deferred ops queued against `ptr`. The queue /// borrow is released before the caller applies them, so a further /// re-entrant mutation during replay can queue again without conflict. -fn take_deferred_set_ops(ptr: usize) -> Vec { - SET_DEFERRED_OPS.with(|q| { +/// Whether any set mutation is waiting in the deferred queue (see +/// `SET_DEFERRED_OPS`), which a direct insert would overtake. +pub(crate) fn set_ops_deferred() -> bool { + SET_DEFERRED_OPS.with(|q| q.try_borrow().map_or(true, |q| !q.is_empty())) +} + +fn take_deferred_set_ops(set: &Rc>) -> Vec { + let (drained, dead) = SET_DEFERRED_OPS.with(|q| { let mut q = q.borrow_mut(); if q.is_empty() { - return Vec::new(); + return (Vec::new(), Vec::new()); } + let dead = take_dead_set_ops(&mut q); + let ptr = Rc::as_ptr(set); let mut drained = Vec::new(); let mut i = 0; while i < q.len() { - if q[i].0 == ptr { + if std::ptr::eq(q[i].0.as_ptr(), ptr) { drained.push(q.remove(i).1); } else { i += 1; } } - drained - }) + (drained, dead) + }); + drop(dead); + drained } fn set_apply_inplace(args: &[Object], op: SetInplaceOp) -> Result { match set_self(args)? { Object::Set(s) => { - let ptr = Rc::as_ptr(&s) as usize; - match s.try_borrow_mut() { - Ok(mut b) => { + // (Held by another thread, blocked in a call that one of its + // comparisons made: wait for it rather than defer to a frame + // that isn't this thread's.) + let held = s + .try_borrow_mut() + .ok() + .or_else(|| crate::sync::retry_past_parked(|| s.try_borrow_mut().ok())); + match held { + Some(mut b) => { + // Ops deferred while another operation held the set came + // first. + for op in take_deferred_set_ops(&s) { + apply_set_inplace_op(&mut b, op); + } // A colliding `__eq__` that raises during `add`/`discard` // aborts the mutation in CPython (test_badcmp `s.add`/ // `s.discard`/`s.remove` of a `BadCmp`). @@ -14866,7 +16930,7 @@ fn set_apply_inplace(args: &[Object], op: SetInplaceOp) -> Result Result { + None => { // An outer frame holds the borrow (re-entrant mutation // from a `__hash__`/`__eq__` callback). Defer; the outer // frame replays once it finishes. - SET_DEFERRED_OPS.with(|q| q.borrow_mut().push((ptr, op))); + defer_set_op(&s, op); Ok(Object::None) } } @@ -14909,7 +16973,7 @@ fn set_iter_items(obj: &Object) -> Result, RuntimeError> { } } -fn set_add(args: &[Object]) -> Result { +pub(crate) fn set_add(args: &[Object]) -> Result { let v = args .get(1) .cloned() @@ -14981,12 +17045,181 @@ fn set_copy(args: &[Object]) -> Result { } } +/// A value a set hashes and compares without running code. +#[inline] +fn set_value_native(v: &Object) -> bool { + matches!( + v, + Object::Int(_) + | Object::Str(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Bytes(_) + ) +} + +/// Whether a re-entrant mutation of some set waits to be replayed (see +/// `SET_DEFERRED_OPS`): the full method replays it first. +#[inline] +pub(crate) fn set_ops_pending() -> bool { + SET_DEFERRED_OPS.with(|q| q.try_borrow().map_or(true, |q| !q.is_empty())) +} + +/// Whether every operand is an exact set or frozenset (a set method's +/// leaf half reads their tables in place). +fn all_sets(args: &[Object]) -> bool { + args.iter() + .all(|a| matches!(a, Object::Set(_) | Object::FrozenSet(_))) +} + +/// `a.issubset(b)`, `a.issuperset(b)` and `a.isdisjoint(b)`'s leaf half: +/// two sets or frozensets whose keys compare natively. `None` for anything +/// else, which the full call answers. +fn set_test_fast( + args: &[Object], + f: fn(&crate::object::SetData, &crate::object::SetData) -> bool, + flip: bool, +) -> Option> { + let [a, b] = args else { + return None; + }; + if !all_sets(args) || set_ops_pending() { + return None; + } + let (a, b) = if flip { (b, a) } else { (a, b) }; + set_pair_test(a, b, f).map(|r| Ok(Object::Bool(r))) +} + +fn set_issubset_fast(args: &[Object]) -> Option> { + set_test_fast(args, crate::setalg::subset, false) +} + +fn set_issuperset_fast(args: &[Object]) -> Option> { + set_test_fast(args, crate::setalg::subset, true) +} + +fn set_isdisjoint_fast(args: &[Object]) -> Option> { + set_test_fast(args, crate::setalg::disjoint, false) +} + +/// `a.union(*others)`, `a.intersection(b)`, `a.difference(b)` and +/// `a.symmetric_difference(b)`'s leaf half: sets and frozensets whose keys +/// compare natively, the result's kind the receiver's. `None` for anything +/// else. +fn set_algebra_fast( + args: &[Object], + f: fn(&crate::object::SetData, &crate::object::SetData) -> crate::object::SetData, + many: bool, +) -> Option> { + if !all_sets(args) || set_ops_pending() { + return None; + } + let out = match args { + [_, _] => set_pair_pure(args, f)?, + [_, _, _, ..] if many => crate::setalg::pure(|| crate::setalg::union_many(args))??, + _ => return None, + }; + Some(Ok(set_result_like(args.first(), out))) +} + +fn set_union_fast(args: &[Object]) -> Option> { + set_algebra_fast(args, crate::setalg::union, true) +} + +fn set_intersection_fast(args: &[Object]) -> Option> { + set_algebra_fast(args, crate::setalg::intersection, false) +} + +fn set_difference_fast(args: &[Object]) -> Option> { + set_algebra_fast(args, crate::setalg::difference, false) +} + +fn set_symmetric_difference_fast(args: &[Object]) -> Option> { + set_algebra_fast(args, crate::setalg::symmetric_difference, false) +} + +/// `s.add(x)`'s leaf half: a plain set, a value that hashes and compares +/// natively. `None` for anything else. +fn set_add_fast(args: &[Object]) -> Option> { + let [Object::Set(s), v] = args else { + return None; + }; + if !set_value_native(v) || set_ops_pending() { + return None; + } + s.try_borrow_mut().ok()?.insert(DictKey(v.clone())); + Some(Ok(Object::None)) +} + +/// `s.update(*others)`'s leaf half: a plain set from tuples, lists, sets +/// and frozensets of values that hash and compare natively, inserted in +/// place (no code runs, so no snapshot is needed). `None`, touching +/// nothing, for anything else. +fn set_update_fast(args: &[Object]) -> Option> { + let [Object::Set(s), rest @ ..] = args else { + return None; + }; + if set_ops_pending() { + return None; + } + // SAFETY: guard-free views of the sources, each ended before anything + // could borrow it (nothing below runs code). + let fits = |o: &Object| unsafe { + match o { + Object::Tuple(t) => t.iter().all(set_value_native), + Object::List(l) => l.peek().is_some_and(|l| l.iter().all(set_value_native)), + Object::Set(o) => { + !Rc::ptr_eq(o, s) + && o.peek() + .is_some_and(|o| o.iter().all(|k| set_value_native(&k.0))) + } + Object::FrozenSet(o) => o.iter().all(|k| set_value_native(&k.0)), + _ => false, + } + }; + if !rest.iter().all(fits) { + return None; + } + let mut b = s.try_borrow_mut().ok()?; + for o in rest { + // SAFETY: as above. + unsafe { + match o { + Object::Tuple(t) => t.iter().for_each(|v| { + b.insert(DictKey(v.clone())); + }), + Object::List(l) => l.peek()?.iter().for_each(|v| { + b.insert(DictKey(v.clone())); + }), + Object::Set(o) => o.peek()?.iter().for_each(|k| { + b.insert(k.clone()); + }), + Object::FrozenSet(o) => o.iter().for_each(|k| { + b.insert(k.clone()); + }), + _ => {} + } + } + } + Some(Ok(Object::None)) +} + fn set_update(args: &[Object]) -> Result { let receiver = set_self(args)?; if let Object::FrozenSet(_) = receiver { return Err(type_error("frozenset is immutable")); } if let Object::Set(s) = &receiver { + // Mutations deferred while another operation held the set came + // first (see `SET_DEFERRED_OPS`). + let pending = take_deferred_set_ops(s); + if !pending.is_empty() { + let mut b = s.borrow_mut(); + for op in pending { + apply_set_inplace_op(&mut b, op); + } + } // Build on a snapshot so an element `__hash__` that re-enters and // mutates `s` can't fire while we hold `s.borrow_mut()` (bpo-46615). let mut acc: crate::object::SetData = s.borrow().clone(); @@ -15022,7 +17255,41 @@ fn set_result_like(receiver: Option<&Object>, body: crate::object::SetData) -> O } } +/// `a.(b)` for an exact set or frozenset and another, when the +/// tables settle it without Python (see `setalg`): the result's table. +fn set_pair_pure( + args: &[Object], + f: impl FnOnce(&crate::object::SetData, &crate::object::SetData) -> crate::object::SetData, +) -> Option { + let [a, b] = args else { + return None; + }; + crate::setalg::with_sets(a, b, |x, y| crate::setalg::pure(|| f(x, y)))? +} + +/// The items of an exact tuple or list when every one hashes and +/// compares natively (a set method's iterable argument, which then needs +/// no set built from it and runs no Python). +fn set_native_items(o: &Object) -> Option> { + let native = |xs: &[Object]| xs.iter().all(set_value_native).then(|| xs.to_vec()); + match o { + Object::Tuple(t) => native(t), + Object::List(l) => native(&l.try_borrow().ok()?), + _ => None, + } +} + fn set_union(args: &[Object]) -> Result { + if let Some(out) = set_pair_pure(args, crate::setalg::union) { + return Ok(set_result_like(args.first(), out)); + } + // (`a.union(b, c)` of sets: folded over their tables, each key's hash + // read where it's stored.) + if args.len() > 2 { + if let Some(Some(out)) = crate::setalg::pure(|| crate::setalg::union_many(args)) { + return Ok(set_result_like(args.first(), out)); + } + } let mut out = crate::object::SetData::default(); if let Some(first) = args.first() { for k in set_iter_items(first)? { @@ -15038,6 +17305,30 @@ fn set_union(args: &[Object]) -> Result { } fn set_intersection(args: &[Object]) -> Result { + if let Some(out) = set_pair_pure(args, crate::setalg::intersection) { + return Ok(set_result_like(args.first(), out)); + } + // An iterable of native values: its items that the set holds, in its + // order (CPython's `set_intersection` adds the iterable's own item). + if let [a, other] = args { + if let Some(items) = set_native_items(other) { + let out = crate::setalg::with_set(a, |x| { + crate::setalg::pure(|| { + let mut out = crate::object::SetData::new(); + for v in &items { + let key = DictKey(v.clone()); + if x.contains(&key) { + out.insert(key); + } + } + out + }) + }); + if let Some(Some(out)) = out { + return Ok(set_result_like(args.first(), out)); + } + } + } let mut acc = match args.first() { Some(first) => { let mut s = crate::object::SetData::default(); @@ -15056,6 +17347,9 @@ fn set_intersection(args: &[Object]) -> Result { } fn set_difference(args: &[Object]) -> Result { + if let Some(out) = set_pair_pure(args, crate::setalg::difference) { + return Ok(set_result_like(args.first(), out)); + } let mut acc = match args.first() { Some(first) => { let mut s = crate::object::SetData::default(); @@ -15074,6 +17368,9 @@ fn set_difference(args: &[Object]) -> Result { } fn set_symmetric_difference(args: &[Object]) -> Result { + if let Some(out) = set_pair_pure(args, crate::setalg::symmetric_difference) { + return Ok(set_result_like(args.first(), out)); + } let a: crate::object::SetData = match args.first() { Some(first) => set_iter_items(first)?.into_iter().collect(), None => return Ok(Object::new_set()), @@ -15092,7 +17389,22 @@ fn set_symmetric_difference(args: &[Object]) -> Result { Ok(set_result_like(args.first(), out)) } +/// `a b` for an exact set or frozenset and another, when the tables +/// settle it without Python. +fn set_pair_test( + a: &Object, + b: &Object, + f: impl FnOnce(&crate::object::SetData, &crate::object::SetData) -> bool, +) -> Option { + crate::setalg::with_sets(a, b, |x, y| crate::setalg::pure(|| f(x, y)))? +} + fn set_issubset(args: &[Object]) -> Result { + if let [a, b] = args { + if let Some(r) = set_pair_test(a, b, crate::setalg::subset) { + return Ok(Object::Bool(r)); + } + } let a = set_iter_items(args.first().unwrap())?; let b: crate::object::SetData = match args.get(1) { Some(o) => set_iter_items(o)?.into_iter().collect(), @@ -15102,6 +17414,20 @@ fn set_issubset(args: &[Object]) -> Result { } fn set_issuperset(args: &[Object]) -> Result { + if let [a, b] = args { + if let Some(r) = set_pair_test(b, a, crate::setalg::subset) { + return Ok(Object::Bool(r)); + } + // An iterable of native values: each looked up in the set. + if let Some(items) = set_native_items(b) { + let r = crate::setalg::with_set(a, |x| { + crate::setalg::pure(|| items.iter().all(|v| x.contains(&DictKey(v.clone())))) + }); + if let Some(Some(r)) = r { + return Ok(Object::Bool(r)); + } + } + } let a: crate::object::SetData = set_iter_items(args.first().unwrap())?.into_iter().collect(); let b = match args.get(1) { Some(o) => set_iter_items(o)?, @@ -15130,6 +17456,9 @@ fn set_isdisjoint(args: &[Object]) -> Result { Object::FrozenSet(s) => Some(s.len()), _ => None, }; + if let Some(r) = set_pair_test(this, other, crate::setalg::disjoint) { + return Ok(Object::Bool(r)); + } let Some(n) = len(this) else { // A subclass instance's receiver: both sides' items. let a: crate::object::SetData = set_iter_items(this)?.into_iter().collect(); @@ -15186,6 +17515,11 @@ fn set_intersection_update(args: &[Object]) -> Result { if matches!(set_self(args)?, Object::FrozenSet(_)) { return Err(type_error("frozenset is immutable")); } + if let [a, b] = args { + if crate::setalg::update(a, b, weavepy_compiler::BinOpKind::BitAnd) { + return Ok(Object::None); + } + } if let Object::Set(s) = set_self(args)? { let mut keep: crate::object::SetData = s.borrow().clone(); for other in args.iter().skip(1) { @@ -15201,6 +17535,30 @@ fn set_difference_update(args: &[Object]) -> Result { if matches!(set_self(args)?, Object::FrozenSet(_)) { return Err(type_error("frozenset is immutable")); } + if let [a, b] = args { + if crate::setalg::update(a, b, weavepy_compiler::BinOpKind::Sub) { + return Ok(Object::None); + } + // An iterable of native values: each taken out of the set. + if let (Object::Set(cell), Some(items)) = (a, set_native_items(b)) { + if !set_ops_pending() { + let gone = crate::setalg::with_set(a, |x| { + crate::setalg::pure(|| { + items + .iter() + .filter_map(|v| x.get_index_of(&DictKey(v.clone()))) + .collect::>() + }) + }); + if let (Some(Some(gone)), Ok(mut x)) = (gone, cell.try_borrow_mut()) { + let out = crate::setalg::Plan::Remove(gone).apply(&mut x); + drop(x); + drop(out); + return Ok(Object::None); + } + } + } + } if let Object::Set(s) = set_self(args)? { // Compute on a snapshot so the element `__hash__`/`__eq__` we // invoke (which may re-enter and clear `s`) never runs while we @@ -15220,6 +17578,11 @@ fn set_symmetric_difference_update(args: &[Object]) -> Result set_iter_items(o)?.into_iter().collect(), @@ -15240,10 +17603,12 @@ fn set_symmetric_difference_update(args: &[Object]) -> Result Result, RuntimeError> { +fn bytes_data(args: &[Object]) -> Result, RuntimeError> { match args.first() { - Some(Object::Bytes(b)) => Ok(b.to_vec()), - Some(Object::ByteArray(b)) => Ok(b.borrow().clone()), + // (An immutable receiver is read in place; a `bytearray` is copied, + // as the method may run code that resizes it.) + Some(Object::Bytes(b)) => Ok(std::borrow::Cow::Borrowed(&b[..])), + Some(Object::ByteArray(b)) => Ok(std::borrow::Cow::Owned(b.borrow().clone())), _ => Err(type_error("expected bytes-like receiver")), } } @@ -15268,6 +17633,18 @@ fn with_bytes_data( } pub(crate) fn bytes_argview(arg: &Object) -> Result, RuntimeError> { + bytes_argview_cow(arg).map(std::borrow::Cow::into_owned) +} + +/// [`bytes_argview`], reading a `bytes` argument in place. +pub(crate) fn bytes_argview_cow(arg: &Object) -> Result, RuntimeError> { + if let Object::Bytes(b) = arg { + return Ok(std::borrow::Cow::Borrowed(&b[..])); + } + bytes_argview_owned(arg).map(std::borrow::Cow::Owned) +} + +fn bytes_argview_owned(arg: &Object) -> Result, RuntimeError> { match arg { Object::Bytes(b) => Ok(b.to_vec()), Object::ByteArray(b) => Ok(b.borrow().clone()), @@ -15371,6 +17748,14 @@ fn byte_is_pyspace(c: u8) -> bool { } fn bytes_decode_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result { + if let Some((name, _)) = kwargs + .iter() + .find(|(k, _)| k != "encoding" && k != "errors") + { + return Err(type_error(format!( + "decode() got an unexpected keyword argument '{name}'" + ))); + } let data = bytes_data(args)?; let encoding = match arg_or_kw(args, 1, kwargs, "encoding") { Some(Object::Str(e)) => e.to_string(), @@ -15431,12 +17816,64 @@ pub fn buffer_exported_view(obj: &Object, flags: i64) -> Option Some(mv), _ => None, } -} - -fn bytes_hex_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result { +} + +/// The lowercase hex digits of `data`, two a byte. +fn hex_ascii(data: &[u8]) -> SharedStr { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let len = data.len() * 2; + // SAFETY: hex digits are ASCII, one code point a byte, `len` in all. + unsafe { + SharedStr::build_unchecked(len, Some(len), |w| { + for &b in data { + w.push(&[HEX[usize::from(b >> 4)], HEX[usize::from(b & 15)]]); + } + }) + } +} + +/// [`hex_ascii`] with the ASCII byte `sep` between bytes' digits. +fn hex_ascii_sep(data: &[u8], sep: u8) -> SharedStr { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let len = (data.len() * 3).saturating_sub(1); + // SAFETY: hex digits and `sep` are ASCII, one code point a byte, `len` + // in all. + unsafe { + SharedStr::build_unchecked(len, Some(len), |w| { + for (i, &b) in data.iter().enumerate() { + if i > 0 { + w.push(&[sep]); + } + w.push(&[HEX[usize::from(b >> 4)], HEX[usize::from(b & 15)]]); + } + }) + } +} + +fn bytes_hex_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result { + // `b.hex()` of bytes without a separator: the digits straight into the + // string's own allocation. + if let ([Object::Bytes(b)], []) = (args, kwargs) { + return Ok(Object::Str(hex_ascii(b))); + } + // A `bytearray`'s likewise, read under its borrow (nothing runs while + // the digits are written, so no export need guard it). + if let ([Object::ByteArray(b)], []) = (args, kwargs) { + if let Ok(data) = b.try_borrow() { + return Ok(Object::Str(hex_ascii(&data))); + } + } + // `b.hex(":")`: one ASCII separator between every byte's digits. + if let ([Object::Bytes(b), Object::Str(sep)], []) = (args, kwargs) { + if let &[c] = sep.as_bytes() { + if c.is_ascii() { + return Ok(Object::Str(hex_ascii_sep(b, c))); + } + } + } let data = match args.first() { Some(Object::MemoryView(mv)) => mv.to_bytes(), - _ => bytes_data(args)?, + _ => bytes_data(args)?.into_owned(), }; let mut sep_obj = args.get(1).cloned(); let mut bps_obj = args.get(2).cloned(); @@ -15589,6 +18026,57 @@ fn bytes_fromhex(args: &[Object]) -> Result { } } +/// `b.startswith(affix)` (`endswith` with `prefix` false) of a `bytes` or +/// `bytearray` receiver and affix, with no window. A leaf half, like +/// [`file_write_fast`]. +fn bytes_affix_fast(args: &[Object], prefix: bool) -> Option> { + let [recv, affix] = args else { + return None; + }; + let test = |data: &[u8]| { + let with = |needle: &[u8]| { + if prefix { + data.starts_with(needle) + } else { + data.ends_with(needle) + } + }; + match affix { + Object::Bytes(n) => Some(with(n)), + Object::ByteArray(n) => Some(with(&n.try_borrow().ok()?)), + // A tuple of `bytes` (`name.endswith((b".py", b".txt"))`); any + // other item leaves it to the full method. + Object::Tuple(parts) => { + let mut hit = false; + for p in parts.iter() { + let Object::Bytes(n) = p else { + return None; + }; + if !hit && with(n) { + hit = true; + } + } + Some(hit) + } + _ => None, + } + }; + let hit = match recv { + Object::Bytes(b) => test(b)?, + Object::ByteArray(b) => test(&b.try_borrow().ok()?)?, + _ => return None, + }; + Some(Ok(Object::Bool(hit))) +} + +fn bytes_startswith_fast(args: &[Object]) -> Option> { + bytes_affix_fast(args, true) +} + +fn bytes_endswith_fast(args: &[Object]) -> Option> { + bytes_affix_fast(args, false) +} + fn bytes_startswith(args: &[Object]) -> Result { bytes_search_arity("startswith", args)?; let target = args @@ -15641,6 +18129,12 @@ fn bytes_match_prefix_suffix( match target { Object::Tuple(parts) => { for item in parts.iter() { + if let Object::Bytes(n) = item { + if test(n) { + return Ok(true); + } + continue; + } let needle = bytes_argview(item).map_err(|_| { type_error(format!( "tuple for {name} must only contain bytes-like objects, \ @@ -15654,6 +18148,7 @@ fn bytes_match_prefix_suffix( } Ok(false) } + Object::Bytes(n) => Ok(test(n)), _ => { let needle = bytes_argview(target).map_err(|_| { type_error(format!( @@ -15708,7 +18203,7 @@ fn bytes_find_in(data: &[u8], sub: &[u8], start: usize, end: usize) -> i64 { if sub.is_empty() { return start as i64; } - memchr::memmem::find(hay, sub).map_or(-1, |i| (start + i) as i64) + bytes_search(hay, sub).map_or(-1, |i| (start + i) as i64) } /// gh-142560: converting a search argument can run Python code (a user @@ -15788,8 +18283,13 @@ fn bytes_rfind(args: &[Object]) -> Result { if sub.is_empty() { return Ok(Object::Int(end as i64)); } - let last = - memchr::memmem::rfind(&data[start..end], &sub).map_or(-1, |i| (start + i) as i64); + let hay = &data[start..end]; + let last = match sub.as_slice() { + [b] => memchr::memrchr(*b, hay), + _ if hay.len() <= 64 => memchr::memmem::rfind(hay, &sub), + _ => bytes_rfind_windows(hay, &sub), + } + .map_or(-1, |i| (start + i) as i64); Ok(Object::Int(last)) }) } @@ -15853,6 +18353,84 @@ fn bytes_lower(args: &[Object]) -> Result { Ok(bytes_like_result(args, out)) } +/// Whether a bytes or bytearray method's operands are plain data: the +/// receiver, then bytes, bytearrays, ints, bools and `None`. Its body then +/// reads them in place and runs no code (a buffer exporter's `__buffer__`, +/// or an `__index__`, could), so a call site may run it as a leaf. +fn bytes_plain_args(args: &[Object]) -> bool { + match args.split_first() { + Some((Object::Bytes(_) | Object::ByteArray(_), rest)) => rest.iter().all(|a| { + matches!( + a, + Object::Bytes(_) + | Object::ByteArray(_) + | Object::Int(_) + | Object::Bool(_) + | Object::None + ) + }), + _ => false, + } +} + +/// Leaf halves of the pure bytes and bytearray methods (see +/// [`bytes_plain_args`]): the full body over plain operands, `None` for +/// any other (the full call). +macro_rules! bytes_leaf_halves { + ($($fast:ident => $body:ident),* $(,)?) => {$( + pub(crate) fn $fast(args: &[Object]) -> Option> { + bytes_plain_args(args).then(|| $body(args)) + } + )*}; +} + +/// [`bytes_leaf_halves`] for a method that also takes keywords, called +/// with positional operands only. +macro_rules! bytes_leaf_halves_kw { + ($($fast:ident => $body:ident),* $(,)?) => {$( + pub(crate) fn $fast(args: &[Object]) -> Option> { + bytes_plain_args(args).then(|| $body(args, &[])) + } + )*}; +} + +bytes_leaf_halves! { + bytes_upper_fast => bytes_upper, + bytes_lower_fast => bytes_lower, + bytes_strip_fast => bytes_strip, + bytes_lstrip_fast => bytes_lstrip, + bytes_rstrip_fast => bytes_rstrip, + bytes_count_fast => bytes_count, + bytes_rfind_fast => bytes_rfind, + bytes_index_fast => bytes_index, + bytes_rindex_fast => bytes_rindex, + bytes_partition_fast => bytes_partition, + bytes_rpartition_fast => bytes_rpartition, + bytes_removeprefix_fast => bytes_removeprefix, + bytes_removesuffix_fast => bytes_removesuffix, + bytes_center_fast => bytes_center, + bytes_ljust_fast => bytes_ljust, + bytes_rjust_fast => bytes_rjust, + bytes_zfill_fast => bytes_zfill, + bytes_capitalize_fast => bytes_capitalize, + bytes_title_fast => bytes_title, + bytes_swapcase_fast => bytes_swapcase, + bytes_isalnum_fast => bytes_isalnum, + bytes_isalpha_fast => bytes_isalpha, + bytes_isdigit_fast => bytes_isdigit, + bytes_isspace_fast => bytes_isspace, + bytes_islower_fast => bytes_islower, + bytes_isupper_fast => bytes_isupper, +} + +bytes_leaf_halves_kw! { + bytes_split_fast => bytes_split_kw, + bytes_rsplit_fast => bytes_rsplit_kw, + bytes_replace_fast => bytes_replace_kw, + bytes_splitlines_fast => bytes_splitlines_kw, + bytes_expandtabs_fast => bytes_expandtabs, +} + fn bytes_upper(args: &[Object]) -> Result { bytes_no_args("upper", args)?; let out: Vec = bytes_data(args)? @@ -15862,19 +18440,41 @@ fn bytes_upper(args: &[Object]) -> Result { Ok(bytes_like_result(args, out)) } +/// The bytes `bytes.strip` and its kin remove (ASCII whitespace by +/// default), as a membership table: one lookup a byte, whatever the set's +/// size (`quote_from_bytes` strips 66 of them). +fn bytes_strip_set(args: &[Object]) -> Result<[bool; 256], RuntimeError> { + let mut table = [false; 256]; + match args.get(1) { + None | Some(Object::None) => { + for &b in b" \t\n\r\x0b\x0c" { + table[usize::from(b)] = true; + } + } + Some(Object::Bytes(set)) => { + for &b in set.iter() { + table[usize::from(b)] = true; + } + } + Some(other) => { + for b in bytes_argview(other)? { + table[usize::from(b)] = true; + } + } + } + Ok(table) +} + fn bytes_strip(args: &[Object]) -> Result { let data = bytes_data(args)?; - let trim_set: Vec = match args.get(1) { - None | Some(Object::None) => b" \t\n\r\x0b\x0c".to_vec(), - Some(other) => bytes_argview(other)?, - }; + let trim_set = bytes_strip_set(args)?; let start = data .iter() - .position(|b| !trim_set.contains(b)) + .position(|b| !trim_set[usize::from(*b)]) .unwrap_or(data.len()); let end = data .iter() - .rposition(|b| !trim_set.contains(b)) + .rposition(|b| !trim_set[usize::from(*b)]) .map_or(start, |i| i + 1); if let Some(same) = bytes_unchanged_self(args, end - start == data.len()) { return Ok(same); @@ -15896,13 +18496,10 @@ fn bytes_unchanged_self(args: &[Object], unchanged: bool) -> Option { fn bytes_lstrip(args: &[Object]) -> Result { let data = bytes_data(args)?; - let trim_set: Vec = match args.get(1) { - None | Some(Object::None) => b" \t\n\r\x0b\x0c".to_vec(), - Some(other) => bytes_argview(other)?, - }; + let trim_set = bytes_strip_set(args)?; let start = data .iter() - .position(|b| !trim_set.contains(b)) + .position(|b| !trim_set[usize::from(*b)]) .unwrap_or(data.len()); if let Some(same) = bytes_unchanged_self(args, start == 0) { return Ok(same); @@ -15912,13 +18509,10 @@ fn bytes_lstrip(args: &[Object]) -> Result { fn bytes_rstrip(args: &[Object]) -> Result { let data = bytes_data(args)?; - let trim_set: Vec = match args.get(1) { - None | Some(Object::None) => b" \t\n\r\x0b\x0c".to_vec(), - Some(other) => bytes_argview(other)?, - }; + let trim_set = bytes_strip_set(args)?; let end = data .iter() - .rposition(|b| !trim_set.contains(b)) + .rposition(|b| !trim_set[usize::from(*b)]) .map_or(0, |i| i + 1); if let Some(same) = bytes_unchanged_self(args, end == data.len()) { return Ok(same); @@ -15934,17 +18528,13 @@ fn bytes_split_args( name: &str, ) -> Result<(Vec, Option>, i64), RuntimeError> { let data = bytes_data(args)?; + split_keywords(name, args, kwargs)?; let mut sep_obj = args.get(1).cloned(); let mut maxsplit_obj = args.get(2).cloned(); for (k, v) in kwargs { match k.as_str() { "sep" => sep_obj = Some(v.clone()), - "maxsplit" => maxsplit_obj = Some(v.clone()), - other => { - return Err(type_error(format!( - "{name}() got an unexpected keyword argument '{other}'" - ))) - } + _ => maxsplit_obj = Some(v.clone()), } } let sep = match sep_obj { @@ -15968,10 +18558,65 @@ fn bytes_split_args( .as_i64() .ok_or_else(|| type_error("integer argument expected"))?, }; - Ok((data, sep, maxsplit)) + Ok((data.into_owned(), sep, maxsplit)) +} + +/// `b.split()` or `b.split(sep)` of bytes by bytes, no `maxsplit`: each +/// piece made from its slice once. +fn bytes_split_plain(data: &[u8], sep: Option<&[u8]>) -> Object { + // (The empty and one-byte pieces are the shared objects.) + let piece = |p: &[u8]| Object::new_bytes(p); + let mut parts = Vec::new(); + match sep { + None => { + let mut i = 0; + while i < data.len() { + while i < data.len() && byte_is_pyspace(data[i]) { + i += 1; + } + if i >= data.len() { + break; + } + let start = i; + while i < data.len() && !byte_is_pyspace(data[i]) { + i += 1; + } + parts.push(piece(&data[start..i])); + } + } + // One byte (`b.split(b" ")`): the matches counted in one pass to + // size the list, then the pieces cut between them in another. + Some(&[b]) => { + parts.reserve_exact(memchr::memchr_iter(b, data).count() + 1); + let mut start = 0; + for at in memchr::memchr_iter(b, data) { + parts.push(piece(&data[start..at])); + start = at + 1; + } + parts.push(piece(&data[start..])); + } + Some(sep) => { + let mut start = 0; + while let Some(rel) = bytes_search(&data[start..], sep) { + parts.push(piece(&data[start..start + rel])); + start += rel + sep.len(); + } + parts.push(piece(&data[start..])); + } + } + Object::new_list(parts) } fn bytes_split_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result { + match (args, kwargs) { + ([Object::Bytes(b)], []) | ([Object::Bytes(b), Object::None], []) => { + return Ok(bytes_split_plain(b, None)); + } + ([Object::Bytes(b), Object::Bytes(sep)], []) if !sep.is_empty() => { + return Ok(bytes_split_plain(b, Some(sep))); + } + _ => {} + } let (data, sep, maxsplit) = bytes_split_args(args, kwargs, "split")?; let mut parts: Vec> = Vec::new(); match sep { @@ -16001,7 +18646,7 @@ fn bytes_split_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result { parts.push(data[start..start + rel].to_vec()); start += rel + sep.len(); @@ -16209,7 +18854,61 @@ fn bytes_dunder_rmod(args: &[Object]) -> Result { } } +/// `bytes.join(parts)`'s leaf half: a list or tuple of `bytes` and +/// `bytearray` parts (see [`bytes_join`]); `None` for anything else. +fn bytes_join_fast(args: &[Object]) -> Option> { + match args { + [Object::Bytes(_), Object::List(_) | Object::Tuple(_)] => bytes_join_parts(args).map(Ok), + _ => None, + } +} + fn bytes_join(args: &[Object]) -> Result { + if let Some(r) = bytes_join_parts(args) { + return Ok(r); + } + bytes_join_general(args) +} + +fn bytes_join_parts(args: &[Object]) -> Option { + // `bytes` joining a list or tuple of `bytes`: one allocation of the + // exact size, the parts read in place (reading them runs no code). + if let Some(Object::Bytes(sep)) = args.first() { + // (A `bytearray` part is read in place too.) + let join = |items: &[Object]| -> Option { + let mut total = sep.len().checked_mul(items.len().saturating_sub(1))?; + for v in items { + let len = match v { + Object::Bytes(b) => b.len(), + Object::ByteArray(b) => b.try_borrow().ok()?.len(), + _ => return None, + }; + total = total.checked_add(len)?; + } + let mut out = Vec::with_capacity(total); + for (i, v) in items.iter().enumerate() { + if i > 0 { + out.extend_from_slice(sep); + } + match v { + Object::Bytes(b) => out.extend_from_slice(b), + Object::ByteArray(b) => out.extend_from_slice(&b.try_borrow().ok()?), + _ => return None, + } + } + // (No part changed size: nothing ran between the passes.) + (out.len() == total).then(|| Object::new_bytes(out)) + }; + return match args.get(1) { + Some(Object::List(l)) => l.try_borrow().ok().and_then(|l| join(&l)), + Some(Object::Tuple(t)) => join(t), + _ => None, + }; + } + None +} + +fn bytes_join_general(args: &[Object]) -> Result { let sep = bytes_data(args)?; let it = args .get(1) @@ -16217,8 +18916,8 @@ fn bytes_join(args: &[Object]) -> Result { // Iterate through the interpreter so user iterables / generators // work, not just native containers. let items: Vec = match it { - Object::List(l) => l.borrow().clone(), - Object::Tuple(t) => t.to_vec(), + Object::List(l) => crate::object::cloned_vec(&l.borrow()), + Object::Tuple(t) => crate::object::cloned_vec(t), other => { if let Some(ptr) = crate::vm_singletons::current_interpreter_ptr() { // SAFETY: published by an enclosing VM frame still live on @@ -16267,11 +18966,11 @@ fn bytes_join(args: &[Object]) -> Result { fn bytes_replace_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result { let data = bytes_data(args)?; - let from = bytes_argview( + let from = bytes_argview_cow( args.get(1) .ok_or_else(|| type_error("replace() expected 2 args"))?, )?; - let to = bytes_argview( + let to = bytes_argview_cow( args.get(2) .ok_or_else(|| type_error("replace() expected 2 args"))?, )?; @@ -16292,28 +18991,41 @@ fn bytes_replace_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result Result Option> { + match args { + [Object::Bytes(_) | Object::ByteArray(_), Object::None | Object::Bytes(_)] + | [Object::Bytes(_) | Object::ByteArray(_), Object::None | Object::Bytes(_), Object::Bytes(_)] => { + Some(bytes_translate_kw(args, &[])) + } + _ => None, + } +} + fn bytes_translate_kw( args: &[Object], kwargs: &[(String, Object)], ) -> Result { - let data = bytes_data(args)?; + // (Only a receiver check here: the table and deletion set are read, + // which can run code, before the receiver's bytes are.) + if !matches!(args.first(), Some(Object::Bytes(_) | Object::ByteArray(_))) { + return Err(type_error("expected bytes-like receiver")); + } let mut delete_obj = args.get(2).cloned(); for (k, v) in kwargs { match k.as_str() { @@ -16356,16 +19085,35 @@ fn bytes_translate_kw( None => Vec::new(), Some(o) => bytes_argview(&o)?, }; - let mut out = Vec::with_capacity(data.len()); - for &b in &data { - if delete.contains(&b) { - continue; - } - out.push(match &table { - Some(t) => t[b as usize], - None => b, - }); - } + let table: Option<[u8; 256]> = table.map(|t| { + let mut a = [0u8; 256]; + a.copy_from_slice(&t); + a + }); + let out: Vec = with_bytes_data(args, |data| { + Ok(match (&table, delete.is_empty()) { + // (Nothing deleted: every byte maps to one byte, in one pass.) + (Some(t), true) => data.iter().map(|&b| t[b as usize]).collect(), + (None, true) => data.to_vec(), + _ => { + // (The bytes to delete, as a table of their own.) + let mut gone = [false; 256]; + for &b in &delete { + gone[b as usize] = true; + } + let mut out = Vec::with_capacity(data.len()); + for &b in data.iter() { + if !gone[b as usize] { + out.push(match &table { + Some(t) => t[b as usize], + None => b, + }); + } + } + out + } + }) + })?; if matches!(args.first(), Some(Object::ByteArray(_))) { Ok(Object::new_bytearray(out)) } else { @@ -16403,13 +19151,13 @@ fn bytes_partition(args: &[Object]) -> Result { if sep.is_empty() { return Err(value_error("empty separator")); } - let (head, mid, tail) = match memchr::memmem::find(&data, &sep) { + let (head, mid, tail) = match bytes_search(&data, &sep) { Some(i) => ( data[..i].to_vec(), sep.clone(), data[i + sep.len()..].to_vec(), ), - None => (data, Vec::new(), Vec::new()), + None => (data.into_owned(), Vec::new(), Vec::new()), }; Ok(Object::new_tuple_array([ bytes_like_result(args, head), @@ -16433,7 +19181,7 @@ fn bytes_rpartition(args: &[Object]) -> Result { sep.clone(), data[i + sep.len()..].to_vec(), ), - None => (Vec::new(), Vec::new(), data), + None => (Vec::new(), Vec::new(), data.into_owned()), }; Ok(Object::new_tuple_array([ bytes_like_result(args, head), @@ -16457,7 +19205,7 @@ fn bytes_removeprefix(args: &[Object]) -> Result { let out = if data.starts_with(&prefix) { data[prefix.len()..].to_vec() } else { - data + data.into_owned() }; Ok(bytes_like_result(args, out)) } @@ -16477,7 +19225,7 @@ fn bytes_removesuffix(args: &[Object]) -> Result { let out = if !suffix.is_empty() && data.ends_with(&suffix) { data[..data.len() - suffix.len()].to_vec() } else { - data + data.into_owned() }; Ok(bytes_like_result(args, out)) } @@ -16508,7 +19256,7 @@ fn bytes_expandtabs(args: &[Object], kwargs: &[(String, Object)]) -> Result { if tabsize > 0 { @@ -16554,7 +19302,7 @@ fn bytes_pad_args(args: &[Object], name: &str) -> Result<(Vec, i64, u8), Run } } }; - Ok((data, width, fill)) + Ok((data.into_owned(), width, fill)) } fn bytes_center(args: &[Object]) -> Result { @@ -16600,7 +19348,7 @@ fn bytes_zfill(args: &[Object]) -> Result { .ok_or_else(|| type_error("zfill() expected integer width"))?; let len = data.len() as i64; if width <= len { - return Ok(bytes_like_result(args, data)); + return Ok(bytes_like_result(args, data.into_owned())); } let pad = (width - len) as usize; let mut out = Vec::with_capacity(width as usize); @@ -16634,7 +19382,7 @@ fn bytes_title(args: &[Object]) -> Result { let data = bytes_data(args)?; let mut out = Vec::with_capacity(data.len()); let mut prev_alpha = false; - for &b in &data { + for &b in data.iter() { if b.is_ascii_alphabetic() { out.push(if prev_alpha { b.to_ascii_lowercase() @@ -16689,7 +19437,7 @@ fn bytes_istitle(args: &[Object]) -> Result { let data = bytes_data(args)?; let mut cased = false; let mut prev_cased = false; - for &b in &data { + for &b in data.iter() { if b.is_ascii_uppercase() { if prev_cased { return Ok(Object::Bool(false)); @@ -16871,6 +19619,74 @@ pub(crate) fn bytearray_init(args: &[Object]) -> Result { bytearray_init_kw(args, &[]) } +/// `b.append(n)` of a byte value onto a `bytearray` no view exports (a +/// resize under one, like every other argument, is the full method's). +pub(crate) fn bytearray_append_leaf(args: &[Object]) -> Option> { + let [Object::ByteArray(b), Object::Int(v @ 0..=255)] = args else { + return None; + }; + if crate::object::bytearray_is_exported(b) { + return None; + } + b.try_borrow_mut().ok()?.push(*v as u8); + Some(Ok(Object::None)) +} + +/// `b.extend(data)` of a `bytes` or another `bytearray` onto a +/// `bytearray` no view exports. +pub(crate) fn bytearray_extend_leaf(args: &[Object]) -> Option> { + let [Object::ByteArray(b), data] = args else { + return None; + }; + if crate::object::bytearray_is_exported(b) { + return None; + } + match data { + Object::Bytes(s) => b.try_borrow_mut().ok()?.extend_from_slice(s), + Object::ByteArray(s) if !Rc::ptr_eq(s, b) => { + let s = s.try_borrow().ok()?; + b.try_borrow_mut().ok()?.extend_from_slice(&s); + } + // A list or tuple of ints in `range(256)`, checked whole first (any + // other item is the full method's to convert or refuse). + Object::List(_) | Object::Tuple(_) => { + let push = |items: &[Object]| -> Option<()> { + if !items + .iter() + .all(|v| matches!(v, Object::Int(i) if (0..256).contains(i))) + { + return None; + } + let mut out = b.try_borrow_mut().ok()?; + out.extend(items.iter().map(|v| match v { + Object::Int(i) => *i as u8, + _ => 0, + })); + Some(()) + }; + match data { + Object::List(l) => push(&l.try_borrow().ok()?)?, + Object::Tuple(t) => push(t)?, + _ => return None, + } + } + _ => return None, + } + Some(Ok(Object::None)) +} + +/// `b.pop()`: the last byte of a non-empty `bytearray` no view exports. +pub(crate) fn bytearray_pop_leaf(args: &[Object]) -> Option> { + let [Object::ByteArray(b)] = args else { + return None; + }; + if crate::object::bytearray_is_exported(b) { + return None; + } + let byte = b.try_borrow_mut().ok()?.pop()?; + Some(Ok(Object::Int(i64::from(byte)))) +} + fn bytearray_append(args: &[Object]) -> Result { let b = bytearray_self(args)?; let value = args @@ -17087,6 +19903,10 @@ pub(crate) fn file_self(args: &[Object]) -> Result, Ru /// `ValueError("I/O operation on closed file.")` (`test_io.test_io_after_close`). pub(crate) fn file_check_open(f: &Rc) -> Result<(), RuntimeError> { if *f.closed.borrow() { + // (CPython's `StringIO` words it without the period.) + if f.io_kind.get() == crate::object::IoKind::StringIO { + return Err(value_error("I/O operation on closed file")); + } return Err(value_error("I/O operation on closed file.")); } Ok(()) @@ -17154,7 +19974,34 @@ pub(crate) fn file_read(args: &[Object]) -> Result { f.io_kind.get(), crate::object::IoKind::Raw | crate::object::IoKind::BytesIO ); - match f.read_bytes_opt(n)? { + // A buffered sized read of a disk file: straight into the result's + // storage when one read fills it. + #[cfg(unix)] + let first = match (buffered, n) { + (true, Some(want)) => match f.read_sized_shared(want) { + Some(r) => match r? { + Ok(full) => return Ok(full), + Err(partial) => Some(Some(partial)), + }, + None => None, + }, + _ => None, + }; + #[cfg(not(unix))] + let first = None; + // A read to the end of a regular file: sized by its length, into + // the result's storage. + #[cfg(unix)] + if n.is_none() { + if let Some(r) = f.read_all_shared() { + return r; + } + } + let first = match first { + Some(read) => read, + None => f.read_bytes_opt(n)?, + }; + match first { Some(mut data) => { // A *buffered* size-`n` read keeps issuing raw reads until it // has `n` bytes or hits EOF/would-block — a raw read cut @@ -17326,9 +20173,29 @@ pub(crate) fn file_readinto(args: &[Object]) -> Result { )); } let capacity = mv.len.get(); + let start = mv.start.get(); + // A buffered file's read of less than half its buffer, through the + // read-ahead (the view's storage borrowed only to copy each run). + #[cfg(unix)] + { + let mut at = 0; + let served = f.readinto_buffered(capacity, |run| { + let took = mv.buffer.with_write(|d| { + let n = run.len().min(capacity - at); + d.get_mut(start + at..start + at + n)? + .copy_from_slice(&run[..n]); + Some(n) + }); + let n = took.flatten().unwrap_or(0); + at += n; + n + }); + if let Some(n) = served { + return Ok(Object::Int(n? as i64)); + } + } let bytes = f.read_bytes(Some(capacity))?; let n = bytes.len(); - let start = mv.start.get(); let wrote = mv .buffer .with_write(|d| d[start..start + n].copy_from_slice(&bytes)); @@ -17387,6 +20254,24 @@ pub(crate) fn file_readinto(args: &[Object]) -> Result { } }; let capacity = target.borrow().len(); + // A buffered file's read of less than half its buffer, through the + // read-ahead (the target borrowed only to copy each run). + #[cfg(unix)] + { + let mut at = 0; + let served = f.readinto_buffered(capacity, |run| { + let Ok(mut dst) = target.try_borrow_mut() else { + return 0; + }; + let n = run.len().min(dst.len().saturating_sub(at)); + dst[at..at + n].copy_from_slice(&run[..n]); + at += n; + n + }); + if let Some(n) = served { + return Ok(Object::Int(n? as i64)); + } + } let bytes = f.read_bytes(Some(capacity))?; let n = bytes.len(); target.borrow_mut()[..n].copy_from_slice(&bytes); @@ -17559,13 +20444,122 @@ fn file_write_fast(args: &[Object]) -> Option> { } f.stdout_write_pure(s).map(|r| r.map(|()| count())) } - [Object::File(f), Object::Bytes(b)] => f - .write_bytes_pure(b) + [Object::File(f), Object::Bytes(b)] => (f.write_bytes_pure(b) || f.mem_bytes_append(b)) .then(|| Ok(Object::Int(b.len() as i64))), + // (A buffer's bytes, read in place, into a `BytesIO`: the stream's + // own buffer is refused by the append, which can't borrow it.) + [Object::File(f), Object::ByteArray(b)] => { + let b = b.try_borrow().ok()?; + f.mem_bytes_append(&b) + .then(|| Ok(Object::Int(b.len() as i64))) + } + // (A live one-dimensional view of unsigned bytes, likewise; a view + // of the stream's own buffer is an export the append refuses.) + [Object::File(f), Object::MemoryView(mv)] if !mv.released.get() => { + let (start, len) = crate::mv_plain_bytes(mv)?; + mv.buffer.with_read(|all| { + let data = all.get(start..start.checked_add(len)?)?; + f.mem_bytes_append(data) + .then(|| Ok(Object::Int(len as i64))) + }) + } _ => None, } } +/// `f.tell()` of an open `BytesIO`: its position. A leaf half, like +/// [`file_write_fast`]. +fn file_tell_fast(args: &[Object]) -> Option> { + let [Object::File(f)] = args else { + return None; + }; + let p = f.mem_bytes_tell()?; + Some(Ok(Object::Int(i64::try_from(p).ok()?))) +} + +/// `f.seek(n)` or `f.seek(n, 0)` of an open `BytesIO`, `n` not negative: +/// the new position. A leaf half, like [`file_write_fast`]. +fn file_seek_fast(args: &[Object]) -> Option> { + let (f, at) = match args { + [Object::File(f), Object::Int(n)] | [Object::File(f), Object::Int(n), Object::Int(0)] => { + (f, *n) + } + _ => return None, + }; + let at_usize = usize::try_from(at).ok()?; + f.mem_bytes_seek(at_usize)?; + Some(Ok(Object::Int(at))) +} + +/// `BytesIO.getvalue()` or `StringIO.getvalue()` of an open stream: the +/// contents, as the full method returns them. A leaf half, like +/// [`file_write_fast`]. +fn file_getvalue_fast(args: &[Object]) -> Option> { + let [Object::File(f)] = args else { + return None; + }; + if let Some(v) = f.mem_value_cached() { + return Some(Ok(v)); + } + if f.is_closed() { + return None; + } + f.getvalue().map(Ok) +} + +/// `f.read([n])` of an open `BytesIO`: its bytes at the position, copied +/// once into the result. A leaf half, like [`file_write_fast`]. +fn file_read_fast(args: &[Object]) -> Option> { + let (f, n) = match args { + [Object::File(f)] | [Object::File(f), Object::None] => (f, None), + [Object::File(f), Object::Int(n)] => (f, usize::try_from(*n).ok()), + _ => return None, + }; + if f.binary { + if let Some(v) = f.mem_bytes_read_with(n, |run| (Object::new_bytes(run), run.len())) { + return Some(Ok(v)); + } + // (A buffered disk file's read the read-ahead holds whole.) + return n.and_then(|n| f.read_ahead_pure(n)).map(Ok); + } + f.mem_text_read_ascii(n).map(Ok) +} + +/// `f.readinto(b)` of an open `BytesIO` into a `bytearray` no view +/// exports, or a live, writable, contiguous `memoryview`: the bytes copied +/// straight from the stream. A leaf half, like [`file_write_fast`]. +fn file_readinto_fast(args: &[Object]) -> Option> { + let [Object::File(f), target] = args else { + return None; + }; + // (A `BytesIO`'s bytes where they are; a buffered file's from its + // read-ahead when that holds the whole target.) + let fill = |dst: &mut [u8]| { + let room = dst.len(); + f.mem_bytes_read_with(Some(room), |run| { + dst[..run.len()].copy_from_slice(run); + (run.len(), run.len()) + }) + .or_else(|| { + f.read_ahead_into(room, |run| dst.copy_from_slice(run)) + .map(|()| room) + }) + }; + let copied = match target { + Object::ByteArray(b) => fill(&mut b.try_borrow_mut().ok()?)?, + Object::MemoryView(mv) + if !mv.released.get() && !mv.readonly.get() && mv.is_c_contiguous() => + { + let (start, room) = (mv.start.get(), mv.len.get()); + mv.buffer + .with_write(|all| fill(all.get_mut(start..start + room)?)) + .flatten()? + } + _ => return None, + }; + Some(Ok(Object::Int(copied as i64))) +} + /// `f.readline()` when a whole line waits in the stream's buffer (see /// `PyFile::next_line_pure`). A leaf half, like [`file_write_fast`]. fn file_readline_fast(args: &[Object]) -> Option> { @@ -17653,6 +20647,9 @@ pub(crate) fn file_write(args: &[Object]) -> Result { if !f.binary { return Err(type_error("string argument expected, got 'memoryview'")); } + // (A released view's `ValueError`, a strided one's + // `BufferError`, as CPython's `PyBUF_SIMPLE` request raises.) + data.check_simple_buffer()?; f.write_bytes(&mv.to_bytes())? } // A `str`/`bytes` subclass instance writes its wrapped native @@ -18290,6 +21287,7 @@ pub(crate) fn file_setstate_mem(args: &[Object]) -> Result }; let pos = pos_from_state(&items[1], "second")?; if let FileBackend::MemBytes { data, pos: bpos } = &mut *f.backend.borrow_mut() { + f.mem_changed(); *data.borrow_mut() = buf; *bpos = pos; } @@ -18437,7 +21435,9 @@ fn memoryview_tobytes( ) -> Result { let mv = memoryview_self(args)?; if mv.released.get() { - return Err(value_error("memoryview: released")); + return Err(value_error( + "operation forbidden on released memoryview object", + )); } // `tobytes(order=None)`: 'C'/None gather row-major, 'F' column-major, // 'A' follows the view's own layout ('F' only when Fortran-contiguous). @@ -18471,9 +21471,9 @@ fn memoryview_tobytes( _ => false, }; if !fortran { - return Ok(Object::Bytes(SharedSlice::from( - mv.to_bytes().into_boxed_slice(), - ))); + // (A contiguous view's bytes go straight into the result; a + // strided one's are gathered first.) + return Ok(Object::Bytes(mv.with_bytes(|b| SharedSlice::from(b)))); } // Fortran gather: first index varies fastest. let shape = mv.shape_dims(); @@ -18505,12 +21505,25 @@ fn memoryview_tobytes( fn memoryview_tolist(args: &[Object]) -> Result { let mv = memoryview_self(args)?; if mv.released.get() { - return Err(value_error("memoryview: released")); + return Err(value_error( + "operation forbidden on released memoryview object", + )); } // CPython `memoryview.tolist` unpacks elements per the view's format // (`'l'` → ints, `'d'` → floats, …), nesting one list per dimension. // Non-native / multi-member formats raise NotImplementedError // (`adjust_fmt` parity). + // (A contiguous one-dimensional view of unsigned bytes: its bytes, as + // ints, in one pass.) + if mv.itemsize.get() == 1 + && !mv.zero_dim.get() + && mv.shape.borrow().is_empty() + && mv.format.borrow().as_str() == "B" + && mv.is_c_contiguous() + { + let items = mv.with_bytes(|run| run.iter().map(|&b| Object::Int(i64::from(b))).collect()); + return Ok(Object::new_list(items)); + } let shape = mv.shape_dims(); let fmt = crate::mv_adjust_fmt(&mv.format.borrow())?; // Recurse one dimension per level, accumulating the multi-index; @@ -18864,7 +21877,7 @@ fn memoryview_cast(args: &[Object], kwargs: &[(String, Object)]) -> Result Result { .get(1) .cloned() .ok_or_else(|| type_error("isdisjoint() expected an argument"))?; + // A keys view against a view or a set: on their tables. + if let Some(r) = crate::keys_disjoint(&args[0], &other) { + return Ok(Object::Bool(r)); + } let mut other_iter = other.make_iter()?; // `DictKey` is hashable like CPython's dict keys; the inner Rcs are // borrowed read-only during hashing, so the mutable-key-type lint diff --git a/crates/weavepy-vm/src/descr_registry.rs b/crates/weavepy-vm/src/descr_registry.rs index a68cef0e8..000420a64 100644 --- a/crates/weavepy-vm/src/descr_registry.rs +++ b/crates/weavepy-vm/src/descr_registry.rs @@ -86,7 +86,8 @@ fn note_key(k: usize) { /// under the lock and dropped after it is released (their drops can /// re-enter here). pub(crate) fn forget(k: usize) { - if !TAGGED.write().remove(&k) { + // (The common case, a builtin no table knows, under the read lock.) + if !TAGGED.read().contains(&k) || !TAGGED.write().remove(&k) { return; } DESCR_META.write().remove(&k); @@ -98,6 +99,8 @@ pub(crate) fn forget(k: usize) { LIVE_C_DOC.write().remove(&k); let writable = BUILTIN_WRITABLE_MODULE.write().remove(&k); drop(writable); + let doc = BUILTIN_DOC.write().remove(&k); + drop(doc); } /// The stored form of [`DescrMeta`]. `objclass` is held *weakly*: the @@ -279,6 +282,30 @@ pub fn is_native_descr_accessor(b: &Rc) -> bool { static BUILTIN_WRITABLE_MODULE: LazyLock>> = LazyLock::new(|| parking_lot::RwLock::new(HashMap::default())); +/// The docstring a native function carries in place of the Python +/// method it replaced (a `decimal` method's). PROCESS-GLOBAL for the same +/// reason as [`BUILTIN_MODULE`]. +static BUILTIN_DOC: LazyLock>> = + LazyLock::new(|| parking_lot::RwLock::new(HashMap::default())); + +/// Give the builtin `obj` the docstring `doc` (a `str`). +pub fn register_doc(obj: &Object, doc: Object) { + if let Some(k) = key(obj) { + note_key(k); + BUILTIN_DOC.write().insert(k, doc); + } +} + +/// The docstring given to `obj` by [`register_doc`], if any. +pub fn doc_of(obj: &Object) -> Option { + let k = key(obj)?; + // (Almost no builtin has one: the tagged set answers first.) + if !TAGGED.read().contains(&k) { + return None; + } + BUILTIN_DOC.read().get(&k).cloned() +} + /// Record a runtime `__module__` assignment on a builtin function. /// Returns `false` if `obj` is not a taggable representation. pub fn set_builtin_module(obj: &Object, value: Object) -> bool { diff --git a/crates/weavepy-vm/src/dictmap.rs b/crates/weavepy-vm/src/dictmap.rs index 8e3b3ad11..0d7eaf1ce 100644 --- a/crates/weavepy-vm/src/dictmap.rs +++ b/crates/weavepy-vm/src/dictmap.rs @@ -14,11 +14,19 @@ //! compares the slot's half-hash before it touches an entry, and an entry //! only when the full stored hash matches, so a key's `__eq__` runs only //! against keys of equal hash, as in CPython. Removal shifts the run that -//! follows a freed slot back over it, so there are no tombstones. +//! follows a freed slot back over it, so the slot table has no tombstones. //! -//! Positions are dense: removing an entry shifts the later ones down, so -//! `get_index(i)` is always the `i`-th key in order (the contract the -//! iterators and the position caches rely on). +//! Positions are dense: `get_index(i)` is always the `i`-th key in order +//! (the contract the iterators and the position caches rely on), and +//! removing a key moves the later ones down by one. Moving them in memory +//! costs time in proportion to the entries behind the key, so the removals +//! a program makes in bulk (`del d[k]`, `d.pop(k)`, an `OrderedDict`'s) +//! leave a tombstone in the entry list instead +//! ([`Table::lazy_remove_index`]). Positions stay dense all the same: a +//! rank index over the tombstones ([`Holes`]) turns a position into its +//! entry and back, and the table closes the gaps in one pass when the +//! entry list fills or the tombstones outnumber the keys. A table that has +//! no tombstone (nearly every table) pays one test per positional access. //! //! A lookup takes any [`Probe`]: a stored key's own type, or one of the //! borrowed probes in [`crate::object`] (a `&str` name, a native-equality @@ -26,6 +34,7 @@ use crate::object::{DictKey, Object}; use std::fmt; +use std::sync::atomic::{AtomicU64, Ordering}; /// The most entries a table keeps without slots. pub const SMALL: usize = 8; @@ -44,6 +53,31 @@ pub struct Bucket { pub value: V, } +/// Whether `b` is a tombstone: a removed key's place in the entry list, +/// kept until the table closes its gaps (its key is the unbound marker, +/// which no dict stores, and nothing points at it). +#[inline(always)] +fn is_tomb(b: &Bucket) -> bool { + matches!(b.key.0, Object::Unbound) +} + +/// A value a tombstone can hold: one whose drop does nothing. +pub trait Vacant { + fn vacant() -> Self; +} + +impl Vacant for Object { + #[inline(always)] + fn vacant() -> Self { + Object::None + } +} + +impl Vacant for () { + #[inline(always)] + fn vacant() -> Self {} +} + /// A key a table can be probed with: its Python hash and its equality with /// a stored key of the same hash. pub trait Probe { @@ -214,6 +248,20 @@ impl NativeEq for TypeEq<'_> { } } +/// An instance probe hashed by identity: equal to itself (a stored key of +/// equal hash but another identity leaves the lookup undecided). +struct InstEq<'a>(&'a crate::Rc); + +impl NativeEq for InstEq<'_> { + #[inline(always)] + fn native_eq(&self, stored: &DictKey) -> Option { + match &stored.0 { + Object::Instance(u) if crate::Rc::ptr_eq(self.0, u) => Some(true), + _ => None, + } + } +} + /// [`key_bytes_eq`] for a native lookup: in line (calling nothing) up to /// 16 bytes, the commonest keys; a longer pair out of line. #[inline(always)] @@ -238,12 +286,274 @@ fn long_key_bytes_eq(a: &[u8], b: &[u8]) -> bool { /// An ordered hash table from [`DictKey`] to `V` (see the module docs): /// [`DictMap`] for a dict, [`SetMap`] for a set. pub struct Table { + /// The keys in order, with a tombstone wherever a lazy removal took + /// one; the last entry is always a key. entries: Vec>, - /// The slot table: empty for a small table, else a power of two long. - slots: Box<[u64]>, - /// `64 - log2(slots.len())`: the shift that takes a mixed hash to its - /// home slot. + /// The slot table: `1 << (64 - shift)` words this table owns, none + /// (a dangling pointer) for a small table. (One word, not a boxed + /// slice's two: the count is in `shift`.) + slots: std::ptr::NonNull, + /// `64 - log2(the slot count)`: the shift that takes a mixed hash to + /// its home slot; 64 for a small table. shift: u32, + /// How many of `entries` are tombstones. + dead: u32, + /// Where they are, once the table has had one. + holes: Option>, +} + +// SAFETY: the slot words are owned by the table (allocated in +// `alloc_slots`, freed in `free_slots` and on drop) and reached only +// through it, as a boxed slice's would be. +unsafe impl Send for Table {} +// SAFETY: as above. +unsafe impl Sync for Table {} + +impl Drop for Table { + fn drop(&mut self) { + self.free_slots(); + } +} + +/// `n` zeroed slot words (`n` a power of two). +fn alloc_slots(n: usize) -> std::ptr::NonNull { + let words: Box<[u64]> = vec![0u64; n].into_boxed_slice(); + // SAFETY: a box's pointer is never null. + unsafe { std::ptr::NonNull::new_unchecked(Box::into_raw(words).cast::()) } +} + +/// No translation remembered (see [`Holes::last`]). +const NO_PAIR: u64 = u64::MAX; + +/// The most entries a lazy removal moves down, in a table without +/// tombstones, before it leaves a tombstone instead. +const SHIFT_MAX: usize = 16; + +/// Where a table's tombstones are: what turns a key's position (its rank +/// among the keys) into its entry's index and back. +struct Holes { + /// One bit per entry, set for a tombstone. A power of two of words; + /// entries past them are keys. + bits: Vec, + /// A Fenwick tree over the words' tombstone counts: `tree[i]` counts + /// the `i & -i` words that end with word `i - 1` (`tree[0]` is unused). + tree: Vec, + /// Whether `tree` is kept: from the first tombstone past the front + /// run on (until then no position needs a count). + counted: bool, + /// How many entries at the front are tombstones: a table that loses + /// its oldest keys (a queue, a cache that evicts in order) keeps all + /// its tombstones there. + head: usize, + /// The first tombstone past those (or one before it), `usize::MAX` + /// for none: a key below it has its entry `head` past its position. + first: usize, + /// The last translation made, `position << 32 | entry`, or + /// [`NO_PAIR`]: a walk by position continues from it, and a position + /// just found by key is its entry again without a search. + last: AtomicU64, +} + +impl Holes { + fn new() -> Self { + Self { + bits: Vec::new(), + tree: Vec::new(), + counted: false, + head: 0, + first: usize::MAX, + last: AtomicU64::new(NO_PAIR), + } + } + + /// Forget every tombstone (the entries were closed up). + fn reset(&mut self) { + self.bits.fill(0); + self.counted = false; + self.head = 0; + self.first = usize::MAX; + *self.last.get_mut() = NO_PAIR; + } + + /// Entry `p` (not the last) becomes a tombstone, one of `total` now, + /// in an entry list with room for `cap`. + fn mark(&mut self, p: usize, cap: usize, total: usize) { + let w = p / 64; + if w >= self.bits.len() { + let n = cap.max(p + 1).div_ceil(64).next_power_of_two(); + self.bits.resize(n, 0); + if self.counted { + self.count(); + } + } + self.bits[w] |= 1 << (p % 64); + if self.counted { + let mut i = w + 1; + while i < self.tree.len() { + self.tree[i] += 1; + i += i & i.wrapping_neg(); + } + } + if p == self.head { + // The front run grows, through any tombstones that follow it. + self.head = self.next_live(p); + if self.first < self.head { + self.first = if total == self.head { + usize::MAX + } else { + self.next_dead(self.head) + }; + } + } else { + self.first = self.first.min(p); + } + if self.first != usize::MAX && !self.counted { + self.count(); + } + *self.last.get_mut() = NO_PAIR; + } + + /// Build `tree` from `bits`, and keep it from here on. + #[cold] + fn count(&mut self) { + let n = self.bits.len(); + self.tree.clear(); + self.tree.resize(n + 1, 0); + for i in 1..=n { + let c = self.tree[i] + self.bits[i - 1].count_ones(); + self.tree[i] = c; + let up = i + (i & i.wrapping_neg()); + if up <= n { + self.tree[up] += c; + } + } + self.counted = true; + } + + /// The first tombstone at or after entry `p` (`usize::MAX` for none). + /// (Each call from `mark` starts past where the last one ended, so + /// between two resets they read the bits once over.) + fn next_dead(&self, p: usize) -> usize { + let mut w = p / 64; + if w >= self.bits.len() { + return usize::MAX; + } + let mut word = self.bits[w] & (u64::MAX << (p % 64)); + loop { + if word != 0 { + return w * 64 + word.trailing_zeros() as usize; + } + w += 1; + if w >= self.bits.len() { + return usize::MAX; + } + word = self.bits[w]; + } + } + + /// Tombstone `p` is gone (popped off the end of the entries). + fn unmark(&mut self, p: usize) { + let w = p / 64; + self.bits[w] &= !(1 << (p % 64)); + if self.counted { + let mut i = w + 1; + while i < self.tree.len() { + self.tree[i] -= 1; + i += i & i.wrapping_neg(); + } + } + *self.last.get_mut() = NO_PAIR; + } + + /// How many of the `total` tombstones precede entry `p`, one at or + /// past [`Self::first`] (so the tree is kept). + fn rank(&self, p: usize, total: usize) -> usize { + debug_assert!(self.counted); + let w = p / 64; + if w >= self.bits.len() { + return total; + } + let mut n = (self.bits[w] & ((1u64 << (p % 64)) - 1)).count_ones() as usize; + let mut i = w; + while i > 0 { + n += self.tree[i] as usize; + i &= i - 1; + } + n + } + + /// The entry of the `l`-th key, one at or past [`Self::first`] (so the + /// tree is kept). + fn select(&self, l: usize) -> usize { + debug_assert!(self.counted); + let n = self.bits.len(); + // The last word with at most `l` keys before it, by descent. + let (mut word, mut rem, mut k) = (0, l, n); + while k > 0 { + let next = word + k; + if next <= n { + let keys = 64 * k - self.tree[next] as usize; + if keys <= rem { + word = next; + rem -= keys; + } + } + k >>= 1; + } + if word == n { + return 64 * n + rem; + } + // (That word holds more than `rem` keys.) + let mut live = !self.bits[word]; + let mut base = 0; + loop { + let c = (live as u16).count_ones() as usize; + if rem < c { + break; + } + rem -= c; + live >>= 16; + base += 16; + } + let mut low = live as u16; + for _ in 0..rem { + low &= low - 1; + } + 64 * word + base + low.trailing_zeros() as usize + } + + /// The first key's entry after entry `p` (there is one). + fn next_live(&self, p: usize) -> usize { + let mut q = p + 1; + loop { + let w = q / 64; + if w >= self.bits.len() { + return q; + } + let live = !self.bits[w] >> (q % 64); + if live != 0 { + return q + live.trailing_zeros() as usize; + } + q = (w + 1) * 64; + } + } + + /// The last key's entry before entry `p` (there is one). + fn prev_live(&self, p: usize) -> usize { + let mut q = p; + loop { + let w = (q - 1) / 64; + if w >= self.bits.len() { + return q - 1; + } + let upto = (q - 1) % 64 + 1; + let live = !self.bits[w] & (u64::MAX >> (64 - upto)); + if live != 0 { + return w * 64 + 63 - live.leading_zeros() as usize; + } + q = w * 64; + } + } } #[inline(always)] @@ -258,7 +568,6 @@ fn mix(hash: i64) -> u64 { pub(crate) struct TableLayout { pub(crate) entries_ptr: usize, pub(crate) slots_ptr: usize, - pub(crate) slots_len: usize, pub(crate) shift: usize, pub(crate) bucket_size: usize, pub(crate) bucket_hash: usize, @@ -269,16 +578,19 @@ pub(crate) struct TableLayout { } /// [`TableLayout`], read off a sample table (`None` if it isn't the shape -/// the code assumes: a vector's and a boxed slice's words told apart by -/// their values, a 32-bit shift). +/// the code assumes: a vector's words told apart by their values, a +/// one-word slot pointer, a 32-bit shift that reads 64 for a table +/// without slots). pub(crate) fn table_layout() -> Option { let n = SMALL + 4; let mut t: Table = Table::with_capacity(n); for i in 0..n as i64 { t.insert_hashed(i, DictKey(Object::Int(i)), Object::Int(i)); } - if t.slots.is_empty() - || t.entries.capacity() == t.entries.len() && t.entries.len() == t.slots.len() + if t.is_small() + || t.entries.capacity() == t.entries.len() + || Table::::new().shift != 64 + || std::mem::size_of_val(&t.slots) != std::mem::size_of::() { return None; } @@ -289,18 +601,12 @@ pub(crate) fn table_layout() -> Option { let entries_ptr = (0..3) .map(|k| vec_at + 8 * k) .find(|&off| word(off) == t.entries.as_ptr() as usize)?; - let slots_at = std::mem::offset_of!(Table, slots); - let slots_ptr = (0..2) - .map(|k| slots_at + 8 * k) - .find(|&off| word(off) == t.slots.as_ptr() as usize)?; - let slots_len = (0..2) - .map(|k| slots_at + 8 * k) - .find(|&off| word(off) == t.slots.len())?; + let slots_ptr = std::mem::offset_of!(Table, slots); + (word(slots_ptr) == t.slots.as_ptr() as usize).then_some(())?; (std::mem::size_of::() == std::mem::size_of_val(&t.shift)).then_some(())?; Some(TableLayout { entries_ptr, slots_ptr, - slots_len, shift: std::mem::offset_of!(Table, shift), bucket_size: std::mem::size_of::>(), bucket_hash: std::mem::offset_of!(Bucket, hash), @@ -323,21 +629,98 @@ impl Default for Table { } } -impl Clone for Table { +/// A copy of `entries` with room for `extra` more. A dict's or a set's +/// entries are copied whole and their keys' and values' counts then taken +/// in a second pass (a `Bucket` cloned field by field moves each object by +/// way of the stack, at several times the instructions). +fn clone_entries(entries: &[Bucket], extra: usize) -> Vec> { + use std::any::TypeId; + let mut out = Vec::with_capacity(entries.len() + extra); + let valued = TypeId::of::() == TypeId::of::(); + if !valued && TypeId::of::() != TypeId::of::<()>() { + out.extend_from_slice(entries); + return out; + } + // SAFETY: the copy fills `entries.len()` reserved slots, and each + // object copied (a key, and a value where `V` is `Object`: checked + // above) has its count taken before the length covers it; nothing here + // runs code or unwinds, and the bias can't change hands meanwhile. + unsafe { + std::ptr::copy_nonoverlapping(entries.as_ptr(), out.as_mut_ptr(), entries.len()); + let biased = crate::rc::refcounts_biased(); + let retain = |o: &Object| { + if let Some(word) = o.strong_word() { + if biased { + crate::rc::plain_increment(word); + } else { + crate::rc::increment_word(word); + } + } + }; + for b in entries { + retain(&b.key.0); + if valued { + retain(&*std::ptr::from_ref(&b.value).cast::()); + } + } + out.set_len(entries.len()); + } + out +} + +impl Clone for Table { fn clone(&self) -> Self { + if self.dead != 0 { + return self.clone_keys(0); + } Self { - entries: self.entries.clone(), - slots: self.slots.clone(), + entries: clone_entries(&self.entries, 0), + slots: self.clone_slots(), shift: self.shift, + dead: 0, + holes: None, + } + } +} + +impl Table { + /// A copy whose entry list has room for `extra` more entries (a + /// union's), allocated once. + pub fn clone_with_room(&self, extra: usize) -> Self { + if self.dead != 0 { + return self.clone_keys(extra); + } + Self { + entries: clone_entries(&self.entries, extra), + slots: self.clone_slots(), + shift: self.shift, + dead: 0, + holes: None, + } + } + + /// A copy of a table with tombstones, without them. + #[inline(never)] + fn clone_keys(&self, extra: usize) -> Self { + let mut entries = Vec::with_capacity(self.len() + extra); + entries.extend(self.entries.iter().filter(|b| !is_tomb(b)).cloned()); + let mut m = Self { + entries, + slots: std::ptr::NonNull::dangling(), + shift: 64, + dead: 0, + holes: None, + }; + if m.entries.len() > SMALL { + m.rebuild_slots(slots_for(m.entries.len())); } + m } } impl fmt::Debug for Table { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_map() - .entries(self.entries.iter().map(|b| (&b.key, &b.value))) - .finish() + f.debug_map().entries(self.iter()).finish() } } @@ -347,8 +730,10 @@ impl Table { pub fn new() -> Self { Self { entries: Vec::new(), - slots: Box::new([]), + slots: std::ptr::NonNull::dangling(), shift: 64, + dead: 0, + holes: None, } } @@ -356,8 +741,10 @@ impl Table { pub fn with_capacity(n: usize) -> Self { let mut m = Self { entries: Vec::with_capacity(n), - slots: Box::new([]), + slots: std::ptr::NonNull::dangling(), shift: 64, + dead: 0, + holes: None, }; if n > SMALL { m.rebuild_slots(slots_for(n)); @@ -383,8 +770,10 @@ impl Table { unsafe { entries.set_len(n) }; let mut m = Self { entries, - slots: Box::new([]), + slots: std::ptr::NonNull::dangling(), shift: 64, + dead: 0, + holes: None, }; if m.entries.len() > SMALL { m.rebuild_slots(slots_for(m.entries.len())); @@ -401,26 +790,239 @@ impl Table { #[inline] pub fn len(&self) -> usize { - self.entries.len() + self.entries.len() - self.dead as usize } + /// (The last entry is a key, so a table without keys has no entry.) #[inline] pub fn is_empty(&self) -> bool { self.entries.is_empty() } + /// Whether the table has no slots (a probe scans its entries). + #[inline(always)] + fn is_small(&self) -> bool { + self.shift == 64 + } + + /// How many slots the table has. + #[inline(always)] + fn nslots(&self) -> usize { + if self.shift == 64 { + 0 + } else { + 1 << (64 - self.shift) + } + } + + /// The slot count less one, of a table with slots. + #[inline(always)] + fn slot_mask(&self) -> usize { + debug_assert!(!self.is_small()); + (u64::MAX >> (self.shift & 63)) as usize + } + + /// The slot words. + #[cfg(test)] + fn slot_words(&self) -> &[u64] { + // SAFETY: `nslots` words the table owns (none: a dangling + // pointer, which an empty slice may hold). + unsafe { std::slice::from_raw_parts(self.slots.as_ptr(), self.nslots()) } + } + + /// [`Self::slot_words`], to write. + #[inline(always)] + fn slot_words_mut(&mut self) -> &mut [u64] { + // SAFETY: as `slot_words`, and the table is borrowed mutably. + unsafe { std::slice::from_raw_parts_mut(self.slots.as_ptr(), self.nslots()) } + } + + /// Slot `pos` (below the slot count). + #[inline(always)] + fn slot(&self, pos: usize) -> u64 { + debug_assert!(pos < self.nslots()); + // SAFETY: inside the table's slot words, per the caller. + unsafe { *self.slots.as_ptr().add(pos) } + } + + /// Set slot `pos` (below the slot count). + #[inline(always)] + fn set_slot(&mut self, pos: usize, s: u64) { + debug_assert!(pos < self.nslots()); + // SAFETY: as `slot`, and the table is borrowed mutably. + unsafe { *self.slots.as_ptr().add(pos) = s } + } + + /// Give the slot words back: the table is small again. + fn free_slots(&mut self) { + let n = self.nslots(); + if n != 0 { + // SAFETY: the boxed slice `alloc_slots` made, of `n` words, + // which nothing else refers to. + drop(unsafe { + Box::from_raw(std::ptr::slice_from_raw_parts_mut(self.slots.as_ptr(), n)) + }); + self.slots = std::ptr::NonNull::dangling(); + self.shift = 64; + } + } + + /// A copy of the slot words (to go with a copy of `shift`). + fn clone_slots(&self) -> std::ptr::NonNull { + let n = self.nslots(); + if n == 0 { + return std::ptr::NonNull::dangling(); + } + let copy = alloc_slots(n); + // SAFETY: two allocations of `n` words each. + unsafe { std::ptr::copy_nonoverlapping(self.slots.as_ptr(), copy.as_ptr(), n) }; + copy + } + + /// The entry index of position `i` (past the entries for a position + /// past the keys). + #[inline(always)] + fn entry_of(&self, i: usize) -> usize { + if self.dead == 0 { + i + } else { + self.entry_of_holed(i) + } + } + + #[inline(never)] + fn entry_of_holed(&self, i: usize) -> usize { + let Some(h) = self.holes.as_deref() else { + return i; + }; + if i >= self.len() { + return usize::MAX; + } + if i + h.head < h.first { + return i + h.head; + } + let pair = h.last.load(Ordering::Relaxed); + let (at, entry) = ((pair >> 32) as usize, (pair & IX_MASK) as usize); + let p = if pair == NO_PAIR { + h.select(i) + } else if i == at { + return entry; + } else if i == at + 1 { + h.next_live(entry) + } else if i + 1 == at { + h.prev_live(entry) + } else { + h.select(i) + }; + h.last + .store(((i as u64) << 32) | p as u64, Ordering::Relaxed); + p + } + + /// The position of the key in entry `p`. + #[inline(always)] + fn position_of(&self, p: usize) -> usize { + if self.dead == 0 { + p + } else { + self.position_of_holed(p) + } + } + + #[inline(never)] + fn position_of_holed(&self, p: usize) -> usize { + let Some(h) = self.holes.as_deref() else { + return p; + }; + if p < h.first { + return p - h.head; + } + let i = p - h.rank(p, self.dead as usize); + h.last + .store(((i as u64) << 32) | p as u64, Ordering::Relaxed); + i + } + + /// The entries without their tombstones (the slots are stale until + /// rebuilt). + fn drop_tombstones(&mut self) { + if self.dead == 0 { + return; + } + self.entries.retain(|b| !is_tomb(b)); + self.dead = 0; + if let Some(h) = self.holes.as_deref_mut() { + h.reset(); + } + } + + /// Close the tombstones' gaps: the keys move down in order, and the + /// slot table is rebuilt at `n` slots. + #[inline(never)] + fn compact(&mut self, n: usize) { + self.drop_tombstones(); + self.rebuild_slots(n); + } + + /// [`Self::compact`] for an operation that works on the entry list as + /// a whole (a sort, a reversal, a cut). + #[inline(always)] + fn make_dense(&mut self) { + if self.dead != 0 { + self.compact(self.nslots()); + } + } + + /// Pop the tombstones a removal left at the end of the entries. + #[inline(always)] + fn trim(&mut self) { + if self.dead != 0 { + self.trim_holed(); + } + } + + #[inline(never)] + fn trim_holed(&mut self) { + let Some(h) = self.holes.as_deref_mut() else { + return; + }; + while self.entries.last().is_some_and(is_tomb) { + self.entries.pop(); + h.unmark(self.entries.len()); + self.dead -= 1; + } + *h.last.get_mut() = NO_PAIR; + if self.dead == 0 { + h.head = 0; + } + if self.dead as usize == h.head { + h.first = usize::MAX; + } + } + /// How many entries fit before the entry vector reallocates. #[inline] pub fn capacity(&self) -> usize { self.entries.capacity() } - /// The entries in order. + /// The entries in order, of a table that takes no lazy removal (a + /// set's). #[inline] pub fn as_entries(&self) -> &[Bucket] { + debug_assert_eq!(self.dead, 0, "entries with tombstones"); &self.entries } + /// Each key with its stored Python hash, in order. + #[inline] + pub fn hashed_keys(&self) -> impl Iterator { + self.entries + .iter() + .filter(|b| !is_tomb(b)) + .map(|b| (b.hash, &b.key)) + } + /// Make room for `additional` more entries. pub fn reserve(&mut self, additional: usize) { self.entries.reserve(additional); @@ -440,18 +1042,25 @@ impl Table { fn reserve_slots(&mut self, additional: usize) { let want = self.entries.len().saturating_add(additional); - if want > SMALL && (want * 3 > self.slots.len() * 2) { + if want > SMALL && (want * 3 > self.nslots() * 2) { + if self.dead != 0 { + // Tombstones took the room: close them up (see + // `push_growing`). + let keys = self.len().saturating_add(additional); + self.compact(slots_for(keys + keys / 2).max(self.nslots())); + return; + } self.rebuild_slots(slots_for(want)); } } /// Release spare capacity. pub fn shrink_to_fit(&mut self) { + self.make_dense(); self.entries.shrink_to_fit(); if self.entries.len() <= SMALL { - self.slots = Box::new([]); - self.shift = 64; - } else if slots_for(self.entries.len()) < self.slots.len() { + self.free_slots(); + } else if slots_for(self.entries.len()) < self.nslots() { self.rebuild_slots(slots_for(self.entries.len())); } } @@ -466,8 +1075,20 @@ impl Table { // cost about 100 ns (glibc's AVX-512 `memset` stores through a mask // there, apparently taking a microcode assist for the unmapped // page). - if !self.slots.is_empty() { - self.slots.fill(0); + if !self.is_small() { + self.slot_words_mut().fill(0); + } + self.forget_tombstones(); + } + + /// The entry list was emptied: so is the tombstones' index. + #[inline(always)] + fn forget_tombstones(&mut self) { + if self.dead != 0 { + self.dead = 0; + if let Some(h) = self.holes.as_deref_mut() { + h.reset(); + } } } @@ -479,18 +1100,23 @@ impl Table { n <= 1 << 32 && self.entries.len() < IX_MASK as usize, "dict too large" ); - self.slots = vec![0u64; n].into_boxed_slice(); + self.free_slots(); + self.slots = alloc_slots(n); self.shift = 64 - n.trailing_zeros(); let mask = n - 1; + let holed = self.dead != 0; for (i, b) in self.entries.iter().enumerate() { + if holed && is_tomb(b) { + continue; + } let m = mix(b.hash); let mut pos = (m >> self.shift) as usize; // SAFETY: `pos` is masked into the table throughout. unsafe { - while *self.slots.get_unchecked(pos) != 0 { + while *self.slots.as_ptr().add(pos) != 0 { pos = (pos + 1) & mask; } - *self.slots.get_unchecked_mut(pos) = (m & !IX_MASK) | (i as u64 + 1); + *self.slots.as_ptr().add(pos) = (m & !IX_MASK) | (i as u64 + 1); } } } @@ -498,18 +1124,17 @@ impl Table { /// Re-derive the slots after the entries were reordered or dropped in /// bulk. fn reindex(&mut self) { - if self.slots.is_empty() { + if self.is_small() { return; } - self.rebuild_slots(self.slots.len()); + self.rebuild_slots(self.nslots()); } - /// The position of the entry equal to `key` with hash `hash`, or, on a - /// miss, `Err` with the empty slot where it would go (unused for a - /// small table). + /// The entry equal to `key` with hash `hash`, or, on a miss, `Err` with + /// the empty slot where it would go (unused for a small table). #[inline(always)] fn find_hashed(&self, hash: i64, key: &Q) -> Result { - if self.slots.is_empty() { + if self.is_small() { for (i, b) in self.entries.iter().enumerate() { if b.hash == hash && key.probe_eq(&b.key) { return Ok(i); @@ -518,13 +1143,13 @@ impl Table { return Err(0); } let m = mix(hash); - let mask = self.slots.len() - 1; + let mask = self.slot_mask(); let mut pos = (m >> self.shift) as usize; loop { // SAFETY: `pos` is masked into the table, and a nonzero slot // holds a live entry index plus one. unsafe { - let s = *self.slots.get_unchecked(pos); + let s = *self.slots.as_ptr().add(pos); if s == 0 { return Err(pos); } @@ -544,13 +1169,13 @@ impl Table { #[inline] fn slot_of(&self, hash: i64, ix: usize) -> usize { let m = mix(hash); - let mask = self.slots.len() - 1; + let mask = self.slot_mask(); let mut pos = (m >> self.shift) as usize; let want = ix as u64 + 1; loop { // SAFETY: masked into the table; entry `ix` is present, so // the walk ends at its slot before any empty one. - let s = unsafe { *self.slots.get_unchecked(pos) }; + let s = unsafe { *self.slots.as_ptr().add(pos) }; debug_assert!(s != 0, "entry {ix} has no slot"); if s & IX_MASK == want { return pos; @@ -561,11 +1186,11 @@ impl Table { /// Free slot `pos`, shifting back the run after it (no tombstones). fn erase_slot(&mut self, mut pos: usize) { - let mask = self.slots.len() - 1; + let mask = self.slot_mask(); let bits = 64 - self.shift; let mut next = (pos + 1) & mask; loop { - let s = self.slots[next]; + let s = self.slot(next); if s == 0 { break; } @@ -573,28 +1198,35 @@ impl Table { // The entry at `next` may fill the hole when its home is not // strictly between the hole and itself. if (next.wrapping_sub(home) & mask) >= (next.wrapping_sub(pos) & mask) { - self.slots[pos] = s; + self.set_slot(pos, s); pos = next; } next = (next + 1) & mask; } - self.slots[pos] = 0; + self.set_slot(pos, 0); } /// Point the slot of entry `from` (hash `hash`) at entry `to`. #[inline] fn repoint(&mut self, hash: i64, from: usize, to: usize) { let pos = self.slot_of(hash, from); - self.slots[pos] = (self.slots[pos] & !IX_MASK) | (to as u64 + 1); + self.set_slot(pos, (self.slot(pos) & !IX_MASK) | (to as u64 + 1)); } // ---------------------------------------------------------------- // Lookups. - /// The position of the entry equal to `key`. + /// The position of the key equal to `key`. #[inline] pub fn get_index_of(&self, key: &Q) -> Option { - if self.slots.is_empty() { + let p = self.find(key)?; + Some(self.position_of(p)) + } + + /// The entry of the key equal to `key`. + #[inline] + fn find(&self, key: &Q) -> Option { + if self.is_small() { if self.entries.is_empty() { return None; } @@ -624,7 +1256,7 @@ impl Table { /// fast paths, where the call would cost a fair share of the probe. #[inline(always)] pub fn get_hot(&self, key: &Q) -> Option<&V> { - let i = self.get_index_hot(key)?; + let i = self.find_hot(key)?; // SAFETY: a found position is in bounds. Some(unsafe { &self.entries.get_unchecked(i).value }) } @@ -632,11 +1264,12 @@ impl Table { /// A lookup that settles natively, always in line and calling nothing /// (the subscript fast paths that use it need no stack frame): `eq` /// compares the probe with a stored key of equal hash. `Ok(i)` found - /// at `i`, `Err(pos)` exactly absent (`pos` as [`Self::find_hashed`] - /// gives it), `None` undecided. + /// in entry `i` (for [`Self::value_at_unchecked`]; not a position), + /// `Err(pos)` exactly absent (`pos` as [`Self::find_hashed`] gives + /// it), `None` undecided. #[inline(always)] pub fn find_native(&self, hash: i64, eq: &E) -> Option> { - if self.slots.is_empty() { + if self.is_small() { for (i, b) in self.entries.iter().enumerate() { if b.hash == hash && eq.native_eq(&b.key)? { return Some(Ok(i)); @@ -645,12 +1278,12 @@ impl Table { return Some(Err(0)); } let m = mix(hash); - let mask = self.slots.len() - 1; + let mask = self.slot_mask(); let mut pos = (m >> self.shift) as usize; loop { // SAFETY: as in `find_hashed`. unsafe { - let s = *self.slots.get_unchecked(pos); + let s = *self.slots.as_ptr().add(pos); if s == 0 { return Some(Err(pos)); } @@ -703,6 +1336,19 @@ impl Table { self.find_native(hash, &TypeEq(t)) } + /// [`Self::find_native`] for instance `i`, which the caller found + /// hashed by identity (no native value; its class keeps `object`'s + /// `__hash__`). + #[inline(always)] + pub fn find_instance_native( + &self, + i: &crate::Rc, + ) -> Option> { + // (As `identity_hash` hashes an instance.) + let hash = crate::object::pointer_hash(crate::Rc::as_ptr(i).cast()); + self.find_native(hash, &InstEq(i)) + } + /// [`Self::find_object_native`], hashing a `str` key first (as an /// insert would; the hash is cached in the string). #[inline] @@ -729,17 +1375,17 @@ impl Table { if i == self.entries.capacity() { return false; } - if self.slots.is_empty() { + if self.is_small() { if i >= SMALL { return false; } } else { - if (i + 1) * 3 > self.slots.len() * 2 || i >= IX_MASK as usize - 1 { + if (i + 1) * 3 > self.nslots() * 2 || i >= IX_MASK as usize - 1 { return false; } // SAFETY: `pos` is an empty slot inside the table. unsafe { - *self.slots.get_unchecked_mut(pos) = (mix(hash) & !IX_MASK) | (i as u64 + 1); + *self.slots.as_ptr().add(pos) = (mix(hash) & !IX_MASK) | (i as u64 + 1); } } // SAFETY: `i` is below the capacity (checked); the length covers @@ -755,11 +1401,13 @@ impl Table { true } - /// The value at position `i`, which the caller found. + /// The value of entry `i`, which a [`Self::find_native`] of the + /// caller's found. /// /// # Safety /// - /// `i` is below [`Self::len`]. + /// `i` is an entry that lookup gave, with no change to the table + /// since. #[inline(always)] pub unsafe fn value_at_unchecked(&self, i: usize) -> &V { // SAFETY: per the caller. @@ -780,7 +1428,14 @@ impl Table { /// [`Self::get_index_of`], always in line (see [`Self::get_hot`]). #[inline(always)] pub fn get_index_hot(&self, key: &Q) -> Option { - if self.slots.is_empty() { + let p = self.find_hot(key)?; + Some(self.position_of(p)) + } + + /// [`Self::find`], always in line. + #[inline(always)] + fn find_hot(&self, key: &Q) -> Option { + if self.is_small() { if self.entries.is_empty() { return None; } @@ -793,23 +1448,23 @@ impl Table { #[inline] pub fn get(&self, key: &Q) -> Option<&V> { - let i = self.get_index_of(key)?; + let i = self.find(key)?; // SAFETY: a found position is in bounds. Some(unsafe { &self.entries.get_unchecked(i).value }) } #[inline] pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> { - let i = self.get_index_of(key)?; + let i = self.find(key)?; // SAFETY: a found position is in bounds. Some(unsafe { &mut self.entries.get_unchecked_mut(i).value }) } #[inline] pub fn get_full(&self, key: &Q) -> Option<(usize, &DictKey, &V)> { - let i = self.get_index_of(key)?; - let b = &self.entries[i]; - Some((i, &b.key, &b.value)) + let p = self.find(key)?; + let b = &self.entries[p]; + Some((self.position_of(p), &b.key, &b.value)) } #[inline] @@ -817,21 +1472,37 @@ impl Table { &mut self, key: &Q, ) -> Option<(usize, &DictKey, &mut V)> { - let i = self.get_index_of(key)?; - let b = &mut self.entries[i]; + let p = self.find(key)?; + let i = self.position_of(p); + let b = &mut self.entries[p]; Some((i, &b.key, &mut b.value)) } #[inline] pub fn get_key_value(&self, key: &Q) -> Option<(&DictKey, &V)> { - let i = self.get_index_of(key)?; + let i = self.find(key)?; let b = &self.entries[i]; Some((&b.key, &b.value)) } #[inline] pub fn contains_key(&self, key: &Q) -> bool { - self.get_index_of(key).is_some() + self.find(key).is_some() + } + + /// Whether a key equal to `key`, whose Python hash is `hash`, is + /// present (no hash is computed). + #[inline] + pub fn contains_hashed(&self, hash: i64, key: &DictKey) -> bool { + self.find_hashed(hash, key).is_ok() + } + + /// The position of the key equal to `key`, whose Python hash is + /// `hash` (no hash is computed). + #[inline] + pub fn index_hashed(&self, hash: i64, key: &DictKey) -> Option { + let p = self.find_hashed(hash, key).ok()?; + Some(self.position_of(p)) } /// The position of the first entry with Python hash `hash` that `eq` @@ -848,6 +1519,7 @@ impl Table { } self.find_hashed(hash, &Pred(std::cell::RefCell::new(&mut eq))) .ok() + .map(|p| self.position_of(p)) } /// Every stored key with Python hash `hash`, in probe order. @@ -865,7 +1537,7 @@ impl Table { /// The stored Python hash of the entry at `i`. #[inline] pub fn hash_at(&self, i: usize) -> Option { - self.entries.get(i).map(|b| b.hash) + self.entries.get(self.entry_of(i)).map(|b| b.hash) } // ---------------------------------------------------------------- @@ -873,19 +1545,23 @@ impl Table { #[inline] pub fn get_index(&self, i: usize) -> Option<(&DictKey, &V)> { - self.entries.get(i).map(|b| (&b.key, &b.value)) + self.entries + .get(self.entry_of(i)) + .map(|b| (&b.key, &b.value)) } #[inline] pub fn get_index_mut(&mut self, i: usize) -> Option<(&DictKey, &mut V)> { - self.entries.get_mut(i).map(|b| (&b.key, &mut b.value)) + let p = self.entry_of(i); + self.entries.get_mut(p).map(|b| (&b.key, &mut b.value)) } /// Mutable access to a key in place. The caller must keep its hash /// and equality unchanged. #[inline] pub fn get_index_mut2(&mut self, i: usize) -> Option<(&mut DictKey, &mut V)> { - self.entries.get_mut(i).map(|b| (&mut b.key, &mut b.value)) + let p = self.entry_of(i); + self.entries.get_mut(p).map(|b| (&mut b.key, &mut b.value)) } #[inline] @@ -902,19 +1578,19 @@ impl Table { // Insertion. /// Append `key` (hash `hash`), known to be absent, at slot `pos` (from - /// a missed [`Self::find_hashed`]): its position. + /// a missed [`Self::find_hashed`]): its entry. #[inline(always)] fn push_at(&mut self, pos: usize, hash: i64, key: DictKey, value: V) -> usize { let i = self.entries.len(); - if self.slots.is_empty() { + if self.is_small() { if i < SMALL { self.entries.push(Bucket { hash, key, value }); return i; } - } else if (i + 1) * 3 <= self.slots.len() * 2 && i < IX_MASK as usize - 1 { + } else if (i + 1) * 3 <= self.nslots() * 2 && i < IX_MASK as usize - 1 { // SAFETY: `pos` is an empty slot inside the table. unsafe { - *self.slots.get_unchecked_mut(pos) = (mix(hash) & !IX_MASK) | (i as u64 + 1); + *self.slots.as_ptr().add(pos) = (mix(hash) & !IX_MASK) | (i as u64 + 1); } self.entries.push(Bucket { hash, key, value }); return i; @@ -926,12 +1602,23 @@ impl Table { /// table is rebuilt larger with it. #[inline(never)] fn push_growing(&mut self, bucket: Bucket) -> usize { + if self.dead != 0 { + // Tombstones took the room: close them up instead, in a table + // with room for half as many keys again (so a table that loses + // a key for each it gains makes this pass once per that many). + let keys = self.len() + 1; + self.drop_tombstones(); + let i = self.entries.len(); + self.entries.push(bucket); + self.rebuild_slots(slots_for(keys + keys / 2).max(self.nslots())); + return i; + } let i = self.entries.len(); assert!(i < IX_MASK as usize - 1, "dict too large"); - let n = if self.slots.is_empty() { + let n = if self.is_small() { slots_for(i + 1) } else { - self.slots.len() * 2 + self.nslots() * 2 }; self.entries.push(bucket); self.rebuild_slots(n); @@ -945,12 +1632,13 @@ impl Table { pub fn insert_full(&mut self, key: DictKey, value: V) -> (usize, Option) { if let Some((hash, r)) = self.find_object_hashing(&key.0) { return match r { - Ok(i) => { - // SAFETY: a found position. - let slot = unsafe { &mut self.entries.get_unchecked_mut(i).value }; - (i, Some(std::mem::replace(slot, value))) + Ok(p) => { + // SAFETY: a found entry. + let slot = unsafe { &mut self.entries.get_unchecked_mut(p).value }; + let old = std::mem::replace(slot, value); + (self.position_of(p), Some(old)) } - Err(pos) => (self.push_at(pos, hash, key, value), None), + Err(pos) => (self.push_last(pos, hash, key, value), None), }; } let hash = key.probe_hash(); @@ -961,15 +1649,23 @@ impl Table { #[inline] pub fn insert_hashed(&mut self, hash: i64, key: DictKey, value: V) -> (usize, Option) { match self.find_hashed(hash, &key) { - Ok(i) => { - // SAFETY: a found position is in bounds. - let slot = unsafe { &mut self.entries.get_unchecked_mut(i).value }; - (i, Some(std::mem::replace(slot, value))) + Ok(p) => { + // SAFETY: a found entry is in bounds. + let slot = unsafe { &mut self.entries.get_unchecked_mut(p).value }; + let old = std::mem::replace(slot, value); + (self.position_of(p), Some(old)) } - Err(pos) => (self.push_at(pos, hash, key, value), None), + Err(pos) => (self.push_last(pos, hash, key, value), None), } } + /// [`Self::push_at`], giving the new key's position (the last). + #[inline(always)] + fn push_last(&mut self, pos: usize, hash: i64, key: DictKey, value: V) -> usize { + let p = self.push_at(pos, hash, key, value); + p - self.dead as usize + } + #[inline] pub fn insert(&mut self, key: DictKey, value: V) -> Option { self.insert_full(key, value).1 @@ -978,16 +1674,16 @@ impl Table { /// Append `key` with Python hash `hash` without looking for an equal /// key: the caller knows there is none. Its position. pub fn insert_unique_hashed(&mut self, hash: i64, key: DictKey, value: V) -> usize { - if self.slots.is_empty() { + if self.is_small() { return self.push_at(0, hash, key, value); } let m = mix(hash); - let mask = self.slots.len() - 1; + let mask = self.slot_mask(); let mut pos = (m >> self.shift) as usize; - while self.slots[pos] != 0 { + while self.slot(pos) != 0 { pos = (pos + 1) & mask; } - self.push_at(pos, hash, key, value) + self.push_last(pos, hash, key, value) } /// The entry for `key`, to read, change, or fill. @@ -1022,58 +1718,34 @@ impl Table { // ---------------------------------------------------------------- // Removal. - /// Remove entry `i`, shifting the later entries down. - pub fn shift_remove_index(&mut self, i: usize) -> Option<(DictKey, V)> { + /// Remove entry `p`, moving the last entry into its place. + fn swap_remove_entry(&mut self, p: usize) -> (DictKey, V) { let n = self.entries.len(); - if i >= n { - return None; - } - if self.slots.is_empty() { - let b = self.entries.remove(i); - return Some((b.key, b.value)); - } - let pos = self.slot_of(self.entries[i].hash, i); - self.erase_slot(pos); - let b = self.entries.remove(i); - // Renumber the entries that moved down: one slot walk each when - // few moved, else one pass over the table. - let moved = n - 1 - i; - if moved * 4 <= self.slots.len() { - for j in i..n - 1 { - let h = self.entries[j].hash; - self.repoint(h, j + 1, j); - } - } else { - let above = i as u64 + 1; - for s in self.slots.iter_mut() { - if *s & IX_MASK > above { - *s -= 1; - } + if !self.is_small() { + let pos = self.slot_of(self.entries[p].hash, p); + self.erase_slot(pos); + if p != n - 1 { + let h = self.entries[n - 1].hash; + self.repoint(h, n - 1, p); } } - Some((b.key, b.value)) + let b = self.entries.swap_remove(p); + self.trim(); + (b.key, b.value) } - /// Remove entry `i`, moving the last entry into its place. + /// Remove the key at position `i`, moving the last key into its place. pub fn swap_remove_index(&mut self, i: usize) -> Option<(DictKey, V)> { - let n = self.entries.len(); - if i >= n { + let p = self.entry_of(i); + if p >= self.entries.len() { return None; } - if !self.slots.is_empty() { - let pos = self.slot_of(self.entries[i].hash, i); - self.erase_slot(pos); - if i != n - 1 { - let h = self.entries[n - 1].hash; - self.repoint(h, n - 1, i); - } - } - let b = self.entries.swap_remove(i); - Some((b.key, b.value)) + Some(self.swap_remove_entry(p)) } - /// Put `key` (hash `hash`), known to be absent, in entry `i`'s place, - /// leaving every other entry where it is: the replaced key and value. + /// Put `key` (hash `hash`), known to be absent, in the place of the + /// key at position `i`, leaving every other key where it is: the + /// replaced key and value. pub fn replace_index_unique( &mut self, i: usize, @@ -1081,73 +1753,64 @@ impl Table { key: DictKey, value: V, ) -> Option<(DictKey, V)> { + let i = self.entry_of(i); let old = self.entries.get(i)?.hash; - if !self.slots.is_empty() { + if !self.is_small() { let pos = self.slot_of(old, i); self.erase_slot(pos); let m = mix(hash); - let mask = self.slots.len() - 1; + let mask = self.slot_mask(); let mut pos = (m >> self.shift) as usize; - while self.slots[pos] != 0 { + while self.slot(pos) != 0 { pos = (pos + 1) & mask; } - self.slots[pos] = (m & !IX_MASK) | (i as u64 + 1); + self.set_slot(pos, (m & !IX_MASK) | (i as u64 + 1)); } let b = std::mem::replace(&mut self.entries[i], Bucket { hash, key, value }); Some((b.key, b.value)) } - /// Remove the last entry. + /// Remove the last key. pub fn pop(&mut self) -> Option<(DictKey, V)> { let n = self.entries.len(); if n == 0 { return None; } - if !self.slots.is_empty() { + if !self.is_small() { let pos = self.slot_of(self.entries[n - 1].hash, n - 1); self.erase_slot(pos); } let b = self.entries.pop()?; + self.trim(); Some((b.key, b.value)) } - pub fn shift_remove_full(&mut self, key: &Q) -> Option<(usize, DictKey, V)> { - let i = self.get_index_of(key)?; - let (k, v) = self.shift_remove_index(i)?; - Some((i, k, v)) - } - - pub fn shift_remove_entry(&mut self, key: &Q) -> Option<(DictKey, V)> { - let i = self.get_index_of(key)?; - self.shift_remove_index(i) - } - - pub fn shift_remove(&mut self, key: &Q) -> Option { - self.shift_remove_entry(key).map(|(_, v)| v) - } - pub fn swap_remove(&mut self, key: &Q) -> Option { - let i = self.get_index_of(key)?; - self.swap_remove_index(i).map(|(_, v)| v) + let p = self.find(key)?; + Some(self.swap_remove_entry(p).1) } pub fn swap_remove_full(&mut self, key: &Q) -> Option<(usize, DictKey, V)> { - let i = self.get_index_of(key)?; - let (k, v) = self.swap_remove_index(i)?; + let p = self.find(key)?; + let i = self.position_of(p); + let (k, v) = self.swap_remove_entry(p); Some((i, k, v)) } /// Keep the entries `keep` accepts, in order. pub fn retain(&mut self, mut keep: impl FnMut(&DictKey, &mut V) -> bool) { let n = self.entries.len(); - self.entries.retain_mut(|b| keep(&b.key, &mut b.value)); + self.entries + .retain_mut(|b| !is_tomb(b) && keep(&b.key, &mut b.value)); if self.entries.len() != n { + self.forget_tombstones(); self.reindex(); } } /// Keep the first `len` entries. pub fn truncate(&mut self, len: usize) { + self.make_dense(); if len < self.entries.len() { self.entries.truncate(len); self.reindex(); @@ -1156,12 +1819,15 @@ impl Table { /// Split off the entries from `at` on. pub fn split_off(&mut self, at: usize) -> Self { + self.make_dense(); let tail = self.entries.split_off(at); self.reindex(); let mut out = Self { entries: tail, - slots: Box::new([]), + slots: std::ptr::NonNull::dangling(), shift: 64, + dead: 0, + holes: None, }; if out.entries.len() > SMALL { out.rebuild_slots(slots_for(out.entries.len())); @@ -1174,6 +1840,7 @@ impl Table { &mut self, range: R, ) -> std::vec::IntoIter<(DictKey, V)> { + self.make_dense(); let out: Vec<(DictKey, V)> = self .entries .drain(range) @@ -1183,14 +1850,38 @@ impl Table { out.into_iter() } - /// Move entry `from` to position `to`, shifting the ones between. - pub fn move_index(&mut self, from: usize, to: usize) { - let n = self.entries.len(); - assert!(from < n && to < n, "move_index out of bounds"); - if from == to { + /// Move entry `from` to position `to`, shifting the ones between, in + /// a table without tombstones. + fn rotate_index(&mut self, from: usize, to: usize) { + if self.is_small() { + if from < to { + self.entries[from..=to].rotate_left(1); + } else { + self.entries[to..=from].rotate_right(1); + } return; } - if self.slots.is_empty() { + let (lo, hi) = (from.min(to), from.max(to)); + // A run that is a good share of the table (`move_to_end(k, + // last=False)` of a small dict): one pass over the slots, each + // renumbered by its old index alone, with no probe and no list of + // places. + if (hi - lo + 1) * 4 > self.nslots() { + let (lo1, hi1) = (lo as u64 + 1, hi as u64 + 1); + let (from1, to1) = (from as u64 + 1, to as u64 + 1); + for s in self.slot_words_mut() { + let ix = *s & IX_MASK; + if (lo1..=hi1).contains(&ix) { + let new = if ix == from1 { + to1 + } else if from < to { + ix - 1 + } else { + ix + 1 + }; + *s = (*s & !IX_MASK) | new; + } + } if from < to { self.entries[from..=to].rotate_left(1); } else { @@ -1198,7 +1889,6 @@ impl Table { } return; } - let (lo, hi) = (from.min(to), from.max(to)); // Locate every affected slot before renumbering any. let at: Vec = (lo..=hi) .map(|k| self.slot_of(self.entries[k].hash, k)) @@ -1211,7 +1901,7 @@ impl Table { } else { k + 1 }; - self.slots[pos] = (self.slots[pos] & !IX_MASK) | (new as u64 + 1); + self.set_slot(pos, (self.slot(pos) & !IX_MASK) | (new as u64 + 1)); } if from < to { self.entries[from..=to].rotate_left(1); @@ -1225,17 +1915,19 @@ impl Table { if a == b { return; } - if !self.slots.is_empty() { + let (a, b) = (self.entry_of(a), self.entry_of(b)); + if !self.is_small() { let pa = self.slot_of(self.entries[a].hash, a); let pb = self.slot_of(self.entries[b].hash, b); - self.slots[pa] = (self.slots[pa] & !IX_MASK) | (b as u64 + 1); - self.slots[pb] = (self.slots[pb] & !IX_MASK) | (a as u64 + 1); + self.set_slot(pa, (self.slot(pa) & !IX_MASK) | (b as u64 + 1)); + self.set_slot(pb, (self.slot(pb) & !IX_MASK) | (a as u64 + 1)); } self.entries.swap(a, b); } /// Reverse the order. pub fn reverse(&mut self) { + self.make_dense(); self.entries.reverse(); self.reindex(); } @@ -1245,6 +1937,7 @@ impl Table { &mut self, mut cmp: impl FnMut(&DictKey, &V, &DictKey, &V) -> std::cmp::Ordering, ) { + self.make_dense(); self.entries .sort_by(|a, b| cmp(&a.key, &a.value, &b.key, &b.value)); self.reindex(); @@ -1255,6 +1948,7 @@ impl Table { &mut self, mut cmp: impl FnMut(&DictKey, &DictKey) -> std::cmp::Ordering, ) { + self.make_dense(); self.entries.sort_by(|a, b| cmp(&a.key, &b.key)); self.reindex(); } @@ -1264,42 +1958,209 @@ impl Table { #[inline] pub fn iter(&self) -> Iter<'_, V> { - Iter(self.entries.iter()) + Iter { + left: self.len(), + inner: self.entries.iter(), + } } #[inline] pub fn iter_mut(&mut self) -> IterMut<'_, V> { - IterMut(self.entries.iter_mut()) + IterMut { + left: self.len(), + inner: self.entries.iter_mut(), + } } /// Mutable keys and values. The caller must keep every key's hash and /// equality unchanged. #[inline] pub fn iter_mut2(&mut self) -> IterMut2<'_, V> { - IterMut2(self.entries.iter_mut()) + IterMut2 { + left: self.len(), + inner: self.entries.iter_mut(), + } } #[inline] pub fn keys(&self) -> Keys<'_, V> { - Keys(self.entries.iter()) + Keys { + left: self.len(), + inner: self.entries.iter(), + } } #[inline] pub fn values(&self) -> Values<'_, V> { - Values(self.entries.iter()) + Values { + left: self.len(), + inner: self.entries.iter(), + } } #[inline] pub fn values_mut(&mut self) -> ValuesMut<'_, V> { - ValuesMut(self.entries.iter_mut()) + ValuesMut { + left: self.len(), + inner: self.entries.iter_mut(), + } + } + + pub fn into_keys(mut self) -> impl DoubleEndedIterator + ExactSizeIterator { + self.drop_tombstones(); + std::mem::take(&mut self.entries).into_iter().map(|b| b.key) + } + + pub fn into_values(mut self) -> impl DoubleEndedIterator + ExactSizeIterator { + self.drop_tombstones(); + std::mem::take(&mut self.entries) + .into_iter() + .map(|b| b.value) + } +} + +impl Table { + /// Remove entry `p` of a table with slots. The entries behind it move + /// down, unless the table has tombstones already, or `lazy` and more + /// than [`SHIFT_MAX`] would move: then a tombstone takes its place. + fn remove_entry(&mut self, p: usize, lazy: bool) -> (DictKey, V) { + let n = self.entries.len(); + let pos = self.slot_of(self.entries[p].hash, p); + self.erase_slot(pos); + if p == n - 1 { + let b = self.entries.pop().expect("entry `p`"); + self.trim(); + return (b.key, b.value); + } + let moved = n - 1 - p; + if self.dead == 0 && (!lazy || moved <= SHIFT_MAX) { + let b = self.entries.remove(p); + // Renumber the entries that moved down: one slot walk each + // when few moved, else one pass over the table. + if moved * 4 <= self.nslots() { + for j in p..n - 1 { + let h = self.entries[j].hash; + self.repoint(h, j + 1, j); + } + } else { + let above = p as u64 + 1; + for s in self.slot_words_mut() { + if *s & IX_MASK > above { + *s -= 1; + } + } + } + return (b.key, b.value); + } + let tomb = Bucket { + hash: 0, + key: DictKey(Object::Unbound), + value: V::vacant(), + }; + let b = std::mem::replace(&mut self.entries[p], tomb); + self.dead += 1; + let cap = self.entries.capacity(); + self.holes + .get_or_insert_with(|| Box::new(Holes::new())) + .mark(p, cap, self.dead as usize); + // More tombstones than keys: close them up (a pass over the keys, + // paid for by the removals that made the tombstones). + if self.dead as usize > self.len() + SHIFT_MAX { + self.compact(self.nslots()); + } + (b.key, b.value) + } + + /// Remove entry `p` (see [`Self::remove_entry`]). + #[inline] + fn take(&mut self, p: usize, lazy: bool) -> (DictKey, V) { + if self.is_small() { + let b = self.entries.remove(p); + return (b.key, b.value); + } + self.remove_entry(p, lazy) + } + + /// Remove the key at position `i`, shifting the later entries down. + pub fn shift_remove_index(&mut self, i: usize) -> Option<(DictKey, V)> { + let p = self.entry_of(i); + if p >= self.entries.len() { + return None; + } + Some(self.take(p, false)) + } + + /// Remove the key at position `i`; the later keys' positions go down + /// by one, but their entries may stay where they are, a tombstone in + /// the removed one's place (see the module docs). For a table that + /// loses keys anywhere, many times over: the cost doesn't grow with + /// the keys behind the removed one. + pub fn lazy_remove_index(&mut self, i: usize) -> Option<(DictKey, V)> { + let p = self.entry_of(i); + if p >= self.entries.len() { + return None; + } + Some(self.take(p, true)) + } + + pub fn shift_remove_full(&mut self, key: &Q) -> Option<(usize, DictKey, V)> { + let p = self.find(key)?; + let i = self.position_of(p); + let (k, v) = self.take(p, false); + Some((i, k, v)) + } + + pub fn shift_remove_entry(&mut self, key: &Q) -> Option<(DictKey, V)> { + let p = self.find(key)?; + Some(self.take(p, false)) + } + + pub fn shift_remove(&mut self, key: &Q) -> Option { + self.shift_remove_entry(key).map(|(_, v)| v) + } + + /// [`Self::lazy_remove_index`] of the key equal to `key`. + pub fn lazy_remove_entry(&mut self, key: &Q) -> Option<(DictKey, V)> { + let p = self.find(key)?; + Some(self.take(p, true)) } - pub fn into_keys(self) -> impl DoubleEndedIterator + ExactSizeIterator { - self.entries.into_iter().map(|b| b.key) + /// [`Self::lazy_remove_entry`] if `ok` accepts the key's value (one + /// probe for the test and the removal). + pub fn lazy_remove_entry_if( + &mut self, + key: &Q, + ok: impl FnOnce(&V) -> bool, + ) -> Option<(DictKey, V)> { + let p = self.find(key)?; + if !ok(&self.entries[p].value) { + return None; + } + Some(self.take(p, true)) } - pub fn into_values(self) -> impl DoubleEndedIterator + ExactSizeIterator { - self.entries.into_iter().map(|b| b.value) + /// [`Self::lazy_remove_entry`], giving the value alone. + pub fn lazy_remove(&mut self, key: &Q) -> Option { + self.lazy_remove_entry(key).map(|(_, v)| v) + } + + /// Move the key at position `from` to position `to`, shifting the ones + /// between. A move to the end is a lazy removal and an append. + pub fn move_index(&mut self, from: usize, to: usize) { + let n = self.len(); + assert!(from < n && to < n, "move_index out of bounds"); + if from == to { + return; + } + if to == n - 1 && !self.is_small() { + let p = self.entry_of(from); + let hash = self.entries[p].hash; + let (key, value) = self.remove_entry(p, true); + self.insert_unique_hashed(hash, key, value); + return; + } + self.make_dense(); + self.rotate_index(from, to); } } @@ -1310,7 +2171,7 @@ pub enum Entry<'a, V = Object> { Vacant(VacantEntry<'a, V>), } -/// A present entry. +/// A present entry (`index` is its entry, not its position). #[derive(Debug)] pub struct OccupiedEntry<'a, V = Object> { map: &'a mut Table, @@ -1358,16 +2219,17 @@ impl<'a, V> Entry<'a, V> { pub fn index(&self) -> usize { match self { - Entry::Occupied(e) => e.index, + Entry::Occupied(e) => e.index(), Entry::Vacant(e) => e.map.len(), } } } impl<'a, V> OccupiedEntry<'a, V> { + /// The key's position. #[inline] pub fn index(&self) -> usize { - self.index + self.map.position_of(self.index) } #[inline] @@ -1394,11 +2256,11 @@ impl<'a, V> OccupiedEntry<'a, V> { pub fn insert(&mut self, value: V) -> V { std::mem::replace(self.get_mut(), value) } +} +impl OccupiedEntry<'_, V> { pub fn shift_remove_entry(self) -> (DictKey, V) { - self.map - .shift_remove_index(self.index) - .expect("occupied entry is present") + self.map.take(self.index, false) } pub fn shift_remove(self) -> V { @@ -1429,35 +2291,56 @@ impl ProbeVacancy<'_, V> { /// its position. #[inline] pub fn insert(self, key: DictKey, value: V) -> usize { - self.map.push_at(self.pos, self.hash, key, value) + self.map.push_last(self.pos, self.hash, key, value) } } macro_rules! entry_iter { ($name:ident, $inner:ty, $item:ty, |$b:ident| $map:expr) => { - pub struct $name<'a, V = Object>($inner); + /// (`left` counts the keys ahead: the entries less their + /// tombstones.) + pub struct $name<'a, V = Object> { + inner: $inner, + left: usize, + } impl<'a, V> Iterator for $name<'a, V> { type Item = $item; #[inline] fn next(&mut self) -> Option { - self.0.next().map(|$b| $map) + loop { + let $b = self.inner.next()?; + if !is_tomb(&*$b) { + self.left -= 1; + return Some($map); + } + } } #[inline] fn size_hint(&self) -> (usize, Option) { - self.0.size_hint() + (self.left, Some(self.left)) } #[inline] fn nth(&mut self, n: usize) -> Option { - self.0.nth(n).map(|$b| $map) + if self.left == self.inner.len() { + // No tombstone ahead. + let found = self.inner.nth(n); + self.left = self.inner.len(); + let $b = found?; + return Some($map); + } + for _ in 0..n { + self.next()?; + } + self.next() } #[inline] fn count(self) -> usize { - self.0.len() + self.left } #[inline] @@ -1469,19 +2352,34 @@ macro_rules! entry_iter { impl DoubleEndedIterator for $name<'_, V> { #[inline] fn next_back(&mut self) -> Option { - self.0.next_back().map(|$b| $map) + loop { + let $b = self.inner.next_back()?; + if !is_tomb(&*$b) { + self.left -= 1; + return Some($map); + } + } } #[inline] fn nth_back(&mut self, n: usize) -> Option { - self.0.nth_back(n).map(|$b| $map) + if self.left == self.inner.len() { + let found = self.inner.nth_back(n); + self.left = self.inner.len(); + let $b = found?; + return Some($map); + } + for _ in 0..n { + self.next_back()?; + } + self.next_back() } } impl ExactSizeIterator for $name<'_, V> { #[inline] fn len(&self) -> usize { - self.0.len() + self.left } } @@ -1525,19 +2423,28 @@ entry_iter!( impl Clone for Iter<'_, V> { fn clone(&self) -> Self { - Self(self.0.clone()) + Self { + inner: self.inner.clone(), + left: self.left, + } } } impl Clone for Keys<'_, V> { fn clone(&self) -> Self { - Self(self.0.clone()) + Self { + inner: self.inner.clone(), + left: self.left, + } } } impl Clone for Values<'_, V> { fn clone(&self) -> Self { - Self(self.0.clone()) + Self { + inner: self.inner.clone(), + left: self.left, + } } } @@ -1577,8 +2484,9 @@ impl IntoIterator for Table { type Item = (DictKey, V); type IntoIter = IntoIter; - fn into_iter(self) -> IntoIter { - IntoIter(self.entries.into_iter()) + fn into_iter(mut self) -> IntoIter { + self.drop_tombstones(); + IntoIter(std::mem::take(&mut self.entries).into_iter()) } } @@ -1645,13 +2553,50 @@ impl std::ops::Index for Table { type Output = V; fn index(&self, i: usize) -> &V { - &self.entries[i].value + &self.entries[self.entry_of(i)].value } } /// The table behind a `dict`. pub type DictMap = Table; +impl Table { + /// Drop every entry, in order, without the out-of-line drop of a + /// scalar key or value (an `int` key, a `None` value): a dying dict's + /// release. The entry list keeps its allocation, now empty. + #[inline] + pub(crate) fn clear_entries_inline(&mut self) { + let n = self.entries.len(); + let base = self.entries.as_mut_ptr(); + /// Release `o` in place: nothing for a scalar, a plain decrement + /// for a shared value that isn't its last owner, else its drop. + #[inline(always)] + unsafe fn release(o: *mut Object) { + // SAFETY: per the caller, `o` is a live object dropped once. + unsafe { + if let Some(word) = (*o).strong_word() { + if !crate::rc::try_release_word(word) { + std::ptr::drop_in_place(o); + } + } + } + } + // SAFETY: the length goes to zero first, so a drop that panics + // leaks the rest rather than dropping one twice; each entry is + // released once. + // (A tombstone's key and value are scalars: nothing to release.) + unsafe { + self.entries.set_len(0); + for i in 0..n { + let b = base.add(i); + release(&raw mut (*b).key.0); + release(&raw mut (*b).value); + } + } + self.forget_tombstones(); + } +} + /// The table behind a `set` or `frozenset`: [`Table`]'s entries without /// values (a key and its hash), with the set operations' names. Iteration /// is in insertion order; a removal moves the last entry into the freed @@ -1826,6 +2771,24 @@ impl SetMap { self.0.find_object_native(key) } + /// [`Table::contains_hashed`] over the set's keys. + #[inline] + pub fn contains_hashed(&self, hash: i64, key: &DictKey) -> bool { + self.0.contains_hashed(hash, key) + } + + /// [`Table::index_hashed`] over the set's keys. + #[inline] + pub fn index_hashed(&self, hash: i64, key: &DictKey) -> Option { + self.0.index_hashed(hash, key) + } + + /// [`Table::find_object_hashing`] over the set's keys. + #[inline] + pub fn find_object_hashing(&self, key: &Object) -> Option<(i64, Result)> { + self.0.find_object_hashing(key) + } + /// [`Table::find_type_native`] over the set's keys. #[inline(always)] pub fn find_type_native( @@ -1835,6 +2798,15 @@ impl SetMap { self.0.find_type_native(t) } + /// [`Table::find_instance_native`] over the set's keys. + #[inline(always)] + pub fn find_instance_native( + &self, + i: &crate::Rc, + ) -> Option> { + self.0.find_instance_native(i) + } + /// [`Self::contains`], always in line, for a probe whose hash runs no /// code (the interpreter's membership fast paths). #[inline(always)] @@ -2078,15 +3050,294 @@ mod tests { } fn check(m: &DictMap) { - for (i, b) in m.entries.iter().enumerate() { - assert_eq!(m.get_index_of(&b.key), Some(i)); - } - if !m.slots.is_empty() { - let used = m.slots.iter().filter(|s| **s != 0).count(); + let tombs = m.entries.iter().filter(|b| is_tomb(b)).count(); + assert_eq!(tombs, m.dead as usize); + assert!(!m.entries.last().is_some_and(is_tomb)); + assert_eq!(m.iter().len(), m.len()); + for (i, (key, _)) in m.iter().enumerate() { + assert_eq!(m.get_index_of(key), Some(i)); + assert!(m.get_index(i).is_some_and(|(k, _)| k == key)); + } + assert!(m.get_index(m.len()).is_none()); + if !m.is_small() { + let used = m.slot_words().iter().filter(|s| **s != 0).count(); assert_eq!(used, m.len()); } } + fn int(o: &Object) -> i64 { + match o { + Object::Int(i) => *i, + _ => unreachable!(), + } + } + + /// Every operation, in a random order, against a plain vector of + /// pairs: the same keys at the same positions throughout, whatever + /// tombstones the table holds. + #[test] + fn matches_a_vector_through_lazy_removals() { + let mut seed = 0x2545_F491_4F6C_DD1D_u64; + let mut rnd = move |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as usize % n.max(1) + }; + for round in 0..6 { + let mut m = DictMap::new(); + let mut model: Vec<(i64, i64)> = Vec::new(); + let mut fresh = 0_i64; + let steps = [400_i64, 3000, 3000, 6000, 12_000, 20_000][round]; + // (The first third of a round mostly adds keys, more of them + // in the later rounds; the rest loses more than it adds.) + let grow = [2, 3, 3, 4, 6, 8][round]; + let mut most = 0; + for step in 0..steps { + let n = model.len(); + let op = if step < steps / 3 && rnd(grow) != 0 { + 0 + } else { + rnd(22) + }; + most = most.max(m.dead); + match op { + // A new key (several of every draw, so tables grow). + 0..=2 | 22.. => { + fresh += 1; + let key = fresh * 1024 + (fresh % 3); + let (at, old) = m.insert_full(k(key), Object::Int(step)); + assert!(old.is_none()); + assert_eq!(at, n); + model.push((key, step)); + } + // A present key's value. + 3 if n > 0 => { + let i = rnd(n); + let (at, old) = m.insert_full(k(model[i].0), Object::Int(-1)); + assert_eq!(at, i); + assert_eq!(old.as_ref().map(int), Some(model[i].1)); + model[i].1 = -1; + } + // Lazy removals: by key, by position, the first key. + 4..=6 if n > 0 => { + let i = rnd(n); + let (key, v) = m.lazy_remove_entry(&k(model[i].0)).expect("present"); + assert_eq!((int(&key.0), int(&v)), model.remove(i)); + } + 7 | 8 if n > 0 => { + let i = if op == 7 { 0 } else { rnd(n) }; + let (key, v) = m.lazy_remove_index(i).expect("in range"); + assert_eq!((int(&key.0), int(&v)), model.remove(i)); + } + 9 if n > 0 => { + let i = rnd(n); + let (at, key, v) = m.shift_remove_full(&k(model[i].0)).expect("present"); + assert_eq!(at, i); + assert_eq!((int(&key.0), int(&v)), model.remove(i)); + } + 10 if n > 0 => { + let i = rnd(n); + let (key, v) = m.swap_remove_index(i).expect("in range"); + assert_eq!((int(&key.0), int(&v)), model.swap_remove(i)); + } + 11 if n > 0 => { + let (key, v) = m.pop().expect("a key"); + assert_eq!(Some((int(&key.0), int(&v))), model.pop()); + } + // Moves: to the end (a lazy removal and an append), + // to the front, anywhere. + 12 | 13 if n > 0 => { + let from = rnd(n); + // (A move that isn't to the end closes the gaps, + // so it is the rare one.) + let to = match rnd(60) { + 0 => 0, + 1 => rnd(n), + _ => n - 1, + }; + m.move_index(from, to); + let e = model.remove(from); + model.insert(to, e); + } + 14 if n > 1 => { + let (a, b) = (rnd(n), rnd(n)); + m.swap_indices(a, b); + model.swap(a, b); + } + 15 if n > 0 => { + let i = rnd(n); + fresh += 1; + let key = k(fresh * 1024); + let hash = key.probe_hash(); + let (old, _) = m + .replace_index_unique(i, hash, key, Object::Int(7)) + .expect("in range"); + assert_eq!(int(&old.0), model[i].0); + model[i] = (fresh * 1024, 7); + } + // Reads by position and by key. + 16 if n > 0 => { + let i = rnd(n); + let (key, v) = m.get_index(i).expect("in range"); + assert_eq!((int(&key.0), int(v)), model[i]); + assert_eq!(m.get_index_of(&k(model[i].0)), Some(i)); + assert_eq!(m.get_full(&k(model[i].0)).map(|f| f.0), Some(i)); + assert_eq!(m.hash_at(i), Some(k(model[i].0).probe_hash())); + assert_eq!(int(&m[i]), model[i].1); + assert_eq!(m.first().map(|f| int(&f.0 .0)), Some(model[0].0)); + assert_eq!(m.last().map(|f| int(&f.0 .0)), Some(model[n - 1].0)); + // A walk by position, forward and back. + let from = rnd(n); + for (j, e) in model.iter().enumerate().skip(from).take(40) { + assert_eq!(m.get_index(j).map(|f| int(&f.0 .0)), Some(e.0)); + } + for j in (from.saturating_sub(40)..from).rev() { + assert_eq!(m.get_index(j).map(|f| int(&f.0 .0)), Some(model[j].0)); + } + if let Entry::Occupied(e) = m.entry(k(model[i].0)) { + assert_eq!(e.index(), i); + } else { + panic!("present"); + } + } + // Whole-table operations (rare: each closes the gaps). + 17 if rnd(40) == 0 => match rnd(7) { + 0 => { + m.reverse(); + model.reverse(); + } + 1 => { + m.sort_by_key_with(|a, b| int(&a.0).cmp(&int(&b.0))); + model.sort_by_key(|e| e.0); + } + 2 => { + let keep = rnd(n + 1); + m.truncate(keep); + model.truncate(keep); + } + 3 => { + m.retain(|key, _| int(&key.0) % 5 != 0); + model.retain(|e| e.0 % 5 != 0); + } + 4 => { + let (a, b) = (rnd(n + 1), rnd(n + 1)); + let (a, b) = (a.min(b), a.max(b)); + let got: Vec = m.drain(a..b).map(|e| int(&e.0 .0)).collect(); + let want: Vec = model.drain(a..b).map(|e| e.0).collect(); + assert_eq!(got, want); + } + 5 => { + let at = rnd(n + 1); + let tail = m.split_off(at); + let want = model.split_off(at); + check(&tail); + let got: Vec = tail.keys().map(|key| int(&key.0)).collect(); + assert_eq!(got, want.iter().map(|e| e.0).collect::>()); + } + _ => { + m.shrink_to_fit(); + } + }, + 18 if rnd(20) == 0 => { + let c = m.clone(); + check(&c); + assert_eq!(c.dead, 0); + let got: Vec<(i64, i64)> = c + .into_iter() + .map(|(key, v)| (int(&key.0), int(&v))) + .collect(); + assert_eq!(got, model); + } + 19 if n > 0 => { + let i = rnd(n); + if let Entry::Occupied(e) = m.entry(k(model[i].0)) { + let (key, v) = e.shift_remove_entry(); + assert_eq!((int(&key.0), int(&v)), model.remove(i)); + } + } + 20 => { + if rnd(25) == 0 { + m.reserve(rnd(64)); + } + let absent = k(-5); + assert!(m.get(&absent).is_none()); + assert!(m.lazy_remove(&absent).is_none()); + assert!(m.get_index_of(&absent).is_none()); + } + _ => {} + } + assert_eq!(m.len(), model.len()); + assert_eq!(m.is_empty(), model.is_empty()); + if step % 97 == 0 || m.len() < 40 { + check(&m); + let got: Vec<(i64, i64)> = + m.iter().map(|(key, v)| (int(&key.0), int(v))).collect(); + assert_eq!(got, model); + let back: Vec = m.keys().rev().map(|key| int(&key.0)).collect(); + let want: Vec = model.iter().rev().map(|e| e.0).collect(); + assert_eq!(back, want); + assert_eq!(m.values().len(), model.len()); + let skip = rnd(model.len() + 2); + assert_eq!( + m.keys().nth(skip).map(|key| int(&key.0)), + model.get(skip).map(|e| e.0) + ); + assert_eq!( + m.keys().nth_back(skip).map(|key| int(&key.0)), + model.iter().rev().nth(skip).map(|e| e.0) + ); + for e in &model { + assert_eq!(m.get(&k(e.0)).map(int), Some(e.1)); + } + } + } + // Drained from the front: the first key each time. + while let Some((key, _)) = m.first() { + let key = int(&key.0); + assert_eq!(key, model[0].0); + assert!(m.lazy_remove(&k(key)).is_some()); + model.remove(0); + if model.len().is_multiple_of(64) { + check(&m); + } + } + assert!(m.is_empty() && model.is_empty()); + assert_eq!(m.dead, 0); + assert!(round < 3 || most > 200, "round {round}: {most} tombstones"); + } + } + + /// A table that loses its oldest key for each new one keeps its + /// tombstones bounded by its keys, and a set never has one. + #[test] + fn tombstones_stay_bounded() { + let mut m = DictMap::new(); + for i in 0..1000 { + m.insert(k(i), Object::Int(i)); + } + let mut most = 0; + for i in 1000..60_000_i64 { + m.insert(k(i), Object::Int(i)); + assert!(m.lazy_remove(&k(i - 1000)).is_some()); + most = most.max(m.dead as usize); + assert!(m.entries.len() <= 3 * m.len() + SHIFT_MAX + 1); + } + assert!(most > 0); + assert_eq!(m.len(), 1000); + assert_eq!(m.first().map(|f| int(&f.0 .0)), Some(59_000)); + check(&m); + let mut s = SetMap::new(); + for i in 0..200 { + s.insert(k(i)); + } + for i in 0..150 { + assert!(s.shift_remove(&k(i))); + } + assert_eq!(s.0.dead, 0); + assert_eq!(s.as_entries().len(), 50); + } + #[test] fn insert_remove_order() { let mut m = DictMap::new(); @@ -2125,9 +3376,9 @@ mod tests { for i in 0..8 { m.insert(k(i), Object::Int(i)); } - assert!(m.slots.is_empty()); + assert!(m.is_small()); m.insert(k(8), Object::Int(8)); - assert!(!m.slots.is_empty()); + assert!(!m.is_small()); let c = m.clone(); check(&c); assert_eq!( diff --git a/crates/weavepy-vm/src/error.rs b/crates/weavepy-vm/src/error.rs index 04ad53a15..91ae2fd31 100644 --- a/crates/weavepy-vm/src/error.rs +++ b/crates/weavepy-vm/src/error.rs @@ -263,11 +263,11 @@ pub fn type_error(message: impl Into) -> RuntimeError { ); } } - RuntimeError::PyException(PyException::from_builtin("TypeError", message)) + of_class(|bt| &bt.type_error, message) } pub fn value_error(message: impl Into) -> RuntimeError { - RuntimeError::PyException(PyException::from_builtin("ValueError", message)) + of_class(|bt| &bt.value_error, message) } pub fn name_error(message: impl Into) -> RuntimeError { @@ -373,11 +373,11 @@ pub fn key_error_object(key: crate::object::Object) -> RuntimeError { } pub fn index_error(message: impl Into) -> RuntimeError { - RuntimeError::PyException(PyException::from_builtin("IndexError", message)) + of_class(|bt| &bt.index_error, message) } pub fn zero_division_error(message: impl Into) -> RuntimeError { - RuntimeError::PyException(PyException::from_builtin("ZeroDivisionError", message)) + of_class(|bt| &bt.zero_division_error, message) } /// `LookupError` — CPython raises this (not `ValueError`) for unknown @@ -398,7 +398,7 @@ pub fn memory_error(message: impl Into) -> RuntimeError { } pub fn overflow_error(message: impl Into) -> RuntimeError { - RuntimeError::PyException(PyException::from_builtin("OverflowError", message)) + of_class(|bt| &bt.overflow_error, message) } /// `UnicodeEncodeError` carrying the canonical `(encoding, object, start, @@ -457,7 +457,23 @@ pub fn recursion_error(message: impl Into) -> RuntimeError { } pub fn stop_iteration() -> RuntimeError { - RuntimeError::PyException(PyException::from_builtin("StopIteration", "")) + of_class(|bt| &bt.stop_iteration, "") +} + +/// An exception of the built-in class `class` picks, with `message` (none +/// for an empty one): the common kinds' constructors, with no lookup of +/// the class by name. +#[inline] +fn of_class( + class: impl FnOnce( + &crate::builtin_types::BuiltinTypes, + ) -> &crate::sync::Rc, + message: impl Into, +) -> RuntimeError { + let class = class(crate::builtin_types::builtin_types()).clone(); + RuntimeError::PyException(PyException::new( + crate::builtin_types::make_exception_with_class(class, message), + )) } /// `StopAsyncIteration` (PEP 525) — raised by async iterators to @@ -491,7 +507,7 @@ pub fn not_implemented_error(message: impl Into) -> RuntimeError { } pub fn runtime_error(message: impl Into) -> RuntimeError { - RuntimeError::PyException(PyException::from_builtin("RuntimeError", message)) + of_class(|bt| &bt.runtime_error, message) } pub fn assertion_error(message: impl Into) -> RuntimeError { diff --git a/crates/weavepy-vm/src/frame_jit.rs b/crates/weavepy-vm/src/frame_jit.rs index eddbf1aa5..7b213d98e 100644 --- a/crates/weavepy-vm/src/frame_jit.rs +++ b/crates/weavepy-vm/src/frame_jit.rs @@ -104,6 +104,11 @@ const CHAIN: u32 = 7; /// frame JIT takes it anyway (see `Slot::try_compile`). const LEFT_TO_TIER2: u32 = 16; +/// How many times calls make code hot, after tier 2 missed its call entry +/// and with none of its loops run, before the frame JIT takes it (see +/// `Slot::try_compile`). +const CALL_WAITS: u32 = 128; + /// The heat per instruction of a code object at which it compiles (see /// `Slot::warm`; `WEAVEPY_FRAME_JIT_HOT` overrides it, a tuning aid). With /// the code generator a quarter of Cranelift's cost, 500 took 8% off the @@ -336,6 +341,10 @@ pub(crate) struct State { /// `FoldSink`): a yield it takes resumes the body in place, without /// leaving the native code. Null for none. pub(crate) fold: *const crate::FoldSink, + /// A raise's helper already ran the clause that catches it (see + /// [`blind_raise`]), the state at the instruction after the clause: + /// [`h_catch`] has nothing left to do. + pub(crate) caught: bool, } const S_LOCALS: i32 = 0; @@ -387,6 +396,9 @@ pub(crate) struct Native { /// How many entries at each pc handed its first instruction straight /// back (an iterator or operand its helpers never take). fails: Box<[AtomicU8]>, + /// The stack capacity a suspended generator's short resume asks for + /// (see [`Self::lean_cap`]). + lean_cap: std::sync::atomic::AtomicUsize, /// The code's name, opcodes, stack depths and the stack capacity it /// needs (for `WEAVEPY_FRAME_JIT_STATS`). name: String, @@ -521,6 +533,22 @@ impl Native { .is_some_and(|e| e.load(Ordering::Relaxed)) } + /// The stack capacity a suspended generator's short resume needs (see + /// `Interpreter::gen_lean_resume`): none has (`usize::MAX`) until + /// [`Self::note_lean_cap`] says how deep the code's stack runs. + #[inline(always)] + pub(crate) fn lean_cap(&self) -> usize { + self.lean_cap.load(Ordering::Relaxed) + } + + /// Note that the code's stack is `stacksize` deep (see + /// [`Self::lean_cap`]). + #[inline(always)] + pub(crate) fn note_lean_cap(&self, stacksize: usize) { + self.lean_cap + .store(stacksize.max(self.need), Ordering::Relaxed); + } + /// An entry at `pc` got nowhere: after a few, the core loop stops /// entering there. #[cold] @@ -554,7 +582,7 @@ impl Native { #[cold] #[inline(never)] fn ran(&self, st: &State, from: usize, len: usize, cap: usize, last: usize, status: u32) { - if status == INTERP && st.pc == from && st.last == last { + if status == INTERP && st.pc == from && st.last == last && cap >= self.need { self.note_fail(from); } if stats::enabled() { @@ -584,7 +612,9 @@ impl Native { let (from, len, cap, last) = (st.pc, st.len, st.cap, st.last); // SAFETY: the caller's contract. let status = unsafe { self.call(st) }; - if status == INTERP && st.pc == from && st.last == last { + // (An entry a stack too small for the code turned away says + // nothing of the entry: the caller's next run has the room.) + if status == INTERP && st.pc == from && st.last == last && cap >= self.need { self.note_fail(from); } if stats::enabled() { @@ -621,6 +651,9 @@ pub(crate) struct Slot { /// How many times the code got hot while its loops waited for tier 2 /// (see `try_compile`). left: AtomicU32, + /// How many times calls made the code hot after tier 2 had missed its + /// call entry, with none of its loops run (see `try_compile`). + call_waits: AtomicU32, /// A compile whose machine code a worker is generating (see /// [`background`]). pending: background::Pending, @@ -802,7 +835,50 @@ impl Slot { if left > 0 { self.left.store(left, Ordering::Relaxed); } - if left < LEFT_TO_TIER2 || crate::tier2::holds_compiled(code) { + // (Call heat goes to the frame JIT once tier 2 has missed the + // call entry, which it never attempts again, and the code has + // got hot that way `CALL_WAITS` times with none of its loops + // run: a loop that runs is tier 2's to enter by OSR, and one + // that runs only now and then shouldn't be taken too soon.) + // Code whose loops have run but which tier 2 still holds + // nothing for after `LEFT_TO_TIER2` such triggers runs loops + // too short a call for tier 2 to take (`argparse`'s + // `_get_values`, whose comprehensions it only ever left + // cold): it would otherwise stay interpreted for good. + // A generator-family body has no call entry for tier 2 to + // take (a fresh activation is the bootstrap, the + // interpreter's): with none of its loops run (a coroutine + // whose only loop handles a rare case), nothing else will + // ever compile it. + // (Nor does a large body wait for tier 2 to analyze it, which + // it does only after work in proportion to its length.) + let looped = code.jit_hint.backedges_seen(); + let no_call_entry = code.is_generator || code.is_coroutine || code.is_async_generator; + let large = left == 0 && crate::tier2::waits_for_size(code); + let waits = if looped || no_call_entry || large { + LEFT_TO_TIER2 + } else { + CALL_WAITS + }; + let taken_for_calls = left == 0 + && (looped || no_call_entry || large || crate::tier2::missed_call_entry(code)) + && self.call_waits.fetch_add(1, Ordering::Relaxed) + 1 >= waits; + // (Nor is code tier 2 keeps failing to compile its to keep, nor + // a loop it carved out of its plan for the loop's own code, a + // `with` block's `LOAD_SPECIAL`: no later attempt compiles it.) + let carved_out = match at { + Heat::BackEdge(pc) => code.instructions.get(pc).is_some_and(|ins| { + (pc + 1) + .checked_sub(ins.arg as usize) + .is_some_and(|head| crate::tier2::carved_loop_for_code(code, head)) + }), + _ => false, + }; + let left_to_tier2 = left < LEFT_TO_TIER2 + && !taken_for_calls + && !carved_out + && !crate::tier2::gave_up_often(code); + if left_to_tier2 || (!carved_out && crate::tier2::holds_compiled(code)) { if stats::enabled() { let kind = if left > 0 { "loop" } else { "call" }; eprintln!("frame jit: {} left to tier 2 ({kind})", code.qualname); @@ -1162,6 +1238,17 @@ fn worth_compiling(code: &CodeObject, ext: &CodeConstObjects, at: Heat) -> bool | OpCode::DeleteSubscr | OpCode::GetAwaitable | OpCode::GetYieldFromIter + | OpCode::GetAnext + | OpCode::GetAiter + | OpCode::EndAsyncFor + | OpCode::StoreGlobal + | OpCode::LoadName + | OpCode::StoreName + | OpCode::MatchSequence + | OpCode::MatchMapping + | OpCode::GetLen + | OpCode::MatchKeys + | OpCode::MatchClass | OpCode::Send | OpCode::EndSend | OpCode::BuildSet @@ -1227,6 +1314,8 @@ fn worth_compiling(code: &CodeObject, ext: &CodeConstObjects, at: Heat) -> bool ins_k.op, OpCode::EndFor | OpCode::PopIter | OpCode::ReturnValue ) => {} + // (Only a `throw()` into a suspended `await` reaches it.) + None if ins_k.op == OpCode::CleanupThrow => {} // A resume ends at its yield whether or not the body runs // natively: no round trip to pay for. None if ins_k.op == OpCode::YieldValue @@ -1497,6 +1586,8 @@ struct Tags { instance: u8, /// A Python function's (see [`direct_call`]). function: u8, + /// A class's (see [`records::ctor_enter`]). + class: u8, /// A bound method's (see [`h_unpack_bound`]). bound: u8, /// A list's tag. @@ -1609,6 +1700,9 @@ fn tags() -> Option { cell: tag(&cell), instance: tag(&inst), function: tag(&func), + class: tag(&Object::Type( + crate::builtin_types::builtin_types().object_.clone(), + )), bound: tag(&Object::BoundMethod(Rc::new( crate::object::BoundMethod::new(Object::None, func.clone()), ))), @@ -1764,7 +1858,8 @@ fn in_loop(code: &CodeObject, pc: usize) -> bool { } type Entry = (usize, usize, Rc<[bool]>); thread_local! { - static MEMO: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + static MEMO: crate::gil::ReleaseUnderGil>> = + const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(Vec::new())) }; } let key = (std::ptr::from_ref(code) as usize, code.instructions.len()); MEMO.with(|m| { @@ -1793,8 +1888,9 @@ fn in_loop(code: &CodeObject, pc: usize) -> bool { /// Where an iterator value's state is, from its payload word (its `Rc`'s /// allocation): the cell's borrow counter, the iterator's discriminant -/// byte and the values it takes for a list's and a range's iterator, and -/// their fields (`FOR_ITER` steps them in line, see `Lower::for_iter`). +/// byte and the values it takes for a list's, a tuple's and a range's +/// iterator, and their fields (`FOR_ITER` steps them in line, see +/// `Lower::for_iter`). #[derive(Clone, Copy)] struct IterLayout { tag: u8, @@ -1802,8 +1898,11 @@ struct IterLayout { disc: i32, list_disc: u8, range_disc: u8, + tuple_disc: u8, list_items: i32, list_index: i32, + tuple_items: i32, + tuple_index: i32, range_current: i32, range_stop: i32, range_step: i32, @@ -1811,7 +1910,7 @@ struct IterLayout { /// Where a dict value's table is, from its payload word (its `Rc`'s /// allocation): the cell's borrow counter, the entries' and slots' -/// pointers, the slot count and the shift; an entry's size and its +/// pointers and the shift; an entry's size and its /// hash's, key's and value's places; where a string keeps its cached hash /// (`-1` unknown); and the slot mixing constants (see /// `crate::dictmap::TableLayout`). `BINARY_SUBSCR` probes a `str` key's @@ -1821,7 +1920,6 @@ struct DictLayout { borrow: i32, entries: i32, slots: i32, - slots_len: i32, shift: i32, bucket_size: i64, bucket_hash: i32, @@ -1881,7 +1979,6 @@ fn dict_layout() -> Option { borrow: off(cell + borrow)?, entries: off(base + t.entries_ptr)?, slots: off(base + t.slots_ptr)?, - slots_len: off(base + t.slots_len)?, shift: off(base + t.shift)?, bucket_size: i64::try_from(t.bucket_size).ok()?, bucket_hash: off(t.bucket_hash)?, @@ -1938,9 +2035,12 @@ fn iter_layout() -> Option { stop: (MARK + 2) as i64, step: (MARK + 3) as i64, }); + let tuple_items = crate::tuple_storage::TupleStorage::from_vec(vec![Object::None]); + // SAFETY: a tuple handle is one word, its allocation's address. + let tuple_word = unsafe { std::mem::transmute_copy::<_, usize>(&tuple_items) }; let tuple = iter(PyIterator::Tuple { - items: crate::tuple_storage::TupleStorage::from_vec(Vec::new()), - index: 0, + items: tuple_items, + index: MARK + 4, }); let Object::Iter(rc) = &list else { return None; @@ -1968,8 +2068,11 @@ fn iter_layout() -> Option { disc: i32::try_from(start + data).ok()?, list_disc: ld, range_disc: rd, + tuple_disc: td, list_items: at(&list, items_word)?, list_index: at(&list, MARK)?, + tuple_items: at(&tuple, tuple_word)?, + tuple_index: at(&tuple, MARK + 4)?, range_current: at(&range, MARK + 1)?, range_stop: at(&range, MARK + 2)?, range_step: at(&range, MARK + 3)?, @@ -2156,6 +2259,17 @@ unsafe fn plain_release(v: &Object) -> bool { true } +/// Whether releasing one reference to `v` leaves it alive (another owner +/// holds it) and nothing observes releases: a container holding it can +/// free with no finalizer queued (`for flag in self, other`). +#[inline] +fn held_elsewhere(v: &Object) -> bool { + crate::sync::release_gates() == 0 + && v.strong_word() + // SAFETY: `v` owns a reference to the live allocation. + .is_some_and(|w| unsafe { &*w }.load(Ordering::Relaxed) > 1) +} + /// One operand a flush writes to the frame's stack (see [`h_copies`]). pub(crate) struct CopyItem { /// The stack slot it goes to. @@ -2194,6 +2308,39 @@ unsafe extern "C" fn h_clone(dst: *mut Object, src: *const Object) { /// Release the heap value at `slot` (it leaves the stack): `0` released, /// anything else declined with the slot untouched. +/// Whether releasing the value at `slot` could run code: `0` when it is +/// droppable (see [`droppable`]), `1` otherwise. +unsafe extern "C" fn h_droppable(slot: *const Object) -> u32 { + // SAFETY: the code passes an initialized stack slot. + u32::from(!droppable(unsafe { &*slot })) +} + +/// A stack receiver's kernel ran (see `stack_method_kernel`): the +/// receiver at `recv` released as the full call releases its operands +/// (promptly reaped: a temporary it was the last owner of dies here, its +/// finalizers before the next instruction) and the result at `out` moved +/// into its slot: `0`, or `LEFT_MARKED` past the `CALL` at `pc` (the +/// result on the stack, `len` deep) when a finalizer must run first, as +/// [`call_status`] leaves after a call. +unsafe extern "C" fn h_kernel_result( + st: *mut State, + recv: *mut Object, + out: *mut Object, + pc: u32, + len: u32, +) -> u32 { + // SAFETY: the code passes its live state, the receiver's initialized + // slot and the kernel's result in the slot above it. + unsafe { + crate::release_operands(&*(*st).interp, recv, 1); + recv.write(out.read()); + if (*(*st).maybe_dead).get() { + return left_marked(st, pc, len as usize); + } + } + 0 +} + unsafe extern "C" fn h_pop(slot: *mut Object) -> u32 { // SAFETY: the code passes an initialized stack slot. unsafe { @@ -2287,6 +2434,60 @@ pub(crate) struct BinopSite { direct: *mut DirectSite, /// Whether to try a comparison method. dunder: bool, + /// Whether an error raises through the code's handlers (not in an + /// inlined body): the code writes anything virtual out on the status. + raisable: bool, + /// For `x = x + t` (or `x += t`) of a local `x` whose store comes + /// next: `x`'s index, so that a `str` nothing else holds grows in + /// place (see [`str_grow_local`]); `NO_GROW` otherwise. + grow_local: u32, +} + +/// No local grows in place at a [`BinopSite`]. +const NO_GROW: u32 = u32::MAX; + +/// `x = x + t` at a site whose operands are on the stack and whose next +/// instruction stores into the local `x` the left operand came from: when +/// both are `str`s and the left one is `x`'s own string, `x` lets go of it +/// and it grows in place if nothing else holds it (CPython's +/// `BINARY_OP_INPLACE_ADD_UNICODE`, and the core loop's arm), which makes +/// a string built by appending in a loop cost its length once instead of +/// once per append. `true` with the grown string in the left operand's +/// slot, the right one released and `x` left unbound for the store that +/// follows; `false` with everything as it was. +/// +/// # Safety +/// +/// The state is live, the site's two slots hold its operands, and +/// `grow_local` is one of the frame's locals. +#[inline] +unsafe fn str_grow_local(st: *mut State, s: &BinopSite) -> bool { + use crate::shared_value::SharedStr; + // SAFETY: the caller's contract. + unsafe { + let at = (*st).stack.add(s.slot as usize); + let local = (*st).locals.add(s.grow_local as usize); + if !matches!( + (&*local, &*at, &*at.add(1)), + (Object::Str(x), Object::Str(a), Object::Str(_)) if SharedStr::ptr_eq(x, a) + ) { + return false; + } + // (The operand holds the string too: a plain decrement.) + crate::drop_hot(std::ptr::replace(local, Object::Unbound)); + let grown = match (&mut *at, &*at.add(1)) { + (Object::Str(a), Object::Str(t)) => SharedStr::try_append(a, t), + _ => false, + }; + if grown { + crate::drop_hot_at(at.add(1)); + return true; + } + // Held elsewhere: `x` takes it back, and the ordinary + // concatenation runs. + local.write(crate::clone_hot(&*at)); + false + } } /// `BINARY_OP` at `site` through [`h_binop`], then an operator method that @@ -2300,9 +2501,31 @@ unsafe extern "C" fn h_binop_site(st: *mut State, site: *const BinopSite) -> u32 if !s.copies.is_empty() { h_copies(st, s.copies.as_ptr(), s.copies.len() as u64); } - if h_binop((*st).stack.add(s.slot as usize), s.arg) == 0 { + if s.grow_local != NO_GROW && str_grow_local(st, s) { return 0; } + match h_binop((*st).stack.add(s.slot as usize), s.arg) { + 0 => return 0, + // Two ints whose operation raised (a division by zero, a + // negative shift count): the error it kept, raised through + // this code's handlers at a site that may raise (not an + // inlined body; anything virtual below the operands is + // written out on the status). + KERNEL_RAISED => { + if let Some(e) = kernel_err_take() { + if s.raisable && !(*st).sw.is_null() { + // (Numbers: nothing to release.) + let st = &mut *st; + st.err = Some(e); + st.len = s.slot as usize; + st.pc = s.pc as usize + 1; + st.last = s.pc as usize; + return RAISED; + } + } + } + _ => {} + } binop_method(st, s) } } @@ -2318,10 +2541,76 @@ unsafe fn binop_method(st: *mut State, s: &BinopSite) -> u32 { return r; } } + if s.raisable { + if let Some(r) = binop_number_error(st, s) { + return r; + } + } left(st, s.pc, s.last, s.slot as usize + 2) } } +/// [`binop_method`]'s `a // 0`, `a / 0`, `a % 0`, `a << -1` and `0 ** -1` of two +/// exact numbers (a site that may raise: not an inlined body): the error the full operation answers, +/// which runs no code, raised through this code's handlers (`RAISED`, the +/// operands gone, the state past the instruction) instead of leaving for +/// the core loop to compute it. `None` touches nothing. +#[cold] +#[inline(never)] +unsafe fn binop_number_error(st: *mut State, s: &BinopSite) -> Option { + // SAFETY: as `h_binop_site`'s. + unsafe { + let st = &mut *st; + if st.sw.is_null() { + return None; + } + let at = st.stack.add(s.slot as usize); + let (a, b) = (&*at, &*at.add(1)); + let kind: BinOpKind = std::mem::transmute(s.arg as u8); + let number = |o: &Object| matches!(o, Object::Int(_) | Object::Bool(_) | Object::Float(_)); + let raises = match kind { + BinOpKind::Div | BinOpKind::FloorDiv | BinOpKind::Mod => { + number(a) + && match *b { + Object::Int(0) | Object::Bool(false) => true, + Object::Float(x) => x == 0.0, + _ => false, + } + } + BinOpKind::LShift | BinOpKind::RShift => { + matches!(a, Object::Int(_) | Object::Bool(_)) + && matches!(*b, Object::Int(n) if n < 0) + } + // (`0 ** -1`.) + BinOpKind::Pow => { + matches!(*a, Object::Int(0) | Object::Bool(false)) + && matches!(*b, Object::Int(n) if n < 0) + } + _ => false, + }; + if !raises { + return None; + } + let interp = &mut *st.interp.cast_mut(); + let globals = &(*st.frame).globals; + let r = if s.arg & weavepy_compiler::BINARY_OP_INPLACE_FLAG != 0 { + interp.dispatch_inplace_op(a, b, kind, globals) + } else { + interp.dispatch_binary_op(a, b, kind, globals) + }; + // (An answer after all is the core loop's to compute again.) + let Err(e) = r else { + return None; + }; + // (Numbers: nothing to release.) + st.err = Some(e); + st.len = s.slot as usize; + st.pc = s.pc as usize + 1; + st.last = s.pc as usize; + Some(RAISED) + } +} + /// [`h_binop_site`] for a site whose result joins in-line numbers: any /// other result leaves for the core loop, past the instruction. unsafe extern "C" fn h_binop_num(st: *mut State, site: *const BinopSite) -> u32 { @@ -2383,6 +2672,25 @@ unsafe extern "C" fn h_compare_site(st: *mut State, site: *const BinopSite) -> u } return left(st, s.pc, s.last, s.slot as usize + 2); } + // The reflected method of a class defining only the other + // ordering (`a > b` of one with `__lt__`): `f(b, a)` in place, + // the operands swapped for it and back on a decline. + if let Some(f) = Interpreter::compare_reflected_dunder(&*at, &*at.add(1), kind) { + std::ptr::swap(at, at.add(1)); + let r = compare_leaf(st, at, &f); + if r <= 1 { + return answered(r != 0); + } + std::ptr::swap(at, at.add(1)); + } + // `a != b` of a class defining only `__eq__`: `object.__ne__` + // inverts the method's bool answer, run in place. + if matches!(kind, CompareKind::NotEq) { + let r = compare_ne_leaf(st, at); + if r <= 1 { + return answered(r != 0); + } + } } let r = h_compare_bool(at, s.arg); if r <= 1 { @@ -2402,6 +2710,32 @@ unsafe extern "C" fn h_compare_site(st: *mut State, site: *const BinopSite) -> u } } +/// `a != b` (the values at `at`) where `a`'s class's `__ne__` is +/// `object`'s and its `__eq__` a warm pure leaf: the inverse of that +/// method's bool answer, the operands released, as [`compare_leaf`] +/// gives it; anything else declined untouched. +/// +/// # Safety +/// +/// As [`compare_leaf`]'s. +#[inline(never)] +unsafe fn compare_ne_leaf(st: *const State, at: *mut Object) -> u32 { + // SAFETY: the caller's contract. + unsafe { + if !Interpreter::ne_inverts_eq(&*at) { + return 2; + } + let Some(f) = Interpreter::compare_instance_dunder(&*at, &*at.add(1), CompareKind::Eq) + else { + return 2; + }; + match compare_leaf(st, at, &f) { + r @ 0..=1 => 1 - r, + r => r, + } + } +} + /// [`h_compare_site`]'s comparison method `f`, called directly /// ([`direct_call`]) as `f(a, b)` on copies of the operands above them: /// the operands wait in their slots, as the full handler holds them across @@ -2580,6 +2914,44 @@ unsafe fn op_after_reload(st: &mut State, op: records::MethodOp<'_>) { } records::MethodOp::Binary(..) => Ok(v), records::MethodOp::Compare(arg) => interp.compare_finish(frame, arg, v), + records::MethodOp::Iter => crate::iter_result(v), + // The store leaves nothing. + records::MethodOp::Store => { + interp.release(v); + return; + } + records::MethodOp::Truth(from_len) => { + crate::truth_result(v, from_len).map(Object::Bool) + } + records::MethodOp::Len => crate::coerce_len_result(v).map(Object::Int), + records::MethodOp::Inplace(op, a, b) + if v.is_same(&crate::vm_singletons::not_implemented()) => + { + let globals = frame.globals.clone(); + interp.inplace_binop_fallback(a, b, op, &globals) + } + records::MethodOp::Inplace(..) => Ok(v), + records::MethodOp::Format => crate::format_result(v), + records::MethodOp::Str => crate::str_result(v), + records::MethodOp::Repr => crate::repr_result(v), + records::MethodOp::Hash => interp.normalize_hash_result(v), + // (Unbound: the hook's swallowed `AttributeError`, see + // `records::raise_unseen`.) + records::MethodOp::HasAttr => { + let found = !matches!(v, Object::Unbound); + interp.release(v); + Ok(Object::Bool(found)) + } + records::MethodOp::GetAttrOr(d) => Ok(match v { + Object::Unbound => d.clone(), + v => v, + }), + records::MethodOp::Contains(invert) => { + let globals = frame.globals.clone(); + interp + .obj_truthy(&v, &globals) + .map(|b| Object::Bool(b != invert)) + } }; match r { Ok(v) => frame.stack.push(v), @@ -2672,20 +3044,33 @@ unsafe extern "C" fn h_for_iter(st: *mut State, it: *mut Object, out: *mut Objec current, stop, step, - } if *step > 0 && *current < *stop => { + } if (*step > 0 && *current < *stop) || (*step < 0 && *current > *stop) => { (*st).out = *current as u64; *current = current.wrapping_add(*step); return 0; } - PyIterator::List { items, index, .. } => { - match items.peek().and_then(|xs| xs.get(*index)) { - Some(v) => { - *index += 1; - v - } - None => return h_for_iter_rest(st, it, out, pc), + PyIterator::List { + items, + index, + owner, + } => match items.peek().and_then(|xs| xs.get(*index)) { + Some(v) => { + *index += 1; + v } - } + // The end of a loop's own cursor (no generator + // expression's `.0` sharing it): it leaves the stack + // here, as `h_for_iter_rest` retires it, without + // that helper's dispatch. + None if owner.is_none() + && items.peek().is_some() + && Rc::strong_count(rc) == 1 => + { + drop(it.read()); + return 2; + } + None => return h_for_iter_rest(st, it, out, pc), + }, PyIterator::Tuple { items, index } => match items.get(*index) { Some(v) => { *index += 1; @@ -2706,9 +3091,10 @@ unsafe extern "C" fn h_for_iter(st: *mut State, it: *mut Object, out: *mut Objec // out of line, so this helper's frame stays what the // steps above need (in line here, they cost a string's // loop 11% more instructions an item). - PyIterator::Reversed { .. } | PyIterator::DictKeys { .. } => { - return h_for_iter_view(st, it, out, pc) - } + PyIterator::DictKeys { .. } => return h_for_iter_dict(st, it, out, pc), + PyIterator::Reversed { .. } + | PyIterator::Bytes { .. } + | PyIterator::ByteArray { .. } => return h_for_iter_view(st, it, out, pc), _ => return h_for_iter_rest(st, it, out, pc), }; if let Object::Int(i) = *v { @@ -2722,12 +3108,205 @@ unsafe extern "C" fn h_for_iter(st: *mut State, it: *mut Object, out: *mut Objec if matches!(&*it, Object::Generator(_)) && !(*st).sw.is_null() { return h_for_iter_gen(st, it, out, pc); } + if matches!(&*it, Object::LazyIter(_)) { + return h_for_iter_lazy(st, it, out, pc); + } + if matches!(&*it, Object::Instance(_)) && !(*st).sw.is_null() { + return h_for_iter_inst(st, it, out, pc); + } + h_for_iter_rest(st, it, out, pc) + } +} + +/// [`h_for_iter`] of an instance: a deque iterator's next item read in +/// place, and its end (the iterator leaves the stack) with no +/// `StopIteration` raised to say so, in a small frame of their own; every +/// other instance, and every other step, is [`h_for_iter_rest`]'s. +#[inline(never)] +unsafe extern "C" fn h_for_iter_inst( + st: *mut State, + it: *mut Object, + out: *mut Object, + pc: u64, +) -> u32 { + use crate::stdlib::collections_native::{deque_for_step, DequeStep}; + use crate::stdlib::elementtree_native::ForStep; + use crate::stdlib::struct_mod::{array_for_step, ArrayStep}; + // SAFETY: as `h_for_iter_rest`'s; the step runs no code. + unsafe { + if let Object::Instance(inst) = &*it { + // An array's iterator: its next item read off the buffer. + match array_for_step(inst, droppable(&*it)) { + ArrayStep::Item(Object::Int(i)) => { + (*st).out = i as u64; + return 0; + } + ArrayStep::Item(v) => { + out.write(v); + return 1; + } + ArrayStep::End(array) => { + drop(array); + drop(it.read()); + return 2; + } + ArrayStep::Other => {} + } + match deque_for_step(inst) { + DequeStep::Item(v) => { + out.write(v); + return 1; + } + DequeStep::End if droppable(&*it) => { + drop(it.read()); + return 2; + } + _ => {} + } + // An `xml.etree` element's iterator (`for e in elem`, + // `elem.iter()`, `elem.itertext()`), likewise. + match crate::stdlib::elementtree_native::for_step(inst) { + ForStep::Item(v) => { + out.write(v); + return 1; + } + ForStep::End if droppable(&*it) => { + drop(it.read()); + return 2; + } + _ => {} + } + // A `struct.iter_unpack` iterator: its next tuple read off the + // buffer, its end letting the buffer go, as its `__next__` + // steps it. + match crate::stdlib::struct_mod::unpack_for_step(inst) { + Some(Some(v)) => { + out.write(v); + return 1; + } + Some(None) if droppable(&*it) => { + drop(it.read()); + return 2; + } + _ => {} + } + // A `csv.reader` (`for row in csv.reader(lines)`): its next + // record as its `__next__`'s leaf half reads it, and its end. + match crate::stdlib::csv_mod::reader_for_step(inst) { + Some(Some(v)) => { + out.write(v); + return 1; + } + Some(None) if droppable(&*it) => { + drop(it.read()); + return 2; + } + _ => {} + } + // An `os.scandir` iterator (`for e in it`): its next entry, + // its end closing it, as its `__next__` steps it. + match crate::stdlib::os::scandir_step(inst) { + Some(Some(v)) => { + out.write(v); + return 1; + } + Some(None) if droppable(&*it) => { + drop(it.read()); + return 2; + } + _ => {} + } + } h_for_iter_rest(st, it, out, pc) } } -/// [`h_for_iter`] of a reversed list's iterator, or a dict's or dict -/// view's: the next item, key or value read in place, as the general step +/// [`h_for_iter`] of a native adapter: `islice`'s, `chain`'s, `count`'s +/// and `cycle`'s commonest steps (see [`crate::seqiter::lazy_hot_next`]) +/// in a small frame of their own; every other step is +/// [`h_for_iter_rest`]'s. +#[inline(never)] +unsafe extern "C" fn h_for_iter_lazy( + st: *mut State, + it: *mut Object, + out: *mut Object, + pc: u64, +) -> u32 { + // SAFETY: as `h_for_iter_rest`'s; the step runs no code. + unsafe { + let Object::LazyIter(l) = &*it else { + return h_for_iter_rest(st, it, out, pc); + }; + if let Some(v) = l + .state + .peek_mut() + .and_then(crate::seqiter::lazy_hot_step_in_line) + { + out.write(v); + return 1; + } + // Any other step that runs no code (an adapter stepping a + // generator has a lane of its own in `for_iter_lazy_rest`). + let tried = (*st).sw.is_null() || !crate::seqiter::lazy_steps_generator(l); + if tried { + if let Some(Some(v)) = (*(*st).interp).lazy_core_next(l) { + out.write(v); + return 1; + } + } + for_iter_lazy_rest(&mut *st, it, out, pc, tried) + } +} + +/// `FOR_ITER` at a site whose cache settled on a dict's iterator (`for k +/// in d`): a plain dict's next key, the dict unchanged since the +/// iterator's first step, read ahead of every other shape's checks (as +/// [`h_for_iter_view`] reads it, which takes everything else). +unsafe extern "C" fn h_for_iter_dict( + st: *mut State, + it: *mut Object, + out: *mut Object, + pc: u64, +) -> u32 { + // SAFETY: as `h_for_iter_rest`'s; nothing here runs code while the + // iterator is borrowed. + unsafe { + if let Object::Iter(rc) = &*it { + if let Some(PyIterator::DictKeys { + kind: crate::object::DictViewKind::Keys, + index, + dict: Some(d), + len, + watch: Some(w), + reverse: false, + odict: None, + .. + }) = rc.peek_mut() + { + if !w.changed() { + if let Some(data) = d.peek() { + if data.len() == *len { + if let Some((k, _)) = data.get_index(*index) { + *index += 1; + if let Object::Int(i) = k.0 { + (*st).out = i as u64; + return 0; + } + out.write(crate::clone_hot(&k.0)); + return 1; + } + } + } + } + } + } + h_for_iter_view(st, it, out, pc) + } +} + +/// [`h_for_iter`] of a reversed list's iterator, a byte string's or +/// buffer's, or a dict's or dict view's: the next item, byte, key or value +/// read in place, as the general step /// takes it (the end, a list that shrank and a dict that changed are that /// step's, through [`h_for_iter_rest`]). #[inline(never)] @@ -2743,6 +3322,20 @@ unsafe extern "C" fn h_for_iter_view( if let Object::Iter(rc) = &*it { if let Some(iter) = rc.peek_mut() { match iter { + // A byte string's or buffer's next byte, an int (the end + // is the general step's). + PyIterator::Bytes { data, index } if *index < data.len() => { + (*st).out = u64::from(data[*index]); + *index += 1; + return 0; + } + PyIterator::ByteArray { data, index } => { + if let Some(&b) = data.peek().and_then(|d| d.get(*index)) { + *index += 1; + (*st).out = u64::from(b); + return 0; + } + } PyIterator::Reversed { items, index, .. } if *index >= 0 => { if let Some(v) = items.peek().and_then(|xs| xs.get(*index as usize)) { *index -= 1; @@ -2754,21 +3347,88 @@ unsafe extern "C" fn h_for_iter_view( return 1; } } - view @ PyIterator::DictKeys { .. } => { - match Interpreter::core_dict_next(view, false, false) { - crate::DictStep::Item(Object::Int(i), _) => { + // Exhausted, held by the stack alone, over a list that + // lives on: it leaves the stack, as the core loop's end + // retires it (its release frees nothing). + PyIterator::Reversed { + items, + index, + owner: None, + } if *index < 0 + && Rc::strong_count(rc) == 1 + && crate::sync::Rc::strong_count(items) > 1 => + { + drop(it.read()); + return 2; + } + // A plain dict's next key, the dict unchanged since the + // iterator's first step (its watch set then): as + // `core_dict_next` steps it, without the other shapes' + // checks. + PyIterator::DictKeys { + kind: crate::object::DictViewKind::Keys, + index, + dict: Some(d), + len, + watch: Some(w), + reverse: false, + odict: None, + .. + } if !w.changed() => { + if let Some((k, _)) = d + .peek() + .filter(|data| data.len() == *len) + .and_then(|data| data.get_index(*index)) + { + *index += 1; + if let Object::Int(i) = k.0 { (*st).out = i as u64; return 0; } - crate::DictStep::Item(v, _) => { - out.write(v); - return 1; - } - _ => {} + out.write(crate::clone_hot(&k.0)); + return 1; } } - _ => {} - } + // Its next value likewise, for a values view. + PyIterator::DictKeys { + kind: crate::object::DictViewKind::Values, + index, + dict: Some(d), + len, + watch: Some(w), + reverse: false, + odict: None, + .. + } if !w.changed() => { + if let Some((_, v)) = d + .peek() + .filter(|data| data.len() == *len) + .and_then(|data| data.get_index(*index)) + { + *index += 1; + if let Object::Int(i) = *v { + (*st).out = i as u64; + return 0; + } + out.write(crate::clone_hot(v)); + return 1; + } + } + view @ PyIterator::DictKeys { .. } => { + match Interpreter::core_dict_next(view, false, false) { + crate::DictStep::Item(Object::Int(i), _) => { + (*st).out = i as u64; + return 0; + } + crate::DictStep::Item(v, _) => { + out.write(v); + return 1; + } + _ => {} + } + } + _ => {} + } } } h_for_iter_rest(st, it, out, pc) @@ -2904,16 +3564,18 @@ unsafe fn for_iter_drain( if !matches!( g.state_raw().peek(), Some(crate::object::GeneratorState::Created(_)) - ) || !crate::gen_fast::steps_body(g) - { + ) { return None; } + // (A body the fast steps don't run, one that calls, drains by its + // lean resume instead: see `for_iter_fold`.) + let steps = crate::gen_fast::steps_body(g); let ins = &(&*st.frame).code.instructions; let (append, back) = (ins.get(pc + 1)?, ins.get(pc + 2)?); // An inlined `all(...)` or `any(...)` (`FOR_ITER; TO_BOOL; // POP_JUMP_IF_FALSE/TRUE; NOT_TAKEN; JUMP_BACKWARD`). if append.op == OpCode::ToBool { - return for_iter_truth(st, it, out, pc); + return for_iter_truth(st, it, out, pc, steps); } if append.op != OpCode::ListAppend || append.arg != 2 @@ -2932,6 +3594,25 @@ unsafe fn for_iter_drain( if Rc::strong_count(list) != 1 { return None; } + if !steps { + // (Code runs while the body does: the items gather apart and + // join the list as the drain stops, before the loop's own + // append of a yield it hands back.) + let mut gathered = Vec::new(); + let list = list.clone(); + return for_iter_fold( + st, + it, + out, + pc, + crate::FoldSink::Collect(&raw mut gathered), + || { + if let Some(items) = list.peek_mut() { + items.append(&mut gathered); + } + }, + ); + } // (Growing the list runs no code: nothing reaches it while it's // peeked at.) let items: *mut Vec = list.peek_mut()?; @@ -2986,6 +3667,7 @@ unsafe fn for_iter_truth( it: *mut Object, out: *mut Object, pc: usize, + steps: bool, ) -> Option { use crate::gen_fast::GenNext; // SAFETY: the caller's contract. @@ -3003,6 +3685,9 @@ unsafe fn for_iter_truth( { return None; } + if !steps { + return for_iter_fold(st, it, out, pc, crate::FoldSink::Truth(decides), || {}); + } let Object::Generator(g) = &*it else { return None; }; @@ -3038,6 +3723,130 @@ unsafe fn for_iter_truth( } } +/// [`for_iter_drain`] of a fresh generator whose body the fast steps +/// don't run (it calls): its lean resume drains it into `fold` (see +/// `Interpreter::core_gen_fold`), the frame synced as a native call's is +/// (see [`native_body_here`]), and `joined` runs as the drain stops. Its +/// end leaves the loop (`2`); a yield the sink declined is the +/// instruction's result (`1`); a raise is the instruction's (`FOR_RAISED`). +/// When the drain left the activation's code (a switch, a pending exit), +/// the frame is left as the core loop's `FOR_ITER` would leave it +/// (`FOR_SWITCHED`). +/// +/// # Safety +/// +/// As [`for_iter_drain`]'s, `it` holding a fresh generator. +#[inline(never)] +unsafe fn for_iter_fold( + st: &mut State, + it: *mut Object, + out: *mut Object, + pc: usize, + fold: crate::FoldSink, + joined: impl FnOnce(), +) -> Option { + // SAFETY: the caller's contract; the stack slot keeps the generator + // alive while it runs. + unsafe { + if st.sw.is_null() + || !(*st.sw).calls_ok + || crate::hot_gates::loop_gen() != st.snap_gen + || (*st.maybe_dead).get() + { + return None; + } + let Object::Generator(g) = &*it else { + return None; + }; + let g = g.clone(); + let at = it.offset_from(st.stack) as usize; + // The frame synced, as the core loop's arm syncs it. + let frame = &mut *st.frame; + frame.stack.set_len(at + 1); + let lazy = !st.lazy.is_null() && !crate::sync::cells_unguarded(); + if !lazy { + settle(st); + *(*st.sw).last = st.last; + } + let sw = &mut *st.sw; + let interp = &mut *st.interp.cast_mut(); + let r = interp.core_gen_fold( + sw, + frame, + pc, + &g, + fold, + if lazy { + std::ptr::from_mut(st) + } else { + std::ptr::null_mut() + }, + ); + drop(g); + joined(); + let mut in_place = false; + if !st.lazy.is_null() { + in_place = sw.pending.is_none() && crate::hot_gates::loop_gen() == st.snap_gen; + if !in_place { + settle(st); + } + } + let sw = &mut *st.sw; + in_place = in_place + || (sw.pending.is_none() + && std::ptr::eq(sw.cur, st.frame) + && crate::hot_gates::loop_gen() == st.snap_gen); + if in_place { + return Some(match r { + Ok(Some(v)) => { + out.write(v); + 1 + } + Ok(None) => { + // The finished generator leaves the stack. + drop(it.read()); + if (*st.maybe_dead).get() { + return Some(for_iter_gen_marked(st, it, pc as u64)); + } + 2 + } + Err(e) => { + st.len = at + 1; + st.pc = pc + 1; + st.err = Some(e); + FOR_RAISED + } + }); + } + // The core loop goes on from the frame, left as its `FOR_ITER` + // leaves it. + let frame = &mut *st.frame; + match r { + Ok(Some(v)) => { + out.write(v); + frame.stack.set_len(at + 2); + frame.pc = pc as u32 + 1; + } + Ok(None) => { + drop(it.read()); + frame.stack.set_len(at); + frame.pc = for_iter_exit(&frame.code, pc) as u32; + } + Err(e) => { + frame.stack.set_len(at + 1); + frame.pc = pc as u32 + 1; + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Raised(e))); + return Some(FOR_SWITCHED); + } + } + *sw.last = pc; + if sw.pending.is_none() && (*sw.maybe_dead).get() { + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Marked)); + } + Some(FOR_SWITCHED) + } +} + /// [`h_for_iter_gen`] of a generator its fast step declined: resumed /// lazily ([`lazy_gen_resume`]), or else as an inline activation /// ([`for_iter_gen_switch`]). @@ -3226,10 +4035,15 @@ fn simple_delegate(gf: &crate::Frame, depth: u32) -> bool { } } -/// How deep a `yield from` chain that isn't collapsed resumes lazily -/// level by level (see [`simple_delegate`]); a deeper one collapses. +/// How deep an `await` chain that isn't collapsed resumes lazily level +/// by level (see [`simple_delegate`]); a deeper one collapses. const LAZY_CHAIN_DEPTH: u32 = 3; +/// [`LAZY_CHAIN_DEPTH`] for a generator's `yield from`: a delegate in a +/// `yield from` of its own collapses (a tree walk's short-lived levels run +/// cheaper collapsed). +const LAZY_GEN_CHAIN_DEPTH: u32 = 1; + /// How a lazy generator resume ([`lazy_gen_resume`]) went. pub(crate) enum LazyGen { /// Declined, nothing touched. @@ -3327,7 +4141,14 @@ pub(crate) unsafe fn lazy_gen_resume( // one that is itself in a `yield from` makes a chain, which the // switch's chain collapse takes.) if crate::yield_from_resend(&gf.code.instructions, gf.pc as usize).is_some() - && !simple_delegate(gf, LAZY_CHAIN_DEPTH) + && !simple_delegate( + gf, + if gf.code.is_generator { + LAZY_GEN_CHAIN_DEPTH + } else { + LAZY_CHAIN_DEPTH + }, + ) { crate::burst_stats::note_decline("lazy gen: chain", &gf.code.qualname); return LazyGen::No; @@ -3559,6 +4380,7 @@ unsafe fn lazy_state( wait_pending: None, outer_lazy: 0, fold: std::ptr::null(), + caught: false, } } } @@ -4118,6 +4940,7 @@ pub(crate) unsafe fn core_lazy_resume( wait_pending: None, outer_lazy: 0, fold: std::ptr::null(), + caught: false, }; let st = &mut st; let arg = frame.code.instructions[pc].arg; @@ -4193,6 +5016,75 @@ pub(crate) unsafe fn core_lazy_resume( } } +/// [`h_for_iter_rest`] of a native adapter: a step that runs no code +/// (`zip` of native iterators, `map` with a pure callback, ...) in place; +/// any other (a Python callback, exhaustion) through the core loop's lane. +/// `tried` when the caller already took (and was declined) the step that +/// runs no code. +#[inline(never)] +unsafe fn for_iter_lazy_rest( + st: &mut State, + it: *mut Object, + out: *mut Object, + pc: u64, + tried: bool, +) -> u32 { + // SAFETY: the caller passes an initialized slot holding the adapter. + let Object::LazyIter(l) = (unsafe { &*it }) else { + return 3; + }; + // SAFETY: the code passes its live state, whose interpreter + // is dormant while the helper runs. + let interp = unsafe { &*st.interp }; + // A `chain`, `filter` or `islice` over a generator: its own + // step, past the ones that can't take it. + if !st.sw.is_null() && crate::seqiter::lazy_steps_generator(l) { + // SAFETY: as above. + let interp = unsafe { &mut *st.interp.cast_mut() }; + if let Some(v) = interp.lazy_gen_one(l, st.snap_gen, st.maybe_dead, st.depth_cell) { + // SAFETY: the slot above the iterator is free. + unsafe { out.write(v) }; + return 1; + } + // SAFETY: as above. + return unsafe { for_iter_lane(st, it, pc) }; + } + if !tried { + if let Some(Some(v)) = interp.lazy_core_next(l) { + // SAFETY: the slot above the iterator is free. + unsafe { out.write(v) }; + return 1; + } + } + // A `zip` at the end of its first sequence (or an + // `accumulate` at its source's), whose release runs nothing: it + // leaves the stack, as the core loop's end does. + if crate::seqiter::lazy_stops_quietly(l) { + // SAFETY: the iterator leaves the stack. + drop(unsafe { it.read() }); + return 2; + } + // `enumerate(gen)` and a two-source `zip` over a generator, as + // `h_for_iter_pair` steps them, here with the pair's tuple. + if !st.sw.is_null() { + // SAFETY: as above. + let interp = unsafe { &mut *st.interp.cast_mut() }; + if let Some((a, b)) = interp.lazy_gen_pair(l, st.snap_gen, st.maybe_dead, st.depth_cell) { + // SAFETY: the slot above the iterator is free. + unsafe { out.write(Object::new_tuple_array([a, b])) }; + return 1; + } + // `chain` and `islice` over a generator, likewise. + if let Some(v) = interp.lazy_gen_one(l, st.snap_gen, st.maybe_dead, st.depth_cell) { + // SAFETY: as above. + unsafe { out.write(v) }; + return 1; + } + } + // SAFETY: as above. + unsafe { for_iter_lane(st, it, pc) } +} + /// [`h_for_iter`]'s other shapes. #[inline(never)] unsafe extern "C" fn h_for_iter_rest( @@ -4244,8 +5136,16 @@ unsafe extern "C" fn h_for_iter_rest( unsafe { out.write(v) }; 1 } + // The end (a deque iterator's): the iterator leaves the + // stack, as the core loop's end retires it. Some(Err(RuntimeError::PyException(exc))) if exc.type_name() == "StopIteration" => { - 3 + if droppable(obj) { + // SAFETY: the slot holds the iterator. + drop(unsafe { it.read() }); + 2 + } else { + 3 + } } Some(Err(e)) => { st.len = unsafe { it.offset_from(st.stack) } as usize + 1; @@ -4253,43 +5153,33 @@ unsafe extern "C" fn h_for_iter_rest( st.err = Some(e); FOR_RAISED } - None => 3, + // A Python `__next__` that evaluates frameless, its bare + // `raise StopIteration` included; any other (and any other + // end) called through the core loop's lane. + None => match interp.leaf_python_step(obj, inst) { + Some(Some(v)) => { + // SAFETY: the slot above the iterator is free. + unsafe { out.write(v) }; + 1 + } + // The exhausted iterator leaves the stack, as a + // finished generator does. + Some(None) => { + // SAFETY: the slot holds the iterator. + drop(unsafe { it.read() }); + 2 + } + // SAFETY: the caller's contract. + None => unsafe { for_iter_lane(st, it, pc) }, + }, }; } // A native adapter: a step that runs no code (`zip` of native // iterators, `map` with a pure callback, ...) in place; any other // (a Python callback, exhaustion) through the core loop's lane. - Object::LazyIter(l) => { - // SAFETY: the code passes its live state, whose interpreter - // is dormant while the helper runs. - let interp = unsafe { &*st.interp }; - if let Some(Some(v)) = interp.lazy_core_next(l) { - // SAFETY: the slot above the iterator is free. - unsafe { out.write(v) }; - return 1; - } - // `enumerate(gen)` and a two-source `zip` over a generator, as - // `h_for_iter_pair` steps them, here with the pair's tuple. - if !st.sw.is_null() { - // SAFETY: as above. - let interp = unsafe { &mut *st.interp.cast_mut() }; - if let Some((a, b)) = - interp.lazy_gen_pair(l, st.snap_gen, st.maybe_dead, st.depth_cell) - { - // SAFETY: the slot above the iterator is free. - unsafe { out.write(Object::new_tuple_array([a, b])) }; - return 1; - } - // `chain` and `islice` over a generator, likewise. - if let Some(v) = interp.lazy_gen_one(l, st.snap_gen, st.maybe_dead, st.depth_cell) { - // SAFETY: as above. - unsafe { out.write(v) }; - return 1; - } - } - // SAFETY: as above. - return unsafe { for_iter_lane(st, it, pc) }; - } + // A native adapter, in a frame of its own. + // SAFETY: the caller's contract. + Object::LazyIter(_) => return unsafe { for_iter_lazy_rest(st, it, out, pc, false) }, // A file (its own iterator): a line waiting in its buffer in place, // and a line read that may fill the buffer (and so run a signal // handler) through the lane. @@ -4362,7 +5252,7 @@ unsafe extern "C" fn h_for_iter_rest( || xs.iter().all(plain_scalar)) => { if !unique { - *items = crate::sync::Rc::new(crate::sync::RefCell::new(Vec::new())); + *items = crate::object::detached_store(); } // SAFETY: as above. drop(unsafe { it.read() }); @@ -4381,7 +5271,7 @@ unsafe extern "C" fn h_for_iter_rest( // tuple of names, `for k in key[:-1]`.) if unique && crate::shared_value::ThinArc::strong_count(items) == 1 - && !items.iter().all(plain_scalar) + && !items.iter().all(frees_quietly) { return 3; } @@ -4423,23 +5313,42 @@ unsafe extern "C" fn h_for_iter_rest( // only the stack holds leaves it, as the core loop's arm // retires it, when its release frees nothing that could // finalize (the list or tuple lives on). - let frees_nothing = unique - && match &*inner { - PyIterator::List { - items, - index, - owner: None, - } => { - crate::sync::Rc::strong_count(items) > 1 - && items.try_borrow().is_ok_and(|v| *index >= v.len()) - } - PyIterator::Tuple { items, index } => { - *index >= items.len() - && crate::shared_value::ThinArc::strong_count(items) > 1 + // A shared one (a generator expression's `.0` holds it too) + // leaves likewise, a list cursor detaching from its list as + // its own end detaches it (where that frees nothing that + // could finalize: the list lives on, or holds plain scalars). + // (An iterator only the stack holds may free a temporary + // list or tuple of plain values as it goes, as a plain + // cursor's end does: `for i, x in enumerate([a, b])`.) + let frees_nothing = match &mut *inner { + PyIterator::List { + items, + index, + owner: None, + } => { + let ok = items.try_borrow().is_ok_and(|v| { + *index >= v.len() + && (crate::sync::Rc::strong_count(items) > 1 + || v.iter().all(plain_scalar)) + }); + if ok && !unique { + *items = crate::object::detached_store(); } - PyIterator::Range { .. } => true, - _ => false, - }; + ok + } + PyIterator::Tuple { items, index } => { + *index >= items.len() + && (!unique + || crate::shared_value::ThinArc::strong_count(items) > 1 + || items.iter().all(frees_quietly)) + } + PyIterator::Range { .. } => unique, + // A str's or bytes' cursor: immutable data whose release + // runs nothing (`for i, c in enumerate(s)`). + PyIterator::Str { s, index } => *index >= s.len(), + PyIterator::Bytes { data, index } => *index >= data.len(), + _ => false, + }; if !frees_nothing { return 3; } @@ -4485,7 +5394,10 @@ unsafe extern "C" fn h_for_iter_rest( // the core loop's arm steps it (a change of size, a reverse view, an // exhaustion that could release anything are its own). view @ PyIterator::DictKeys { .. } => { - match Interpreter::core_dict_next(view, false, unique) { + // (A shared iterator, a generator expression's `.0`, exhausts + // as a sole one does: its other holder finds it exhausted, and + // the stack's reference leaves by a plain decrement.) + match Interpreter::core_dict_next(view, false, true) { crate::DictStep::Item(v, _) => v, crate::DictStep::Exhausted => { // SAFETY: the iterator, held by the stack alone, leaves @@ -4569,23 +5481,13 @@ unsafe extern "C" fn h_for_iter_pair(st: *mut State, it: *mut Object, out: *mut *index += 1; pair } - // (An items view's fused step gives the key apart; its - // exhaustion, declined here, is the unfused helper's.) - view @ PyIterator::DictKeys { - kind: crate::object::DictViewKind::Items, - .. - } => match Interpreter::core_dict_next(view, true, false) { - crate::DictStep::Item(v, Some(k)) => (k, v), - crate::DictStep::Item(..) => unreachable!("an items view's fused step"), - _ => return 3, - }, - _ => match crate::seqiter::enumerate_pure_pair(&*it) { + _ => match fresh_pair(st, it) { Some(pair) => pair, None => return 3, }, } } - Object::LazyIter(l) => match crate::seqiter::lazy_pure_pair(l) { + Object::LazyIter(l) => match fresh_pair(st, it) { Some(pair) => pair, // `enumerate(gen)`, or a `zip` with a generator among its // two sources: each generator stepped by its native code. @@ -4607,6 +5509,100 @@ unsafe extern "C" fn h_for_iter_pair(st: *mut State, it: *mut Object, out: *mut } } +/// The next pair of the iterator at `it` whose step builds a fresh pair +/// and runs no code: a dict's items view, `enumerate` over a cursor, a +/// two-source `zip`, or `enumerate` over a native adapter (`enumerate(zip(xs, +/// ys))`). `None`, nothing consumed, for any other step (an exhausted +/// iterator's included). +/// +/// # Safety +/// +/// `st` is the code's live state and `it` an initialized slot. +unsafe fn fresh_pair(st: *mut State, it: *mut Object) -> Option<(Object, Object)> { + // SAFETY: the caller's contract; nothing below runs code while the + // iterator is borrowed. + unsafe { + match &*it { + Object::Iter(rc) => { + let iter = rc.peek_mut()?; + // (An items view's fused step gives the key apart; its + // exhaustion, declined here, is the unfused helper's.) + if matches!( + iter, + PyIterator::DictKeys { + kind: crate::object::DictViewKind::Items, + .. + } + ) { + return match Interpreter::core_dict_next(iter, true, false) { + crate::DictStep::Item(v, Some(k)) => Some((k, v)), + crate::DictStep::Item(..) => unreachable!("an items view's fused step"), + _ => None, + }; + } + crate::seqiter::enumerate_pure_pair(&*it) + } + Object::LazyIter(l) => { + crate::seqiter::lazy_pure_pair(l).or_else(|| (*(*st).interp).lazy_enumerate_pair(l)) + } + _ => None, + } + } +} + +/// `FOR_ITER` fused with the `STORE_FAST` after it (`for t in +/// enumerate(xs)`, `for kv in d.items()`), for an iterator at `it` whose +/// step builds a fresh pair (see [`fresh_pair`]) while the local at `local` +/// holds the previous step's pair alone, its items released without running +/// anything: the new pair refilled into that tuple in place (no allocation, +/// as CPython's free list hands the old one back, and no release through +/// the store's helper). `0` stored; anything else declined untouched (the +/// unfused helpers take it, the first step and exhaustion included). +unsafe extern "C" fn h_for_iter_store(st: *mut State, it: *mut Object, local: *mut Object) -> u32 { + // SAFETY: the code passes its live state, an initialized iterator slot + // and its local's; the tuple is the local's alone, so refilling it is + // invisible (its cached hash reset by the mutable view). + unsafe { + let Object::Tuple(t) = &mut *local else { + return 3; + }; + let Some(slots) = crate::shared_value::ThinArc::get_mut(t) else { + return 3; + }; + let [a, b] = &mut slots[..] else { + return 3; + }; + if !(plain_scalar(a) || held_elsewhere(a)) || !(plain_scalar(b) || held_elsewhere(b)) { + return 3; + } + let Some((x, y)) = fresh_pair(st, it) else { + return 3; + }; + // (The old items released last first, as a tuple's release goes.) + let old_b = std::mem::replace(b, y); + let old_a = std::mem::replace(a, x); + drop(old_b); + drop(old_a); + 0 + } +} + +/// Whether the `FOR_ITER` at `pc` of `code` stores its item straight into +/// a local of its own (the `STORE_FAST` after it, no cell's), which +/// [`h_for_iter_store`] fuses: that local. +fn fused_store_at(code: &CodeObject, pc: usize) -> Option { + let op = |pc: usize| code.instructions.get(pc).map(|i| (i.op, i.arg)); + match (op(pc), op(pc + 1)) { + (Some((OpCode::ForIter, _)), Some((OpCode::StoreFast, i))) + if pc + 2 < code.instructions.len() + && Interpreter::shared_cell_index(code, i as usize).is_none() => + { + Some(i) + } + _ => None, + } +} + /// The `FOR_ITER` at `pc` over the native adapter at `it` (the stack's top) /// whose step may run Python code (a `map` over a Python function), as the /// core loop's lane runs it (`Interpreter::core_for_iter_lane`): the frame @@ -4666,6 +5662,37 @@ fn plain_scalar(x: &Object) -> bool { ) } +/// Whether a container's release of its reference to `x` frees nothing +/// that could finalize: a plain scalar, a value another owner holds, or +/// (while nothing observes releases) a list or tuple of plain scalars +/// that goes with it (`for xs in ([1, 2], [3])`). +fn frees_quietly(x: &Object) -> bool { + if plain_scalar(x) || held_elsewhere(x) { + return true; + } + if crate::sync::release_gates() != 0 { + return false; + } + match x { + // SAFETY: a read that runs no code; the view ends here. + Object::List(l) => unsafe { l.peek() }.is_some_and(|v| v.iter().all(plain_scalar)), + Object::Tuple(t) => t.iter().all(plain_scalar), + _ => false, + } +} + +/// [`fused_store_at`]'s local where the `FOR_ITER`'s cache says its +/// iterator may be one a fused step takes: an adapter no specialization +/// covers (`enumerate`, `zip`: a cooldown, or the empty state one cycles +/// back to), or a dict's view (`d.items()`). +fn store_fusion_at(code: &CodeObject, pc: usize) -> Option { + use weavepy_compiler::InlineCache as IC; + match code.caches.get(pc as u32) { + IC::Empty | IC::Cooldown(_) | IC::ForIterDict => fused_store_at(code, pc), + _ => None, + } +} + /// Whether the `FOR_ITER` at `pc` of `code` unpacks a pair (the /// `UNPACK_SEQUENCE 2` after it), which [`h_for_iter_pair`] fuses. fn fused_pair_at(code: &CodeObject, pc: usize) -> bool { @@ -4675,35 +5702,259 @@ fn fused_pair_at(code: &CodeObject, pc: usize) -> bool { && pc + 2 < code.instructions.len() } -/// [`h_for_iter`] switched to a generator's activation (`RELOAD`). -const FOR_SWITCHED: u32 = 4; -/// [`h_for_iter`]'s iterator raised (`RAISED`, the state past it). -const FOR_RAISED: u32 = 5; +/// Whether the `FOR_ITER` at `pc` of `code` unpacks three or four items +/// (the `UNPACK_SEQUENCE` after it), which [`h_for_iter_tuple`] fuses: +/// their count. +fn fused_tuple_at(code: &CodeObject, pc: usize) -> Option { + let op = |pc: usize| code.instructions.get(pc).map(|i| (i.op, i.arg)); + match (op(pc), op(pc + 1)) { + (Some((OpCode::ForIter, _)), Some((OpCode::UnpackSequence, n @ 3..=4))) + if pc + 2 < code.instructions.len() => + { + Some(n) + } + _ => None, + } +} -/// `LIST_APPEND` onto the exact list at `list` of the value at `value`: -/// `0` the value moved in, anything else declined untouched. -unsafe extern "C" fn h_list_append(list: *const Object, value: *const Object) -> u32 { - // SAFETY: the code passes two initialized stack slots; growing the - // list runs no code, so nothing reaches it while it is peeked at. - unsafe { +/// [`h_for_iter_pair`] for a `FOR_ITER` fused with the `UNPACK_SEQUENCE n` +/// (three or four) after it: a `zip` of `n` plain sequence cursors, or a +/// list's or tuple's next item when it is an exact `n`-tuple. `0` the items +/// written from `out` as the unpacking leaves them (the last lowest), no +/// tuple built; anything else declined untouched. +unsafe extern "C" fn h_for_iter_tuple(it: *mut Object, out: *mut Object, n: u64) -> u32 { + let n = n as usize; + // SAFETY: the code passes an initialized slot with `n` free ones above + // it; nothing below runs code while the iterator is borrowed. + unsafe { + match &*it { + Object::Iter(rc) => { + let Some(iter) = rc.peek_mut() else { + return 3; + }; + // (The row's items written in place, the last lowest.) + let put = |t: &[Object]| { + if t.len() != n { + return false; + } + for (j, x) in t.iter().enumerate() { + out.add(n - 1 - j).write(crate::clone_hot(x)); + } + true + }; + let stepped = match iter { + PyIterator::List { + items: xs, + index, + owner: None, + } => match xs.peek().and_then(|xs| xs.get(*index)) { + Some(Object::Tuple(t)) if put(t) => index, + _ => return 3, + }, + PyIterator::Tuple { items: xs, index } => match xs.get(*index) { + Some(Object::Tuple(t)) if put(t) => index, + _ => return 3, + }, + _ => return 3, + }; + *stepped += 1; + 0 + } + Object::LazyIter(l) if crate::seqiter::lazy_pure_cursors_to(l, out, n) => 0, + _ => 3, + } + } +} + +/// [`h_for_iter`] switched to a generator's activation (`RELOAD`). +const FOR_SWITCHED: u32 = 4; +/// [`h_for_iter`]'s iterator raised (`RAISED`, the state past it). +const FOR_RAISED: u32 = 5; + +/// `LIST_APPEND` onto the exact list at `list` of the value at `value`: +/// `0` the value moved in, anything else declined untouched. +unsafe extern "C" fn h_list_append(list: *const Object, value: *const Object) -> u32 { + // SAFETY: the code passes two initialized stack slots; growing the + // list runs no code, so nothing reaches it while it is peeked at. + unsafe { h_list_append_ref(list, value, 1) } +} + +/// [`h_list_append`] of a value read in place: moved from its stack slot +/// (`owned` nonzero) or copied from a local or constant. +unsafe extern "C" fn h_list_append_ref( + list: *const Object, + value: *const Object, + owned: u32, +) -> u32 { + // SAFETY: as `h_list_append`'s; a borrowed value outlives the call. + unsafe { let Object::List(l) = &*list else { return 1; }; let Some(items) = l.peek_mut() else { return 1; }; - crate::push_fast(items, value.read()); + let v = if owned != 0 { + value.read() + } else { + crate::clone_hot(&*value) + }; + crate::push_fast(items, v); + 0 + } +} + +/// `MAP_ADD` (a dict comprehension's store) into the exact dict at `dict` +/// of the key at `key` and the value at `value`: `0` both moved in, a new +/// key the native probe settles (no stored key could equal it) or a scalar +/// value replaced (its release runs nothing); anything else declined +/// untouched. +/// [`crate::object::LeafProbe::new`], or for an instance whose class's +/// Python `__hash__` evaluates as a pure leaf (an `Enum` member, a frozen +/// dataclass; see `Interpreter::leaf_instance_hash`), a probe carrying that +/// hash: a stored key it meets is equal by identity alone, and any other of +/// the same hash makes the probe foreign (its miss inexact). +fn leaf_or_pure_probe(key: &Object) -> Option> { + crate::object::LeafProbe::new(key).or_else(|| { + let p = crate::vm_singletons::current_interpreter_ptr()?; + // SAFETY: the interpreter running on this thread, dormant while the + // helper runs; a pure-leaf evaluation runs no other code. + let h = unsafe { &*p }.leaf_instance_hash(key)?; + Some(crate::object::LeafProbe::with_hash(key, h)) + }) +} + +unsafe extern "C" fn h_map_add( + dict: *const Object, + key: *const Object, + value: *const Object, + owned: u32, +) -> u32 { + // SAFETY: the code passes three initialized values (the key in its + // stack slot when bit 0 of `owned` is set and the value when bit 1 is, + // else a local or constant that outlives the call); the probe and the + // insert run no code, so nothing reaches the dict meanwhile. + unsafe { + let take = |p: *const Object, bit: u32| { + if owned & bit != 0 { + p.read() + } else { + crate::clone_hot(&*p) + } + }; + let Object::Dict(cell) = &*dict else { + return 1; + }; + if crate::capi_watchers::dicts_active() { + return 1; + } + let Some(probe) = leaf_or_pure_probe(&*key) else { + return 1; + }; + let Some(d) = cell.peek_mut() else { + return 1; + }; + let added = match d.probe_entry(&probe) { + crate::dictmap::ProbeEntry::Occupied(e) => { + let slot = e.into_mut(); + // (An instance key hits by identity: the dict holds it, so + // the new reference's release is never its last.) + if !matches!( + slot, + Object::Int(_) | Object::Float(_) | Object::Bool(_) | Object::None + ) || !matches!( + &*key, + Object::Int(_) + | Object::Str(_) + | Object::Bool(_) + | Object::None + | Object::Instance(_) + ) { + return 1; + } + // (The key the dict holds stays; the new one leaves.) + *slot = take(value, 2); + if owned & 1 != 0 { + crate::drop_hot_at(key); + } + false + } + crate::dictmap::ProbeEntry::Vacant(e) => { + if !probe.miss_is_exact() { + return 1; + } + e.insert(crate::object::DictKey(take(key, 1)), take(value, 2)); + true + } + }; + if added { + crate::object::dict_watch_bump(cell); + } + crate::object::dict_mutation_event(cell); 0 } } +/// `SET_ADD` (a set comprehension's store) into the exact set at `set` of +/// the value at `value`: `0` the value moved in (or, a scalar or string +/// equal to an element, released), anything else declined untouched. +unsafe extern "C" fn h_set_add(set: *const Object, value: *const Object, owned: u32) -> u32 { + // SAFETY: the code passes two initialized values (the value in its + // stack slot when `owned` is nonzero, else a local or constant that + // outlives the call); the probe and the insert run no code, so nothing + // reaches the set meanwhile. + unsafe { + let Object::Set(cell) = &*set else { + return 1; + }; + let Some(probe) = leaf_or_pure_probe(&*value) else { + return 1; + }; + let Some(s) = cell.peek_mut() else { + return 1; + }; + let take = || { + if owned != 0 { + value.read() + } else { + crate::clone_hot(&*value) + } + }; + match s.insert_probe_if( + &probe, + |p| p.miss_is_exact(), + || crate::object::DictKey(take()), + ) { + Some(true) => 0, + // (An instance hits by identity: the set holds it.) + Some(false) + if matches!( + &*value, + Object::Int(_) + | Object::Str(_) + | Object::Bool(_) + | Object::None + | Object::Instance(_) + ) => + { + if owned != 0 { + crate::drop_hot_at(value); + } + 0 + } + _ => 1, + } + } +} + /// A method kernel: `recv.m(a, b)` for an exact `list`, `dict`, `set` or /// `str` receiver (its tag checked by the caller), with the arguments the /// site passes (null past them) read in place, and the method's builtin /// `f` (for the kernels that run its body): `0` the result written to the -/// free slot `out`, anything else declined untouched (the call then runs -/// as before). A kernel runs no Python code, raises nothing, and releases -/// nothing that could run a finalizer. +/// free slot `out`, [`KERNEL_RAISED`] the method's body raised (the error +/// kept for the caller, see [`kernel_err_take`]), anything else declined +/// untouched (the call then runs as before). A kernel runs no Python +/// code and releases nothing that could run a finalizer. type Kernel = unsafe extern "C" fn( out: *mut Object, recv: *const Object, @@ -4721,10 +5972,11 @@ fn kernel_for(tag: u64, kind: crate::LeafKind, nargs: usize) -> Option { (1, K::ListPop, 0) => k_list_pop, (1, K::ListExtend, 1) => k_list_extend, (1, K::ListInsert, 2) => k_list_insert, + (1, K::ListRemove, 1) => k_list_remove, (1, K::ListReverse | K::ListCopy, 0) => k_body, (2, K::DictGet, 1 | 2) => k_dict_get, - (2, K::DictKeys | K::DictValues | K::DictItems, 0) => k_body, - (3, K::SetPop, 0) => k_body, + (2, K::DictKeys | K::DictValues | K::DictItems | K::Opaque, 0) => k_body, + (3, K::SetPop | K::Opaque, 0) => k_body, (3, K::SetAdd, 1) => k_set_add, (3, K::SetDiscard, 1) => k_set_discard, (3, K::SetRemove, 1) => k_set_remove, @@ -4745,9 +5997,55 @@ fn kernel_for(tag: u64, kind: crate::LeafKind, nargs: usize) -> Option { }) } +/// A [`Kernel`]'s status when the method's body raised: the operands +/// untouched, the error waiting in [`KERNEL_ERR`]. +const KERNEL_RAISED: u32 = 2; + +thread_local! { + /// The error of the last method body a [`Kernel`] ran that raised + /// (see [`run_body`]): the kernel's caller takes it at once, to raise + /// it where the call stands ([`kernel_err_take`]) or to drop it where + /// the full call runs instead ([`h_kernel_forget`]). The body ran + /// once either way: without this, `"abc".index("z")` under a `try` + /// built its `ValueError` twice, once for the kernel to drop. + static KERNEL_ERR: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +/// The error a kernel that answered [`KERNEL_RAISED`] left. +fn kernel_err_take() -> Option { + KERNEL_ERR.try_with(std::cell::Cell::take).ok().flatten() +} + +/// A kernel answered [`KERNEL_RAISED`] where the full call runs instead +/// (an inlined body): its error dropped. +unsafe extern "C" fn h_kernel_forget() { + drop(kernel_err_take()); +} + +/// A kernel answered [`KERNEL_RAISED`] at the `CALL` at `pc`, the frame's +/// stack `len` deep and written out (a stack receiver still on it, for +/// the unwinding to release: it was checked droppable): `RAISED` its +/// error in the state, past the call; `1` (no error kept) for the full +/// call. +unsafe extern "C" fn h_kernel_raised(st: *mut State, pc: u32, len: u32) -> u32 { + let Some(e) = kernel_err_take() else { + return 1; + }; + // SAFETY: the code passes its live state. + unsafe { + let st = &mut *st; + st.last = pc as usize; + st.pc = pc as usize + 1; + st.len = len as usize; + st.err = Some(e); + } + RAISED +} + /// The method's own body on bitwise views of the operands (as the core -/// loop's leaf call runs it): `0` its result written to `out`, anything -/// else (an error, which the full call raises) declined. +/// loop's leaf call runs it): `0` its result written to `out`, +/// [`KERNEL_RAISED`] its error kept for the caller. /// /// # Safety /// @@ -4786,7 +6084,13 @@ unsafe fn run_body( out.write(v); 0 } - Err(_) => 1, + Err(e) => { + if KERNEL_ERR.try_with(|c| c.set(Some(e))).is_ok() { + KERNEL_RAISED + } else { + 1 + } + } } } } @@ -4873,6 +6177,43 @@ unsafe extern "C" fn k_list_pop( } } +/// `list.remove(x)` where every item up to the match compares with `x` +/// without running code, and the removed item releases without running +/// any: anything else (a miss's `ValueError` included) is declined. +unsafe extern "C" fn k_list_remove( + out: *mut Object, + recv: *const Object, + a: *const Object, + _: *const Object, + _: *const crate::object::BuiltinFn, +) -> u32 { + // SAFETY: as `Kernel`'s; the removed item moves out. + unsafe { + let (list, needle) = (&*recv, &*a); + let Object::List(l) = list else { + return 1; + }; + let mut at = None; + if crate::builtins::list_scan_native(list, needle, |i| { + at = Some(i); + false + }) + .is_none() + { + return 1; + } + let (Some(i), Some(items)) = (at, l.peek_mut()) else { + return 1; + }; + if i >= items.len() || !droppable(&items[i]) { + return 1; + } + crate::drop_hot(items.remove(i)); + out.write(Object::None); + 0 + } +} + unsafe extern "C" fn k_dict_get( out: *mut Object, recv: *const Object, @@ -4941,6 +6282,86 @@ unsafe extern "C" fn k_set_add( } } +/// [`k_set_add`] of an instance key whose class's Python `__hash__` +/// evaluates frameless ([`Interpreter::leaf_instance_hash`]): found by +/// identity, or added when no stored key could equal it (one with an equal +/// hash that isn't the same object would need `__eq__`: declined). `false` +/// touches nothing. +/// +/// # Safety +/// +/// As `Kernel`'s. +#[inline(never)] +unsafe fn set_add_leaf_hashed(interp: &Interpreter, recv: *const Object, a: *const Object) -> bool { + // SAFETY: the caller's contract. + unsafe { + let (Object::Set(s), k @ Object::Instance(_)) = (&*recv, &*a) else { + return false; + }; + let Some(h) = interp.leaf_instance_hash(k) else { + return false; + }; + let probe = crate::object::LeafProbe::with_hash(k, h); + let Some(m) = s.peek_mut() else { + return false; + }; + if m.get_index_of(&probe).is_none() { + if !probe.miss_is_exact() { + return false; + } + // (Absent, as the probe found: the hash goes in as computed, + // the key's own never run under the set's borrow.) + m.insert_unique_hashed(h, crate::object::DictKey(crate::clone_hot(k))); + } + true + } +} + +/// [`k_dict_get`] of an instance key whose class's Python `__hash__` +/// evaluates frameless (as [`set_add_leaf_hashed`] hashes one): the value +/// of the entry that is the same object or equal by a frameless `__eq__` +/// (see [`Interpreter::leaf_eq_match`]), or the default (`b`, or `None`) +/// when no stored key equals it. `None` touches nothing. +/// +/// # Safety +/// +/// As `Kernel`'s. +#[inline(never)] +unsafe fn dict_get_leaf_hashed( + interp: &Interpreter, + recv: *const Object, + a: *const Object, + b: *const Object, +) -> Option { + // SAFETY: the caller's contract. + unsafe { + let (Object::Dict(d), k @ Object::Instance(_)) = (&*recv, &*a) else { + return None; + }; + let h = interp.leaf_instance_hash(k)?; + let probe = crate::object::LeafProbe::with_hash(k, h); + let m = d.peek()?; + let found = match m.get_hot(&probe) { + Some(v) => Some(v), + None if probe.miss_is_exact() => None, + // (A stored key of its hash that a pure `__eq__` settles.) + None => { + let declined = std::cell::Cell::new(false); + let i = m.find_by_hash(h, interp.leaf_eq_match(k, &declined)); + if declined.get() { + return None; + } + i.and_then(|i| m.get_index(i)).map(|(_, v)| v) + } + }; + Some(match found { + Some(v) => crate::clone_hot(v), + None if b.is_null() => Object::None, + None => crate::clone_hot(&*b), + }) + } +} + /// `set.discard` (`remove`: a miss declines, for the full call's /// `KeyError`) of a key that compares natively (see `LeafProbe`): the /// removed key is the same object, or an equal `str`, `int` or tuple of @@ -5039,6 +6460,42 @@ unsafe fn ascii_from( Some(Some((&bytes[i as usize..], i as usize))) } +/// `s.startswith(t)` / `s.endswith(t)` of a tuple of `str`s with no start +/// position: whether any matches (a byte prefix or suffix of valid UTF-8 is +/// a character one). `None` to decline. +/// +/// # Safety +/// +/// As [`Kernel`]'s. +unsafe fn str_affix_tuple( + recv: *const Object, + a: *const Object, + b: *const Object, + ends: bool, +) -> Option { + // SAFETY: the caller's contract. + let (Object::Str(s), Object::Tuple(t)) = (unsafe { (&*recv, &*a) }) else { + return None; + }; + if !b.is_null() { + return None; + } + let text = s.as_bytes(); + let mut hit = false; + for p in t.iter() { + let Object::Str(p) = p else { + return None; + }; + let p = p.as_bytes(); + hit |= if ends { + text.ends_with(p) + } else { + text.starts_with(p) + }; + } + Some(hit) +} + unsafe extern "C" fn k_str_startswith( out: *mut Object, recv: *const Object, @@ -5048,6 +6505,10 @@ unsafe extern "C" fn k_str_startswith( ) -> u32 { // SAFETY: as `Kernel`'s. unsafe { + if let Some(hit) = str_affix_tuple(recv, a, b, false) { + out.write(Object::Bool(hit)); + return 0; + } let Some((s, p)) = two_strs(recv, a) else { return 1; }; @@ -5069,6 +6530,10 @@ unsafe extern "C" fn k_str_endswith( ) -> u32 { // SAFETY: as `Kernel`'s. unsafe { + if let Some(hit) = str_affix_tuple(recv, a, b, true) { + out.write(Object::Bool(hit)); + return 0; + } let Some((s, p)) = two_strs(recv, a) else { return 1; }; @@ -5273,10 +6738,13 @@ unsafe extern "C" fn k_str_join( // join with no iteration hook. unsafe { let strs = match &*a { - Object::List(l) => l - .peek() - .is_some_and(|xs| xs.iter().all(|x| matches!(x, Object::Str(_)))), - Object::Tuple(t) => t.iter().all(|x| matches!(x, Object::Str(_))), + Object::List(l) => l.peek().is_some_and(|xs| { + xs.iter() + .all(|x| crate::builtins::join_item_str(x).is_some()) + }), + Object::Tuple(t) => t + .iter() + .all(|x| crate::builtins::join_item_str(x).is_some()), _ => false, }; if !strs { @@ -5324,6 +6792,9 @@ pub(crate) struct SuperSite { recv: usize, ver: u64, f: Option>, + /// The getter of the property the name resolved to instead (the + /// attribute form; see [`h_super_property`]). + getter: Option>, } /// `LOAD_SUPER_ATTR` `ins` at `pc` over the `len`-deep stack: a hit in @@ -5359,6 +6830,13 @@ unsafe extern "C" fn h_super_attr( } _ => None, }; + // A property's site declines at once (its getter is called by + // `h_super_property`). + if let (Some((cls, recv, ver)), Some(_)) = (key, &site.getter) { + if cls == site.cls && recv == site.recv && ver == site.ver { + return u64::MAX; + } + } if let (Some((cls, recv, ver)), Some(f)) = (key, &site.f) { if cls == site.cls && recv == site.recv @@ -5385,6 +6863,18 @@ unsafe extern "C" fn h_super_attr( } } let Some(n) = Interpreter::core_super_attr(&*code, ins, pc as usize, base, len) else { + if let Some((cls, recv, ver)) = key { + let ops = std::slice::from_raw_parts(base.add(len - 3), 3); + if let Some(g) = Interpreter::super_property_getter(&*code, ins, ops) { + *site = SuperSite { + cls, + recv, + ver, + f: None, + getter: Some(g), + }; + } + } return u64::MAX; }; if let Some((cls, recv, ver)) = key { @@ -5402,7 +6892,13 @@ unsafe extern "C" fn h_super_attr( _ => None, } }; - *site = SuperSite { cls, recv, ver, f }; + *site = SuperSite { + cls, + recv, + ver, + f, + getter: None, + }; } n as u64 } @@ -5424,7 +6920,38 @@ unsafe fn subscr_raise_missing(st: &mut State, pc: u64, len: usize) -> Option (l.peek()?.len(), "list index out of range"), + Object::Tuple(t) => (t.len(), "tuple index out of range"), + Object::Str(s) if crate::object::str_char_len(s) == s.len() => { + (s.len(), "string index out of range") + } + _ => return None, + }; + let n = i64::try_from(n).ok()?; + if (-n..n).contains(&i) || !droppable(c) { + return None; + } + crate::drop_hot_at(st.stack.add(len - 1)); + crate::drop_hot_at(st.stack.add(len - 2)); + st.len = len - 2; + st.pc = pc as usize + 1; + if blind_raise(st, &crate::builtin_types::builtin_types().index_error) { + return Some(CONTAINER_RAISED); + } + st.err = Some(crate::error::index_error(what)); + return Some(CONTAINER_RAISED); + } + let ( + Object::Dict(d), + Object::Str(_) | Object::Int(_) | Object::Tuple(_) | Object::Bytes(_), + ) = (c, k) + else { return None; }; let probe = crate::object::LeafProbe::new(k)?; @@ -5437,16 +6964,39 @@ unsafe fn subscr_raise_missing(st: &mut State, pc: u64, len: usize) -> Option u64 { + // SAFETY: the code passes its live state and its stack depth. + unsafe { + let st = &mut *st; + let interp = &mut *st.interp.cast_mut(); + let (base, len, cap) = (st.stack, len as usize, st.cap); + let n = match kind { + 0 => interp.exc_op(OpCode::PushExcInfo, base, len, cap), + 1 => interp.exc_op(OpCode::CheckExcMatch, base, len, cap), + _ => interp.exc_op(OpCode::PopExcept, base, len, cap), + }; + n.map_or(u64::MAX, |n| n as u64) + } +} + unsafe extern "C" fn h_container( st: *mut State, ins: *const weavepy_compiler::Instruction, @@ -5631,34 +7181,93 @@ unsafe fn subscr_fast( // A `dict` subclass's instance that keeps `dict.__getitem__` (no // dispatch ahead of this helper: most instances have no payload, // and declines there would cost every other subscript). - if let (Object::Instance(_), Object::Str(_) | Object::Int(_)) = (c, k) { - return match owned & 3 { - 0 => crate::h_inst_dict_get::<0>(out, cont, key), - 1 => crate::h_inst_dict_get::<1>(out, cont, key), - 2 => crate::h_inst_dict_get::<2>(out, cont, key), - _ => crate::h_inst_dict_get::<3>(out, cont, key), - }; - } - if owned != 0 && !(droppable(c) && droppable(k)) { - return 1; - } - let index = |n: usize| -> Option { - let Object::Int(i) = *k else { - return None; - }; - let i = if i < 0 { i.checked_add(n as i64)? } else { i }; - usize::try_from(i).ok().filter(|&i| i < n) - }; - let r = match c { - Object::Dict(d) => { - let Some(probe) = crate::object::LeafProbe::new(k) else { - return 1; - }; - let Some(v) = d.peek().and_then(|m| m.get_hot(&probe)) else { - return 1; - }; - crate::clone_hot(v) + let mut owner = None; + let c = match c { + Object::Instance(inst) => { + if let Object::Str(_) | Object::Int(_) = k { + let r = match owned & 3 { + 0 => crate::h_inst_dict_get::<0>(out, cont, key), + 1 => crate::h_inst_dict_get::<1>(out, cont, key), + 2 => crate::h_inst_dict_get::<2>(out, cont, key), + _ => crate::h_inst_dict_get::<3>(out, cont, key), + }; + if r == 0 { + return 0; + } + } + // Any other key that compares natively (a tuple), and a + // key this subscript holds alone (`d[s.lower()]`, which + // the helper above leaves: releasing it frees it): read + // off the payload as an exact dict's below. + match inst.native.get() { + Some(payload @ Object::Dict(_)) + if inst + .class_dunder(crate::types::Dunder::GetItem) + .dict_owner() => + { + owner = Some(inst); + if owned != 0 && !droppable(c) { + return 1; + } + payload + } + _ => return 1, + } } + other => other, + }; + if owned != 0 && !(droppable(c) && droppable(k)) { + return 1; + } + let index = |n: usize| -> Option { + let i = match k { + Object::Int(i) => *i, + // An instance whose class's `__index__` evaluates as a pure + // leaf to an int (`xs[obj]`); one the helper owns only + // while another reference keeps it alive (its release + // below runs nothing). Anything else, and an index out of + // range, is the full path's (which runs it again: nothing + // observed this evaluation). + Object::Instance(inst) if owned & 2 == 0 || Rc::strong_count(inst) > 1 => { + crate::Interpreter::instance_index_leaf(inst, k)? + } + _ => return None, + }; + let i = if i < 0 { i.checked_add(n as i64)? } else { i }; + usize::try_from(i).ok().filter(|&i| i < n) + }; + let r = match c { + Object::Dict(d) => match crate::object::LeafProbe::new(k) { + Some(probe) => match d.peek().and_then(|m| m.get_hot(&probe)) { + Some(v) => crate::clone_hot(v), + // A `defaultdict`'s miss whose factory builds natively: + // the new value, stored as its `__missing__` stores it. + None => { + let made = owner.and_then(|inst| { + crate::stdlib::collections_native::dd_missing_pure(inst, d, k) + }); + match made { + Some(v) => v, + None => return 1, + } + } + }, + // An instance key whose class's `__hash__` evaluates + // frameless, found as itself or by a frameless `__eq__` + // (see `object::leaf_hashed_instance_get`); one the helper + // owns only while another reference keeps it alive (its + // release below runs nothing). A miss raises through the + // full path. + None => match k { + Object::Instance(inst) if owned & 2 == 0 || Rc::strong_count(inst) > 1 => { + match crate::object::leaf_hashed_instance_get(d, k) { + Some(Some(v)) => v, + _ => return 1, + } + } + _ => return 1, + }, + }, Object::List(xs) => { let Some(xs) = xs.peek() else { return 1; @@ -5715,6 +7324,37 @@ unsafe fn unpack_fast( unsafe { let n = n as usize; let s = &*src; + // A tuple subclass's instance (a `namedtuple`'s) whose class has no + // Python `__iter__` unpacks its tuple, as the generic unpack's + // iteration of it would. + if let Object::Instance(inst) = s { + let Some(Object::Tuple(t)) = inst.native.get() else { + return 1; + }; + if t.len() != n + || (owned != 0 && !droppable(s)) + || Interpreter::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::ITER_FN), + "__iter__", + ) + .is_some() + { + return 1; + } + // An owned instance sits in `dst`'s first slot, which the items + // overwrite: it moves out first (and keeps the tuple alive). + let held = if owned != 0 { Some(src.read()) } else { None }; + let items = t.clone(); + for (k, item) in items.iter().rev().enumerate() { + dst.add(k).write(crate::clone_hot(item)); + } + drop(items); + if let Some(held) = held { + crate::drop_hot(held); + } + return 0; + } let fits = match s { Object::Tuple(t) => t.len() == n, Object::List(l) => l.peek().is_some_and(|xs| xs.len() == n), @@ -5765,9 +7405,10 @@ unsafe fn unpack_fast( } _ => unreachable!("checked above"), } - // (A dead tuple's allocation is recycled, as `release` does it.) + // (A dead tuple's allocation is recycled, as `release` does it; a + // shared one, a `zip`'s result it reuses, is only released.) match seq { - Some(seq @ Object::Tuple(_)) => interp.maybe_donate_tuple(seq), + Some(seq @ Object::Tuple(_)) if unique => interp.maybe_donate_tuple(seq), Some(seq) => crate::drop_hot(seq), None => {} } @@ -5795,18 +7436,50 @@ unsafe fn store_subscr_fast( let (c, k) = (&*cont, &*key); // A `dict` subclass's instance that keeps `dict.__setitem__` (see // `subscr_fast`). - if let (Object::Instance(_), Object::Str(_) | Object::Int(_)) = (c, k) { - return match owned & 7 { - 0 => crate::h_inst_dict_set::<0>(val, cont, key), - 1 => crate::h_inst_dict_set::<1>(val, cont, key), - 2 => crate::h_inst_dict_set::<2>(val, cont, key), - 3 => crate::h_inst_dict_set::<3>(val, cont, key), - 4 => crate::h_inst_dict_set::<4>(val, cont, key), - 5 => crate::h_inst_dict_set::<5>(val, cont, key), - 6 => crate::h_inst_dict_set::<6>(val, cont, key), - _ => crate::h_inst_dict_set::<7>(val, cont, key), - }; - } + let c = match c { + Object::Instance(inst) => { + let plain_key = matches!(k, Object::Str(_) | Object::Int(_)); + // A built-in base's own `__setitem__` with a leaf half (an + // `OrderedDict`'s), which takes any key it probes natively + // (other keys only for an instance with a payload: a plain + // instance's store doesn't pay for the question). + if (plain_key || inst.native.get().is_some()) + && crate::inst_leaf_set(val, cont, key, owned & 7) == 0 + { + return 0; + } + if plain_key { + let r = match owned & 7 { + 0 => crate::h_inst_dict_set::<0>(val, cont, key), + 1 => crate::h_inst_dict_set::<1>(val, cont, key), + 2 => crate::h_inst_dict_set::<2>(val, cont, key), + 3 => crate::h_inst_dict_set::<3>(val, cont, key), + 4 => crate::h_inst_dict_set::<4>(val, cont, key), + 5 => crate::h_inst_dict_set::<5>(val, cont, key), + 6 => crate::h_inst_dict_set::<6>(val, cont, key), + _ => crate::h_inst_dict_set::<7>(val, cont, key), + }; + if r == 0 { + return 0; + } + } + // Any other key that compares natively, and operands this + // store holds alone (see `subscr_fast`): stored into the + // payload as into an exact dict below. + match inst.native.get() { + Some(payload @ Object::Dict(_)) + if inst + .class_dunder(crate::types::Dunder::SetItem) + .dict_owner() + && Interpreter::core_droppable(c) => + { + payload + } + _ => return 1, + } + } + other => other, + }; if !Interpreter::core_droppable(c) || (owned & 4 != 0 && !droppable(k)) { return 1; } @@ -5842,7 +7515,7 @@ unsafe fn store_subscr_fast( if crate::capi_watchers::dicts_active() { return 1; } - let Some(probe) = crate::object::LeafProbe::new(k) else { + let Some(probe) = leaf_or_pure_probe(k) else { return 1; }; let Some(d) = cell.peek_mut() else { @@ -5872,6 +7545,34 @@ unsafe fn store_subscr_fast( } old } + // A unit-step slice of a list assigned an exact list's or + // tuple's items (`xs[:] = xs[n:]`): spliced in place, the + // displaced items released after. + (Object::List(xs), Object::Slice(sl)) if matches!(sl.step, Object::None) => { + let items: Vec = match &*val { + Object::List(ys) => match ys.peek() { + Some(ys) => ys.clone(), + None => return 1, + }, + Object::Tuple(t) => t.to_vec(), + _ => return 1, + }; + let Some(v) = xs.peek_mut() else { + return 1; + }; + let Some((lo, hi)) = Interpreter::slice_bounds(sl, v.len()) else { + return 1; + }; + if !v[lo..hi.max(lo)].iter().all(displaced_ok) { + return 1; + } + let removed: Vec = v.splice(lo..hi.max(lo), items).collect(); + if owned & 1 != 0 { + crate::drop_hot_at(val); + } + drop(removed); + Object::None + } _ => return 1, }; if owned & 4 != 0 { @@ -5987,12 +7688,43 @@ unsafe extern "C" fn h_subscr_ref( unsafe { let at = (*st).stack.add(len as usize - 2); let owned = (flags & 0xff) as u32; + // A slice (`xs[a:b]`) is the container lane's: the index lanes + // below have nothing for it. A string's, with whole-number bounds + // and no step (`x[:8]`, `x[i:j]`), is cut here: neither operand's + // release runs code. + if let Object::Slice(slc) = &*key { + if let Object::Str(s) = &*cont { + if matches!(slc.step, Object::None) + && matches!(slc.start, Object::None | Object::Int(_)) + && matches!(slc.stop, Object::None | Object::Int(_)) + { + if let Ok(v) = crate::str_subscript_slice(s, slc) { + if owned & 2 != 0 { + crate::drop_hot_at(key); + } + if owned & 1 != 0 { + crate::drop_hot_at(cont); + } + at.write(v); + return len - 1; + } + } + } + own_operands(at, &[cont, key], owned); + return h_container(st, ins, code, pc, len, flags >> 8); + } if subscr_fast(at, cont, key, owned) == 0 { return len - 1; } own_operands(at, &[cont, key], owned); - // A dict's missing key raises without the generic subscript. - if flags >> 8 != 0 && matches!(&*at, Object::Dict(_)) { + // A dict's missing key, and a sequence's index out of range, raise + // without the generic subscript. + if flags >> 8 != 0 + && matches!( + &*at, + Object::Dict(_) | Object::List(_) | Object::Tuple(_) | Object::Str(_) + ) + { if let Some(n) = subscr_raise_missing(&mut *st, pc, len as usize) { return n; } @@ -6001,6 +7733,33 @@ unsafe extern "C" fn h_subscr_ref( } } +/// The raise of a subscript [`h_subscr_ref`] declined under virtual +/// items, once the code wrote them out: a dict's missing key or a +/// sequence's index out of range (see [`subscr_raise_missing`]), its two +/// operands owned atop the `len`-deep stack. Nonzero raised (the error in +/// `st`, `st.len` and `st.pc` past the instruction), zero untouched. +/// +/// # Safety +/// +/// `st` is the code's live state, `pc` one of its `BINARY_SUBSCR`s, its +/// whole stack on the frame's. +unsafe extern "C" fn h_subscr_raise(st: *mut State, pc: u64, len: u64) -> u32 { + // SAFETY: the caller's contract. + unsafe { + let st = &mut *st; + let len = len as usize; + if len < 2 + || !matches!( + &*st.stack.add(len - 2), + Object::Dict(_) | Object::List(_) | Object::Tuple(_) | Object::Str(_) + ) + { + return 0; + } + u32::from(subscr_raise_missing(st, pc, len).is_some()) + } +} + /// `UNPACK_SEQUENCE n` as [`h_subscr_ref`] runs a subscript: through /// [`unpack_fast`] on the sequence in the top slot or at `src`, else on /// the stack through [`h_container`]. @@ -6051,6 +7810,12 @@ unsafe extern "C" fn h_store_subscr_ref( return len - 3; } own_operands(at, &[val, cont, key], owned); + // An instance whose `__setitem__` only stores into a dict attribute + // (`self.data[key] = value`): that store, in place. + if Interpreter::setitem_delegate(&*at.add(1), &*at.add(2), &*at) { + crate::release_run(at, 3); + return len - 3; + } h_container(st, ins, code, pc, len, flags >> 8) } } @@ -6061,12 +7826,24 @@ unsafe extern "C" fn h_store_subscr_ref( /// numbers; strings' concatenation, repetition and `%` formatting; two /// tuples' or lists' concatenation, and a list's in-place `+=`; a /// natively served instance's operator): -/// `0` the result at `at` (the operands released), anything else declined -/// untouched. +/// `0` the result at `at` (the operands released), [`KERNEL_RAISED`] two +/// ints' operation raised (untouched, the error kept: the caller takes it +/// at once with [`kernel_err_take`]), anything else declined untouched. unsafe extern "C" fn h_binop(at: *mut Object, kind: u32) -> u32 { // SAFETY: the code passes two initialized stack slots, and a kind the // compiler emitted (`BinOpKind` is `repr(u8)`). unsafe { + // `s + t` whose left operand nothing else holds (the result of + // the concatenation before it, in `a + b + c`): it grows in place + // rather than being copied into a new string and freed. + if kind as u8 == BinOpKind::Add as u8 { + if let (Object::Str(x), Object::Str(t)) = (&mut *at, &*at.add(1)) { + if crate::shared_value::SharedStr::try_append(x, t) { + crate::drop_hot_at(at.add(1)); + return 0; + } + } + } let (a, b) = (&*at, &*at.add(1)); // Two numbers (the core loop's in-line arm), a `bool` as its int // value (but `bool & bool` and its kin stay a `bool`: the core @@ -6108,13 +7885,27 @@ unsafe extern "C" fn h_binop(at: *mut Object, kind: u32) -> u32 { let r = match (a, b) { // Ints past the machine word, and big ints: the full handler's // bignum arithmetic (exact ints run no Python; an error, a - // division by zero say, is the core loop's to raise). + // division by zero say, is kept for the caller to raise, so + // that it's built once). (Object::Int(_) | Object::Long(_), Object::Int(_) | Object::Long(_)) => { - crate::core_bignum_op(a, b, kind).ok() + match crate::core_bignum_op(a, b, kind) { + Ok(v) => Some(v), + Err(e) => { + return if KERNEL_ERR.try_with(|c| c.set(Some(e))).is_ok() { + KERNEL_RAISED + } else { + 1 + }; + } + } } (Object::Str(_), _) | (Object::Int(_), Object::Str(_)) => { Interpreter::core_str_binop(a, b, kind) } + // Complex arithmetic (an exact `complex` with a number). + (Object::Complex(_), _) | (_, Object::Complex(_)) => { + crate::complex_binop_fast(a, b, kind) + } // A list's `+=` extends it in place (`list.__iadd__`), and is // the list itself (`a += a` too: the items are copied first). (Object::List(x), Object::List(y)) @@ -6142,6 +7933,79 @@ unsafe extern "C" fn h_binop(at: *mut Object, kind: u32) -> u32 { { Interpreter::core_seq_concat(a, b) } + // A short tuple's or list's repetition (a list's `*=` repeats + // it in place: the core loop's). + (Object::Tuple(_) | Object::List(_), Object::Int(_)) + | (Object::Int(_), Object::Tuple(_) | Object::List(_)) + if kind == BinOpKind::Mult + && (!inplace || !matches!(a, Object::List(_))) + && droppable(a) + && droppable(b) => + { + Interpreter::core_seq_repeat(a, b) + } + // Two dicts' union (`dict.__or__`) whose keys hash and compare + // natively. + (Object::Dict(_), Object::Dict(_)) + if !inplace && kind == BinOpKind::BitOr && droppable(a) && droppable(b) => + { + crate::dict_union_plain(a, b) + } + // Two sets' union, intersection, difference or symmetric + // difference whose keys hash and compare natively (the core + // loop's set lane; an in-place one mutates, and is its own). + (Object::Set(_) | Object::FrozenSet(_), Object::Set(_) | Object::FrozenSet(_)) + if !inplace + && matches!( + kind, + BinOpKind::BitOr | BinOpKind::BitAnd | BinOpKind::Sub | BinOpKind::BitXor + ) + && droppable(a) + && droppable(b) => + { + crate::set_algebra_fast(a, b, kind) + } + // A set's `|=` with a set whose keys hash and compare natively: + // the keys it lacks added in place (none leaves, so nothing is + // released), the set itself the result. + (Object::Set(_), Object::Set(_) | Object::FrozenSet(_)) + if inplace && kind == BinOpKind::BitOr && droppable(b) => + { + crate::setalg::update(a, b, kind).then(|| a.clone()) + } + // A dict's keys view against a set (`d.keys() & s`): a set. + (Object::DictView(_), Object::Set(_) | Object::FrozenSet(_)) + if !inplace + && matches!( + kind, + BinOpKind::BitOr | BinOpKind::BitAnd | BinOpKind::Sub | BinOpKind::BitXor + ) + && droppable(a) + && droppable(b) => + { + crate::keys_view_algebra(a, b, kind) + } + // `bytes % args` with plain conversions over ints and bytes + // (on success, everything released is one of those). + (Object::Bytes(t), Object::Int(_) | Object::Bytes(_) | Object::Tuple(_)) + if kind == BinOpKind::Mod && droppable(a) && droppable(b) => + { + crate::bytes_percent_simple(t, b).map(Object::new_bytes) + } + // A short `bytes`' repetition. + (Object::Bytes(x), Object::Int(n)) | (Object::Int(n), Object::Bytes(x)) + if kind == BinOpKind::Mult + && x.len().saturating_mul((*n).max(0) as usize) <= 1 << 20 + && droppable(a) + && droppable(b) => + { + if *n == 1 { + // (`b * 1` is `b` itself, as CPython shares it.) + Some(Object::Bytes(x.clone())) + } else { + crate::bytes_repeat(x, (*n).max(0) as usize) + } + } // Two `bytes`' concatenation (`_ALWAYS_SAFE_BYTES + safe`; // immutable, so `+=` is the same). (Object::Bytes(x), Object::Bytes(y)) @@ -6176,6 +8040,19 @@ unsafe extern "C" fn h_binop(at: *mut Object, kind: u32) -> u32 { _ => None, } } + // An `int` or `float` subclass that keeps its base's operator + // (`IntEnum.A + 1`): the payloads' (an exact number). + (Object::Instance(_), _) | (_, Object::Instance(_)) if droppable(a) && droppable(b) => { + number_payload_binop(a, b, kind, inplace).or_else(|| { + // A `list` or `tuple` subclass that keeps its base's + // `+` and `*` (not `+=`, which extends a list in + // place): the payloads' (a plain list or tuple). + if inplace { + return None; + } + Interpreter::seq_payload_binop(a, b, kind)?.ok() + }) + } _ => None, }; let Some(r) = r else { @@ -6188,6 +8065,40 @@ unsafe extern "C" fn h_binop(at: *mut Object, kind: u32) -> u32 { 0 } +/// [`h_binop`]'s answer for `a b` where either is an `int` or `float` +/// subclass's instance whose class keeps its base's methods for `op` (see +/// `Interpreter::binop_number_payload`): the operator over the payloads, +/// through the numbers' own arms (`None` where they decline, a division by +/// zero say, for the core loop to raise). +#[inline(never)] +fn number_payload_binop(a: &Object, b: &Object, op: BinOpKind, inplace: bool) -> Option { + use std::mem::ManuallyDrop; + let x = Interpreter::binop_number_payload(a, op)?; + let y = Interpreter::binop_number_payload(b, op)?; + let mut kind = op as u32; + if inplace { + kind |= weavepy_compiler::BINARY_OP_INPLACE_FLAG; + } + let mut pair = [ManuallyDrop::new(x), ManuallyDrop::new(y)]; + // SAFETY: two initialized slots; on `0` the first holds the result and + // the second is released, otherwise both are untouched. + unsafe { + let at = pair.as_mut_ptr().cast::(); + match h_binop(at, kind) { + 0 => Some(at.read()), + r => { + // (An error it kept is the full operation's to raise.) + if r == KERNEL_RAISED { + drop(kernel_err_take()); + } + ManuallyDrop::drop(&mut pair[0]); + ManuallyDrop::drop(&mut pair[1]); + None + } + } + } +} + /// `BINARY_OP` of `kind` over the values at `a` and `b` (a local's or a /// constant's, read in place) for a site that has seen a natively served /// operand (see `crate::native_site`): `0` the result written to the free @@ -6248,7 +8159,7 @@ unsafe extern "C" fn h_compare(at: *mut Object, arg: u32) -> u32 { Some(o) => o, None => return 1, }, - (Object::Instance(i), Object::Instance(_)) if i.cls_raw().native_kind.get() != 0 => { + (Object::Instance(i), _) if i.cls_raw().native_kind.get() != 0 => { let r = match Interpreter::core_native_compare(kind, a, b) { Some(Ok(r)) if droppable(a) && droppable(b) => r, _ => return 1, @@ -6391,11 +8302,18 @@ pub(crate) struct TruthSite { /// The version of a class whose instances the site found always true /// (no `__bool__` or `__len__`). ver: std::cell::Cell, + /// The version of a class whose instances' truth is a native method + /// (see [`crate::NativeTruthPlan`]), and that plan. + native: std::cell::Cell<(u64, crate::NativeTruthPlan)>, pc: u32, /// The stack slot of the value, or a local's free one above the stack. slot: u32, local: u32, last: u32, + /// The address of the site's direct-call cache, for an instance's + /// Python `__bool__` or `__len__` (see [`truth_call`]); `0` where the + /// code can't call (an inlined body, a value virtual below the slot). + direct: usize, } /// The truth of `v` for [`h_truth_local`] and [`h_truth_stack`], the tests @@ -6435,6 +8353,12 @@ unsafe fn truth_at(st: *mut State, v: &Object, site: &TruthSite) -> Option if ver != 0 && site.ver.get() == ver { return Some(true); } + let (nver, plan) = site.native.get(); + if ver != 0 && nver == ver { + if let Some(b) = plan.run(v) { + return Some(b); + } + } truth_instance(st, v, site)? } // Native objects with neither `__bool__` nor `__len__` (a @@ -6451,11 +8375,73 @@ unsafe fn truth_at(st: *mut State, v: &Object, site: &TruthSite) -> Option | Object::Coroutine(_) | Object::Frame(_) | Object::Traceback(_) => true, - _ => return None, + _ => return native_truth_rest(v), }) } } +/// The truth of a native value of the rarer kinds, decided with no Python +/// code: a class whose metaclass is `type` (another metaclass may define +/// `__bool__` or `__len__`), the descriptors and a slice (always true), a +/// complex number, a range, a live memoryview, a mapping proxy and a dict +/// view (by their lengths). `None` for anything else. +#[inline(never)] +fn native_truth_rest(v: &Object) -> Option { + Some(match v { + Object::Type(t) if t.metaclass_is_type() => true, + Object::Slice(_) + | Object::Property(_) + | Object::StaticMethod(_) + | Object::ClassMethod(_) + | Object::SlotDescriptor(_) + | Object::AsyncGenerator(_) + | Object::SimpleNamespace(_) + | Object::LazyIter(_) + | Object::WStr(_) => true, + Object::Complex(c) => c.real != 0.0 || c.imag != 0.0, + Object::Range(_) => v.is_truthy(), + Object::MemoryView(mv) if !mv.released.get() => mv.len.get() > 0, + // SAFETY: (each) a read between two instructions. + Object::MappingProxy(d) => !unsafe { d.peek() }?.is_empty(), + Object::DictView(view) => !unsafe { view.dict.peek() }?.is_empty(), + _ => return None, + }) +} + +/// [`h_truth`]'s test of a native value its own arms leave out: the kinds +/// [`truth_at`] tests in line, then [`native_truth_rest`]'s, for a value +/// another owner keeps alive (its release here frees nothing). +#[inline(never)] +fn native_truth_shared(v: &Object) -> Option { + let lives_on = v.strong_word().is_none_or(|w| { + // SAFETY: a counted variant's word, live while `v` is. + unsafe { &*w }.load(std::sync::atomic::Ordering::Relaxed) > 1 + }); + if !lives_on { + return None; + } + Some(match v { + Object::Bytes(b) => !b.is_empty(), + // SAFETY: (each) a read between two instructions. + Object::ByteArray(b) => !unsafe { b.peek() }?.is_empty(), + Object::Set(set) => !unsafe { set.peek() }?.is_empty(), + Object::FrozenSet(set) => !set.is_empty(), + Object::Long(b) => b.sign() != num_bigint::Sign::NoSign, + Object::File(_) + | Object::Function(_) + | Object::Builtin(_) + | Object::BoundMethod(_) + | Object::Module(_) + | Object::Code(_) + | Object::Iter(_) + | Object::Generator(_) + | Object::Coroutine(_) + | Object::Frame(_) + | Object::Traceback(_) => true, + _ => return native_truth_rest(v), + }) +} + /// [`truth_at`] of an instance the site hasn't found always true. #[inline(never)] unsafe fn truth_instance(st: *mut State, v: &Object, site: &TruthSite) -> Option { @@ -6466,7 +8452,13 @@ unsafe fn truth_instance(st: *mut State, v: &Object, site: &TruthSite) -> Option site.ver.set(ver); } } - (*(*st).interp).leaf_instance_truth(v) + let r = (*(*st).interp).leaf_instance_truth(v); + if let (Some(_), Object::Instance(inst)) = (r, v) { + if let Some(plan) = (*(*st).interp).native_truth_plan(inst) { + site.native.set(plan); + } + } + r } } @@ -6485,6 +8477,11 @@ unsafe extern "C" fn h_truth_local(st: *mut State, site: *const TruthSite) -> u3 .stack .add(s.slot as usize) .write(crate::clone_hot(&*at)); + if s.direct != 0 { + if let Some(r) = truth_call(st, s) { + return r; + } + } left(st, s.pc, s.last, s.slot as usize + 1) } } @@ -6501,6 +8498,11 @@ unsafe extern "C" fn h_truth_stack(st: *mut State, site: *const TruthSite) -> u3 let s = &*site; let at = (*st).stack.add(s.slot as usize); let Some(b) = truth_at(st, &*at, s) else { + if s.direct != 0 { + if let Some(r) = truth_call(st, s) { + return r; + } + } return left(st, s.pc, s.last, s.slot as usize + 1); }; if plain_release(&*at) { @@ -6510,6 +8512,55 @@ unsafe extern "C" fn h_truth_stack(st: *mut State, site: *const TruthSite) -> u3 } } +/// [`h_truth_local`]'s and [`h_truth_stack`]'s test of an instance whose +/// class decides its truth with a Python `__bool__` (or `__len__`), the +/// value at the site's slot: the method called directly ([`dunder_call`]), +/// its result taken as `TO_BOOL` takes it ([`crate::truth_result`]). The +/// truth, a status (`RAISED` for a result the protocol refuses), or `None` +/// declined with the value still in its slot. +/// +/// # Safety +/// +/// As [`h_truth_stack`]'s, the site's slot holding the value with room for +/// one more above it, and nothing virtual below it (`s.direct` says so). +#[inline(never)] +unsafe fn truth_call(st: *mut State, s: &TruthSite) -> Option { + // SAFETY: the caller's contract. + unsafe { + let st = &mut *st; + if st.sw.is_null() { + return None; + } + let slot = s.slot as usize; + let at = st.stack.add(slot); + let Object::Instance(inst) = &*at else { + return None; + }; + let (f, from_len) = Interpreter::truth_function(inst)?; + let site = s.direct as *mut DirectSite; + let op = Some(records::MethodOp::Truth(from_len)); + match dunder_call(st, s.pc as usize, slot, 1, f, site, op) { + CALL_DECLINED => None, + 0 => match crate::truth_result(at.read(), from_len) { + Ok(b) => { + if (*st.maybe_dead).get() { + at.write(Object::Bool(b)); + return Some(left_marked(st, s.pc, slot + 1)); + } + Some(u32::from(b)) + } + Err(e) => { + st.len = slot; + st.pc = s.pc as usize + 1; + st.err = Some(e); + Some(RAISED) + } + }, + r => Some(r), + } + } +} + /// [`h_truth_stack`]'s release of a value it may free. #[inline(never)] unsafe fn truth_release(st: *mut State, s: &TruthSite, at: *mut Object, b: bool) -> u32 { @@ -6551,7 +8602,10 @@ unsafe extern "C" fn h_truth(st: *mut State, at: *mut Object) -> u32 { Some(b) => b, None => return 2, }, - _ => return 2, + _ => match native_truth_shared(v) { + Some(b) => b, + None => return 2, + }, }; if !droppable(v) { return 2; @@ -6598,6 +8652,19 @@ unsafe extern "C" fn h_local_method( let st = &mut *st; let (code, ext, pc) = (&*code, &*ext, pc as usize); let local = &*st.locals.add(code.instructions[pc].arg as usize); + // (The receivers `core_local_method` serves; any other, a stream + // say, declines here before its set-up.) + if !matches!( + local, + Object::Instance(_) + | Object::Module(_) + | Object::List(_) + | Object::Dict(_) + | Object::Set(_) + | Object::Str(_) + ) { + return 1; + } let Some((r, call_pc)) = (*st.interp).core_local_method::( code, Some(ext), @@ -6627,6 +8694,10 @@ unsafe extern "C" fn h_local_method( } } +/// [`InstMethodSite::ver`] for an exact builtin receiver. (Class attribute +/// versions count up from 1.) +const BUILTIN_RECV: u64 = 0; + /// A `x.m()` site of compiled code whose method is native (see /// [`h_inst_native`]). pub(crate) struct InstMethodSite { @@ -6634,10 +8705,16 @@ pub(crate) struct InstMethodSite { /// The fast half the call site settled on, or `None` for a body that /// is a leaf whole. fast: Option, - /// The receiver's class attribute version the method was cached under. + /// The receiver's class attribute version the method was cached under, + /// or [`BUILTIN_RECV`] for an exact builtin receiver (its tag checked + /// in line, so nothing shadows the method). ver: u64, nargs: u32, call_pc: u32, + /// The method's name and its Python hash: an instance whose own + /// attributes hold the name shadows the method. + name: Box, + hash: i64, } /// `x.m(a, b)` (the site's `nargs` of them, at `a` and `b`) on the instance @@ -6646,8 +8723,8 @@ pub(crate) struct InstMethodSite { /// at `out`; `RAISED` the method raised (the error in the state, the stack /// `len` deep and its last instruction the call); anything else declined /// untouched, when the receiver's class isn't at the site's version, reads -/// attributes its own way, or the instance holds attributes (which could -/// shadow the method). +/// attributes its own way, or the instance holds an attribute of the +/// method's name (which shadows it). unsafe extern "C" fn h_inst_native( st: *mut State, out: *mut Object, @@ -6661,12 +8738,16 @@ unsafe extern "C" fn h_inst_native( // and the arguments' initialized places, and its own site. unsafe { let site = &*site; - let Object::Instance(inst) = &*recv else { - return 1; - }; - let cls = inst.cls_raw(); - if cls.attr_version.get() != site.ver || !crate::inst_method_unshadowed(cls, inst) { - return 1; + if site.ver != BUILTIN_RECV { + let Object::Instance(inst) = &*recv else { + return 1; + }; + let cls = inst.cls_raw(); + if cls.attr_version.get() != site.ver + || !crate::inst_method_unshadowed_by(cls, inst, &site.name, site.hash) + { + return 1; + } } // Bitwise views, never dropped: the method reads them (and clones // what it keeps). @@ -6707,6 +8788,70 @@ unsafe extern "C" fn h_inst_native( } } +/// `m.name = value` for a plain module (no class of its own) and a name +/// it already holds (not a dunder): the entry's value replaced in place, +/// as `STORE_GLOBAL` rebinds one. The keys stay where they are, so the +/// dictionary isn't stamped (every cached global load of the module +/// stands) and the value epoch moves instead. The displaced value must +/// live on: a dying one is the full path's, which reaps it at once, as +/// CPython's `module_setattro` does. The builtins module is the full +/// path's too: a rebound builtin must stamp its dictionary (sites that +/// fuse `len(x)` hold only that stamp). `true` stored (the value cloned +/// in), `false` untouched. +fn module_store_leaf(m: &Rc, key: &Object, value: &Object) -> bool { + let Object::Str(name) = key else { + return false; + }; + if name.starts_with("__") + || m.name == "builtins" + || crate::object::module_classes_possible() + || crate::capi_watchers::dicts_active() + { + return false; + } + let Ok(mut d) = m.dict.try_borrow_mut() else { + return false; + }; + let Some(i) = d.get_index_of(&crate::object::StrKey(name)) else { + return false; + }; + match d.get_index(i) { + Some((_, old)) => { + let lives_on = old.strong_word().is_none_or(|w| { + // SAFETY: a counted variant's word, live while the + // dictionary holds the value. + unsafe { &*w }.load(std::sync::atomic::Ordering::Relaxed) > 1 + }); + if !lives_on || !droppable(old) { + return false; + } + } + None => return false, + } + let Some((_, slot)) = d.map_mut_value_store().get_index_mut(i) else { + return false; + }; + crate::object::bump_global_value_epoch(); + let old = std::mem::replace(slot, crate::clone_hot(value)); + drop(d); + drop(old); + true +} + +/// The write barrier of an in-line store into the instance at `recv` +/// (see `Lower::field_store_in_line`): tracked by the collector from here +/// on, as `PyInstance::note_slot_store` tracks one. +/// +/// # Safety +/// +/// `recv` is an initialized slot holding an instance. +unsafe extern "C" fn h_track_instance(recv: *const Object) { + // SAFETY: the caller's contract. + if let Object::Instance(i) = unsafe { &*recv } { + i.ensure_gc_tracked(); + } +} + /// `LOAD_FAST x` (the `pc`th instruction of `code`) and `x.attr = v` /// after it, with `v` at stack `slot`, as the core loop's fused arm runs /// it: `0` stored (the value left the stack), anything else declined @@ -6728,6 +8873,18 @@ unsafe extern "C" fn h_store_attr( } // (A site that has only run frameless has no inline cache yet.) match local { + // A property's setter site: the setter store decides. + Object::Instance(inst) + if Interpreter::setter_site_hit(code, pc + 1, inst).is_some() => + { + 1 + } + // A `threading.local`'s entry, through its native hook (the + // value cloned in, the slot's reference released). + Object::Instance(_) if Interpreter::local_store_fast(code, local, name, &*slot) => { + crate::drop_hot_at(slot); + 0 + } Object::Instance(inst) => u32::from(!Interpreter::leaf_attr_store_any( code, inst, @@ -6735,14 +8892,52 @@ unsafe extern "C" fn h_store_attr( name, &*slot, )), - // A function's or a plain class's attribute (`wrapper.__wrapped__ - // = f`, `Cls.count = n`): the stack form's store, over the value - // and a reference of the local's own. - Object::Function(_) | Object::Type(_) => { - let mut pair = [slot.read(), crate::clone_hot(local)]; - let recv = pair.as_mut_ptr().add(1); - let stored = if matches!(local, Object::Function(_)) { - Interpreter::core_function_store(code, name, recv) + // A plain module's attribute (`mod.flag = v`). + Object::Module(m) => { + let Some(key) = crate::code_name_obj(code, name) else { + return 1; + }; + if !module_store_leaf(m, key, &*slot) { + return 1; + } + // (The dict holds the value: the slot's reference goes.) + crate::drop_hot_at(slot); + 0 + } + // A `SimpleNamespace`'s attribute (`ns.x = v`): its dictionary's + // entry, as `object.__setattr__` stores it, when the store runs + // no code. + Object::SimpleNamespace(ns) => { + let Some(key @ Object::Str(s)) = crate::code_name_obj(code, name) else { + return 1; + }; + if s.starts_with("__") { + return 1; + } + let args = [ + Object::Dict(ns.clone()), + key.clone(), + crate::clone_hot(&*slot), + ]; + match crate::builtins::dict_setitem_leaf(&args) { + Some(Ok(_)) => { + drop(args); + // (The dict holds the value: the slot's reference + // goes.) + crate::drop_hot_at(slot); + 0 + } + _ => 1, + } + } + // A function's or a plain class's attribute (`wrapper.__wrapped__ + // = f`, `Cls.count = n`): the stack form's store, over the value + // and a reference of the local's own. + Object::Function(_) | Object::Type(_) => { + let mut pair = [slot.read(), crate::clone_hot(local)]; + let recv = pair.as_mut_ptr().add(1); + let stored = if matches!(local, Object::Function(_)) { + Interpreter::core_function_store(code, name, recv) } else { Interpreter::core_class_store(code, name, recv) }; @@ -6777,9 +8972,13 @@ unsafe extern "C" fn h_setter_store( recv: *mut Object, value: *mut Object, release_recv: u64, + site: *mut DirectSite, ) -> u32 { // SAFETY: the code passes its live state, its own code and the - // operands' initialized slots (the receiver's a local's or the stack's). + // operands' initialized slots (the receiver's a local's or the stack's, + // just above the value's), with four free slots from the value's up and + // nothing virtual below, and the store's direct-call cache (null in an + // inlined body: no direct call there). unsafe { let (r, v) = (&*recv, &*value); if !matches!(r, Object::Instance(_)) || !droppable(v) || !droppable(r) { @@ -6787,7 +8986,18 @@ unsafe extern "C" fn h_setter_store( } let interp = &mut *(*st).interp.cast_mut(); if !interp.leaf_setter_at(&*code, pc as usize, r, v) { - return 1; + if site.is_null() { + return 1; + } + return setter_call( + &mut *st, + &*code, + pc as usize, + recv, + value, + release_recv != 0, + site, + ); } crate::drop_hot_at(value); if release_recv != 0 { @@ -6797,6 +9007,120 @@ unsafe extern "C" fn h_setter_store( } } +/// [`h_setter_store`]'s store through the receiver's class's Python +/// `__setattr__`, or a property's Python setter, called directly +/// ([`direct_call`]) as `f(recv, name, value)` or `f(recv, value)`, the +/// call taking the operands' slots from the value's up (the receiver's +/// moved or copied in) and its result dropped: `0` stored, the operands +/// gone, `1` declined untouched (a function without native code, which +/// warms as a compiled caller's switched call warms its callee), `RAISED` +/// or `RELOAD` as [`h_call`]'s (the core loop drops a result it settles: +/// see `records::MethodOp::Store`). +/// +/// # Safety +/// +/// As [`h_setter_store`]'s, both operands droppable. +#[inline(never)] +unsafe fn setter_call( + st: &mut State, + code: &CodeObject, + pc: usize, + recv: *mut Object, + value: *mut Object, + stack_recv: bool, + site: *mut DirectSite, +) -> u32 { + // SAFETY: the caller's contract. + unsafe { + if st.sw.is_null() { + return 1; + } + let Object::Instance(inst) = &*recv else { + return 1; + }; + let name_idx = code.instructions[pc].arg; + let Some((f, how)) = Interpreter::store_attr_function(code, inst, name_idx) else { + return 1; + }; + // The call's argument before the receiver (a descriptor) or after + // it (the hook's name). + let (before, after) = match how { + crate::StoreCall::Hook => match crate::code_name_obj(code, name_idx) { + Some(n) => (None, Some(n.clone())), + None => return 1, + }, + crate::StoreCall::Setter => (None, None), + crate::StoreCall::Descriptor(d) => (Some(d), None), + }; + let slot = value.offset_from(st.stack) as usize; + let at = value; + // `[value, recv]` (or `[value]`, the receiver a local's) becomes the + // call `[f, recv, name, value]` (a setter's `[f, recv, value]`, a + // descriptor's `[f, descriptor, recv, value]`). + let v = at.read(); + let r = if stack_recv { + at.add(1).read() + } else { + crate::clone_hot(&*recv) + }; + let n = 2 + usize::from(before.is_some() || after.is_some()); + // (Where the receiver goes.) + let ri = 1 + usize::from(before.is_some()); + at.write(Object::Function(f)); + if let Some(d) = before { + at.add(1).write(d); + } + at.add(ri).write(r); + if let Some(name) = after { + at.add(2).write(name); + } + at.add(n).write(v); + match direct_call_out( + st, + pc, + slot, + slot + n + 1, + &mut *site, + Some(records::MethodOp::Store), + ) { + None => { + // Back as they were. + let f = at.read(); + let r = at.add(ri).read(); + let extra = (n == 3).then(|| at.add(if ri == 1 { 2 } else { 1 }).read()); + at.write(at.add(n).read()); + if stack_recv { + at.add(1).write(r); + } else { + drop(r); + } + drop(extra); + if let Object::Function(f) = &f { + let fc = f.code(); + if let Some(ext) = crate::code_vm_ext(&fc) { + ext.frame_jit + .warm_switched(&fc, ext, fc.varnames.len().max(n)); + } + } + drop(f); + 1 + } + Some(0) => { + // The setter's result (`None`, as a rule) goes. + let res = at.read(); + if !plain_release(&res) { + (*st.interp.cast_mut()).release(res); + } else { + std::mem::forget(res); + } + st.len = slot; + 0 + } + Some(r) => r, + } + } +} + /// `DELETE_ATTR` (the `pc`th instruction of `code`) of the instance atop a /// `len`-deep stack, as the core loop's arm runs it /// (`Interpreter::core_delete_attr`): `0` the attribute and the receiver @@ -6878,7 +9202,7 @@ unsafe extern "C" fn h_load_global( builtins_id, key_idx, } if builtins_id == crate::specialize::rc_id(&frame.builtins) - && !interp.globals_missing_any.get() + && !interp.globals_missing_gate() && slot.get() == [gid, g_stamp, b_stamp] => { ((*bdict).get_index(key_idx as usize), true) @@ -7054,7 +9378,7 @@ unsafe extern "C" fn h_global(st: *mut State, c: *mut GlobalCache) -> u32 { && (site.builtins == 0 || (word(F_BUILTINS) == site.builtins && stamp(site.bdata) == site.bstamp - && !(*(*st).interp).globals_missing_any.get())) + && !(*(*st).interp).globals_missing_gate())) { if site.len_of != 0 { return global_len_of(st, c); @@ -7076,7 +9400,8 @@ unsafe extern "C" fn h_global(st: *mut State, c: *mut GlobalCache) -> u32 { /// [`h_global`] at a site whose cache holds the fused `len(local)` (see /// [`GlobalCache::len_of`]), the namespaces matching: the length of a /// list, tuple, str or dict straight off the local, as `h_load_global` -/// fuses it; anything else through the miss, which tries the rest. +/// fuses it (an instance's through its leaf `__len__`); anything else +/// through the miss, which tries the rest. #[inline(never)] unsafe fn global_len_of(st: *mut State, c: *mut GlobalCache) -> u32 { // SAFETY: as `h_global`'s; `len_of` names one of the code's locals. @@ -7089,6 +9414,10 @@ unsafe fn global_len_of(st: *mut State, c: *mut GlobalCache) -> u32 { Object::Tuple(t) => Some(t.len()), Object::Str(s) => Some(crate::object::str_char_len(s)), Object::Dict(d) => d.try_borrow().ok().map(|d| d.len()), + v @ Object::Instance(_) => match (*st_ref.interp).leaf_instance_len(v) { + Some(Object::Int(n)) => usize::try_from(n).ok(), + _ => None, + }, _ => None, }; if let Some(n) = n.and_then(|n| i64::try_from(n).ok()) { @@ -7156,6 +9485,9 @@ unsafe fn global_miss(st: *mut State, c: *mut GlobalCache) -> u32 { site.last, ) }; + if (*c).name { + return name_miss(st, c); + } let r = h_load_global( st, code as *const CodeObject, @@ -7176,6 +9508,85 @@ unsafe fn global_miss(st: *mut State, c: *mut GlobalCache) -> u32 { } } +/// [`h_global`]'s miss at a module scope's `LOAD_NAME`: with no namespace +/// in front of the globals, the name found in the globals, then the +/// builtins, as the core loop's arm probes them, and the cache filled as +/// [`h_load_global`] fills it. Anything else (a namespace, a miss, which +/// raises, a key the probe can't compare) is the core loop's. +#[cold] +#[inline(never)] +unsafe fn name_miss(st: *mut State, c: *mut GlobalCache) -> u32 { + // SAFETY: as `h_global`'s; the dict reads are the core loop's arm's + // (no borrow is held while bytecode runs, and nothing here runs code). + unsafe { + let site = &mut *c; + let code = &*(site.code as *const CodeObject); + let frame = &*(*st).frame; + let interp = &*(*st).interp; + let out = |st| left(st, site.pc, site.last, site.len as usize); + if frame.rare.is_some() || code.is_class_body { + return out(st); + } + let Some(probe) = + crate::code_name_leaf_probe(code, code.instructions[site.pc as usize].arg) + else { + return out(st); + }; + let (gdict, bdict) = (frame.globals.as_ptr(), frame.builtins.as_ptr()); + let (hit, builtin) = match (*gdict).get_index_of(&probe) { + Some(i) => ((*gdict).get_index(i), false), + None if !interp.globals_missing_gate() => ( + (*bdict) + .get_index_of(&probe) + .and_then(|i| (*bdict).get_index(i)), + true, + ), + None => (None, true), + }; + let (Some((_, v)), false) = (hit, probe.saw_exotic()) else { + return out(st); + }; + site.len_of = 0; + site.cls_attr = false; + site.globals = std::ptr::addr_of!((*(*st).frame).globals) + .cast::() + .read(); + site.gstamp = (*gdict).mutation_stamp(); + site.gdata = gdict as u64; + (site.builtins, site.bstamp, site.bdata) = if builtin { + let b = std::ptr::addr_of!((*(*st).frame).builtins) + .cast::() + .read(); + (b, (*bdict).mutation_stamp(), bdict as u64) + } else { + (0, 0, 0) + }; + site.value = std::ptr::from_ref(v) as u64; + (*st) + .stack + .add(site.len as usize) + .write(crate::clone_hot(v)); + PUSHED + } +} + +/// `STORE_NAME` at a module scope: [`h_store_global`]'s store, with no +/// namespace in front of the globals; anything else declined untouched. +unsafe extern "C" fn h_store_name( + st: *mut State, + code: *const CodeObject, + name: u64, + at: *mut Object, +) -> u32 { + // SAFETY: as `h_store_global`'s. + unsafe { + if (*(*st).frame).rare.is_some() || (*code).is_class_body { + return 1; + } + h_store_global(st, code, name, at) + } +} + /// A `LOAD_GLOBAL` site's in-line cache: the frame's namespaces (their /// `Rc` handles' bits) and the dicts' stamps the value at `value` was /// found under (`builtins` 0 for a module global; `globals` 0 empty). @@ -7204,6 +9615,12 @@ pub(crate) struct GlobalCache { /// The site fuses the class's `Cls.CONST` its `LOAD_ATTR` reads (see /// `h_load_global`). cls_attr: bool, + /// The site is a module scope's `LOAD_NAME` (see [`name_miss`]). + name: bool, + /// The stamp slot of the `LOAD_ATTR` an inlined body's `LOAD_GLOBAL` + /// fuses (see `inline::h_inline_global_attr`), as an address; `0` + /// elsewhere. + attr_slot: u64, } /// Where the frame's namespaces, the interpreter's missing-globals flag @@ -7245,7 +9662,10 @@ unsafe extern "C" fn h_load_method( // `gen.send(...)` and the other generator and coroutine methods: the // bound method with an empty self slot, as the core loop's arm loads // it. - if matches!(&*top, Object::Generator(_) | Object::Coroutine(_)) { + if matches!( + &*top, + Object::Generator(_) | Object::Coroutine(_) | Object::AsyncGenerator(_) + ) { return u32::from(!crate::core_gen_method(code, name, top)); } // `module.func(...)`: the attribute with an empty self slot, as the @@ -7278,7 +9698,7 @@ unsafe extern "C" fn h_load_method( // the instance holds no dictionary and no value at or past the // name's position (see `Lower::load_method`). if let (Object::Instance(inst), false) = (&*top, cache.is_null()) { - let ver = inst.cls_raw().attr_version.get(); + let ver = inst.cls_raw().bind_version.get(); if let Some(e) = (*cache).poly.iter().find(|e| e.ver == ver) { let shadow_free = inst.dict.published().is_none() && match inst.dict.split_peek() { @@ -7309,13 +9729,40 @@ unsafe extern "C" fn h_load_method( return 0; } let Some(ms) = ext.method_slot(pc) else { - // An attribute the instance holds itself (a stored callable, - // `self.fget(x)`), at a site that never needed a method slot. if let Object::Instance(inst) = &*top { - if Interpreter::default_getattribute(inst.cls_raw()) - && crate::inst_may_shadow(inst, code, name) - { - return u32::from(!Interpreter::core_value_method(code, name, pc, top)); + let cls = inst.cls_raw(); + if Interpreter::default_getattribute(cls) { + // An attribute the instance holds itself (a stored + // callable, `self.fget(x)`), at a site that never needed + // a method slot. + if crate::inst_may_shadow(inst, code, name) { + return u32::from(!Interpreter::core_value_method(code, name, pc, top)); + } + // A plain function the class resolves the name to, at a + // site that has no method slot (its first call changed + // the class, and the core loop's fused call took the + // calls after): the method, kept in the site's in-line + // cache from here on. + let found = ext.name_objs.get(name as usize).and_then(|n| match n { + Object::Str(n) => cls.lookup(n), + _ => None, + }); + if let Some(f @ Object::Function(_)) = found { + if !cache.is_null() { + fill_method_cache( + &mut *cache, + cls, + cls.bind_version.get(), + &f, + ext, + name, + ); + } + let recv = top.read(); + top.write(f); + st.stack.add(len).write(recv); + return 0; + } } } return 1; @@ -7336,7 +9783,14 @@ unsafe extern "C" fn h_load_method( Some(f) => { let f = Object::Function(f); if !cache.is_null() { - fill_method_cache(&mut *cache, cls, ver, &f, ext, name); + fill_method_cache( + &mut *cache, + cls, + cls.bind_version.get(), + &f, + ext, + name, + ); } f } @@ -7347,7 +9801,14 @@ unsafe extern "C" fn h_load_method( Some(b) => { let b = Object::Builtin(b); if !cache.is_null() && builtin_counted() { - fill_method_cache(&mut *cache, cls, ver, &b, ext, name); + fill_method_cache( + &mut *cache, + cls, + cls.bind_version.get(), + &b, + ext, + name, + ); } b } @@ -7380,14 +9841,38 @@ unsafe extern "C" fn h_load_method( ms.set(ver, &f); Object::Function(f) } - // A value the class holds (a static method's - // function): the value with an empty self slot, - // as the core loop's arm loads it. - None => { - return u32::from(!Interpreter::core_value_method( - code, name, pc, top, - )) - } + None => match ext.name_objs.get(name as usize).and_then(|n| match n { + Object::Str(n) => cls.lookup(n), + _ => None, + }) { + // A plain function the class resolves the + // name to at a version no memo has seen (the + // site's first call changed the class): the + // site's method from here on. + Some(Object::Function(f)) => { + ms.set(ver, &f); + let f = Object::Function(f); + if !cache.is_null() { + fill_method_cache( + &mut *cache, + cls, + cls.bind_version.get(), + &f, + ext, + name, + ); + } + f + } + // A value the class holds (a static method's + // function): the value with an empty self + // slot, as the core loop's arm loads it. + _ => { + return u32::from(!Interpreter::core_value_method( + code, name, pc, top, + )) + } + }, }, }, }; @@ -7416,6 +9901,19 @@ unsafe extern "C" fn h_load_method( } } } + // A native adapter's method (`zip(xs, ys).__next__`, an exact + // `itertools` object's): its type's binding builtin, which the + // site keeps by the type's version, the adapter in the self + // slot. + Object::LazyIter(l) => { + let Some(b) = lazy_iter_method(ms, l, &*top, ext, name) else { + return 1; + }; + let recv = top.read(); + top.write(Object::Builtin(b)); + st.stack.add(len).write(recv); + return 0; + } recv => { let Some(b) = crate::builtin_recv_tag(recv).and_then(|tag| ms.get_builtin(tag)) else { @@ -7434,6 +9932,48 @@ unsafe extern "C" fn h_load_method( } } +/// The method `name` (a `name_objs` index of `ext`) of the native adapter +/// `l` (`recv`) when its type's attribute is a binding builtin that runs +/// through the native call lanes, as the attribute load finds it (no +/// adapter has attributes of its own): from the site's slot `ms` while +/// the type's version holds, else looked up and kept there. +fn lazy_iter_method( + ms: &crate::MethodSlot, + l: &crate::object::PyLazyIter, + recv: &Object, + ext: &CodeConstObjects, + name: u32, +) -> Option> { + if !crate::seqiter::lazy_methods_from_type(l) { + return None; + } + let owned; + let cls = match &l.cls { + Some(c) => c, + None => { + owned = crate::builtins::class_of(recv); + &owned + } + }; + let ver = cls.attr_version.get(); + if ver == 0 { + return None; + } + if let Some(b) = ms.get_inst_builtin(ver) { + return Some(b); + } + let Some(Object::Str(n)) = ext.name_objs.get(name as usize) else { + return None; + }; + match cls.lookup(n) { + Some(Object::Builtin(b)) if b.binds_instance && crate::native_call_ic_safe(b.name) => { + ms.set_inst_builtin(ver, &b); + Some(b) + } + _ => None, + } +} + /// `LOAD_SPECIAL` (the `pc`th instruction of `code`) of the receiver atop /// a `len`-deep stack, as the core loop's arm runs it /// (`Interpreter::core_load_special`): `0` the method and its self in @@ -7469,7 +10009,7 @@ unsafe extern "C" fn h_load_special( // stands. let [head, word] = std::ptr::from_ref(m).cast::<[u64; 2]>().read(); let cache = &mut *cache; - cache.ver = inst.cls_raw().attr_version.get(); + cache.ver = inst.cls_raw().bind_version.get(); cache.head = head; cache.func = word; } @@ -7521,8 +10061,10 @@ pub(crate) struct MethodSite { builtin_recv: u8, builtin: [u64; 2], /// A value of the receiver's own (`self.fn(...)` of a function an - /// instance holds): its class's version, its values' shared names and - /// the value's position among them (`0` versions: none yet). + /// instance holds): its class's version, its values' shared names (or + /// [`OWN_PUBLISHED`] for a materialized dict, [`OWN_SLOT`] for a + /// `__slots__` member) and the value's position among them (`0` + /// versions: none yet). own: (u64, u64, u32), /// A `staticmethod` or `classmethod` of the receiver's class the site /// loaded last: the class's version, whether it binds the class, and @@ -7530,6 +10072,18 @@ pub(crate) struct MethodSite { desc: Option<(u64, bool, Object)>, /// The class version whose attribute the site found isn't one. desc_miss: u64, + /// A native stream's method the site loaded last (`out.write`), or a + /// builtin value's of a kind the first cache doesn't hold: the kind, + /// as `builtins::method_memo_tag` keys it (a stream's methods follow + /// from the kind alone while it has no attributes of its own), and + /// the method. + stream: Option<(u8, Object)>, + /// A class receiver the site loaded an attribute of + /// (`object.__setattr__(self, ...)`, `dict.fromkeys(...)`, a user + /// class's static or class method): the class, its version, its + /// metaclass's, the attribute, and whether the class itself goes in + /// the self slot (a class method) or it stays empty. + type_attr: Option<(usize, u64, u64, Object, bool)>, } /// `LOAD_ATTR` with the method flag at `site`: the method in the @@ -7564,7 +10118,7 @@ unsafe extern "C" fn h_method(st: *mut State, site: *mut MethodSite) -> u32 { let hit = match &*top { Object::Instance(inst) => { let c = &s.cache; - let ver = inst.cls_raw().attr_version.get(); + let ver = inst.cls_raw().bind_version.get(); (c.ver == ver && ver != 0 && match inst.dict.split_peek() { @@ -7586,10 +10140,31 @@ unsafe extern "C" fn h_method(st: *mut State, site: *mut MethodSite) -> u32 { (*st).stack.add(s.len as usize).write(recv); return 0; } + // A native stream's method of the kind the site loaded it for (as + // `method_slow` finds it, without its other lanes' checks). + if let (Object::File(_), Some((want, f))) = (&*top, &s.stream) { + if crate::builtins::method_memo_tag(&*top) == Some(*want) { + let f = crate::clone_hot(f); + let recv = top.read(); + top.write(f); + (*st).stack.add(s.len as usize).write(recv); + return 0; + } + } method_slow(st, site) } } +/// [`MethodSite::own`]'s names for a value in an instance's materialized +/// dict, which the site finds by position and name (no shared-names table +/// sits at this address). +const OWN_PUBLISHED: u64 = 1; + +/// [`MethodSite::own`]'s names for a `__slots__` member (`self._fn(...)` +/// of a callable a slot holds), at its position in the class's slot +/// layout: a data descriptor, which no instance entry shadows. +const OWN_SLOT: u64 = 2; + /// [`h_method`] for a receiver the site's first cache doesn't know. #[inline(never)] unsafe fn method_slow(st: *mut State, site: *mut MethodSite) -> u32 { @@ -7622,6 +10197,62 @@ unsafe fn method_slow(st: *mut State, site: *mut MethodSite) -> u32 { } } } + // A native stream's method of the kind the site loaded it for, the + // stream in the self slot. Likewise a builtin value's of a kind the + // site's first cache doesn't hold (a big `int`'s `to_bytes`, a + // float's, a tuple's, a `bytes` object's): the kind and the site's + // name decide the method (a native iterator's `__next__`, too). + let stream_tag = match &*top { + Object::File(_) + | Object::Long(_) + | Object::Int(_) + | Object::Bool(_) + | Object::Float(_) + | Object::Complex(_) + | Object::Tuple(_) + | Object::Bytes(_) + | Object::ByteArray(_) + | Object::FrozenSet(_) + | Object::Range(_) + | Object::Iter(_) => crate::builtins::method_memo_tag(&*top), + _ => None, + }; + if let (Some(t), Some((want, f))) = (stream_tag, &s.stream) { + if t == *want { + let f = crate::clone_hot(f); + let recv = top.read(); + top.write(f); + (*st).stack.add(s.len as usize).write(recv); + return 0; + } + } + // A class's attribute the site loaded last, while the class's and + // its metaclass's versions hold: it and an empty self slot (or the + // class, for a class method), the receiver released. + let type_recv = match &*top { + Object::Type(t) if t.flags.is_builtin || t.attr_version.get() != 0 => { + let (ptr, ver, meta) = ( + Rc::as_ptr(t) as usize, + t.attr_version.get(), + meta_version(t), + ); + if let Some((p, v, m, attr, binds)) = &s.type_attr { + if *p == ptr && *v == ver && *m == meta { + let attr = crate::clone_hot(attr); + let recv = std::mem::replace(&mut *top, attr); + if *binds { + (*st).stack.add(s.len as usize).write(recv); + } else { + crate::drop_hot(recv); + (*st).stack.add(s.len as usize).write(Object::Unbound); + } + return 0; + } + } + Some((ptr, ver, meta, t.flags.is_builtin)) + } + _ => None, + }; // The instance's own value the site found last, at its position // among the instance's names while the class version holds (no // data descriptor of the name has come since): it and an empty @@ -7629,16 +10260,30 @@ unsafe fn method_slow(st: *mut State, site: *mut MethodSite) -> u32 { let recv = match &*top { Object::Instance(inst) => { let (ver, keys, idx) = s.own; - if ver != 0 - && ver == inst.cls_raw().attr_version.get() - && inst.dict.published().is_none() - && droppable(&*top) - { - if let Some(v) = inst - .dict - .split_peek() - .and_then(|split| split.get_over(keys as *const _, idx as usize)) - { + if ver != 0 && ver == inst.cls_raw().attr_version.get() && droppable(&*top) { + let v = if keys == OWN_SLOT { + // (The class's version settles its layout.) + inst.laid_out_slot(idx as usize) + } else if keys == OWN_PUBLISHED { + // (Its entry at the position, by the site's name.) + let code = &*s.code; + inst.attr_peek_index(idx as usize) + .filter(|(k, _)| { + crate::slot_name_matches( + code, + code.instructions[s.pc as usize].arg, + k, + ) + }) + .map(|(_, v)| v) + } else if inst.dict.published().is_none() { + inst.dict + .split_peek() + .and_then(|split| split.get_over(keys as *const _, idx as usize)) + } else { + None + }; + if let Some(v) = v { if !matches!(v, Object::Unbound) { let v = crate::clone_hot(v); crate::drop_hot(std::mem::replace(&mut *top, v)); @@ -7669,6 +10314,41 @@ unsafe fn method_slow(st: *mut State, site: *mut MethodSite) -> u32 { return 0; } } + // A `__slots__` member the class resolves the name to (its + // slot descriptor, which no instance entry shadows): the + // value and an empty self slot, its position for the next + // time. + if let Some(i) = slot_member_position(s, inst) { + if let (Some(v), true) = (inst.laid_out_slot(i as usize), droppable(&*top)) { + let v = crate::clone_hot(v); + s.own = (inst.cls_raw().attr_version.get(), OWN_SLOT, i); + crate::drop_hot(std::mem::replace(&mut *top, v)); + (*st).stack.add(s.len as usize).write(Object::Unbound); + return 0; + } + } + // A missing name a class's pure-leaf `__getattr__` answers + // (`w.count` of a wrapper delegating to its target), as the + // attribute load evaluates it: the value and an empty self + // slot, the receiver released. + if inst + .cls_raw() + .dunder(crate::types::Dunder::GetAttr) + .present() + && droppable(&*top) + { + let code = &*s.code; + let arg = code.instructions[s.pc as usize].arg; + if let Some(v) = code + .names + .get(arg as usize) + .and_then(|name| (*(*st).interp).leaf_getattr_hook(&*top, name, code, arg)) + { + crate::drop_hot(std::mem::replace(&mut *top, v)); + (*st).stack.add(s.len as usize).write(Object::Unbound); + return 0; + } + } Some(inst.clone()) } _ => None, @@ -7685,6 +10365,37 @@ unsafe fn method_slow(st: *mut State, site: *mut MethodSite) -> u32 { if r != 0 { return left(st, s.pc, s.last, s.len as usize); } + // A builtin type's unbound function or builtin, or a user class's + // plain, static or class method that the class's attributes alone + // decide: for the next time. + if let Some((ptr, ver, meta, builtin)) = type_recv { + let callable = &*(*st).stack.add(s.len as usize - 1); + let binds = match &*(*st).stack.add(s.len as usize) { + Object::Unbound => Some(false), + Object::Type(t) if Rc::as_ptr(t) as usize == ptr => Some(true), + _ => None, + }; + if let (Some(binds), Object::Builtin(_) | Object::Function(_)) = (binds, callable) { + if builtin || class_method_plain(s, ptr, binds) { + s.type_attr = Some((ptr, ver, meta, callable.clone(), binds)); + } + } + } + // A native stream's method bound to it: for the next stream of the + // kind. + if let Some(t) = stream_tag { + let (callable, self_slot) = ( + &*(*st).stack.add(s.len as usize - 1), + &*(*st).stack.add(s.len as usize), + ); + if let Object::Builtin(b) = callable { + // (The receiver itself in the self slot: the method as + // the kind's unbound builtin.) + if b.binds_instance && crate::builtins::method_memo_tag(self_slot) == Some(t) { + s.stream = Some((t, callable.clone())); + } + } + } // A `staticmethod`'s or `classmethod`'s function: the descriptor, for // the next time. if let Some(inst) = &recv { @@ -7709,15 +10420,24 @@ unsafe fn method_slow(st: *mut State, site: *mut MethodSite) -> u32 { let name = code .names .get(code.instructions[s.pc as usize].arg as usize); - if let (Some(name), None, Some(split)) = - (name, inst.dict.published(), inst.dict.split_peek()) - { + let found = &*(*st).stack.add(s.len as usize - 1); + let same = + |v: &Object| v.strong_word().is_some() && v.strong_word() == found.strong_word(); + if inst.dict.published().is_some() { + // A materialized dict's entry (an instance that assigned + // its names out of the class's order): where it sits. + let arg = code.instructions[s.pc as usize].arg; + if let Some((crate::LeafAttr::Value(v), Some(ix))) = + Interpreter::leaf_resolve_instance_attr_ix(code, &inst, arg) + { + if same(&v) { + s.own = (inst.cls_raw().attr_version.get(), OWN_PUBLISHED, ix); + } + } + } else if let (Some(name), Some(split)) = (name, inst.dict.split_peek()) { let (keys, _) = split.keys_and_len(); if let Some(idx) = split.position_str(name) { - let found = &*(*st).stack.add(s.len as usize - 1); - if split.get_over(keys as *const _, idx).is_some_and(|v| { - v.strong_word().is_some() && v.strong_word() == found.strong_word() - }) { + if split.get_over(keys as *const _, idx).is_some_and(same) { s.own = (inst.cls_raw().attr_version.get(), keys as u64, idx as u32); } } @@ -7730,6 +10450,31 @@ unsafe fn method_slow(st: *mut State, site: *mut MethodSite) -> u32 { } } +/// The position in `inst`'s class's slot layout of the `__slots__` member +/// the method site `s` loads, when the class resolves the name to that +/// member's descriptor under its default attribute lookup. `None` for any +/// other name. +fn slot_member_position(s: &MethodSite, inst: &crate::types::PyInstance) -> Option { + let cls = inst.cls_raw(); + if cls.slot_layout.get().is_none_or(Option::is_none) + || cls.attr_version.get() == 0 + || !Interpreter::default_getattribute(cls) + { + return None; + } + // SAFETY: the site's code is live (the caller's code runs it). + let code = unsafe { &*s.code }; + let name = code + .names + .get(code.instructions[s.pc as usize].arg as usize)?; + if matches!(name.as_str(), "__dict__" | "__weakref__") + || !matches!(cls.lookup(name), Some(Object::SlotDescriptor(sd)) if sd.name == *name && sd.default.is_none()) + { + return None; + } + inst.laid_out_position(name).map(|(i, _)| i) +} + /// Record in `s` the `staticmethod` or `classmethod` of `inst`'s class that /// the site's load just found, as `callable` and `self_slot` hold its /// result: its function, and the class (or nothing) bound to it. @@ -7737,21 +10482,77 @@ unsafe fn method_slow(st: *mut State, site: *mut MethodSite) -> u32 { /// # Safety /// /// `s`'s code is live. -unsafe fn note_method_desc( - s: &mut MethodSite, - inst: &Rc, - callable: &Object, - self_slot: &Object, -) { - // (Only a result shaped as a descriptor's is worth a lookup: a plain - // method's has the instance in the self slot. A builtin function kept - // on the class, `converter = time.localtime`, binds nothing either.) - let plain_builtin = matches!(callable, Object::Builtin(b) if !b.binds_instance); - if !(matches!(callable, Object::Function(_)) || plain_builtin) - || !matches!(self_slot, Object::Unbound | Object::Type(_)) - { - return; - } +/// Whether the user class at `ptr` (the site's receiver) yields its +/// method at the site as a function of its attributes and its +/// metaclass's: its metaclass reads attributes as `type` does and defines +/// the name, if at all, as a non-data descriptor (`EnumType.__new__`, +/// which the class's own entry overrides), and the class's own value is a +/// plain function (no self bound), a `staticmethod`, or a `classmethod` +/// (`binds`). +/// +/// # Safety +/// +/// `ptr` is the receiver class, alive on the stack. +unsafe fn class_method_plain(s: &MethodSite, ptr: usize, binds: bool) -> bool { + // SAFETY: the caller's contract. + let cls = unsafe { &*(ptr as *const crate::types::TypeObject) }; + if crate::object::exotic_str_keys_possible() { + return false; + } + // SAFETY: the site's code is live. + let code = unsafe { &*s.code }; + let Some(name) = code + .names + .get(code.instructions[s.pc as usize].arg as usize) + else { + return false; + }; + if !cls.metaclass_is_type() { + let meta = cls.metaclass_or_type(); + let ty = &crate::builtin_types::builtin_types().type_; + let same_getattr = match ( + meta.lookup("__getattribute__"), + ty.lookup("__getattribute__"), + ) { + (Some(a), Some(b)) => a.is_same(&b), + _ => false, + }; + let non_data = match meta.lookup(name) { + None => true, + Some( + Object::Function(_) + | Object::StaticMethod(_) + | Object::ClassMethod(_) + | Object::Builtin(_), + ) => true, + Some(_) => false, + }; + if !same_getattr || !non_data { + return false; + } + } + matches!( + (cls.lookup(name), binds), + (Some(Object::Function(_) | Object::StaticMethod(_)), false) + | (Some(Object::ClassMethod(_)), true) + ) +} + +unsafe fn note_method_desc( + s: &mut MethodSite, + inst: &Rc, + callable: &Object, + self_slot: &Object, +) { + // (Only a result shaped as a descriptor's is worth a lookup: a plain + // method's has the instance in the self slot. A builtin function kept + // on the class, `converter = time.localtime`, binds nothing either.) + let plain_builtin = matches!(callable, Object::Builtin(b) if !b.binds_instance); + if !(matches!(callable, Object::Function(_)) || plain_builtin) + || !matches!(self_slot, Object::Unbound | Object::Type(_)) + { + return; + } let cls = inst.cls_raw(); let ver = cls.attr_version.get(); if ver == s.desc_miss || !Interpreter::default_getattribute(cls) { @@ -7817,7 +10618,9 @@ fn builtin_counted() -> bool { }) } -/// Record in `cache` that instances of `cls` at version `ver` load the +/// Record in `cache` that instances of `cls` at bind version `ver` (see +/// `TypeObject::bind_version`: a cache holds a function and layout facts, +/// never a plain class value) load the /// method `f` (a plain function, or a native method when /// [`builtin_counted`]) for the name `co_names[name]` (the caller proved /// this instance doesn't shadow it, and that `cls` keeps the default @@ -8042,6 +10845,10 @@ fn slot_note(code: &CodeObject, recv: &Object, pc: usize, cache: *const SlotCach } } +/// How many receiver classes an [`AttrSite`] remembers a field for besides +/// its code's shared field slot. +const FIELD_MORE: usize = 3; + /// A `LOAD_ATTR` site of compiled code: what [`h_attr_local`] and /// [`h_attr_stack`] need, so that the code passes one pointer. pub(crate) struct AttrSite { @@ -8058,10 +10865,11 @@ pub(crate) struct AttrSite { property: bool, /// The site's field cache, if the code has any. field: *const FieldSlot, - /// A second receiver class's field, as `field` holds one: a split - /// instance's position for the class version (`0`, none), which the - /// site's polymorphic entries proved (see [`attr_hit`]). - field2: Cell<(u64, u32)>, + /// Other receiver classes' fields, as `field` holds one, newest first: + /// a split instance's position for the class version (`0`, none), + /// which the site's polymorphic entries proved, or a `__slots__` + /// member's place (see [`field_remember`]). + field2: [Cell<(u64, u32)>; FIELD_MORE], /// A property's direct call's cache, when nothing virtual lies below /// the receiver (the call can raise or switch); null otherwise. direct: *mut DirectSite, @@ -8075,6 +10883,15 @@ pub(crate) struct AttrSite { /// The class version under which the site's read last turned out not /// to be such a descriptor's. no_descr: Cell, + /// The class version under which a receiver's Python `__getattr__` + /// last answered the site's read in place (see `attr_miss`): the slow + /// path tries that hook first. + py_hook: Cell, + /// The class version under which a receiver's Python `__getattr__` + /// was last called directly for the site's read with the class's half + /// of the default lookup settled by that version (see [`hook_call`]): + /// the slow path calls the hook first. + py_hook_call: Cell, /// A receiver's class's native `__getattribute__` hook, for the /// class's version (see [`native_hook`]). hook: std::cell::RefCell)>>, @@ -8095,6 +10912,49 @@ pub(crate) struct AttrSite { /// as a value last (see [`builtin_attr_read`]): the receiver's kind /// and the method. builtin_attr: std::cell::RefCell)>>, + /// The pure leaf getters of a property the site last read in place, + /// latest first (see [`site_property_leaf`]): the class version each + /// read for, the getter function and its code, and the property's + /// getter cell. + prop_leaf: [Cell<(u64, usize, usize, usize)>; PROP_LEAVES], + /// Where an instance with a published dict (one `copy`, `pickle` or + /// `vars()` made) last had the site's name: its class's version and + /// the dict position (see [`pub_hit`]). + pub_hint: Cell<(u64, u32)>, + /// The version of an exception class whose read of the site's name is + /// one of its slot descriptors (`e.args`; see [`exc_slot_read`]). + exc_slot: Cell, + /// That descriptor's default for an unset slot, as [`EXC_DEFAULT_NONE`] + /// and its kin. + exc_default: Cell, + /// Which pseudo-slot the site's name is: [`EXC_SLOT_ARGS`], an + /// [`crate::types::ExcTail`] plus one, or [`EXC_SLOT_OTHER`]. + exc_which: Cell, +} + +/// [`AttrSite::exc_which`] of `args`, and of any other slot name. +const EXC_SLOT_ARGS: u8 = 0; +const EXC_SLOT_OTHER: u8 = 0xff; + +/// [`AttrSite::exc_default`]: the slot descriptor has no default (an unset +/// slot raises), `None`, `False`, or another value (read from the +/// descriptor). +const EXC_DEFAULT_ABSENT: u8 = 0; +const EXC_DEFAULT_NONE: u8 = 1; +const EXC_DEFAULT_FALSE: u8 = 2; +const EXC_DEFAULT_OTHER: u8 = 3; + +/// [`exc_slot_read`] at a site that has already found its name to be the +/// exception class's slot descriptor at the class's current version: the +/// read every `e.args` after the first makes, ahead of the lanes for +/// other instances. +#[inline] +fn exc_slot_known(site: &AttrSite, inst: &crate::types::PyInstance) -> Option { + let cls = inst.cls_raw(); + if !cls.flags.is_exception || site.exc_slot.get() != cls.attr_version.get() { + return None; + } + exc_slot_read(site, inst) } /// The value `recv`'s read at `site` finds through the site's caches past @@ -8114,14 +10974,9 @@ unsafe fn attr_hit<'a>(site: &'a AttrSite, recv: &'a Object) -> Option<&'a Objec match recv { Object::Instance(inst) => { let ver = inst.cls_raw().attr_version.get(); - if !site.field.is_null() { - let (want, idx) = (*site.field).get(); - if want == ver && want != 0 && idx & crate::SLOT_FIELD != 0 { - let v = inst.laid_out_slot((idx & !crate::SLOT_FIELD) as usize); - if v.is_some() { - return v; - } - } + let v = slot_field_hit(site, inst); + if v.is_some() { + return v; } let c = &site.cache; if c.cver.get() == ver && ver != 0 { @@ -8176,13 +11031,17 @@ unsafe fn field_hit_slow<'a>( if let Some((k, v)) = inst.attr_peek_index(ix as usize) { if crate::slot_name_matches(code, name, k) { // A split instance's position is its class's name's, - // for every instance at this version. - if inst.dict.published().is_none() - && inst - .split_field(ix as usize) - .is_some_and(|f| std::ptr::eq(f, v)) + // for every instance at this version; a published + // dict's is its hint's (see `pub_hit`, which checks + // the entry again), so the site's next read stops + // short of here. + if published { + site.pub_hint.set((ver, ix)); + } else if inst + .split_field(ix as usize) + .is_some_and(|f| std::ptr::eq(f, v)) { - site.field2.set((ver, ix)); + field_remember(site, ver, ix); } return Some(v); } @@ -8198,6 +11057,7 @@ unsafe fn field_hit_slow<'a>( if want == ver { if let Some((k, v)) = inst.attr_peek_index(key_idx as usize) { if crate::slot_name_matches(code, name, k) { + site.pub_hint.set((ver, key_idx)); return Some(v); } } @@ -8245,6 +11105,15 @@ unsafe fn attr_miss_quick( return Some(v); } } + // (A tuple's field first: it has no dict to probe.) + if matches!(inst.native.get(), Some(Object::Tuple(_))) { + if let Some(v) = (*site.ext) + .stamp_slot(site.pc as usize) + .and_then(|s| crate::tuple_field_hit(s, inst)) + { + return Some(v); + } + } if let Some(d) = inst_dict_read(site, inst) { return Some(d); } @@ -8302,6 +11171,21 @@ unsafe fn attr_miss_quick( } } +/// [`inst_dict_read`] once it has answered for the instance's class at +/// its version: the dict, from the memo alone (no name to compare). +#[inline] +fn inst_dict_known(site: &AttrSite, inst: &crate::types::PyInstance) -> Option { + let cls = inst.cls_raw(); + let (p, ver) = (std::ptr::from_ref(cls) as usize | 1, cls.attr_version.get()); + let known = site + .type_attr + .try_borrow() + .ok()? + .as_ref() + .is_some_and(|m| m.cls == p && m.ver == ver && ver != 0); + (known && inst.native.get().is_none()).then(|| Object::Dict(inst.dict_shared())) +} + /// `inst.__dict__` at `site`, where the instance's class keeps its default /// managed dict (see `Interpreter::managed_dict_attr`): the dict, the /// class's answer memoized in the site's class memo under its attribute @@ -8371,6 +11255,22 @@ unsafe fn native_field_read(site: &AttrSite, inst: &crate::types::PyInstance) -> unsafe fn attr_miss(st: *mut State, site: &AttrSite, at: *mut Object, local: bool) -> u32 { // SAFETY: the caller's contract. unsafe { + // An exact container's method read as a value (`j2lenget = + // j2len.get` in `difflib`'s inner loop): the site's memo, ahead of + // the checks below, none of which such a receiver meets. + if matches!( + &*at, + Object::List(_) | Object::Dict(_) | Object::Set(_) | Object::Str(_) + ) { + if let Some(v) = builtin_attr_read(st, site, &*at, local) { + if local { + (*st).stack.add(site.slot as usize).write(v); + } else { + crate::drop_hot(std::mem::replace(&mut *at, v)); + } + return 0; + } + } // (A live frame's line with the running activation's own // instruction, as `h_property`'s frame read has it.) let running = match &*at { @@ -8379,6 +11279,109 @@ unsafe fn attr_miss(st: *mut State, site: &AttrSite, at: *mut Object, local: boo } _ => None, }; + // A missing attribute a class's pure leaf `__getattr__` answers, + // evaluated in place ahead of the lanes that can't. + if let Object::Instance(inst) = &*at { + let cls = inst.cls_raw(); + if cls.dunder(crate::types::Dunder::GetAttr).present() { + let code = &*site.code; + let arg = code.instructions[site.pc as usize].arg; + // (The default lookup's certain miss, checked once for + // both of the hook's lanes.) + if let Some(name) = code.names.get(arg as usize).filter(|name| { + !crate::object::exotic_str_keys_possible() + && Interpreter::default_getattribute(cls) + && crate::default_lookup_misses(&*at, name, true) + }) { + // (A memo is kept only where the class's half of the + // lookup is settled by its version: see + // `leaf_getattr_hook_known`.) + let settled = Interpreter::getattr_hook_class_misses(inst, name); + let ver = cls.attr_version.get(); + if let Some(v) = + (*(*st).interp).leaf_getattr_hook_run(inst, &*at, name, code, arg) + { + if settled { + site.py_hook.set(ver); + } + if local { + (*st).stack.add(site.slot as usize).write(v); + } else { + if !droppable(&*at) { + drop(v); + return left(st, site.pc, site.last, site.slot as usize + 1); + } + crate::drop_hot(std::mem::replace(&mut *at, v)); + } + return 0; + } + // A hook that runs as an activation (a loop, a call or + // a handler in its body): none of the reads below can + // answer, so the hook is called now, directly where it + // has native code. + if !site.direct.is_null() + && !(*st).sw.is_null() + && code.instructions[site.pc as usize].op == OpCode::LoadAttr + { + if settled { + site.py_hook_call.set(ver); + } + if let Some(r) = hook_call(&mut *st, site, at, local, inst, name) { + return r; + } + if local || droppable(&*at) { + let (pc, slot) = (site.pc as usize, site.slot as usize); + let r = attr_lane(&mut *st, pc, slot, at, u64::from(local)); + if r != CALL_DECLINED { + return r; + } + } + } + } + } + } + // A bound method's receiver, function, or its function's names. + if let Object::BoundMethod(bm) = &*at { + let code = &*site.code; + let arg = code.instructions[site.pc as usize].arg; + if let Some(v) = Interpreter::leaf_bound_method_read(code, bm, arg) { + if local { + (*st).stack.add(site.slot as usize).write(v); + } else { + if !droppable(&*at) { + drop(v); + return left(st, site.pc, site.last, site.slot as usize + 1); + } + crate::drop_hot(std::mem::replace(&mut *at, v)); + } + return 0; + } + } + // A namespace's own entry (a `typing` union's `__args__`, a + // `SimpleNamespace`'s field): the full handler's first answer. + if let Object::SimpleNamespace(d) = &*at { + let code = &*site.code; + let v = code + .names + .get(code.instructions[site.pc as usize].arg as usize) + .and_then(|name| { + d.try_borrow() + .ok() + .and_then(|d| d.get(&crate::object::StrKey(name)).cloned()) + }); + if let Some(v) = v { + if local { + (*st).stack.add(site.slot as usize).write(v); + } else { + if !droppable(&*at) { + drop(v); + return left(st, site.pc, site.last, site.slot as usize + 1); + } + crate::drop_hot(std::mem::replace(&mut *at, v)); + } + return 0; + } + } // An instance of a class with a `__getattribute__` of its own: no // cached read applies, and the full handler runs the hook. if let Object::Instance(inst) = &*at { @@ -8401,9 +11404,68 @@ unsafe fn attr_miss(st: *mut State, site: &AttrSite, at: *mut Object, local: boo return r; } } + // A published dict's own value, its position remembered, or + // an exception's pseudo-slot. + if let Some(v) = pub_note(site, inst).or_else(|| exc_slot_read(site, inst)) { + if local { + (*st).stack.add(site.slot as usize).write(v); + } else { + if !droppable(&*at) { + drop(v); + return left(st, site.pc, site.last, site.slot as usize + 1); + } + crate::drop_hot(std::mem::replace(&mut *at, v)); + } + return 0; + } + // A property whose getter the site's slot holds for the class + // (settled after the code compiled, or read in a generator's + // step), evaluated in place when it's a pure leaf. (A property + // is a data descriptor: nothing the reads below find wins.) + if site_property_leaf(&mut *st, site, at, local) { + return 0; + } + // (Read now: a stack receiver leaves with the read.) + let ver = inst.cls_raw().attr_version.get(); + if let Some(ms) = (*site.ext) + .method_slot(site.pc as usize) + .filter(|m| m.holds_getter()) + { + let (pc, slot) = (site.pc as usize, site.slot as usize); + if property_leaf_here(&mut *st, site.code, pc, slot, at, u64::from(local)).is_some() + { + site_property_note(site, ver); + return 0; + } + // A getter the site cached for the class that runs as an + // activation (`TokenList.value` read over a token tree's + // nodes): the property wins over every read below, so it's + // called now. + // A generator's fast step can't run one (it has no switch): + // it declines at once, as every read below would. + if (*st).sw.is_null() && ms.getter(ver).is_some() { + return CALL_DECLINED; + } + if !(*st).sw.is_null() && !site.direct.is_null() { + if let Some(getter) = ms.getter(ver).map(|(f, _)| f) { + if let Some(r) = property_call( + &mut *st, + pc, + slot, + at, + u64::from(local), + site.direct, + getter, + ) { + return r; + } + } + } + } } if let Some(v) = attr_miss_quick(site, &*at, local, running) .or_else(|| builtin_attr_read(st, site, &*at, local)) + .or_else(|| leaf_property_read(st, site, &*at, local)) { if local { (*st).stack.add(site.slot as usize).write(v); @@ -8431,7 +11493,7 @@ unsafe fn attr_miss(st: *mut State, site: &AttrSite, at: *mut Object, local: boo } // A certain miss (an unset `__slots__` member among them) raises in // place, as the full handler would, whatever else the site can do. - if let Some(r) = attr_miss_raise(st, site, at, local) { + if let Some(r) = attr_miss_raise(st, site, at, local, false) { return r; } if site.direct.is_null() { @@ -8502,6 +11564,32 @@ fn native_hook( /// # Safety /// /// As [`descr_get`]'s. +/// [`native_hook_call`] for an instance whose class has a native +/// `__getattribute__` hook ([`native_hook`]), ahead of the slow paths' +/// lanes for the default lookup, none of which can answer it: `None` for +/// any other receiver, or when the call declined. +/// +/// # Safety +/// +/// As [`native_hook_call`]'s. +#[inline(always)] +unsafe fn native_hook_first( + st: *mut State, + site: &AttrSite, + at: *mut Object, + local: bool, + inst: &crate::types::PyInstance, +) -> Option { + let cls = inst.cls_raw(); + if Interpreter::default_getattribute(cls) { + return None; + } + let hook = native_hook(site, cls)?; + // SAFETY: the caller's contract. + let r = unsafe { native_hook_call(st, site, at, local, hook) }; + (r != CALL_DECLINED).then_some(r) +} + #[inline(never)] unsafe fn native_hook_call( st: *mut State, @@ -8584,6 +11672,19 @@ unsafe fn descr_get(st: *mut State, site: &AttrSite, at: *mut Object, local: boo site.no_descr.set(inst.cls_raw().attr_version.get()); return CALL_DECLINED; }; + // `member.name` / `member.value` through `enum.property`: the + // member's field, read in place (a stack receiver another owner + // holds released). + if local || Rc::strong_count(inst) > 1 { + if let Some(v) = Interpreter::enum_property_value(&descr, inst) { + let base = st.stack.add(slot); + if !local { + crate::drop_hot_at(base); + } + base.write(v); + return 0; + } + } let owner = Object::Type(inst.cls()); // The call's operands from the site's slot: the descriptor, the // receiver (a local's copied, the stack's moved up) and its class. @@ -8617,7 +11718,9 @@ unsafe fn descr_get(st: *mut State, site: &AttrSite, at: *mut Object, local: boo /// without running code (see `attr_certainly_missing`): its /// `AttributeError` raised here, as the full handler would raise it, a /// stack receiver gone (`RAISED`, the error in `st` for the catch block). -/// `None`, untouched, for anything else. +/// `None`, untouched, for anything else. `known`: the caller proved the +/// miss (an unset `__slots__` member, see [`slot_unset_known`]), which +/// isn't looked up again. /// /// # Safety /// @@ -8628,6 +11731,7 @@ unsafe fn attr_miss_raise( site: &AttrSite, at: *mut Object, local: bool, + known: bool, ) -> Option { // SAFETY: the caller's contract. unsafe { @@ -8646,10 +11750,29 @@ unsafe fn attr_miss_raise( let recv = &*at; if !matches!(recv, Object::Instance(_)) || (!local && !droppable(recv)) - || !crate::attr_certainly_missing(recv, name) + || !(known || crate::attr_certainly_missing(recv, name)) { return None; } + // A clause that can't observe the `AttributeError` catches it + // (see `blind_raise`): none is built. The clause cuts the stack, + // so all of it has to be on the frame's (the site's `direct` + // says so: see `Lower::load_attr_shared`). (A receiver the stack + // alone holds would die after the clause's body instead of before + // it: that one raises as before.) + if !site.direct.is_null() && (local || held_elsewhere(recv)) { + let keep = (!local).then(|| at.read()); + st.len = site.slot as usize; + st.pc = site.pc as usize + 1; + if blind_raise(st, &crate::builtin_types::builtin_types().attribute_error) { + drop(keep); + return Some(RAISED); + } + if let Some(keep) = keep { + at.write(keep); + } + } + let recv = &*at; let name_obj = (&*site.ext).name_objs.get(ins.arg as usize); let err = match crate::certain_miss_error_obj(recv, name, name_obj) { crate::RuntimeError::PyException(mut exc) => { @@ -8693,63 +11816,457 @@ unsafe fn field_hit<'a>(site: &AttrSite, inst: &'a crate::types::PyInstance) -> if want == ver && want != 0 && idx & crate::SLOT_FIELD == 0 { return inst.split_field(idx as usize); } - let (want, idx) = site.field2.get(); - if want == ver && want != 0 { - return inst.split_field(idx as usize); + // (A published dict's fields are its hint's: the entries below + // place split fields.) + if inst.dict.published().is_some() { + return pub_hit(site, inst); + } + if ver != 0 { + for e in &site.field2 { + let (want, idx) = e.get(); + if want == ver && idx & crate::SLOT_FIELD == 0 { + return inst.split_field(idx as usize); + } + } } None } } -/// [`h_attr_local`] at a site that last read a `__slots__` member. -unsafe extern "C" fn h_attr_local_slot(st: *mut State, site: *const AttrSite) -> u32 { - // SAFETY: as `h_attr_local`'s. - unsafe { - let s = &*site; - let at = (*st).locals.add(s.local as usize); - if let Object::Instance(inst) = &*at { - let (want, idx) = (*s.field).get(); - if want == inst.cls_raw().attr_version.get() && idx & crate::SLOT_FIELD != 0 { - if let Some(v) = inst.laid_out_slot((idx & !crate::SLOT_FIELD) as usize) { - (*st).stack.add(s.slot as usize).write(crate::clone_hot(v)); - return 0; - } - } +/// Remember, for `site`, that instances of the class at version `ver` keep +/// the site's attribute at `idx` (a split position, or with +/// [`crate::SLOT_FIELD`] a `__slots__` member's place in the class's +/// layout). A site holds a few such entries, its code's shared field slot +/// and [`FIELD_MORE`] of its own: the new entry goes first among its own, +/// and the oldest of them, displaced, moves to the shared slot. A site +/// that reads a handful of classes in turn so settles with one in each +/// place, whatever the shared slot held (nothing, where the code only ever +/// ran in line or frameless; a class version since retired); with a +/// single entry of its own, simply replaced, a site alternating between +/// two classes missed on every read. +/// +/// # Safety +/// +/// The site's field slot, if it has one, is live. +#[inline] +unsafe fn field_remember(site: &AttrSite, ver: u64, idx: u32) { + let mut carry = (ver, idx); + for e in &site.field2 { + carry = e.replace(carry); + // (An empty place, or the class's own older entry: nothing to + // carry further.) + if carry.0 == 0 || carry.0 == ver { + return; } - attr_local_slow(st, site) } + if !site.field.is_null() { + // SAFETY: the caller's contract. + unsafe { (*site.field).set(carry) }; + } +} + +/// A set `__slots__` member that neither of `site`'s entries names for the +/// instance's class (a site's second or later receiver class: the inline +/// cache, the slot cache and the shared field slot each hold one class, +/// and nothing re-specializes a site that compiled code or the frameless +/// evaluator runs), resolved as the default lookup resolves it: the class +/// finds the name's member descriptor first (see +/// [`crate::slot_member_class`]), and the instance, laid out over its +/// class's layout, holds a value there. The position is remembered (see +/// [`field_remember`]). `None` for anything else, an unset member (whose +/// `AttributeError` is the full path's) included. Without it, each such +/// read went through the whole miss chain and a lookup by name, some 1,300 +/// instructions. +/// +/// # Safety +/// +/// As [`attr_hit`]. +#[inline(never)] +unsafe fn slot_field_resolve<'a>( + site: &AttrSite, + inst: &'a crate::types::PyInstance, +) -> Option<&'a Object> { + let cls = inst.cls_raw(); + if cls.slot_layout.get().is_none_or(Option::is_none) { + return None; + } + let ver = cls.attr_version.get(); + if ver == 0 || cls.native_kind.get() != 0 || crate::object::exotic_str_keys_possible() { + return None; + } + // SAFETY: the site's code is live. + let code = unsafe { &*site.code }; + let name = code + .names + .get(code.instructions[site.pc as usize].arg as usize)?; + if matches!(name.as_str(), "__weakref__" | "__dict__") || !crate::slot_member_class(cls, name) { + return None; + } + let (i, _) = inst.laid_out_position(name)?; + // (An unset member's position too: its next miss raises at once, see + // `slot_unset_known`.) + // SAFETY: as above. + unsafe { field_remember(site, ver, i | crate::SLOT_FIELD) }; + // SAFETY: the caller's contract. + unsafe { inst.laid_out_slot(i as usize) } } -/// `LOAD_ATTR` at `site` of a local: `0` the value written to the site's -/// free slot, or a status (see [`LEFT_INTERP`]). -unsafe extern "C" fn h_attr_local(st: *mut State, site: *const AttrSite) -> u32 { - // SAFETY: the code passes its live state and its site, whose local and - // slot are in range. The read runs no code. - unsafe { - let s = &*site; - let at = (*st).locals.add(s.local as usize); - let v = match &*at { - Object::Instance(inst) => field_hit(s, inst), - Object::Module(_) => attr_hit(s, &*at), - _ => None, - }; - if let Some(v) = v { - (*st).stack.add(s.slot as usize).write(crate::clone_hot(v)); - return 0; - } - attr_local_slow(st, site) +/// Whether `site` read a `__slots__` member of `inst`'s class at its +/// version (its position remembered by [`slot_field_resolve`]) that +/// `inst` hasn't set: a certain miss unless the class has a `__getattr__` +/// (a `try: self._tail_cached` / `except AttributeError:` read of +/// `pathlib`'s). Such a read went through every probe of the slow helpers +/// and a class lookup before it raised. +/// +/// # Safety +/// +/// As [`slot_field_hit`]'s. +#[inline(never)] +unsafe fn slot_unset_known(site: &AttrSite, inst: &crate::types::PyInstance) -> bool { + let cls = inst.cls_raw(); + let ver = cls.attr_version.get(); + if ver == 0 || cls.dunder(crate::types::Dunder::GetAttr).present() { + return false; } + let unset = |(want, idx): (u64, u32)| { + // SAFETY: as in `slot_field_hit`: the position was noted for this + // class at this version, over its own layout. + want == ver + && idx & crate::SLOT_FIELD != 0 + // Unset in the laid-out block itself: storage in another form + // (a natively built `Decimal`'s) reads `None` from + // `laid_out_slot` though the member is set. + && matches!( + unsafe { inst.laid_out_slot_any((idx & !crate::SLOT_FIELD) as usize) }, + Some(Object::Unbound) + ) + }; + // SAFETY: the site's field slot lives as long as the code does. + (!site.field.is_null() && unset(unsafe { (*site.field).get() })) + || site.field2.iter().any(|e| unset(e.get())) } -/// [`h_attr_local`] past its commonest shape. +/// The value at the position [`AttrSite::pub_hint`] remembers in `inst`'s +/// published dict, if the class is at the hint's version (so no data +/// descriptor has come to shadow the dict) and that entry is still the +/// site's name. +/// +/// # Safety +/// +/// As [`attr_hit`]. #[inline(never)] -unsafe extern "C" fn attr_local_slow(st: *mut State, site: *const AttrSite) -> u32 { - // SAFETY: as `h_attr_local`'s. +unsafe fn pub_hit<'a>(site: &AttrSite, inst: &'a crate::types::PyInstance) -> Option<&'a Object> { + let (ver, idx) = site.pub_hint.get(); + if ver == 0 || inst.cls_raw().attr_version.get() != ver { + return None; + } + // SAFETY: the caller's contract; the site's code is live. unsafe { - let site = &*site; - let at = (*st).locals.add(site.local as usize); - let slot = site.slot as usize; - match &*at { + let (k, v) = inst.attr_peek_index(idx as usize)?; + let code = &*site.code; + crate::slot_name_matches(code, code.instructions[site.pc as usize].arg, k).then_some(v) + } +} + +/// A read at `site` of an exception's pseudo-slot (`e.args`): the value +/// its slot storage holds, when the class resolves the site's name to a +/// slot descriptor (a data descriptor: no instance dict shadows it), as +/// the site last found for the class's version; an unset one's default +/// (a never-raised exception's `__traceback__` is `None`). `None` for +/// anything else, an unset slot with no default included. +fn exc_slot_read(site: &AttrSite, inst: &crate::types::PyInstance) -> Option { + let cls = inst.cls_raw(); + if !cls.flags.is_exception { + return None; + } + // SAFETY: the site's code is live. + let code = unsafe { &*site.code }; + let name = code + .names + .get(code.instructions[site.pc as usize].arg as usize)?; + let ver = cls.attr_version.get(); + if ver == 0 { + return None; + } + if site.exc_slot.get() != ver { + let Some(Object::SlotDescriptor(sd)) = cls.lookup(name) else { + return None; + }; + site.exc_default.set(match &sd.default { + None => EXC_DEFAULT_ABSENT, + Some(Object::None) => EXC_DEFAULT_NONE, + Some(Object::Bool(false)) => EXC_DEFAULT_FALSE, + Some(_) => EXC_DEFAULT_OTHER, + }); + site.exc_which + .set(match crate::types::ExcTail::of_name(name) { + Some(which) => which as u8 + 1, + None if &**name == "args" => EXC_SLOT_ARGS, + None => EXC_SLOT_OTHER, + }); + site.exc_slot.set(ver); + } + let held = match site.exc_which.get() { + EXC_SLOT_ARGS => inst.exc_args_get(), + w @ 1..=4 => inst.exc_tail_get(match w { + 1 => crate::types::ExcTail::Traceback, + 2 => crate::types::ExcTail::Context, + 3 => crate::types::ExcTail::Cause, + _ => crate::types::ExcTail::SuppressContext, + }), + _ => inst.slot_get(name), + }; + held.or_else(|| match site.exc_default.get() { + EXC_DEFAULT_NONE => Some(Object::None), + EXC_DEFAULT_FALSE => Some(Object::Bool(false)), + EXC_DEFAULT_OTHER => match cls.lookup(name) { + Some(Object::SlotDescriptor(sd)) => sd.default.clone(), + _ => None, + }, + _ => None, + }) +} + +/// A read at `site` of an instance with a published dict, resolved as the +/// leaf path resolves it: the dict's own value, its position remembered for +/// [`pub_hit`]; `None` for anything else. +/// +/// # Safety +/// +/// As [`attr_hit`]. +unsafe fn pub_note(site: &AttrSite, inst: &crate::types::PyInstance) -> Option { + inst.dict.published()?; + // SAFETY: the site's code is live. + let code = unsafe { &*site.code }; + let arg = code.instructions[site.pc as usize].arg; + let ver = inst.cls_raw().attr_version.get(); + match Interpreter::leaf_resolve_instance_attr_ix(code, inst, arg)? { + (crate::LeafAttr::Value(v), Some(ix)) if ver != 0 => { + site.pub_hint.set((ver, ix)); + Some(v) + } + _ => None, + } +} + +/// [`h_attr_local`] at a site that last read a `__slots__` member. +unsafe extern "C" fn h_attr_local_slot(st: *mut State, site: *const AttrSite) -> u32 { + // SAFETY: as `h_attr_local`'s. + unsafe { + let s = &*site; + let at = (*st).locals.add(s.local as usize); + if let Object::Instance(inst) = &*at { + let (want, idx) = (*s.field).get(); + if want == inst.cls_raw().attr_version.get() && idx & crate::SLOT_FIELD != 0 { + if let Some(v) = inst.laid_out_slot((idx & !crate::SLOT_FIELD) as usize) { + (*st).stack.add(s.slot as usize).write(crate::clone_hot(v)); + return 0; + } + } + } + attr_local_slow(st, site) + } +} + +/// `LOAD_ATTR` at `site` of a local: `0` the value written to the site's +/// free slot, or a status (see [`LEFT_INTERP`]). +/// The split field of `inst` at the position one of a polymorphic site's +/// entries (its own, then the code's shared slot) names for its class, while +/// its dict isn't published. +/// +/// # Safety +/// +/// As [`field_hit`]'s. +#[inline(always)] +unsafe fn poly_split_hit<'a>( + s: &AttrSite, + inst: &'a crate::types::PyInstance, +) -> Option<&'a Object> { + // SAFETY: the caller's contract. + unsafe { + let ver = inst.cls_raw().attr_version.get(); + if ver == 0 { + return None; + } + let mut idx = s + .field2 + .iter() + .map(Cell::get) + .find(|e| e.0 == ver) + .map(|e| e.1); + if idx.is_none() && !s.field.is_null() { + let (want, i) = (*s.field).get(); + if want == ver { + idx = Some(i); + } + } + idx.filter(|i| i & crate::SLOT_FIELD == 0) + .and_then(|i| inst.split_field(i as usize)) + } +} + +/// [`h_attr_local`] at a polymorphic site (see [`poly_split_hit`]). +/// +/// # Safety +/// +/// As [`h_attr_local`]'s. +unsafe extern "C" fn h_attr_local_poly(st: *mut State, site: *const AttrSite) -> u32 { + // SAFETY: as `h_attr_local`'s. + unsafe { + let s = &*site; + if let Object::Instance(inst) = &*(*st).locals.add(s.local as usize) { + if let Some(v) = poly_split_hit(s, inst) { + (*st).stack.add(s.slot as usize).write(crate::clone_hot(v)); + return 0; + } + } + h_attr_local(st, site) + } +} + +/// [`h_attr_stack`] at a polymorphic site (see [`poly_split_hit`]). +/// +/// # Safety +/// +/// As [`h_attr_stack`]'s. +unsafe extern "C" fn h_attr_stack_poly(st: *mut State, site: *const AttrSite) -> u32 { + // SAFETY: as `h_attr_stack`'s. + unsafe { + let s = &*site; + let at = (*st).stack.add(s.slot as usize); + if let Object::Instance(inst) = &*at { + if let Some(v) = poly_split_hit(s, inst) { + let v = crate::clone_hot(v); + if plain_release(&*at) { + at.write(v); + return 0; + } + drop(v); + } + } + h_attr_stack(st, site) + } +} + +unsafe extern "C" fn h_attr_local(st: *mut State, site: *const AttrSite) -> u32 { + // SAFETY: the code passes its live state and its site, whose local and + // slot are in range. The read runs no code. + unsafe { + let s = &*site; + let at = (*st).locals.add(s.local as usize); + let v = match &*at { + // (Or a class attribute the site memoized, as `h_attr_stack`.) + Object::Instance(inst) => field_hit(s, inst) + .map(crate::clone_hot) + .or_else(|| class_poly_hit(s, inst, &*at)), + Object::Module(_) => attr_hit(s, &*at).map(crate::clone_hot), + _ => None, + }; + if let Some(v) = v { + (*st).stack.add(s.slot as usize).write(v); + return 0; + } + attr_local_slow(st, site) + } +} + +/// A native method of the instance's class that the site last bound (an +/// `RLock`'s `__exit__`, read to be called with `*args`; see +/// `Interpreter::leaf_attr_resolve_site`), which the instance doesn't +/// shadow: bound to the receiver `recv`. +/// +/// # Safety +/// +/// The site's code and extension are live. +unsafe fn inst_builtin_bound( + site: &AttrSite, + inst: &crate::types::PyInstance, + recv: &Object, +) -> Option { + // SAFETY: the caller's contract. + let (code, ext) = unsafe { (&*site.code, &*site.ext) }; + let b = ext + .method_slot(site.pc as usize)? + .get_inst_builtin(inst.cls_raw().attr_version.get())?; + if crate::inst_may_shadow(inst, code, code.instructions[site.pc as usize].arg) { + return None; + } + Some(Object::BoundMethod(Rc::new( + crate::object::BoundMethod::new(recv.clone(), Object::Builtin(b)), + ))) +} + +/// A `__slots__` member the site's field slot names for the instance's +/// class at its version (`p.x` of a global's, after `slot_note`): read off +/// the instance's laid-out slots. +#[inline] +unsafe fn slot_field_hit<'a>( + site: &AttrSite, + inst: &'a crate::types::PyInstance, +) -> Option<&'a Object> { + let ver = inst.cls_raw().attr_version.get(); + if ver == 0 { + return None; + } + if !site.field.is_null() { + // SAFETY: the site's field slot lives as long as the code does. + let (want, idx) = unsafe { (*site.field).get() }; + if want == ver && idx & crate::SLOT_FIELD != 0 { + // SAFETY: as in `h_attr_local_slot`: the position was noted for + // this class at this version (`slot_field_note`), over its own + // layout. + let v = unsafe { inst.laid_out_slot((idx & !crate::SLOT_FIELD) as usize) }; + if v.is_some() { + return v; + } + } + } + // (The site's other classes: see `field_remember`. Only + // `slot_field_resolve` leaves a member's entry, for a class with a + // layout.) + if inst.cls_raw().slot_layout.get().is_none_or(Option::is_none) { + return None; + } + for e in &site.field2 { + let (want, idx) = e.get(); + if want == ver && idx & crate::SLOT_FIELD != 0 { + // SAFETY: as above (`slot_field_resolve` proved the position). + return unsafe { inst.laid_out_slot((idx & !crate::SLOT_FIELD) as usize) }; + } + } + None +} + +/// A named tuple's field (a data descriptor: no instance shadows it), as +/// the site's stamp remembers it for the instance's class version. The +/// field's descriptor never memoizes in the class memo, so every read of +/// one would otherwise take the slow lanes first. +/// +/// # Safety +/// +/// The site's extension is live. +#[inline] +pub(super) unsafe fn tuple_stamp_hit( + site: &AttrSite, + inst: &crate::types::PyInstance, +) -> Option { + if !matches!(inst.native.get(), Some(Object::Tuple(_))) { + return None; + } + // SAFETY: the caller's contract. + unsafe { (*site.ext).stamp_slot(site.pc as usize) } + .and_then(|x| crate::tuple_field_hit(x, inst)) +} + +/// [`h_attr_local`] past its commonest shape. +#[inline(never)] +unsafe extern "C" fn attr_local_slow(st: *mut State, site: *const AttrSite) -> u32 { + // SAFETY: as `h_attr_local`'s. + unsafe { + let site = &*site; + let at = (*st).locals.add(site.local as usize); + let slot = site.slot as usize; + match &*at { Object::Type(cls) => { if let Some(v) = type_attr_memo(site, cls) { (*st).stack.add(slot).write(v); @@ -8764,8 +12281,114 @@ unsafe extern "C" fn attr_local_slow(st: *mut State, site: *const AttrSite) -> u } // (A class attribute the site has read before.) Object::Instance(inst) => { + // A named tuple's field, as its stamp remembers it for the + // class's version (no memo `h_attr_local` probes holds a + // field descriptor's answer): first, since the lanes below + // can't answer it. + if let Some(v) = tuple_stamp_hit(site, inst) { + (*st).stack.add(slot).write(v); + return 0; + } + // A `threading.local`'s native `__getattribute__`, which + // answers every read of it: called first, past lanes that + // serve only the default lookup. + if let Some(r) = native_hook_first(st, site, at, true, inst) { + return r; + } + // A property that runs as an activation, called first. + if let Some(r) = getter_first(st, site, at, true) { + return r; + } + // A `__slots__` member either of the site's entries names + // for the class (its second receiver class's). + if let Some(v) = slot_field_hit(site, inst) { + (*st).stack.add(slot).write(crate::clone_hot(v)); + return 0; + } + // An unset one: the raise, at once. + if slot_unset_known(site, inst) { + if let Some(r) = attr_miss_raise(st, site, at, true, true) { + return r; + } + } + // A property whose pure leaf getter the site ran for this + // class version (a data descriptor: it wins over every + // read below), evaluated ahead of the memos that can't + // answer it. + if site_property_leaf(&mut *st, site, at, true) { + return 0; + } + // A read the class's Python `__getattr__` answered before, + // for this class version: the hook first (it checks the + // default lookup still misses), ahead of the memos that + // can't answer it. + let ver = inst.cls_raw().attr_version.get(); + if ver != 0 && site.py_hook.get() == ver { + let code = &*site.code; + let arg = code.instructions[site.pc as usize].arg; + if let Some(v) = code.names.get(arg as usize).and_then(|name| { + (*(*st).interp).leaf_getattr_hook_known(&*at, name, code, arg) + }) { + (*st).stack.add(slot).write(v); + return 0; + } + } + if ver != 0 && site.py_hook_call.get() == ver { + if let Some(r) = hook_call_known(st, site, at, true, inst) { + return r; + } + } + // An exception's pseudo-slot (`e.args`), as the site found + // it for the class's version. + if let Some(v) = exc_slot_known(site, inst) { + (*st).stack.add(slot).write(v); + return 0; + } + // A natively served value's public field (`dt.hour`), read + // off its packed state: every read of one comes here (the + // site keeps nothing for it), so it goes ahead of the + // lanes that probe the site's other memos. + if inst.cls_raw().native_kind.get() != 0 { + if let Some(v) = native_field_read(site, inst) { + (*st).stack.add(slot).write(v); + return 0; + } + } + // A polymorphic site's third class and on: the instance's + // own field at the position the site's table holds for the + // class version, at which the class resolved the name to + // the instance (no data descriptor, the default + // `__getattribute__`), so nothing below would answer + // otherwise. Reached only after the whole miss chain, such + // a read cost about a thousand instructions (a site reading + // `action.dest` over three action classes). + if let Some(v) = field_hit_slow(site, inst) { + (*st).stack.add(slot).write(crate::clone_hot(v)); + return 0; + } + // A `__slots__` member of a class the site hasn't read it + // from, likewise. + if let Some(v) = slot_field_resolve(site, inst) { + (*st).stack.add(slot).write(crate::clone_hot(v)); + return 0; + } + // `inst.__dict__`, as the site answered it before. + if let Some(v) = inst_dict_known(site, inst) { + (*st).stack.add(slot).write(v); + return 0; + } + // A named tuple's field (a data descriptor: no instance + // shadows it), as the site's stamp remembers it. + if let Some(v) = (*site.ext) + .stamp_slot(site.pc as usize) + .and_then(|s| crate::tuple_field_hit(s, inst)) + .or_else(|| inst_builtin_bound(site, inst, &*at)) + { + (*st).stack.add(slot).write(v); + return 0; + } if let Some(v) = - class_poly_hit(site, inst).or_else(|| instance_class_read(site, inst)) + class_poly_hit(site, inst, &*at).or_else(|| instance_class_read(site, inst)) { (*st).stack.add(slot).write(v); return 0; @@ -8821,7 +12444,12 @@ unsafe extern "C" fn h_attr_stack(st: *mut State, site: *const AttrSite) -> u32 let s = &*site; let at = (*st).stack.add(s.slot as usize); let v = match &*at { - Object::Instance(inst) => field_hit(s, inst).map(crate::clone_hot), + // (Or a class attribute the site memoized for the class, which + // the instance doesn't shadow: `self.LIMIT`.) + Object::Instance(inst) => field_hit(s, inst) + .or_else(|| slot_field_hit(s, inst)) + .map(crate::clone_hot) + .or_else(|| class_poly_hit(s, inst, &*at)), // A class's constant the site memoized (`Direction.FORWARD`). Object::Type(cls) => type_attr_memo(s, cls), // A module's value the site noted (`os.path`). @@ -8887,7 +12515,14 @@ unsafe fn builtin_attr_read( let name: &str = code .names .get(code.instructions[site.pc as usize].arg as usize)?; - if name.starts_with("__") { + // (Of the dunders, only the container protocol's methods, which the + // full read binds the same way: `quoter = d.__getitem__`.) + if name.starts_with("__") + && !matches!( + name, + "__getitem__" | "__setitem__" | "__delitem__" | "__contains__" | "__len__" | "__iter__" + ) + { return None; } // SAFETY: the interpreter outlives the code it runs. @@ -8900,6 +12535,44 @@ unsafe fn builtin_attr_read( Some(bind(&b)) } +/// A plain instance's read of a property whose getter is a builtin +/// registered as a leaf for any arguments (a struct sequence's field, as +/// `os.stat_result.st_mode`): the getter's result, or `None` for the full +/// path (which raises what the getter would). +unsafe fn leaf_property_read( + st: *mut State, + site: &AttrSite, + recv: &Object, + local: bool, +) -> Option { + let Object::Instance(inst) = recv else { + return None; + }; + if (!local && !droppable(recv)) || !Interpreter::default_getattribute(inst.cls_raw()) { + return None; + } + // SAFETY: the site's code is live. + let code = unsafe { &*site.code }; + let name: &str = code + .names + .get(code.instructions[site.pc as usize].arg as usize)?; + if name.starts_with("__") { + return None; + } + let Some(Object::Property(p)) = inst.cls_raw().lookup(name) else { + return None; + }; + let Object::Builtin(b) = p.fget() else { + return None; + }; + // SAFETY: the interpreter outlives the code it runs. + let interp = unsafe { &*(*st).interp }; + if !matches!(interp.leaf_call_kind(&b), Some(crate::LeafKind::Opaque)) { + return None; + } + (b.call)(std::slice::from_ref(recv)).ok() +} + /// The classes an attribute site's polymorphic class-attribute memo holds. const CLASS_POLY: usize = 4; @@ -8939,8 +12612,12 @@ pub(crate) struct ClassPolyEntry { /// # Safety /// /// `site`'s code is live. -unsafe fn class_poly_hit(site: &AttrSite, inst: &crate::types::PyInstance) -> Option { - let ver = inst.cls_raw().attr_version.get(); +unsafe fn class_poly_hit( + site: &AttrSite, + inst: &crate::types::PyInstance, + recv: &Object, +) -> Option { + let ver = inst.cls_raw().attr_version.get(); if ver == 0 { return None; } @@ -8966,7 +12643,19 @@ unsafe fn class_poly_hit(site: &AttrSite, inst: &crate::types::PyInstance) -> Op // version stands; the view is never dropped. let v = std::mem::ManuallyDrop::new(unsafe { std::ptr::from_ref(&e.val).cast::().read() }); - Some(crate::clone_hot(&v)) + // (A function, staticmethod or classmethod entry gives what its + // `__get__` gives through an instance: see `class_poly_note`.) + Some(match &*v { + Object::Function(_) => Object::BoundMethod(Rc::new(crate::object::BoundMethod::new( + recv.clone(), + crate::clone_hot(&v), + ))), + Object::StaticMethod(w) => w.func(), + Object::ClassMethod(w) => Object::BoundMethod(Rc::new( + crate::object::BoundMethod::py_method(Object::Type(inst.cls()), w.func()), + )), + _ => crate::clone_hot(&v), + }) } /// Remember what proves, at `site`, that an instance of `inst`'s class @@ -8999,20 +12688,40 @@ fn class_poly_prove(site: &AttrSite, inst: &crate::types::PyInstance, code: &Cod /// /// `site`'s code is live. unsafe fn class_poly_note(site: &AttrSite, inst: &crate::types::PyInstance, v: &Object) { - if !matches!( - v, + // (Values a read through an instance gives back as they are: plain + // data, a module (`pathlib`'s `self.parser`), or an object or class + // whose type has no `__get__`, such as a compiled pattern a class + // keeps.) + let plain = match v { Object::Str(_) - | Object::Int(_) - | Object::Float(_) - | Object::Bool(_) - | Object::None - | Object::Bytes(_) - | Object::Tuple(_) - | Object::FrozenSet(_) - | Object::List(_) - | Object::Dict(_) - | Object::Set(_) - ) { + | Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Bytes(_) + | Object::ByteArray(_) + | Object::Complex(_) + | Object::Range(_) + | Object::Module(_) + | Object::Tuple(_) + | Object::FrozenSet(_) + | Object::List(_) + | Object::Dict(_) + | Object::Set(_) => true, + Object::Instance(_) | Object::Type(_) => { + crate::builtins::class_of(v).lookup("__get__").is_none() + } + _ => false, + }; + // (Or a read a function, staticmethod or classmethod in the class gave: + // the entry itself is memoized, and a hit gives what its `__get__` + // gives, see `class_poly_hit`.) + let bound = !plain + && matches!( + v, + Object::Function(_) | Object::Builtin(_) | Object::BoundMethod(_) + ); + if !plain && !bound { return; } let cls = inst.cls_raw(); @@ -9036,6 +12745,24 @@ unsafe fn class_poly_note(site: &AttrSite, inst: &crate::types::PyInstance, v: & if crate::inst_may_shadow(inst, code, arg) { return; } + if bound { + let found = cls.lookup(name); + let entry = match (&found, v) { + (Some(f @ Object::Function(fun)), Object::BoundMethod(bm)) + if !bm.redispatch_descriptor + && matches!(&bm.function, Object::Function(g) if Rc::ptr_eq(fun, g)) => + { + f + } + (Some(w @ Object::StaticMethod(sm)), _) if sm.func().is_same(v) => w, + (Some(w @ Object::ClassMethod(_)), Object::BoundMethod(_)) => w, + _ => return, + }; + // SAFETY: as below. + let val = unsafe { std::ptr::from_ref(entry).cast::<[u64; 2]>().read() }; + class_poly_put(site, ver, val); + return; + } // The class's own entry, the very value the read gave (else the read // came from a descriptor, or a `__getattr__`: never memoized here). let same = cls.lookup(name).is_some_and(|found| match (v, &found) { @@ -9069,14 +12796,35 @@ fn type_attr_memo(site: &AttrSite, cls: &Rc) -> Option && m.ver == ver && ver != 0 && m.meta == meta_version(cls) - && !matches!(*m.val, Object::Unbound) => + && !matches!(*m.val, Object::Unbound) + && module_memo_stands(&m.val) => { - Some(crate::clone_hot(&m.val)) + Some(memo_value(&m.val, cls)) } _ => None, } } +/// Whether a class memo's value stands as the class's read: anything but a +/// module once some module got a class of its own (`module.__class__ = +/// Sub`, whose `__get__` would bind it), which no class version follows. +#[inline(always)] +fn module_memo_stands(val: &Object) -> bool { + !matches!(val, Object::Module(_)) || !crate::object::module_classes_possible() +} + +/// The read of a class's memoized value: the value itself, or, for a +/// native class method's descriptor, a method bound to the class. +#[inline] +fn memo_value(val: &Object, cls: &Rc) -> Object { + match val { + Object::ClassMethod(cm) => Object::BoundMethod(Rc::new( + crate::object::BoundMethod::py_method(Object::Type(cls.clone()), cm.func()), + )), + v => crate::clone_hot(v), + } +} + /// `inst.__class__` at `site`, where `object`'s descriptor is what answers /// (no `__class__` or `__getattribute__` anywhere on the class, which isn't /// a builtin's, and no extension body): the instance's class. This is @@ -9092,8 +12840,7 @@ fn instance_class_read(site: &AttrSite, inst: &Rc) -> return None; } let cls = inst.cls_raw(); - (inst.c_body.get() == 0 && !cls.flags.is_builtin && cls.class_attr_is_plain()) - .then(|| Object::Type(inst.cls())) + (inst.c_body.get() == 0 && cls.class_read_is_plain()).then(|| Object::Type(inst.cls())) } /// `x.__class__` of the value at `src` into the stack slot `dst` (the same @@ -9108,14 +12855,19 @@ unsafe extern "C" fn h_class_read(dst: *mut Object, src: *const Object) -> u32 { return 1; }; let cls = inst.cls_raw(); - if inst.c_body.get() != 0 || cls.flags.is_builtin || !cls.class_attr_is_plain() { + if inst.c_body.get() != 0 || !cls.class_read_is_plain() { return 1; } let ty = Object::Type(inst.cls()); if std::ptr::eq(dst.cast_const(), src) && !plain_release(&*src) { - // (The receiver's last reference: its release is the helper's.) - drop(ty); - return 1; + // The receiver's last reference (a fresh `super(C, obj)`'s): it + // dies here, and a finalizer its release queues runs before the + // next instruction (the code checks after the read). + if !droppable(&*src) { + drop(ty); + return 1; + } + crate::drop_hot_at(src); } dst.write(ty); 0 @@ -9124,14 +12876,14 @@ unsafe extern "C" fn h_class_read(dst: *mut Object, src: *const Object) -> u32 { /// Whether `site` reads one of the names every class answers with a string /// of its own (`cls.__name__`, as logging, reprs and error messages read -/// it), which [`type_name_note`] memoizes. (Not `__qualname__`: assigning -/// it leaves the class's version where it was.) +/// it), which [`type_name_note`] memoizes. (Assigning any of them moves +/// the class's version.) fn type_name_site(site: &AttrSite) -> bool { // SAFETY: the site's code is live (the caller's code runs it). let code = unsafe { &*site.code }; code.names .get(code.instructions[site.pc as usize].arg as usize) - .is_some_and(|name| matches!(name.as_str(), "__name__" | "__module__")) + .is_some_and(|name| matches!(name.as_str(), "__name__" | "__module__" | "__qualname__")) } /// Remember what the full lookup just read for `cls.__name__` (or @@ -9140,7 +12892,10 @@ fn type_name_site(site: &AttrSite) -> bool { /// assignment to a class attribute, these among them, moves it). fn type_name_note(site: &AttrSite, cls: &Rc, value: &Object) { let ver = cls.attr_version.get(); - if ver == 0 || !matches!(value, Object::Str(_)) || !cls.metaclass_is_type() { + if ver == 0 + || !matches!(value, Object::Str(_)) + || !(cls.metaclass_is_type() || meta_leaves_names(cls)) + { return; } if let Ok(mut memo) = site.type_attr.try_borrow_mut() { @@ -9150,6 +12905,41 @@ fn type_name_note(site: &AttrSite, cls: &Rc, value: &O } } +/// Whether `cls`'s metaclass is a Python subclass of `type` (`ABCMeta`) +/// that leaves `__name__` and `__module__` to `type`: no class on its MRO +/// before `type` defines them or `__getattribute__`. (The memo is held +/// under the metaclass's version, which an assignment there moves.) +fn meta_leaves_names(cls: &crate::types::TypeObject) -> bool { + // SAFETY: GIL-serialized raw read; the reference ends with the check. + let Some(meta) = (unsafe { (*cls.metaclass.as_ptr()).as_ref() }) else { + return false; + }; + let Ok(mro) = meta.mro.try_borrow() else { + return false; + }; + for t in mro.iter() { + if t.flags.is_builtin { + return t.name == "type"; + } + let Ok(d) = t.dict.try_borrow() else { + return false; + }; + // (A metaclass's own `__module__` is a string, which a class's read + // passes over: only a descriptor would intercept it.) + if d.get(&crate::object::StrKey("__getattribute__")).is_some() + || ["__name__", "__module__"].iter().any(|n| { + !matches!( + d.get(&crate::object::StrKey(n)), + None | Some(Object::Str(_) | Object::None) + ) + }) + { + return false; + } + } + false +} + /// A class attribute an [`AttrSite`] memoized: the class's address and /// attribute version, and the value, which the memo owns (an atom) or /// borrows from the class (a function). A version is never reused and @@ -9207,9 +12997,14 @@ fn type_attr_read(site: &AttrSite, cls: &Rc) -> Option let meta = meta_version(cls); if let Ok(memo) = site.type_attr.try_borrow() { if let Some(m) = memo.as_ref() { - if m.cls == p && m.ver == ver && ver != 0 && m.meta == meta { + if m.cls == p + && m.ver == ver + && ver != 0 + && m.meta == meta + && module_memo_stands(&m.val) + { // (`Unbound`: a read this path declined under that version.) - return (!matches!(*m.val, Object::Unbound)).then(|| crate::clone_hot(&m.val)); + return (!matches!(*m.val, Object::Unbound)).then(|| memo_value(&m.val, cls)); } } } @@ -9312,6 +13107,34 @@ fn type_attr_resolve( } return Some(b); } + // A native class method (`dict.fromkeys`, + // `itertools.chain.from_iterable`), which the memo holds as the + // descriptor and binds to the class at each read (a fresh bound + // method, as `classmethod.__get__` makes), or a native static method's + // function (`str.maketrans`). Owned, as a builtin is. + let v = match v { + Object::ClassMethod(cm) => { + if !matches!(cm.func(), Object::Builtin(_)) { + return None; + } + let entry = Object::ClassMethod(cm); + let out = memo_value(&entry, cls); + if let Ok(mut memo) = site.type_attr.try_borrow_mut() { + *memo = Some(TypeMemo::owned(p, ver, entry).under(meta_ver)); + } + return Some(out); + } + Object::StaticMethod(w) => { + let b @ Object::Builtin(_) = w.func() else { + return None; + }; + if let Ok(mut memo) = site.type_attr.try_borrow_mut() { + *memo = Some(TypeMemo::owned(p, ver, b.clone()).under(meta_ver)); + } + return Some(b); + } + v => v, + }; let plain = matches!( v, Object::Int(_) @@ -9346,6 +13169,10 @@ fn type_attr_resolve( { Object::Instance(i) } + // A module (`cls.parser`, `pathlib`'s `posixpath`, read three times + // a path parse), which `ModuleType` makes no descriptor of: while + // no module has a class of its own (see `module_memo_stands`). + m @ Object::Module(_) if !crate::object::module_classes_possible() => m, _ => return None, }; if let Ok(mut memo) = site.type_attr.try_borrow_mut() { @@ -9449,6 +13276,55 @@ unsafe fn module_attr_note(site: &AttrSite, m: &crate::object::PyModule) { } } +/// Put the value `v` a read found in its stack receiver's slot `at`, +/// releasing the receiver: by a plain decrement where another owner keeps +/// it and nothing observes releases, else as the core loop releases an +/// operand (which runs no code). `false`, with `v` dropped and the +/// receiver in place, when neither applies. The second form matters once +/// reference counts are shared between threads, where a plain decrement +/// is never allowed: every such read then went on through the whole miss +/// chain (`Condition.__exit__`'s `self._lock.__exit__`, twice for every +/// item a queue hands over). +/// +/// # Safety +/// +/// `at` is an initialized stack slot the caller owns. +#[inline(always)] +unsafe fn receiver_leaves(at: *mut Object, v: Object) -> bool { + // SAFETY: the caller's contract. + unsafe { + if plain_release(&*at) { + at.write(v); + return true; + } + if droppable(&*at) { + crate::drop_hot(std::mem::replace(&mut *at, v)); + return true; + } + } + drop(v); + false +} + +/// [`attr_stack_slow`]'s `0` for a read whose receiver left, or, when the +/// receiver's release may have queued a finalizer or a weak reference's +/// callback, the exit that runs it before the next instruction (as the +/// core loop's release would). +/// +/// # Safety +/// +/// As [`attr_stack_slow`]'s. +#[inline(always)] +unsafe fn read_done(st: *mut State, site: &AttrSite, slot: usize) -> u32 { + // SAFETY: the caller's contract. + unsafe { + if (*(*st).maybe_dead).get() { + return left_marked(st, site.pc, slot + 1); + } + } + 0 +} + /// [`h_attr_stack`] past its commonest shape. #[inline(never)] unsafe extern "C" fn attr_stack_slow(st: *mut State, site: *const AttrSite) -> u32 { @@ -9460,16 +13336,122 @@ unsafe extern "C" fn attr_stack_slow(st: *mut State, site: *const AttrSite) -> u match &*at { Object::Frame(_) | Object::Code(_) => { if let Some(v) = frame_code_attr(st, site, &*at) { - if plain_release(&*at) { - at.write(v); - return 0; + if receiver_leaves(at, v) { + return read_done(st, site, slot); } - drop(v); } } // (A class attribute the site has read before.) Object::Instance(inst) => { - let v = class_poly_hit(site, inst) + // A named tuple's field, as `attr_local_slow` takes it first. + if let Some(v) = tuple_stamp_hit(site, inst) { + if receiver_leaves(at, v) { + return read_done(st, site, slot); + } + } + // A `threading.local`'s native `__getattribute__`, as + // `attr_local_slow` calls it first. + if let Some(r) = native_hook_first(st, site, at, false, inst) { + return r; + } + // A property that runs as an activation, called first. + if let Some(r) = getter_first(st, site, at, false) { + if r == CALL_DECLINED { + return left(st, site.pc, site.last, slot + 1); + } + if r == 0 && (*(*st).maybe_dead).get() { + return left_marked(st, site.pc, slot + 1); + } + return r; + } + // The fast helper's own field hits, for a receiver this + // read releases for the last time (`P(i).a` of a fresh + // instance): the instance goes as the core loop's release + // takes it, a finalizer its death queued running before + // the next instruction (as below). + if let Some(v) = field_hit(site, inst).or_else(|| slot_field_hit(site, inst)) { + if receiver_leaves(at, crate::clone_hot(v)) { + return read_done(st, site, slot); + } + } else if slot_unset_known(site, inst) { + // An unset `__slots__` member: the raise, at once. + if let Some(r) = attr_miss_raise(st, site, at, false, true) { + return r; + } + } + // A property whose pure leaf getter the site ran for this + // class version, as `attr_local_slow` takes it first. + if site_property_leaf(&mut *st, site, at, false) { + return read_done(st, site, slot); + } + // A natively served value's public field (`d.year` of a + // global or of an attribute's value), as `attr_local_slow` + // reads it ahead of the site's memos. + if inst.cls_raw().native_kind.get() != 0 { + if let Some(v) = native_field_read(site, inst) { + if receiver_leaves(at, v) { + return read_done(st, site, slot); + } + } + } + // A read the class's Python `__getattr__` answered before, + // for this class version, as `attr_local_slow` takes it + // first (the hook checks the default lookup still misses). + let ver = inst.cls_raw().attr_version.get(); + if ver != 0 && site.py_hook.get() == ver && droppable(&*at) { + let code = &*site.code; + let arg = code.instructions[site.pc as usize].arg; + if let Some(v) = code.names.get(arg as usize).and_then(|name| { + (*(*st).interp).leaf_getattr_hook_known(&*at, name, code, arg) + }) { + crate::drop_hot(std::mem::replace(&mut *at, v)); + return read_done(st, site, slot); + } + } + if ver != 0 && site.py_hook_call.get() == ver { + if let Some(r) = hook_call_known(st, site, at, false, inst) { + return r; + } + } + // An exception's pseudo-slot, as `attr_local_slow` reads it. + if let Some(v) = exc_slot_known(site, inst) { + if receiver_leaves(at, v) { + return read_done(st, site, slot); + } + } + // A polymorphic site's third class and on, as + // `attr_local_slow` reads it first (a receiver whose + // release could run code takes the lanes below). + if droppable(&*at) { + if let Some(v) = + field_hit_slow(site, inst).or_else(|| slot_field_resolve(site, inst)) + { + let v = crate::clone_hot(v); + crate::drop_hot(std::mem::replace(&mut *at, v)); + return read_done(st, site, slot); + } + } + // A plain class value the site memoized for the class (no + // descriptor or native method shares its version), or a + // named tuple's field, as the local read's path finds them + // first. + if let Some(v) = class_poly_hit(site, inst, &*at).or_else(|| { + (*site.ext) + .stamp_slot(site.pc as usize) + .and_then(|s| crate::tuple_field_hit(s, inst)) + }) { + if receiver_leaves(at, v) { + return read_done(st, site, slot); + } + } + if let Some(v) = + inst_dict_known(site, inst).or_else(|| inst_builtin_bound(site, inst, &*at)) + { + if receiver_leaves(at, v) { + return read_done(st, site, slot); + } + } + let v = class_poly_hit(site, inst, &*at) .or_else(|| instance_class_read(site, inst)) .or_else(|| { site.class_attr.get().then(|| { @@ -9478,21 +13460,17 @@ unsafe extern "C" fn attr_stack_slow(st: *mut State, site: *const AttrSite) -> u })? }); if let Some(v) = v { - if plain_release(&*at) { - at.write(v); - return 0; + if receiver_leaves(at, v) { + return read_done(st, site, slot); } - drop(v); } } // (A class's name, as the site read it before.) Object::Type(cls) => { if let Some(v) = type_attr_memo(site, cls) { - if plain_release(&*at) { - at.write(v); - return 0; + if receiver_leaves(at, v) { + return read_done(st, site, slot); } - drop(v); } } Object::Module(m) => module_attr_note(site, m), @@ -9915,9 +13893,57 @@ unsafe extern "C" fn h_stack_store_attr(code: *const CodeObject, pc: u64, at: *m let arg = code.instructions[pc].arg; return u32::from(!Interpreter::core_class_store(code, arg, at.add(1))); } + // A plain module's attribute (`self._module.filters = v`): + // both operands leave. + Object::Module(m) => { + let arg = code.instructions[pc].arg; + let Some(key) = crate::code_name_obj(code, arg) else { + return 1; + }; + if !droppable(recv) || !module_store_leaf(m, key, val) { + return 1; + } + crate::drop_hot_at(at.add(1)); + crate::drop_hot_at(at); + return 0; + } + // A `SimpleNamespace`'s attribute (`cfg.x = v` on a global or + // an attribute's value): its dictionary's entry, as + // [`h_store_attr`] stores a local's (both operands leave). + Object::SimpleNamespace(ns) => { + let arg = code.instructions[pc].arg; + let Some(key @ Object::Str(s)) = crate::code_name_obj(code, arg) else { + return 1; + }; + if s.starts_with("__") || !droppable(recv) { + return 1; + } + let args = [Object::Dict(ns.clone()), key.clone(), crate::clone_hot(val)]; + return match crate::builtins::dict_setitem_leaf(&args) { + Some(Ok(_)) => { + drop(args); + crate::drop_hot_at(at.add(1)); + crate::drop_hot_at(at); + 0 + } + _ => 1, + }; + } _ => return 1, }; let name = code.instructions[pc].arg; + // A property's setter site: the setter store decides. + if Interpreter::setter_site_hit(code, pc, inst).is_some() { + return 1; + } + // A `threading.local`'s entry, through its native hook (the value + // cloned in: both operands leave). + if droppable(recv) && droppable(val) && Interpreter::local_store_fast(code, recv, name, val) + { + crate::drop_hot_at(at.add(1)); + crate::drop_hot_at(at); + return 0; + } if !droppable(recv) || !(Interpreter::core_store_attr(code, inst, pc, name, val) || Interpreter::leaf_attr_store_any(code, inst, pc, name, val)) @@ -9941,14 +13967,16 @@ const MAX_NATIVE_TUPLE: usize = 16; const FSTRING_CONVERT: u64 = 0; const FSTRING_FORMAT: u64 = 1; const FSTRING_JOIN: u64 = 2; +const FSTRING_FORMAT_SPEC: u64 = 3; /// Whether the native code runs the f-string instruction `op` (`arg`): -/// a conversion, a spec-less format, or a join of up to eight parts. +/// a conversion, a format (with a spec, but no conversion), or a join of +/// up to [`crate::BUILD_STRING_MAX`] parts. fn fstring_native(op: OpCode, arg: u32) -> bool { match op { OpCode::ConvertValue => matches!(arg & 0x03, 1 | 2), - OpCode::FormatValue => arg == 0, - OpCode::BuildString => (1..=8).contains(&arg), + OpCode::FormatValue => arg == 0 || arg == 4, + OpCode::BuildString => (1..=crate::BUILD_STRING_MAX as u32).contains(&arg), _ => false, } } @@ -9958,12 +13986,39 @@ fn fstring_native(op: OpCode, arg: u32) -> bool { /// `crate::build_string_at`): `kind`'s low byte names the operation and /// the rest its operand (the conversion, or the join's part count). `0` /// done in place, anything else declined untouched. +/// `FORMAT_VALUE` of the exception at `at` whose class keeps +/// `BaseException.__str__` and `object.__format__` (see +/// [`Interpreter::exc_str_leaf`]): its text in place, the instance +/// released (another owner keeping it alive). `false` touches nothing. +/// +/// # Safety +/// +/// The slot at `at` is initialized, and nothing else reads it. +#[inline(never)] +unsafe fn exc_format_in_place(at: *mut Object) -> bool { + // SAFETY: the caller's contract. + unsafe { + let Object::Instance(inst) = &*at else { + return false; + }; + if !droppable(&*at) { + return false; + } + let Some(text) = Interpreter::exc_str_leaf(inst) else { + return false; + }; + crate::drop_hot(std::mem::replace(&mut *at, text)); + } + true +} + unsafe extern "C" fn h_fstring(at: *mut Object, kind: u64) -> u32 { // SAFETY: the code passes the operation's initialized stack slots. let done = unsafe { match kind & 0xff { FSTRING_CONVERT => crate::convert_in_place(at, (kind >> 8) as u32), - FSTRING_FORMAT => crate::format_simple_in_place(at), + FSTRING_FORMAT => crate::format_simple_in_place(at) || exc_format_in_place(at), + FSTRING_FORMAT_SPEC => crate::format_spec_in_place(at), _ => crate::build_string_at(at, (kind >> 8) as usize), } }; @@ -9987,7 +14042,12 @@ unsafe extern "C" fn h_build(st: *mut State, at: *mut Object, n: u64, list: u32) } let items: Vec = (0..n).map(|j| at.add(j).read()).collect(); let obj = Object::new_list(items); - crate::gc_trace::track(&obj); + // (Deferred as a built list is, a collection promoting it once + // it can anchor a cycle; a call's spread arguments, which only + // the stack holds until they become a tuple, aren't.) + if list == 1 { + crate::gc_trace::track_built(&obj); + } at.write(obj); return 0; } @@ -10041,37 +14101,176 @@ unsafe extern "C" fn h_build_set(at: *mut Object, n: u64) -> u32 { let _ = crate::object::key_cmp_scope(|| data.insert(item)); } let obj = Object::Set(Rc::new(crate::sync::RefCell::new(data))); - crate::gc_trace::track(&obj); + crate::gc_trace::track_built(&obj); at.write(obj); } 0 } -unsafe extern "C" fn h_build_map(at: *mut Object, n: u64) -> u32 { +/// A `BUILD_MAP` of `n` pairs fused with the `DICT_UPDATE` that merges +/// the new dict into the one below it (`{**d, "k": v}`): the pairs, from +/// `at + 1`, go straight into the dict at `at`, in order, a repeated key's +/// value replaced, with no dict built for them. `1`, the stack untouched, +/// unless the target is an exact dict that every pair's key (a `str`, a +/// machine `int` or a finite `float`) probes natively, a stored key of +/// another kind with an equal hash leaving it to the general path, and no +/// dict watcher is set. +unsafe extern "C" fn h_map_into(at: *mut Object, n: u64) -> u32 { + use crate::object::DictKey; let n = n as usize; - // SAFETY: the code passes `2n` initialized stack slots. + // SAFETY: the code passes the target slot and the `2n` initialized + // slots above it; a pair leaves the stack (read out) only once it is + // committed, and the probes run no code. + unsafe { + let Object::Dict(target) = &*at else { + return 1; + }; + if crate::capi_watchers::dicts_active() { + return 1; + } + let Ok(mut t) = target.try_borrow_mut() else { + return 1; + }; + let key = |j: usize| at.add(1 + 2 * j); + // (The first pair is decided below, before anything moves; the + // later ones here, against the keys the dict holds now. A pair + // that then meets an earlier pair's key with an equal hash + // compares with it natively in the general insert.) + if !(1..n).all(|j| t.find_object_hashing(&*key(j)).is_some()) { + return 1; + } + // (Once: a stamped access, as every dict store makes.) + let m: &mut crate::object::DictMap = &mut t; + let mut replaced = [const { std::mem::MaybeUninit::::uninit() }; 8]; + let mut r = 0; + for j in 0..n { + let (k, v) = (key(j), key(j).add(1)); + let old = match m.find_object_hashing(&*k) { + None if j == 0 => return 1, + None => m.insert(DictKey(k.read()), v.read()), + Some((_, Ok(i))) => { + // (The stored key stays; the pair's, a `str` or + // number, is released.) + drop(k.read()); + Some(std::mem::replace(m.value_at_unchecked_mut(i), v.read())) + } + Some((hash, Err(pos))) => { + if !m.push_native(pos, hash, || DictKey(k.read()), || v.read()) { + m.insert_unique_hashed(hash, DictKey(k.read()), v.read()); + } + None + } + }; + if let Some(old) = old { + replaced[r].write(old); + r += 1; + } + } + drop(t); + // (A replaced value is released once the borrow ends.) + for v in &replaced[..r] { + crate::drop_hot(v.assume_init_read()); + } + } + 0 +} + +unsafe extern "C" fn h_build_map(st: *mut State, at: *mut Object, n: u64) -> u32 { + let n = n as usize; + // SAFETY: the code passes its live state and `2n` initialized stack + // slots. unsafe { if crate::stdlib::tracemalloc_real::is_tracking() || crate::stdlib::testinternalcapi_mod::reftrace_print_active() || crate::gc_trace::auto_collect_due() - || !(0..n).all(|j| { - matches!( - &*at.add(2 * j), - Object::Str(_) | Object::Int(_) | Object::Bool(_) | Object::None - ) - }) { return 1; } + // Keys that are natively served values (a `date`, a `datetime`, a + // `Decimal`) or instances whose `__hash__` is a pure leaf (a frozen + // dataclass's) beside `str` and `int` ones: each by its native or + // leaf hash, which runs no code, while no two hashes agree (an + // equal pair is the core loop's to settle). + let native_key = + |k: &Object| matches!(k, Object::Instance(i) if i.cls_raw().native_kind.get() != 0); + if (0..n).any(|j| matches!(&*at.add(2 * j), Object::Instance(_))) { + let mut hashes = [0i64; 8]; + if n > hashes.len() { + return 1; + } + for j in 0..n { + let h = match &*at.add(2 * j) { + Object::Str(s) => crate::shared_value::SharedStr::hash_cached(s), + Object::Int(i) => crate::object::py_hash_long_i64(*i), + k @ Object::Instance(_) if native_key(k) => { + match crate::stdlib::datetime_native::leaf_hash(k) { + Some(h) => h, + None => return 1, + } + } + k @ Object::Instance(_) => match (*(*st).interp).leaf_instance_hash(k) { + Some(h) => h, + None => return 1, + }, + _ => return 1, + }; + if hashes[..j].contains(&h) { + return 1; + } + hashes[j] = h; + } + let mut d = crate::object::DictData::with_capacity_and_hasher( + n, + crate::fasthash::FxBuildHasher, + ); + for (j, &h) in hashes.iter().enumerate().take(n) { + let k = at.add(2 * j).read(); + let v = at.add(2 * j + 1).read(); + d.insert_unique_hashed(h, crate::object::DictKey(k), v); + } + let obj = Object::Dict(Rc::new(crate::sync::RefCell::new(d))); + crate::gc_trace::track_built(&obj); + at.write(obj); + return 0; + } + if !(0..n).all(|j| { + matches!( + &*at.add(2 * j), + Object::Str(_) | Object::Int(_) | Object::Bool(_) | Object::None + ) + }) { + return 1; + } let mut d = crate::object::DictData::with_capacity_and_hasher(n, crate::fasthash::FxBuildHasher); + // `str` and `int` keys whose hashes differ from every earlier key's + // go in without the probe for an equal one (a repeated key, or a + // `bool` or `None` among them, takes it: `True` equals `1`). + let mut seen = [0i64; 8]; + let plain = n <= seen.len() + && (0..n).all(|j| matches!(&*at.add(2 * j), Object::Str(_) | Object::Int(_))); for j in 0..n { let k = at.add(2 * j).read(); let v = at.add(2 * j + 1).read(); + if plain { + let h = match &k { + Object::Str(s) => crate::shared_value::SharedStr::hash_cached(s), + Object::Int(i) => crate::object::py_hash_long_i64(*i), + _ => unreachable!("checked above"), + }; + let fresh = !seen[..j].contains(&h); + seen[j] = h; + if fresh { + d.insert_unique_hashed(h, crate::object::DictKey(k), v); + continue; + } + } d.insert(crate::object::DictKey(k), v); } let obj = Object::Dict(Rc::new(crate::sync::RefCell::new(d))); - crate::gc_trace::track(&obj); + // (Deferred as a built dict is, a collection promoting it once it + // can anchor a cycle.) + crate::gc_trace::track_built(&obj); at.write(obj); } 0 @@ -10180,6 +14379,7 @@ unsafe fn run_switched_directly(st: &mut State) -> bool { wait_pending: None, outer_lazy: 0, fold: std::ptr::null(), + caught: false, }; interp.recs.set_top(nested.add(1)); let status = native.run(&mut cst); @@ -10232,8 +14432,25 @@ unsafe fn run_switched_directly(st: &mut State) -> bool { /// # Safety /// /// As `h_call`'s, with a non-null switch. -#[inline(never)] +#[inline(always)] unsafe fn lazy_await(st: &mut State, pc: usize, start: usize, len: usize) -> Option { + // SAFETY: the caller's contract. + unsafe { + let send_pc = crate::await_send_after(&(*st.frame).code, pc)?; + lazy_await_to(st, send_pc, start, len) + } +} + +/// [`lazy_await`] for the await whose `SEND` is at `send_pc`: a `CALL`'s +/// that an await follows, or an `async for`'s step of a class's coroutine +/// `__anext__` ([`anext_method`]), the callee and its arguments from +/// `start` as a call's. +/// +/// # Safety +/// +/// As [`lazy_await`]'s. +#[inline(never)] +unsafe fn lazy_await_to(st: &mut State, send_pc: usize, start: usize, len: usize) -> Option { // SAFETY: the caller's contract. unsafe { let base = st.stack; @@ -10247,7 +14464,6 @@ unsafe fn lazy_await(st: &mut State, pc: usize, start: usize, len: usize) -> Opt let interp = &mut *st.interp.cast_mut(); let sw = &mut *st.sw; let caller = &mut *st.frame; - let send_pc = crate::await_send_after(&caller.code, pc)?; let has_self = !matches!(&*base.add(start + 1), Object::Unbound); let nargs = len - start - 2 + usize::from(has_self); let nested = interp.recs.top(); @@ -10258,7 +14474,7 @@ unsafe fn lazy_await(st: &mut State, pc: usize, start: usize, len: usize) -> Opt { return None; } - let gen_start = interp.generator_start(f, code_rc, nargs)?; + let gen_start = interp.generator_start_spread(f, code_rc, nargs)?; let cells = f.lean_cells_ref(code_rc)?; let ext = crate::code_vm_ext(code_rc)?; let nlocals = code_rc.varnames.len(); @@ -10345,6 +14561,7 @@ unsafe fn lazy_await(st: &mut State, pc: usize, start: usize, len: usize) -> Opt wait_pending: None, outer_lazy: 0, fold: std::ptr::null(), + caught: false, }; interp.recs.set_top(nested.add(1)); let outer = interp.lazy_top.get(); @@ -10799,8 +15016,11 @@ fn direct_body<'a>( || (missing > 0 && !Interpreter::defaults_cover(f, missing)) || !Interpreter::kwonly_defaults_cover(f, code) // (A frameless leaf with extended parameters evaluates in place: - // see `site_leaf_fits`.) - || (Interpreter::has_extended_params(code) && crate::fn_is_leaf(f)) + // see `site_leaf_fits`. Not one with `**kwargs`, which no leaf + // evaluation binds: it runs here, on its own activation.) + || (Interpreter::has_extended_params(code) + && crate::fn_is_leaf(f) + && !code.has_varkeywords) || code.wire.as_ref().is_some_and(|w| w.exec_error.is_some()) { return None; @@ -10856,8 +15076,18 @@ unsafe extern "C" fn h_binop_dunder( let op: BinOpKind = std::mem::transmute(arg as u8); let inplace = arg & weavepy_compiler::BINARY_OP_INPLACE_FLAG != 0; let at = st.stack.add(slot); + if inplace { + if let Some(f) = Interpreter::inplace_instance_dunder(&*at, op) { + return inplace_call(st, pc, slot, op, f, site); + } + } let Some(f) = Interpreter::binop_instance_dunder(&*at, &*at.add(1), op, inplace) else { - return CALL_DECLINED; + // `n obj` of a plain number and an instance whose class's + // reflected method is a Python function. + if let Some(f) = Interpreter::binop_reflected_dunder(&*at, &*at.add(1), op) { + return reflected_call(st, pc, slot, op, inplace, f, site); + } + return binop_leaf(st, pc, slot, op, inplace); }; if let Some(ext) = crate::code_vm_ext(&*code) { if !crate::dunder_known(ext, pc) { @@ -10884,6 +15114,395 @@ unsafe extern "C" fn h_binop_dunder( } } +/// [`h_binop_dunder`]'s `n obj` of a plain number and an instance +/// whose class's reflected method `f` is a Python function (see +/// `Interpreter::binop_reflected_dunder`): the operands swapped in place, +/// the method called directly ([`dunder_call`]) as `f(obj, n)`, its result +/// at `slot` (a `NotImplemented` the operator's `TypeError`, the operands' +/// classes in their written order); declined, the operands go back. +/// Returns as `h_binop_dunder` does. +/// +/// # Safety +/// +/// As [`h_binop_dunder`]'s. +#[inline(never)] +unsafe fn reflected_call( + st: &mut State, + pc: usize, + slot: usize, + op: BinOpKind, + inplace: bool, + f: Rc, + site: *mut DirectSite, +) -> u32 { + // SAFETY: the caller's contract. + unsafe { + let at = st.stack.add(slot); + let Object::Instance(b) = &*at.add(1) else { + return CALL_DECLINED; + }; + let (left, right) = (crate::builtins::class_of(&*at), b.cls()); + std::ptr::swap(at, at.add(1)); + let r = dunder_call( + st, + pc, + slot, + 2, + f, + site, + Some(records::MethodOp::Binary(op, inplace, &left, &right)), + ); + if r == CALL_DECLINED { + std::ptr::swap(at, at.add(1)); + } + r + } +} + +/// [`h_binop_dunder`]'s `a = b` of an instance whose class's in-place +/// method `f` is a Python function: the method called directly +/// ([`dunder_call`]) on the operands at `slot`, its result there; a +/// `NotImplemented` goes on to the regular operator +/// ([`inplace_rest`]). Returns as `h_binop_dunder` does. +/// +/// # Safety +/// +/// As [`h_binop_dunder`]'s. +#[inline(never)] +unsafe fn inplace_call( + st: &mut State, + pc: usize, + slot: usize, + op: BinOpKind, + f: Rc, + site: *mut DirectSite, +) -> u32 { + // SAFETY: the caller's contract. + unsafe { + let at = st.stack.add(slot); + // The operands, kept for a fallback past `NotImplemented`. + let (a, b) = (crate::clone_hot(&*at), crate::clone_hot(&*at.add(1))); + let r = dunder_call( + st, + pc, + slot, + 2, + f, + site, + Some(records::MethodOp::Inplace(op, &a, &b)), + ); + if r == 0 && (*at).is_same(&crate::vm_singletons::not_implemented()) { + crate::drop_hot_at(at); + return inplace_rest(st, pc, slot, op, &a, &b); + } + r + } +} + +/// [`inplace_call`] whose method answered `NotImplemented`: the regular +/// operator (`Interpreter::inplace_binop_fallback`), which may run Python +/// code, so the caller's frame is synced and its shell built first, as +/// [`compare_rest`] syncs it. `0` the result at `slot`; `RAISED`, or +/// `RELOAD` with the result on the frame's stack. +#[cold] +#[inline(never)] +unsafe fn inplace_rest( + st: &mut State, + pc: usize, + slot: usize, + op: BinOpKind, + a: &Object, + b: &Object, +) -> u32 { + // SAFETY: as `inplace_call`'s, the slot at `slot` free. + unsafe { + let interp = &mut *st.interp.cast_mut(); + let frame = &mut *st.frame; + frame.stack.set_len(slot); + frame.pc = pc as u32 + 1; + settle(st); + let sw = &mut *st.sw; + let mut tmp = None; + let (cf, _, cshell) = sw.activation((*sw.inl).len(), &mut tmp); + interp.flush_lean(&mut *cf, &mut *cshell.cast::>()); + let globals = frame.globals.clone(); + let r = interp.inplace_binop_fallback(a, b, op, &globals); + *sw.last = pc; + let in_place = |sw: &crate::CoreSwitch| { + sw.pending.is_none() + && std::ptr::eq(sw.cur, st.frame) + && crate::hot_gates::loop_gen() == st.snap_gen + }; + let v = match r { + Ok(v) => v, + Err(e) if in_place(sw) => { + st.len = slot; + st.pc = pc + 1; + st.err = Some(e); + return RAISED; + } + Err(e) => { + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Raised(e))); + return RELOAD; + } + }; + if interp.drain_if_maybe_dead() && crate::hot_gates::loop_gen() != st.snap_gen { + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Breaker)); + } + if !in_place(sw) { + frame.stack.push(v); + return RELOAD; + } + st.stack.add(slot).write(v); + st.len = slot + 1; + 0 + } +} + +/// `FORMAT_VALUE` (the `pc`th instruction of `code`) of the value at stack +/// slot `slot` (its spec above it when `spec`), which [`h_fstring`] +/// declined: an instance whose class's `__format__` is a plain Python +/// function, called directly ([`dunder_call`]) as `f(value, spec)` (an +/// empty spec when there is none), its result at `slot` as +/// `PyObject_Format` takes it ([`crate::format_result`]). `0` done, +/// `CALL_DECLINED` declined untouched, `RAISED` or `RELOAD` as [`h_call`]'s +/// (the core loop settles a result it finishes: see +/// `records::MethodOp::Format`). +unsafe extern "C" fn h_format_dunder( + st: *mut State, + _code: *const CodeObject, + pc: u64, + slot: u64, + site: *mut DirectSite, + spec: u64, +) -> u32 { + // SAFETY: the code passes its live state, one of its `FORMAT_VALUE`s, + // the operands' slot (with two free above the value, and nothing + // virtual below), and the site's cache. + unsafe { + let st = &mut *st; + if st.sw.is_null() || crate::trace::any_observers_active() { + return CALL_DECLINED; + } + let (pc, slot) = (pc as usize, slot as usize); + let at = st.stack.add(slot); + let Object::Instance(inst) = &*at else { + return CALL_DECLINED; + }; + if spec != 0 && !matches!(&*at.add(1), Object::Str(_)) { + return CALL_DECLINED; + } + let Some(f) = Interpreter::binary_dunder_function( + inst, + crate::types::vm_key::FORMAT_FN, + "__format__", + ) else { + // `object.__format__` with no spec is `str(obj)`: its Python + // `__str__` (or the `__repr__` that `object.__str__` calls), + // called directly, its result checked as `str()` checks it. + if spec != 0 { + return CALL_DECLINED; + } + let Some(f) = Interpreter::instance_format_str_function(inst) else { + return CALL_DECLINED; + }; + return match dunder_call(st, pc, slot, 1, f, site, Some(records::MethodOp::Str)) { + 0 => match crate::str_result(at.read()) { + Ok(v) => { + at.write(v); + st.len = slot + 1; + 0 + } + Err(e) => { + st.len = slot; + st.pc = pc + 1; + st.err = Some(e); + RAISED + } + }, + r => r, + }; + }; + if spec == 0 { + at.add(1) + .write(Object::Str(crate::shared_value::SharedStr::from(""))); + } + match dunder_call(st, pc, slot, 2, f, site, Some(records::MethodOp::Format)) { + CALL_DECLINED => { + if spec == 0 { + crate::drop_hot_at(at.add(1)); + } + CALL_DECLINED + } + 0 => match crate::format_result(at.read()) { + Ok(v) => { + at.write(v); + st.len = slot + 1; + 0 + } + Err(e) => { + st.len = slot; + st.pc = pc + 1; + st.err = Some(e); + RAISED + } + }, + r => r, + } + } +} + +/// `CONVERT_VALUE` (the `pc`th instruction) of the instance at stack slot +/// `slot`, which [`h_fstring`] declined, whose class's `__str__` (`!s`, +/// `conv` 1) or `__repr__` (`!r`, `conv` 2) is a Python function: the +/// method called directly ([`dunder_call`]), its result at `slot` as +/// `str()` or `repr()` takes it ([`crate::str_result`], +/// [`crate::repr_result`]). `0` done, `CALL_DECLINED` declined untouched, +/// `RAISED` or `RELOAD` as [`h_call`]'s (the core loop settles a result it +/// finishes: see `records::MethodOp::Str` and `records::MethodOp::Repr`). +unsafe extern "C" fn h_convert_dunder( + st: *mut State, + _code: *const CodeObject, + pc: u64, + slot: u64, + site: *mut DirectSite, + conv: u64, +) -> u32 { + // SAFETY: the code passes its live state, one of its `CONVERT_VALUE`s, + // the value's slot (with one free above it, and nothing virtual + // below), and the site's cache. + unsafe { + let st = &mut *st; + if st.sw.is_null() || crate::trace::any_observers_active() { + return CALL_DECLINED; + } + let (pc, slot, repr) = (pc as usize, slot as usize, conv == 2); + let at = st.stack.add(slot); + let Object::Instance(inst) = &*at else { + return CALL_DECLINED; + }; + if let Some(v) = Interpreter::native_text(inst, repr) { + crate::release_operands(&*st.interp, at, 1); + at.write(v); + if (*st.maybe_dead).get() { + return left_marked(st, pc as u32, slot + 1); + } + return 0; + } + let (f, op) = if repr { + ( + Interpreter::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::REPR_FN), + "__repr__", + ), + records::MethodOp::Repr, + ) + } else { + // (Or the `__repr__` that `object.__str__` calls.) + ( + Interpreter::instance_str_function(inst), + records::MethodOp::Str, + ) + }; + let Some(f) = f else { + return CALL_DECLINED; + }; + match dunder_call(st, pc, slot, 1, f, site, Some(op)) { + 0 => { + let v = at.read(); + let r = if repr { + crate::repr_result(v) + } else { + crate::str_result(v) + }; + match r { + Ok(v) => { + at.write(v); + st.len = slot + 1; + 0 + } + Err(e) => { + st.len = slot; + st.pc = pc + 1; + st.err = Some(e); + RAISED + } + } + } + r => r, + } + } +} + +/// `UNARY_OP` (the `pc`th instruction of `code`: `+`, `-` or `~`) of the +/// value at stack slot `slot`: an instance whose class's operator method +/// is a plain Python function, called directly ([`dunder_call`]), its +/// result at `slot`. `0` done, `CALL_DECLINED` declined untouched, +/// `RAISED` or `RELOAD` as [`h_call`]'s. +unsafe extern "C" fn h_unary_dunder( + st: *mut State, + code: *const CodeObject, + pc: u64, + slot: u64, + site: *mut DirectSite, +) -> u32 { + // SAFETY: the code passes its live state, its own code and one of its + // `UNARY_OP`s, the operand's slot (with room for one more above it, + // and nothing virtual below), and the site's cache. + unsafe { + let st = &mut *st; + if st.sw.is_null() { + return CALL_DECLINED; + } + let (pc, slot) = (pc as usize, slot as usize); + let kind = (&(&*code).instructions)[pc].arg; + // A native operator method's pure half (a `timedelta`'s, a + // `Decimal`'s) in place, its result at `slot`. + if droppable(&*st.stack.add(slot)) { + if let Some(v) = (*st.interp).unary_native_fast(&*st.stack.add(slot), kind) { + crate::drop_hot(std::mem::replace(&mut *st.stack.add(slot), v)); + return 0; + } + } + let Object::Instance(inst) = &*st.stack.add(slot) else { + return CALL_DECLINED; + }; + let Some(f) = Interpreter::unary_dunder_function(inst, kind) else { + return CALL_DECLINED; + }; + dunder_call(st, pc, slot, 1, f, site, None) + } +} + +/// `GET_ITER` (the `pc`th instruction of `code`) of the plain instance at +/// stack slot `slot`, which [`h_get_iter`] declined, whose class's +/// `__iter__` is a plain Python function: the method called directly +/// ([`dunder_call`]), its result (checked to be an iterator) at `slot`. +/// `0` done, `CALL_DECLINED` declined untouched, `RAISED` or `RELOAD` as +/// [`h_call`]'s. +unsafe extern "C" fn h_iter_dunder( + st: *mut State, + pc: u64, + slot: u64, + site: *mut DirectSite, +) -> u32 { + // SAFETY: the code passes its live state, one of its `GET_ITER`s, the + // operand's slot (nothing virtual below it), and the site's cache. + unsafe { + let st = &mut *st; + let (pc, slot) = (pc as usize, slot as usize); + // (The call takes the slot above the operand for the method.) + if st.sw.is_null() || slot + 2 > st.cap { + return CALL_DECLINED; + } + let Some(f) = Interpreter::iter_dunder(&*st.stack.add(slot)) else { + return CALL_DECLINED; + }; + dunder_call(st, pc, slot, 1, f, site, Some(records::MethodOp::Iter)) + } +} + /// `BINARY_SUBSCR` (the `pc`th instruction of `code`) of the plain /// instance and key at stack slots `slot` and above it, which the in-place /// helpers declined, whose class's `__getitem__` is a plain Python @@ -10904,16 +15523,463 @@ unsafe extern "C" fn h_subscr_dunder( unsafe { let st = &mut *st; if st.sw.is_null() { + // (No call can be made from here, a generator's fast step: + // only the read that needs none.) + let at = st.stack.add(slot as usize); + if droppable(&*at) && droppable(&*at.add(1)) { + if let Some(f) = Interpreter::getitem_dunder(&*code, pc as usize, &*at) { + if let Some(v) = Interpreter::delegate_subscr(&f, &*at, &*at.add(1)) { + crate::drop_hot_at(at.add(1)); + crate::drop_hot_at(at); + at.write(v); + return 0; + } + } + } return CALL_DECLINED; } let (pc, slot) = (pc as usize, slot as usize); + // A `dict` subclass's instance (a `defaultdict` at a site that + // once ran its `__missing__`): its payload's item in place, with + // no method looked up (see `subscr_fast`). + if let Object::Instance(inst) = &*st.stack.add(slot) { + if matches!(inst.native.get(), Some(Object::Dict(_))) { + let at = st.stack.add(slot); + if subscr_fast(at, at, at.add(1), 3) == 0 { + return 0; + } + } + } + // (A class's `__getitem__` is a native method with a leaf half or + // a Python function, never both.) + if let Some(fast) = getitem_leaf_of(&*st.stack.add(slot)) { + return pair_leaf_call(st, pc, slot, fast, false); + } + if let Some(f) = missing_dunder(&*st.stack.add(slot), &*st.stack.add(slot + 1)) { + return dunder_call(st, pc, slot, 2, f, site, None); + } + // `SomeEnum[name]`: the member, from the class's member map. + if let Object::Type(t) = &*st.stack.add(slot) { + if let Some(v) = Interpreter::enum_getitem(t, &*st.stack.add(slot + 1)) { + let at = st.stack.add(slot); + if droppable(&*at) && droppable(&*at.add(1)) { + crate::drop_hot_at(at.add(1)); + crate::drop_hot_at(at); + at.write(v); + return 0; + } + } + } let Some(f) = Interpreter::getitem_dunder(&*code, pc, &*st.stack.add(slot)) else { return CALL_DECLINED; }; + // (The site's method, for a recompile to lower in line.) + if let Some(ext) = crate::code_vm_ext(&*code) { + if !crate::dunder_known(ext, pc) { + crate::getitem_note(ext, pc, &f, &*st.stack.add(slot)); + } + } + // `return self.items[key]`: the field's own item, with no call; + // or its miss, raised here with no call where this code's own + // handler takes it unseen (`Mapping.get`'s `except KeyError: + // return default`). + let at = st.stack.add(slot); + if droppable(&*at) && droppable(&*at.add(1)) { + match Interpreter::delegate_probe(&f, &*at, &*at.add(1)) { + Some(crate::Delegated::Item(v)) => { + crate::drop_hot_at(at.add(1)); + crate::drop_hot_at(at); + at.write(v); + return 0; + } + // (Raised as `subscr_raise_missing` raises a plain + // container's miss: no call ran, so the state is this + // activation's own.) + Some(miss) => { + let bt = crate::builtin_types::builtin_types(); + let class = match miss { + crate::Delegated::IndexMiss(_) => &bt.index_error, + _ => &bt.key_error, + }; + if (*st.interp).caught_unseen(&*st.frame, pc, class) { + let err = match miss { + crate::Delegated::IndexMiss(what) => crate::error::index_error(what), + _ => crate::error::key_error_object((*at.add(1)).clone()), + }; + crate::drop_hot_at(at.add(1)); + crate::drop_hot_at(at); + st.len = slot; + st.pc = pc + 1; + st.err = Some(err); + return RAISED; + } + } + None => {} + } + } dunder_call(st, pc, slot, 2, f, site, None) } } +/// `STORE_SUBSCR` (the `pc`th instruction of `code`) of the value, container +/// and key in the three stack slots from `slot` up, the faster stores +/// declined: a container whose class's `__setitem__` is a Python function, +/// called directly ([`direct_call`]) as `f(cont, key, value)` on those +/// slots and its result dropped. `0` stored, the operands gone, +/// `CALL_DECLINED` declined untouched (a function without native code, +/// which warms as a compiled caller's switched call warms its callee), +/// `RAISED` or `RELOAD` as [`h_call`]'s (the core loop drops a result it +/// settles: see `records::MethodOp::Store`). +unsafe extern "C" fn h_setitem_dunder( + st: *mut State, + code: *const CodeObject, + pc: u64, + slot: u64, + site: *mut DirectSite, +) -> u32 { + // SAFETY: the code passes its live state, its own code and one of its + // `STORE_SUBSCR`s, the operands' slot (with room for one more above + // them, and nothing virtual below), and the site's cache. + unsafe { + let st = &mut *st; + if st.sw.is_null() { + return CALL_DECLINED; + } + let (pc, slot) = (pc as usize, slot as usize); + let at = st.stack.add(slot); + let Object::Instance(inst) = &*at.add(1) else { + return CALL_DECLINED; + }; + let Some(f) = Interpreter::setitem_function(&*code, pc, inst) else { + return CALL_DECLINED; + }; + // `[value, cont, key]` becomes the call `[f, cont, key, value]`. + at.add(3).write(at.read()); + at.write(Object::Function(f)); + match direct_call_out( + st, + pc, + slot, + slot + 4, + &mut *site, + Some(records::MethodOp::Store), + ) { + None => { + let f = at.read(); + at.write(at.add(3).read()); + if let Object::Function(f) = &f { + let fc = f.code(); + if let Some(ext) = crate::code_vm_ext(&fc) { + ext.frame_jit + .warm_switched(&fc, ext, fc.varnames.len().max(3)); + } + } + drop(f); + CALL_DECLINED + } + Some(0) => { + // The method's result (`None`, as a rule) goes. + let res = at.read(); + if !plain_release(&res) { + (*st.interp.cast_mut()).release(res); + } else { + std::mem::forget(res); + } + st.len = slot; + 0 + } + Some(r) => r, + } + } +} + +/// `DELETE_SUBSCR` (the `pc`th instruction of `code`) of the container and +/// key in the two stack slots from `slot` up, which `h_container` +/// declined: a container whose class's `__delitem__` is a Python function, +/// called directly ([`dunder_call`]) and its result dropped (see +/// `records::MethodOp::Store`). Returns as [`h_setitem_dunder`] does. +unsafe extern "C" fn h_delitem_dunder( + st: *mut State, + _code: *const CodeObject, + pc: u64, + slot: u64, + site: *mut DirectSite, +) -> u32 { + // SAFETY: the code passes its live state, its own code and one of its + // `DELETE_SUBSCR`s, the operands' slot (with room for one more above + // them, and nothing virtual below), and the site's cache. + unsafe { + let st = &mut *st; + if st.sw.is_null() { + return CALL_DECLINED; + } + let (pc, slot) = (pc as usize, slot as usize); + let at = st.stack.add(slot); + let Object::Instance(inst) = &*at else { + return CALL_DECLINED; + }; + let Some(f) = Interpreter::binary_dunder_function( + inst, + crate::types::vm_key::DELITEM_FN, + "__delitem__", + ) else { + return CALL_DECLINED; + }; + match dunder_call(st, pc, slot, 2, f, site, Some(records::MethodOp::Store)) { + 0 => { + // The method's result (`None`, as a rule) goes. + let res = at.read(); + if !plain_release(&res) { + (*st.interp.cast_mut()).release(res); + } else { + std::mem::forget(res); + } + st.len = slot; + 0 + } + r => r, + } + } +} + +/// `CONTAINS_OP` (the `pc`th instruction of `code`; `invert` for `not in`) +/// of the item and container in the two stack slots from `slot` up, the +/// faster tests declined: a container whose class's `__contains__` is a +/// Python function, called directly ([`dunder_call`]) as +/// `f(container, item)`. `0` or `1` whether the item was found (before +/// `invert`), the operands gone; `CALL_DECLINED` declined untouched; +/// `RAISED` or `RELOAD` as [`h_call`]'s (the core loop takes a result it +/// settles as the operator does: see `records::MethodOp::Contains`). +unsafe extern "C" fn h_contains_dunder( + st: *mut State, + _code: *const CodeObject, + pc: u64, + slot: u64, + site: *mut DirectSite, + invert: u64, +) -> u32 { + // SAFETY: the code passes its live state, its own code and one of its + // `CONTAINS_OP`s, the operands' slot (with room for one more above + // them, and nothing virtual below), and the site's cache. + unsafe { + let st = &mut *st; + if st.sw.is_null() { + return CALL_DECLINED; + } + let (pc, slot) = (pc as usize, slot as usize); + let at = st.stack.add(slot); + let Object::Instance(inst) = &*at.add(1) else { + return CALL_DECLINED; + }; + let Some(f) = Interpreter::binary_dunder_function( + inst, + crate::types::vm_key::CONTAINS, + "__contains__", + ) else { + return CALL_DECLINED; + }; + // `[item, cont]` becomes `[cont, item]`, the method's arguments. + let item = at.read(); + at.write(at.add(1).read()); + at.add(1).write(item); + let invert = invert != 0; + let op = Some(records::MethodOp::Contains(invert)); + match dunder_call(st, pc, slot, 2, f, site, op) { + CALL_DECLINED => { + let cont = at.read(); + at.write(at.add(1).read()); + at.add(1).write(cont); + CALL_DECLINED + } + 0 => match &*at { + Object::Bool(b) => { + let b = *b; + st.len = slot; + u32::from(b) + } + _ => contains_rest(st, pc, slot, invert), + }, + r => r, + } + } +} + +/// [`h_contains_dunder`] whose method answered something other than a +/// `bool` (at `slot`): its truth (`Interpreter::obj_truthy`), which may run +/// Python code, so the caller's frame is synced and its shell built first, +/// as [`compare_rest`] syncs it. `0` or `1` as the helper's; `RAISED`, or +/// `RELOAD` with the operator's `bool` on the frame's stack. +#[cold] +#[inline(never)] +unsafe fn contains_rest(st: &mut State, pc: usize, slot: usize, invert: bool) -> u32 { + // SAFETY: as `h_contains_dunder`'s, the method's answer at `slot`. + unsafe { + let interp = &mut *st.interp.cast_mut(); + let frame = &mut *st.frame; + frame.stack.set_len(slot + 1); + frame.pc = pc as u32 + 1; + settle(st); + let sw = &mut *st.sw; + let mut tmp = None; + let (cf, _, cshell) = sw.activation((*sw.inl).len(), &mut tmp); + interp.flush_lean(&mut *cf, &mut *cshell.cast::>()); + let v = frame.stack.pop().expect("the method's answer"); + let globals = frame.globals.clone(); + let r = interp.obj_truthy(&v, &globals); + drop(v); + *sw.last = pc; + let in_place = |sw: &crate::CoreSwitch| { + sw.pending.is_none() + && std::ptr::eq(sw.cur, st.frame) + && crate::hot_gates::loop_gen() == st.snap_gen + }; + let b = match r { + Ok(b) => b, + Err(e) if in_place(sw) => { + st.len = slot; + st.pc = pc + 1; + st.err = Some(e); + return RAISED; + } + Err(e) => { + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Raised(e))); + return RELOAD; + } + }; + if interp.drain_if_maybe_dead() && crate::hot_gates::loop_gen() != st.snap_gen { + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Breaker)); + } + if !in_place(sw) { + frame.stack.push(Object::Bool(b != invert)); + return RELOAD; + } + st.len = slot; + u32::from(b) + } +} + +/// [`h_binop_dunder`]'s lane for `a + b` of two instances of one plain +/// class whose `__add__` is a native method with a leaf half (an +/// `array`'s): the half's answer at `slot` (see [`pair_leaf_call`]). Only +/// one class, so no reflected method comes first; a `+=` is its +/// `__iadd__`'s. +/// +/// # Safety +/// +/// As [`pair_leaf_call`]'s. +unsafe fn binop_leaf(st: &mut State, pc: usize, slot: usize, op: BinOpKind, inplace: bool) -> u32 { + // SAFETY: the caller's contract. + unsafe { + let at = st.stack.add(slot); + let (Object::Instance(a), Object::Instance(b), BinOpKind::Add, false) = + (&*at, &*at.add(1), op, inplace) + else { + return CALL_DECLINED; + }; + if !std::ptr::eq(a.cls_raw(), b.cls_raw()) { + return CALL_DECLINED; + } + match Interpreter::instance_add_leaf(a) { + Some(fast) => pair_leaf_call(st, pc, slot, fast, true), + None => CALL_DECLINED, + } + } +} + +/// The leaf half of the native `__getitem__` of the instance `v`'s plain +/// Python class (see [`Interpreter::instance_getitem_leaf`]). +/// The plain Python `__missing__` of a dict subclass that keeps +/// `dict.__getitem__` (a `Counter`'s, a user class's), when `container` +/// is one of its instances and the `str` or `int` key is settled absent +/// with no code run: CPython's `dict_subscript` calls it with the key, as +/// [`h_subscr_dunder`] then does in place. +fn missing_dunder(container: &Object, key: &Object) -> Option> { + let Object::Instance(inst) = container else { + return None; + }; + let Some(Object::Dict(d)) = inst.native.get() else { + return None; + }; + let cls = inst.cls_raw(); + let getitem = cls.dunder(crate::types::Dunder::GetItem); + if !getitem.present() + || !getitem.builtin_owner() + || !cls.dunder(crate::types::Dunder::Missing).present() + { + return None; + } + let probe = crate::object::LeafProbe::new(key)?; + { + let m = d.try_borrow().ok()?; + if m.get(&probe).is_some() || !probe.miss_is_exact() { + return None; + } + } + match cls.lookup("__missing__")? { + Object::Function(f) => Some(f), + _ => None, + } +} + +fn getitem_leaf_of(v: &Object) -> Option { + match v { + Object::Instance(inst) => Interpreter::instance_getitem_leaf(inst) + .or_else(|| Interpreter::payload_getitem_leaf(inst)), + _ => None, + } +} + +/// [`h_subscr_dunder`]'s, [`h_slice_dunder`]'s and [`binop_leaf`]'s +/// lane for a class whose special method is a native method with a leaf +/// half: `fast` called on the two operands at stack slots `slot` and +/// above it, both released as the full call releases its operands, the +/// result at `slot`. `0` done (or a finalizer's stop), `RAISED` with the +/// half's error, or `CALL_DECLINED` untouched (for an operator, also an +/// answer of `NotImplemented`, whose reflected method the full path +/// tries). +/// +/// # Safety +/// +/// As [`dunder_call`]'s, with `n` two. +unsafe fn pair_leaf_call( + st: &mut State, + pc: usize, + slot: usize, + fast: crate::leaf_builtins::Fast, + operator: bool, +) -> u32 { + // SAFETY: the caller's contract. + unsafe { + let at = st.stack.add(slot); + let Some(r) = fast(std::slice::from_raw_parts(at, 2)) else { + return CALL_DECLINED; + }; + if operator + && r.as_ref() + .is_ok_and(|v| v.is_same(&crate::vm_singletons::not_implemented())) + { + drop(r); + return CALL_DECLINED; + } + crate::release_operands(&*st.interp, at, 2); + match r { + Ok(v) => { + at.write(v); + if (*st.maybe_dead).get() { + return left_marked(st, pc as u32, slot + 1); + } + 0 + } + Err(e) => { + st.len = slot; + st.pc = pc + 1; + st.err = Some(e); + RAISED + } + } + } +} + /// `BINARY_SLICE` (the `pc`th instruction of `code`) of the plain instance /// at stack slot `slot` and the bounds above it, which `h_container` /// declined, whose class's `__getitem__` is a plain Python function @@ -10938,8 +16004,17 @@ unsafe extern "C" fn h_slice_dunder( } let (pc, slot) = (pc as usize, slot as usize); let at = st.stack.add(slot); - let Some(f) = Interpreter::getitem_dunder(&*code, pc, &*at) else { - return CALL_DECLINED; + // (A class's `__getitem__` is a native method with a leaf half or + // a Python function, never both.) + let fast = getitem_leaf_of(&*at); + let f = match fast { + Some(_) => None, + None => { + let Some(f) = Interpreter::getitem_dunder(&*code, pc, &*at) else { + return CALL_DECLINED; + }; + Some(f) + } }; let (start, stop) = (at.add(1).read(), at.add(2).read()); at.add(1) @@ -10948,7 +16023,11 @@ unsafe extern "C" fn h_slice_dunder( stop, step: Object::None, }))); - let r = dunder_call(st, pc, slot, 2, f, site, None); + let r = match (fast, f) { + (Some(fast), _) => pair_leaf_call(st, pc, slot, fast, false), + (None, Some(f)) => dunder_call(st, pc, slot, 2, f, site, None), + (None, None) => unreachable!("one of them, checked above"), + }; if r == CALL_DECLINED { // The bounds back in their slots. let Object::Slice(s) = at.add(1).read() else { @@ -10961,6 +16040,73 @@ unsafe extern "C" fn h_slice_dunder( } } +/// `super().name` (the attribute form of the `LOAD_SUPER_ATTR` at `pc` of +/// `code`) of a property, which `h_super_attr` declined, its three +/// operands from stack slot `slot` up (nothing virtual below them): the +/// getter `Interpreter::super_property_getter` finds called on the +/// receiver as [`dunder_call`] calls a special method, the result at +/// `slot`. `ssite` is the instruction's [`SuperSite`]. Returns as +/// `h_slice_dunder` does (a decline leaves the operands as they were). +unsafe extern "C" fn h_super_property( + st: *mut State, + code: *const CodeObject, + pc: u64, + slot: u64, + site: *mut DirectSite, + ssite: *const SuperSite, +) -> u32 { + // SAFETY: the code passes its live state, its own code and one of its + // `LOAD_SUPER_ATTR`s, the operands' slot (nothing virtual below them), + // and the site's cache. + unsafe { + let st = &mut *st; + if st.sw.is_null() { + return CALL_DECLINED; + } + let (pc, slot) = (pc as usize, slot as usize); + let at = st.stack.add(slot); + let code = &*code; + // The getter `h_super_attr` cached for the receiver's class, or + // the lookup's. + let ssite = &*ssite; + let cached = match (&*at, &*at.add(1), &*at.add(2), &ssite.getter) { + (g, Object::Type(cls), Object::Instance(inst), Some(f)) + if Rc::as_ptr(cls) as usize == ssite.cls + && std::ptr::from_ref(inst.cls_raw()) as usize == ssite.recv + && inst.cls_raw().attr_version.get() == ssite.ver + && crate::is_super_callable(g) + && Interpreter::lean_getter_ok(f) => + { + Some(f.clone()) + } + _ => None, + }; + let Some(f) = cached.or_else(|| { + Interpreter::super_property_getter( + code, + code.instructions[pc], + std::slice::from_raw_parts(at, 3), + ) + }) else { + return CALL_DECLINED; + }; + // The receiver moves down to the operands' first slot; `super` and + // the class are held here until the call settles (each is held + // elsewhere too: the builtins, the class cell). + let (g, cls) = (at.read(), at.add(1).read()); + at.write(at.add(2).read()); + let r = dunder_call(st, pc, slot, 1, f, site, None); + if r == CALL_DECLINED { + at.add(2).write(at.read()); + at.write(g); + at.add(1).write(cls); + } else { + drop((g, cls)); + } + r + } +} + /// The `n` (at most three) operands from stack slot `slot` up, as the /// instruction at `pc` leaves them, called as `f(*operands)` for a class's /// Python special method `f` (an instance operator's, `op` its @@ -10991,6 +16137,7 @@ unsafe fn dunder_call( // SAFETY: the caller's contract. unsafe { let at = st.stack.add(slot); + // (What the operator owes a result returned in place: `true` raised.) let not_implemented = |st: &mut State, v: &Object| match op { Some(records::MethodOp::Binary(op, inplace, a, b)) if v.is_same(&crate::vm_singletons::not_implemented()) => @@ -11000,6 +16147,15 @@ unsafe fn dunder_call( st.err = Some(crate::binop_type_error(op, inplace, a, b)); true } + Some(records::MethodOp::Iter) => match crate::iter_result_check(v) { + Ok(_) => false, + Err(e) => { + st.len = slot; + st.pc = pc + 1; + st.err = Some(e); + true + } + }, _ => false, }; // A pure leaf (no native body of its own: it never runs as an @@ -11017,7 +16173,10 @@ unsafe fn dunder_call( at.add(1).cast_const(), at.add(2).cast_const(), ]; - if let Some(v) = (*st.interp).pure_leaf_eval::(code, &f, &ptrs[..n]) { + // (Through the frameless call's entry: a warm plan runs as its + // native code.) + let depth = crate::recursion::current_depth(); + if let Some(v) = (*st.interp).pure_leaf_call(code, &f, &ptrs[..n], false, depth) { for k in (0..n).rev() { crate::drop_hot_at(at.add(k)); } @@ -11083,7 +16242,19 @@ unsafe extern "C" fn h_property( unsafe { let st = &mut *st; if st.sw.is_null() { - return CALL_DECLINED; + // A generator's fast step: only a getter that runs no + // activation (it can't switch). + return match property_leaf_here( + st, + code, + pc as usize, + slot as usize, + recv, + local & !PROPERTY_ONLY, + ) { + Some(()) => 0, + None => CALL_DECLINED, + }; } let only = local & PROPERTY_ONLY != 0; let local = local & !PROPERTY_ONLY; @@ -11142,32 +16313,95 @@ unsafe extern "C" fn h_property( return 0; } } + if property_leaf_here(st, code, pc, slot, recv, local).is_some() { + return 0; + } let Object::Instance(inst) = &*recv else { return lane(st); }; - let Some((getter, gcode)) = crate::code_vm_ext(&*code) + let Some((getter, _)) = crate::code_vm_ext(&*code) .and_then(|ext| ext.method_slot(pc)) .and_then(|ms| ms.getter(inst.cls_raw().attr_version.get())) else { return lane(st); }; - let at = st.stack.add(slot); - // A pure leaf getter (no native body of its own: it never runs as - // an activation) evaluates in place, as the core loop's arm does. - if crate::code_is_pure_leaf(&gcode) - && crate::pure_leaf_warm(&gcode) - && crate::recursion::current_depth() < crate::recursion::recursion_limit() - && (local != 0 || droppable(&*recv)) - { - let interp = &*st.interp; - if let Some(v) = interp.pure_leaf_eval::(&gcode, &getter, &[recv]) { - if local == 0 { - crate::drop_hot_at(at); - } - at.write(v); - return 0; - } + property_call(st, pc, slot, recv, local, site, getter).unwrap_or_else(|| lane(st)) + } +} + +/// A read at `site` of the instance at `at` (a local's when `local`) whose +/// class the site's method slot holds a `property` getter for at its +/// version, a getter that isn't a pure leaf (one runs in place on the +/// lanes that evaluate it): called now, directly, ahead of the field and +/// class probes of the slow helpers, none of which can answer (a property +/// is a data descriptor). Before, a property read on a class with +/// `__slots__` (`Path.name`, `self._tail` in `pathlib`) went through every +/// slot and field probe to reach `attr_miss`'s call. `None` touched +/// nothing. +/// +/// # Safety +/// +/// As [`attr_miss`]'s. +#[inline] +unsafe fn getter_first( + st: *mut State, + site: &AttrSite, + at: *mut Object, + local: bool, +) -> Option { + // SAFETY: the caller's contract. + unsafe { + if (*st).sw.is_null() || site.direct.is_null() { + return None; + } + let Object::Instance(inst) = &*at else { + return None; + }; + let ms = (*site.ext).method_slot(site.pc as usize)?; + if !ms.holds_getter() { + return None; + } + let cls = inst.cls_raw(); + let ver = cls.attr_version.get(); + if ver == 0 || !Interpreter::default_getattribute(cls) { + return None; + } + if crate::code_is_pure_leaf(ms.getter_peek(ver)?.1) { + return None; } + let (getter, _) = ms.getter(ver)?; + let (pc, slot) = (site.pc as usize, site.slot as usize); + property_call( + &mut *st, + pc, + slot, + at, + u64::from(local), + site.direct, + getter, + ) + } +} + +/// [`h_property`]'s call of `getter`, the `property` getter the site +/// cached for the receiver's class, directly ([`direct_call_out`]): its +/// status, or `None` declined untouched. +/// +/// # Safety +/// +/// As [`h_property`]'s, with a switch, `local` without [`PROPERTY_ONLY`]. +unsafe fn property_call( + st: &mut State, + pc: usize, + slot: usize, + recv: *const Object, + local: u64, + site: *mut DirectSite, + getter: Rc, +) -> Option { + // SAFETY: the caller's contract. + unsafe { + let at = st.stack.add(slot); // `[recv]` becomes the method call `[getter, recv]`. if local != 0 { at.add(1).write(crate::clone_hot(&*recv)); @@ -11175,31 +16409,258 @@ unsafe extern "C" fn h_property( at.add(1).write(at.read()); } at.write(Object::Function(getter)); - match direct_call_out(st, pc, slot, slot + 2, &mut *site, None) { - None => { - let f = at.read(); - // The getter of compiled code runs as a switched call: it - // warms as one (see `Slot::warm_switched`). - if let Object::Function(f) = &f { - let code = f.code(); - if let Some(ext) = crate::code_vm_ext(&code) { - ext.frame_jit - .warm_switched(&code, ext, code.varnames.len().max(1)); - } + let r = direct_call_out(st, pc, slot, slot + 2, &mut *site, None); + if r.is_none() { + let f = at.read(); + // The getter of compiled code runs as a switched call: it + // warms as one (see `Slot::warm_switched`). + if let Object::Function(f) = &f { + let code = f.code(); + if let Some(ext) = crate::code_vm_ext(&code) { + ext.frame_jit + .warm_switched(&code, ext, code.varnames.len().max(1)); } - if local != 0 { - crate::drop_hot_at(at.add(1)); - } else { - at.write(at.add(1).read()); + } + if local != 0 { + crate::drop_hot_at(at.add(1)); + } else { + at.write(at.add(1).read()); + } + drop(f); + } + r + } +} + +/// `recv.name` at `site` by the class's Python `__getattr__`, the default +/// lookup known to miss: the hook called directly, as [`property_call`] +/// calls a getter (`[recv]` becomes the call `[hook, recv, name]`). `None` +/// touched nothing (a hook without native code, or one the direct call +/// doesn't bind). +/// +/// # Safety +/// +/// As [`h_property`]'s, with a switch and a direct site; `at` holds the +/// instance `inst`. +unsafe fn hook_call( + st: &mut State, + site: &AttrSite, + at: *mut Object, + local: bool, + inst: &Rc, + name: &str, +) -> Option { + // SAFETY: the caller's contract. + unsafe { + let hook = Interpreter::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::GETATTR_FN), + "__getattr__", + )?; + let code = &*site.code; + let (pc, slot) = (site.pc as usize, site.slot as usize); + { + let hcode = hook.code(); + if hcode.arg_count != 2 + || hcode.kwonly_count != 0 + || hcode.has_varargs + || hcode.has_varkeywords + || hcode.is_generator + || hcode.is_coroutine + || hcode.is_async_generator + { + return None; + } + // (A hook that can't evaluate as a leaf: the slow path stops + // trying it as one.) + if !crate::code_is_pure_leaf(&hcode) { + site.py_hook.set(0); + } + } + let name = crate::code_name_str(code, code.instructions[pc].arg, name); + let base = st.stack.add(slot); + if local { + base.add(1).write(crate::clone_hot(&*at)); + } else { + base.add(1).write(base.read()); + } + base.write(Object::Function(hook)); + base.add(2).write(name); + let r = direct_call_out(st, pc, slot, slot + 3, &mut *site.direct, None); + if r.is_none() { + drop(base.add(2).read()); + let f = base.read(); + if let Object::Function(f) = &f { + let code = f.code(); + if let Some(ext) = crate::code_vm_ext(&code) { + ext.frame_jit + .warm_switched(&code, ext, code.varnames.len().max(2)); } - drop(f); - lane(st) } - Some(r) => r, + if local { + crate::drop_hot_at(base.add(1)); + } else { + base.write(base.add(1).read()); + } + drop(f); + } + r + } +} + +/// [`hook_call`] at a site whose memo vouches for the class's half of the +/// default lookup (see `AttrSite::py_hook_call`): only the instance's own +/// half is probed. +/// +/// # Safety +/// +/// As [`h_attr_stack`]'s; `at` holds the instance `inst`. +#[inline(never)] +unsafe fn hook_call_known( + st: *mut State, + site: &AttrSite, + at: *mut Object, + local: bool, + inst: &Rc, +) -> Option { + // SAFETY: the caller's contract. + unsafe { + if site.direct.is_null() || (*st).sw.is_null() { + return None; + } + let code = &*site.code; + let name = code + .names + .get(code.instructions[site.pc as usize].arg as usize)?; + if !Interpreter::getattr_hook_inst_misses(inst, name) { + return None; + } + hook_call(&mut *st, site, at, local, inst, name) + } +} + +/// [`h_property`]'s read through the site's cached getter when it's a pure +/// leaf (no native body of its own: it never runs as an activation), which +/// evaluates in place, as the core loop's arm does: `Some` with the value +/// written to `slot`, `None` with nothing done. +/// +/// # Safety +/// +/// As [`h_property`]'s. +unsafe fn property_leaf_here( + st: &mut State, + code: *const CodeObject, + pc: usize, + slot: usize, + recv: *const Object, + local: u64, +) -> Option<()> { + // SAFETY: the caller's contract. + unsafe { + let Object::Instance(inst) = &*recv else { + return None; + }; + let (getter, gcode) = crate::code_vm_ext(&*code) + .and_then(|ext| ext.method_slot(pc)) + .and_then(|ms| ms.getter(inst.cls_raw().attr_version.get()))?; + if !(crate::code_is_pure_leaf(&gcode) + && crate::pure_leaf_warm(&gcode) + && crate::recursion::current_depth() < crate::recursion::recursion_limit() + && (local != 0 || droppable(&*recv))) + { + return None; + } + let interp = &*st.interp; + let v = interp.pure_leaf_eval::(&gcode, &getter, &[recv])?; + let at = st.stack.add(slot); + if local == 0 { + crate::drop_hot_at(at); + } + at.write(v); + Some(()) + } +} + +/// A read at `site` of the receiver at `at` (a local's when `local`, the +/// result then going to the site's slot) through the pure leaf getter the +/// site last ran in place for the receiver's class version (see +/// [`site_property_note`]): `true` with the value written, `false` with +/// nothing done. The class holds the property while its version stands, +/// and the property its getter while the getter cell still holds it. +/// +/// # Safety +/// +/// As [`h_property`]'s. +#[inline] +unsafe fn site_property_leaf( + st: &mut State, + site: &AttrSite, + at: *mut Object, + local: bool, +) -> bool { + // SAFETY: the caller's contract; the pointers are live while the checks + // above each use hold. + unsafe { + let Object::Instance(inst) = &*at else { + return false; + }; + let ver = inst.cls_raw().attr_version.get(); + let (held, f, code, cell) = site.prop_leaf[0].get(); + let (f, code, cell) = if held == ver { + (f, code, cell) + } else { + let (held, f, code, cell) = site.prop_leaf[1].get(); + if held != ver { + return false; + } + (f, code, cell) + }; + if ver == 0 { + return false; + } + if !matches!(&*(cell as *const Object), Object::Function(g) if Rc::as_ptr(g) as usize == f) + || (!local && !droppable(&*at)) + || crate::recursion::current_depth() >= crate::recursion::recursion_limit() + { + return false; + } + let interp = &*st.interp; + let Some(v) = interp.pure_leaf_eval::( + &*(code as *const CodeObject), + &*(f as *const crate::object::PyFunction), + &[at.cast_const()], + ) else { + return false; + }; + let dst = st.stack.add(site.slot as usize); + if !local { + crate::drop_hot_at(dst); + } + dst.write(v); + true + } +} + +/// Remember at `site` the pure leaf getter its slot holds for the class +/// version `ver`, which [`property_leaf_here`] just ran (see +/// [`site_property_leaf`]). +fn site_property_note(site: &AttrSite, ver: u64) { + // SAFETY: the site's code and extension are live. + let ext = unsafe { &*site.ext }; + if let Some((f, cell)) = crate::property_site_getter_at(ext, site.pc as usize, ver) { + let code = Rc::as_ptr(&f.code()) as usize; + let new = (ver, Rc::as_ptr(&f) as usize, code, cell as usize); + // (A site reading two classes in turn keeps both.) + let old = site.prop_leaf[0].replace(new); + if old.0 != ver { + site.prop_leaf[1].set(old); } } } +/// Classes whose property getter a site keeps (see `AttrSite::prop_leaf`). +const PROP_LEAVES: usize = 2; + /// [`h_property`]'s flag (in `local`) for a call that wants the site's /// cached getter only. const PROPERTY_ONLY: u64 = 2; @@ -11282,6 +16743,40 @@ unsafe extern "C" fn h_countdown(countdown: *mut u32) -> u32 { 0 } +/// The `CALL` at `pc` (its operands from `start` up a `len`-deep stack) +/// of a builtin container type with one argument, which +/// `Interpreter::core_type_lane` builds (see `core_type_lane_class`), +/// run there with the frame synced as `h_call` syncs it: `0` or `RELOAD` +/// as `h_call` answers after the lane, `None` when the lane declined. +/// +/// # Safety +/// +/// As `h_call`'s, with a running activation's switch in `st`. +unsafe fn type_lane_direct(st: *mut State, pc: u64, len: usize, start: usize) -> Option { + // SAFETY: the caller's contract. + unsafe { + let st = &mut *st; + if st.sw.is_null() { + return None; + } + let frame = &mut *st.frame; + frame.stack.set_len(len); + frame.pc = pc as u32; + settle(st); + *(*st.sw).last = st.last; + let sw = &mut *st.sw; + let interp = &mut *st.interp.cast_mut(); + if !interp.core_type_lane(sw) { + return None; + } + Some(if finished_in_place(st, start) { + 0 + } else { + RELOAD + }) + } +} + /// `CALL` of a Python class: a class whose memoized plan proved its /// construction to be a store-only `__init__`'s stores runs them straight /// from here (`Interpreter::core_store_init`, as the core loop's @@ -11308,11 +16803,17 @@ unsafe extern "C" fn h_call_ctor( // (a loop that grew hot in its first call), which it notes now. let start = len as usize - argc - 2; if let Object::Type(t) = &*s.stack.add(start) { - if t.flags.is_builtin - && matches!(&*s.stack.add(start + 1), Object::Unbound) - && !s.sw.is_null() + // (A filled self slot is the first argument: a failing + // `assert cond, message` calls `AssertionError` with its + // message there.) + let first = if matches!(&*s.stack.add(start + 1), Object::Unbound) { + start + 2 + } else { + start + 1 + }; + if t.flags.is_builtin && (first == start + 2 || t.flags.is_exception) && !s.sw.is_null() { - let args = std::slice::from_raw_parts(s.stack.add(start + 2), argc); + let args = std::slice::from_raw_parts(s.stack.add(first), len as usize - first); let interp = &*s.interp; if let Some(v) = interp .leaf_type_call(t, args) @@ -11324,6 +16825,14 @@ unsafe extern "C" fn h_call_ctor( s.len = start + 1; return 0; } + // `list(it)`, `tuple(it)` ... of anything else: straight to + // the core loop's lane, as `h_call` would take it after + // the same attempt again. + if argc == 1 && Interpreter::core_type_lane_class(t) { + if let Some(r) = type_lane_direct(st, pc, len as usize, start) { + return r; + } + } } } if ctor_store_init(s, &*code, pc as usize, argc, len as usize) { @@ -11415,6 +16924,7 @@ unsafe fn ctor_store_init( let Some((ver, plan)) = ty.instance_plan.peek().and_then(Option::as_ref) else { return false; }; + let plan = interp.call_plan(plan, ty, argc); if *ver != ty.attr_version.get() || plan.store_init.load(std::sync::atomic::Ordering::Relaxed) != 1 { @@ -11451,6 +16961,8 @@ unsafe fn ctor_store_init( ); if done { st.len = start + 1; + // (Compiled code's class dispatch builds the next one.) + ty.store_ctor.set(ty.attr_version.get()); } done } @@ -11550,11 +17062,72 @@ unsafe extern "C" fn h_call_site( } site.retry -= 1; } else if matches!(callee, Object::Type(_)) { + if argc == 1 + && matches!(callee, Object::Type(t) if Rc::ptr_eq(t, &crate::builtin_types::builtin_types().str_)) + && matches!(&*at.add(1), Object::Unbound) + { + // `str(s)` of an exact `str` is `s` itself: the string + // takes the callee's slot (the class, a builtin, goes with + // a plain decrement). + if matches!(&*at.add(2), Object::Str(_)) { + let s = at.add(2).read(); + drop(std::mem::replace(&mut *at, s)); + (*st).len = len as usize - 2; + return 0; + } + // `str(obj)` through a Python `__str__` (see `str_call`). + if matches!(&*at.add(2), Object::Instance(_)) { + let lenu = len as usize; + let pc = (pc_argc & u64::from(u32::MAX)) as usize; + if let Some(r) = str_call(&mut *st, site, pc, lenu - 3, lenu) { + return r; + } + } + } return h_call_ctor(st, code, ext, pc_argc, len); } else if crate::stdlib::functools_mod::is_lru_wrapper(callee) { return h_call_instance(st, code, ext, pc_argc, len, site); + } else if let (Object::Builtin(b), 1) = (callee, argc) { + if crate::is_object_new(b) { + if let Some(r) = object_new_here(st, len as usize - 3) { + return r; + } + } + } + h_call(st, code, ext, pc_argc & u64::from(u32::MAX), len) + } +} + +/// `object.__new__(cls)` (the callee at `start`, its self slot empty) of +/// a class whose memoized plan proved the call the plain allocation (as +/// `object_new` reads it, a user `__new__`'s usual last step): the +/// instance, in the callee's slot. `None` touched nothing (a collection +/// due, an allocation observer, or a class whose last reference the +/// call holds). +#[inline(never)] +unsafe fn object_new_here(st: *mut State, start: usize) -> Option { + // SAFETY: the caller's contract: three operand slots from `start`. + unsafe { + let at = (*st).stack.add(start); + let (Object::Unbound, Object::Type(cls)) = (&*at.add(1), &*at.add(2)) else { + return None; + }; + if !crate::object_new_plain_memo(cls) + || Rc::strong_count(cls) < 2 + || crate::stdlib::tracemalloc_real::is_tracking() + || crate::stdlib::testinternalcapi_mod::reftrace_print_active() + || crate::stdlib::testinternalcapi_mod::nomem_alloc_fails() + || crate::gc_trace::auto_collect_due() + { + return None; } - h_call(st, code, ext, pc_argc & u64::from(u32::MAX), len) + let (inst, _) = (*(*st).interp).alloc_plain_instance_obj(cls); + // The class (not its last reference) and the builtin (the type's + // own, as long-lived) leave. + crate::drop_hot(at.add(2).read()); + crate::drop_hot(at.replace(inst)); + (*st).len = start + 1; + Some(0) } } @@ -11564,6 +17137,11 @@ unsafe extern "C" fn h_call_site( /// its positional ones given (the keyword-only ones take their defaults). /// How many positional ones take defaults. fn site_leaf_fits(f: &crate::object::PyFunction, code: &CodeObject, nargs: usize) -> Option { + // (A leaf takes no `*args`: a decorator's wrapper that only forwards + // to a pure leaf evaluates as its target, see `site_forward_fits`.) + if code.has_varargs { + return site_forward_fits(f, code).then_some(0); + } let missing = (code.arg_count as usize).checked_sub(nargs)?; (crate::fn_is_leaf(f) && !code.has_varargs @@ -11573,6 +17151,28 @@ fn site_leaf_fits(f: &crate::object::PyFunction, code: &CodeObject, nargs: usize .then_some(missing) } +/// Whether a site may evaluate a call of `f` (running `code`) as its +/// target's (`Interpreter::forward_pure_call`): a wrapper that only +/// forwards its arguments (see [`crate::code_forwards`]) to a function +/// whose code is a pure leaf now. (A wrapper over anything else keeps its +/// own body: declines would cost its site an activation each.) +fn site_forward_fits(f: &crate::object::PyFunction, code: &CodeObject) -> bool { + if !crate::code_forwards(code) { + return false; + } + let Some(Object::Cell(cell)) = f.closure.first() else { + return false; + }; + // SAFETY: a read that runs no code. + match unsafe { cell.peek() } { + Some(Object::Function(g)) => crate::code_is_pure_leaf_pub( + // SAFETY: GIL-serialized raw read of the function's code cell. + unsafe { &*g.code.as_ptr() }, + ), + _ => false, + } +} + /// A `CALL`'s (its operands from `start` up a `len`-deep stack) callee, /// the frameless leaf its site cached (see [`DirectSite::fill_leaf`]), /// whose last `missing` parameters take defaults, evaluated in place as @@ -11716,6 +17316,9 @@ pub(crate) unsafe fn register_lazy(st: &mut State) { sw.scratch = usize::MAX; sw.last = &raw mut sw.scratch; st.lazy_depth = (*sw.inl).len(); + if (*act).back_for.is_some() { + interp.resolve_back_for(&mut *act); + } // A native body running from here: the activation waits on the // pending list, as if it had registered first. if st.wait_pc != usize::MAX { @@ -11731,7 +17334,7 @@ pub(crate) unsafe fn register_lazy(st: &mut State) { /// thread's may: it stays alive for good once threads run, which so rare an /// assignment can afford. pub(crate) fn retire_code(code: Rc) { - if crate::sync::rc_shared_flag().load(Ordering::Relaxed) { + if crate::sync::threads_started() { std::mem::forget(code); } } @@ -11813,7 +17416,10 @@ unsafe fn direct_call( // several leaves, as an operator table's lambdas, takes them all, // caching the first two.) let cached = CALL && (site.leaf_key == key || site.alt_leaf_key == key); - let body_first = CALL && { + // (A forwarding wrapper over a pure leaf evaluates as its + // target rather than running its own body.) + let forwards = CALL && code_rc.has_varargs && (cached || site_forward_fits(f, code_rc)); + let body_first = CALL && !forwards && { let has = direct_body(f, code_rc, nargs).is_some(); if !has && crate::fn_is_leaf(f) { if let Some(ext) = crate::code_vm_ext(code_rc) { @@ -12129,6 +17735,7 @@ unsafe fn direct_run_pushed( wait_pending: None, outer_lazy: 0, fold: std::ptr::null(), + caught: false, }; interp.recs.set_top(nested.add(1)); let status = native.run_direct(&mut cst, from); @@ -12200,7 +17807,13 @@ unsafe fn direct_done( let clean = cst.len == 1 && !st.inl_gone && inl.last().is_some_and(|a| { - a.act.shell.is_none() + // (A shell the callee got catching an exception, or as + // a registered caller of one that did, retires here as + // `core_return` retires it, while nothing observes it.) + a.act + .shell + .as_deref() + .is_none_or(|s| interp.shell_pops_quietly(s, a.exc_depth)) && (cframe.code.cellvars.is_empty() || a.owns_cells) && (a.init_inst.is_none() || matches!(&*cst.stack, Object::None)) && a.new_init.is_none() @@ -12219,6 +17832,13 @@ unsafe fn direct_done( sw.entry_dead = true; } let v = done.init_inst.take().unwrap_or(v); + let had_shell = match done.act.shell.take() { + Some(shell) => { + interp.retire_quiet_shell(shell, cframe, cst.pc); + true + } + None => false, + }; crate::release_activation_locals(cframe, done.owns_cells); drop(done.guard.take()); // A `functools.lru_cache` miss's function returned: its @@ -12230,7 +17850,12 @@ unsafe fn direct_done( // SAFETY: moved out once; the parked slot treats the field // as stale (see `inline_deliver`). let callable = std::ptr::read(&raw const done.callable); - if done.owns_cells { + // (A frame that caught an exception carries the handler + // path's state, which only the full park resets.) + if had_shell { + done.clean = false; + interp.inline_park(done); + } else if done.owns_cells { done.clean = true; interp.inline_park_clean(done); } else { @@ -12291,9 +17916,15 @@ unsafe fn direct_done( if status == RELOAD || status == DIRECT_RET { // Returned into the caller, nothing pending: done. Otherwise // whoever switched last synced what runs next. + // (A probe's answer the delivery settled is the core loop's + // to go on with: its helper reads only the hook's own result.) if sw.pending.is_none() && std::ptr::eq(sw.cur, st.frame) && caller.stack.len() == start + 1 + && !matches!( + op, + Some(records::MethodOp::HasAttr | records::MethodOp::GetAttrOr(_)) + ) { st.len = start + 1; return 0; @@ -12775,6 +18406,22 @@ unsafe extern "C" fn h_call( } return RELOAD; } + // `agen.asend(v)`, `agen.aclose()`, `agen.__anext__()`: the deferred + // awaitable, made in place. + if argc <= 1 + && matches!(&*base.add(start), Object::BoundMethod(_)) + && Interpreter::core_drops_plain() + { + let args = std::slice::from_raw_parts(base.add(start + 2), argc); + if let Some(aw) = + Interpreter::agen_method_await(&*base.add(start), &*base.add(start + 1), args) + { + crate::release_run(base.add(start), argc + 2); + base.add(start).write(aw); + st.len = start + 1; + return 0; + } + } // `next(gen)`: the generator resumes inline, as for `FOR_ITER`, // with the yield as the call's result. if argc == 1 @@ -12962,7 +18609,15 @@ unsafe extern "C" fn h_call( let args = std::slice::from_raw_parts(base.add(first), len - first); if Interpreter::core_all_droppable(args) { let r = match kind { - Some(LeafKind::Fast(f)) => f(args), + // (`next(it)` of a Python iterator class's instance, + // as `FOR_ITER` steps it.) + Some(LeafKind::Fast(f)) => f(args).or_else(|| { + if b.name == "next" { + (*st.interp).leaf_next_instance(args) + } else { + None + } + }), _ => Interpreter::core_isinstance(args), }; match r { @@ -12978,6 +18633,22 @@ unsafe extern "C" fn h_call( } } } + // `__import__(name, ...)` of a module that's already imported: + // the module from the import cache, as the compiled `IMPORT_NAME` + // takes it (the call otherwise leaves compiled code: the + // dispatch runs it). + if b.name.len() == 15 + && b.name == "__vm:__import__" + && matches!(&*base.add(start + 1), Object::Unbound) + && Rc::strong_count(b) > 1 + { + let args = std::slice::from_raw_parts(base.add(start + 2), argc); + if Interpreter::core_all_droppable(args) { + if let Some(m) = interp.cached_dunder_import(args) { + return done(st, m); + } + } + } } let ops = std::slice::from_raw_parts(base.add(start), argc + 2); let python = match &ops[0] { @@ -13076,6 +18747,15 @@ unsafe extern "C" fn h_call( if slot.get_leaf(b).is_some() { return None; } + // A leaf builtin called unbound (`heapreplace(h, x)`): the + // site remembers it, as a settled leaf's (the leaf lanes + // below take it, without asking each call). + if let (Object::Builtin(_), Object::Unbound) = (&ops[0], &ops[1]) { + if let Some(kind) = interp.leaf_call_kind(b) { + slot.set_leaf(b, kind); + return None; + } + } let via_call = interp.builtin_lane(b, recv)?; slot.set_native_body(b, via_call); Some(via_call) @@ -13098,10 +18778,7 @@ unsafe extern "C" fn h_call( let sw = &mut *st.sw; let interp = &mut *st.interp.cast_mut(); if interp.core_builtin_lane(sw, pc, via_call) { - if finished_in_place(st, start) { - return 0; - } - return RELOAD; + return lane_outcome(st, pc, start); } } } @@ -13134,6 +18811,14 @@ unsafe extern "C" fn h_call( } (LeafKind::ListPop, 0) => match items.pop() { Some(v) => (v, len), + // (Raised in place, for the code's handler.) + None if !st.sw.is_null() => { + crate::release_run(base.add(start), len - start); + st.len = start; + st.pc = pc + 1; + st.err = Some(crate::error::index_error("pop from empty list")); + return RAISED; + } None => return CALL_DECLINED, }, _ => return CALL_DECLINED, @@ -13269,8 +18954,31 @@ fn len_fast(args: &[Object]) -> Option> { [Object::Dict(d)] => d.peek()?.len(), [Object::Set(s)] => s.peek()?.len(), [Object::Bytes(b)] => b.len(), + [Object::ByteArray(b)] => b.peek()?.len(), + [Object::FrozenSet(s)] => s.len(), // A dict's keys, values or items view: the dict's size. [Object::DictView(v)] => v.dict.peek()?.len(), + // A machine-word range's count. + [Object::Range(r)] if r.big.is_none() => { + usize::try_from(crate::object::range_len_i128(r)).ok()? + } + // A `mappingproxy` over a dict: the dict's size. + [Object::MappingProxy(d)] => d.peek()?.len(), + // A `memoryview`'s first dimension (a released one's error is + // the full call's). + [v @ Object::MemoryView(_)] => v.len().ok()?, + // A builtin subclass's own `__len__`: its payload's. + [Object::Instance(inst)] => { + let native = Interpreter::native_payload_for( + inst, + crate::types::vm_key::NATIVE_LEN, + "__len__", + )?; + if matches!(native, Object::Instance(_)) { + return None; + } + return len_fast(std::slice::from_ref(native)); + } _ => return None, } }; @@ -13294,6 +19002,11 @@ pub(crate) struct BuiltinSite { /// then run through the core loop's lane, as an unregistered builtin's /// would (`Some(via_call)`), instead of the full handler. lane: Option, + /// The address of the site's direct-call cache, for `len(obj)` or + /// `repr(obj)` of an instance whose class's `__len__` or `__repr__` is a + /// Python function (see [`len_call`]), or `mc(obj)` of a methodcaller + /// whose method is (see [`methodcaller_direct`]); `0` none. + direct: usize, } /// [`h_call`] at a site settled on a container's or string's leaf method @@ -13313,22 +19026,57 @@ unsafe extern "C" fn h_call_kernel( // SAFETY: as `h_call`'s; the site is this `CALL`'s, and the code holds // its builtin. unsafe { - if call_kernel_in_place(&mut *st, &*site, len as usize) { - return 0; + match call_kernel_in_place(&mut *st, &*site, len as usize) { + 0 => return 0, + KERNEL_RAISED => { + if let Some(r) = kernel_raise_in_place(&mut *st, &*site, pc, len as usize) { + return r; + } + } + _ => {} } h_call(st, code, ext, pc, len) } } +/// [`call_kernel_in_place`] answered [`KERNEL_RAISED`] at the `CALL` at +/// `pc`: the operands released and the error in the state, past the call +/// (`RAISED`), as [`call_leaf_in_place`] raises a leaf body's. `None` +/// (no error kept) touches nothing. +/// +/// # Safety +/// +/// As [`h_call_kernel`]'s. +#[cold] +#[inline(never)] +pub(crate) unsafe fn kernel_raise_in_place( + s: &mut State, + site: &BuiltinSite, + pc: u64, + lenu: usize, +) -> Option { + let e = kernel_err_take()?; + // SAFETY: the caller's contract. + unsafe { + let start = lenu - site.argc - 2; + crate::release_operands(&*s.interp, s.stack.add(start), lenu - start); + s.len = start; + s.pc = pc as usize + 1; + s.err = Some(e); + } + Some(RAISED) +} + /// The kernel of the builtin `site` settled on, on the operands up a -/// `lenu`-deep stack: `true` with the result in place, `false` declined -/// untouched. +/// `lenu`-deep stack: `0` with the result in place, [`KERNEL_RAISED`] its +/// body raised (untouched, the error kept: see [`kernel_raise_in_place`]), +/// anything else declined untouched. /// /// # Safety /// /// As [`h_call_kernel`]'s. #[inline(always)] -unsafe fn call_kernel_in_place(s: &mut State, site: &BuiltinSite, lenu: usize) -> bool { +unsafe fn call_kernel_in_place(s: &mut State, site: &BuiltinSite, lenu: usize) -> u32 { // SAFETY: the caller's contract. unsafe { let start = lenu - site.argc - 2; @@ -13346,7 +19094,23 @@ unsafe fn call_kernel_in_place(s: &mut State, site: &BuiltinSite, lenu: usize) - _ => std::ptr::null(), }; if let (false, Some(kernel), false) = (recv.is_null(), site.kernel, s.sw.is_null()) { - if (*recv).tag() == site.recv_tag { + // A builtin subclass's instance (a `Counter`'s `get`, a list + // subclass's `append`): the kernel on the native value backing + // it, as the method's receiver unwrapping runs the body. A dict + // view keeps the instance (its body unwraps it); an opaque body + // isn't run on one. + use crate::LeafKind as K; + let (recv, tag) = match &*recv { + Object::Instance(inst) => match (inst.native.get(), site.kind) { + (None, _) | (_, Some(K::Opaque) | None) => (recv, (*recv).tag()), + (Some(native), Some(K::DictKeys | K::DictValues | K::DictItems)) => { + (recv, native.tag()) + } + (Some(native), _) => (std::ptr::from_ref(native), native.tag()), + }, + r => (recv, r.tag()), + }; + if tag == site.recv_tag { let arg = |k: usize| { if k <= site.argc { base.add(start + 1 + k).cast_const() @@ -13355,15 +19119,39 @@ unsafe fn call_kernel_in_place(s: &mut State, site: &BuiltinSite, lenu: usize) - } }; let mut out = std::mem::MaybeUninit::::uninit(); - if kernel(out.as_mut_ptr(), recv, arg(1), arg(2), site.f) == 0 { + match kernel(out.as_mut_ptr(), recv, arg(1), arg(2), site.f) { + 0 => { + crate::release_operands(&*s.interp, base.add(start), lenu - start); + base.add(start).write(out.assume_init()); + s.len = start + 1; + return 0; + } + KERNEL_RAISED => return KERNEL_RAISED, + _ => {} + } + // `set.add` of an instance whose class's `__hash__` evaluates + // frameless (see `set_add_leaf_hashed`). + if site.kind == Some(K::SetAdd) + && site.argc == 1 + && set_add_leaf_hashed(&*s.interp, recv, arg(1)) + { crate::release_operands(&*s.interp, base.add(start), lenu - start); - base.add(start).write(out.assume_init()); + base.add(start).write(Object::None); s.len = start + 1; - return true; + return 0; + } + // `dict.get` likewise (see `dict_get_leaf_hashed`). + if site.kind == Some(K::DictGet) { + if let Some(v) = dict_get_leaf_hashed(&*s.interp, recv, arg(1), arg(2)) { + crate::release_operands(&*s.interp, base.add(start), lenu - start); + base.add(start).write(v); + s.len = start + 1; + return 0; + } } } } - false + 1 } } @@ -13398,6 +19186,7 @@ unsafe extern "C" fn h_call_leaf( recv_tag: 0, via_call, lane: None, + direct: 0, }; return h_call_native(st, code, ext, pc, len, &raw const whole); } @@ -13429,15 +19218,16 @@ unsafe fn call_leaf_in_place( matches!(&*base.add(start), Object::Builtin(b) if std::ptr::eq(Rc::as_ptr(b), site.f)); // A bound method of the builtin held in a local (`write = f.write`): // its receiver ahead of the arguments, as bitwise views that are - // never dropped. - let mut bound = std::mem::ManuallyDrop::new([const { Object::Unbound }; 4]); + // never dropped (written only where an arm uses them: the array + // isn't initialized for the common call). + let mut bound = [const { std::mem::MaybeUninit::::uninit() }; 4]; let bound_args = match (&*base.add(start), &*base.add(start + 1)) { (Object::BoundMethod(bm), Object::Unbound) if site.argc < bound.len() && !bm.redispatch_descriptor && matches!(&bm.function, Object::Builtin(b) if std::ptr::eq(Rc::as_ptr(b), site.f)) => { - let slots = bound.as_mut_ptr(); + let slots = bound.as_mut_ptr().cast::(); slots.write((&raw const bm.receiver).read()); std::ptr::copy_nonoverlapping(base.add(start + 2), slots.add(1), site.argc); Some(std::slice::from_raw_parts( @@ -13445,6 +19235,20 @@ unsafe fn call_leaf_in_place( site.argc + 1, )) } + // An instance whose class's native `__call__` is the builtin + // (`key(elem)` of an `itemgetter(1)`): the instance first, as + // the call's rewrite in `h_call` would pass it. + (Object::Instance(inst), Object::Unbound) + if site.argc < bound.len() && Interpreter::instance_calls_native(inst, site.f) => + { + let slots = bound.as_mut_ptr().cast::(); + slots.write(base.add(start).read()); + std::ptr::copy_nonoverlapping(base.add(start + 2), slots.add(1), site.argc); + Some(std::slice::from_raw_parts( + slots.cast_const(), + site.argc + 1, + )) + } _ => None, }; if (hit || bound_args.is_some()) && !s.sw.is_null() { @@ -13469,8 +19273,21 @@ unsafe fn call_leaf_in_place( }) }; let r = match site.kind { - Some(LeafKind::Fast(f)) => f(args), - Some(LeafKind::Len) => len_fast(args), + // (`next(it)` of a Python iterator class's instance, as + // `FOR_ITER` steps it.) + Some(LeafKind::Fast(f)) => f(args).or_else(|| { + if b.name == "next" { + (*s.interp).leaf_next_instance(args) + } else { + None + } + }), + // (An instance's frameless `__len__`, as the full call's + // leaf half would find it.) + Some(LeafKind::Len) => len_fast(args).or_else(|| match args { + [Object::Instance(_)] => (*s.interp).leaf_instance_len(&args[0]).map(Ok), + _ => None, + }), Some(LeafKind::Isinstance) => Interpreter::core_isinstance(args), Some(LeafKind::Opaque) => body(), Some(LeafKind::Scalar) => { @@ -13486,6 +19303,26 @@ unsafe fn call_leaf_in_place( Some(k) => (*s.interp).leaf_builtin_call(k, b, args), None => None, }; + // `mc(obj)` of an `operator.methodcaller` whose method is a + // Python function (see `methodcaller_direct`). + if r.is_none() && site.direct != 0 && !hit && b.name == METHODCALLER_CALL { + return methodcaller_direct(s, site, pc as usize, start, lenu); + } + if r.is_none() && site.direct != 0 && hit && site.argc != 1 { + return attr_probe_call(s, site, pc as usize, start, lenu); + } + if r.is_none() && site.direct != 0 && hit && bound_args.is_none() { + let which = match site.kind { + Some(LeafKind::Len) => OneArgDunder::Len, + _ if b.name == "abs" => OneArgDunder::Abs, + _ if b.name == "iter" => OneArgDunder::Iter, + _ if b.name == "format" => OneArgDunder::Format, + _ if b.name == "hash" => OneArgDunder::Hash, + _ if b.name == "next" => OneArgDunder::Next, + _ => OneArgDunder::Repr, + }; + return len_call(s, site, pc as usize, start, lenu, which); + } match r { None => {} Some(Ok(v)) => { @@ -13504,7 +19341,442 @@ unsafe fn call_leaf_in_place( } } } - None + None + } +} + +/// The builtins [`len_call`] calls an instance's Python dunder for. +#[derive(Clone, Copy, PartialEq, Eq)] +enum OneArgDunder { + Len, + Repr, + Abs, + Iter, + /// `format(obj)` of a class that keeps `object.__format__`, which is + /// `str(obj)`. + Format, + /// `hash(obj)`, whose result `Interpreter::normalize_hash_result` + /// settles. + Hash, + /// `next(obj)` with no default, whose `__next__` no leaf step took + /// (one that raises, say): the exception leaves the method as any + /// direct callee's does. + Next, +} + +/// [`call_leaf_in_place`]'s `len(obj)` (`repr(obj)`, `abs(obj)`, +/// `iter(obj)`, `format(obj)`, `hash(obj)` as `which` says; the `CALL` at +/// `pc`, the builtin at `start` on a `lenu`-deep stack) of an instance +/// whose class's `__len__` (`__repr__`, `__abs__`, `__iter__`, the +/// `__str__` that `object.__format__` calls, or `__hash__`) is a Python +/// function: the method called directly ([`direct_call`]) on the instance, +/// the builtin's slot taking the method, and its result taken as the +/// builtin takes it ([`crate::coerce_len_result`], [`crate::repr_result`], +/// [`crate::iter_result_check`], [`crate::str_result`], +/// [`Interpreter::normalize_hash_result`], or as it is). As +/// [`call_leaf_in_place`]'s, `Some(RELOAD)` too (the core loop takes a +/// result it settles as the builtin does: see `records::MethodOp::Len` +/// and `records::MethodOp::Repr`). +/// +/// # Safety +/// +/// As [`call_leaf_in_place`]'s, with a non-null switch and the site's +/// direct-call cache. +#[inline(never)] +unsafe fn len_call( + s: &mut State, + site: &BuiltinSite, + pc: usize, + start: usize, + lenu: usize, + which: OneArgDunder, +) -> Option { + // SAFETY: the caller's contract. + unsafe { + let at = s.stack.add(start); + if lenu != start + 3 || !matches!(&*at.add(1), Object::Unbound) { + return None; + } + let Object::Instance(inst) = &*at.add(2) else { + return None; + }; + if which == OneArgDunder::Repr { + if let Some(v) = Interpreter::native_text(inst, true) { + return Some(text_in_place(s, pc, start, v)); + } + } + // (`hash()`'s native answers first, as `do_hash_call` takes them.) + if which == OneArgDunder::Hash { + if crate::stdlib::decimal_native::is_decimal_instance(inst) { + return None; + } + if let Some(h) = Interpreter::enum_hash(inst) { + return Some(text_in_place(s, pc, start, Object::Int(h))); + } + } + let interp = s.interp.cast_mut(); + // (Each result as its builtin takes it.) + let settle = |v: Object| match which { + OneArgDunder::Repr => crate::repr_result(v), + OneArgDunder::Len => crate::coerce_len_result(v).map(Object::Int), + OneArgDunder::Abs | OneArgDunder::Next => Ok(v), + OneArgDunder::Iter => crate::iter_result_check(&v).map(|()| v), + OneArgDunder::Format => crate::str_result(v), + OneArgDunder::Hash => (*interp).normalize_hash_result(v), + }; + let dunder = |key: u32, name: &str| { + Interpreter::instance_dunder_function(inst, crate::types::AttrKey::vm(key), name) + }; + let f = match which { + OneArgDunder::Repr => dunder(crate::types::vm_key::REPR_FN, "__repr__"), + OneArgDunder::Len => dunder(crate::types::vm_key::LEN_FN, "__len__"), + OneArgDunder::Abs => dunder(crate::types::vm_key::ABS_FN, "__abs__"), + OneArgDunder::Iter => dunder(crate::types::vm_key::ITER_FN, "__iter__"), + OneArgDunder::Format => Interpreter::instance_format_str_function(inst), + OneArgDunder::Hash => dunder(crate::types::vm_key::HASH, "__hash__"), + OneArgDunder::Next => dunder(crate::types::vm_key::NEXT_FN, "__next__"), + }?; + { + // SAFETY: GIL-serialized raw read of the function's code cell. + let fc = &*f.code.as_ptr(); + if fc.arg_count != 1 + || fc.kwonly_count != 0 + || fc.has_varargs + || fc.has_varkeywords + || fc.is_generator + || fc.is_coroutine + || fc.is_async_generator + { + return None; + } + // A warm pure leaf evaluates in place (see `str_call`; a + // `__next__` already declined its step). + if which != OneArgDunder::Next + && crate::code_is_pure_leaf(fc) + && crate::pure_leaf_warm(fc) + { + let depth = crate::recursion::current_depth(); + if depth >= crate::recursion::recursion_limit() || !droppable(&*at.add(2)) { + return None; + } + let ptrs = [at.add(2).cast_const()]; + let v = (*s.interp).pure_leaf_call(fc, &f, &ptrs, false, depth)?; + return Some(match settle(v) { + Ok(v) => text_in_place(s, pc, start, v), + Err(e) => { + crate::release_operands(&*s.interp, at, 3); + s.len = start; + s.pc = pc + 1; + s.err = Some(e); + RAISED + } + }); + } + } + // `[len, NULL, obj]` becomes the method call `[f, obj]`. + let op = match which { + OneArgDunder::Repr => Some(records::MethodOp::Repr), + OneArgDunder::Len => Some(records::MethodOp::Len), + OneArgDunder::Abs | OneArgDunder::Next => None, + OneArgDunder::Iter => Some(records::MethodOp::Iter), + OneArgDunder::Format => Some(records::MethodOp::Str), + OneArgDunder::Hash => Some(records::MethodOp::Hash), + }; + let builtin = at.read(); + at.write(Object::Function(f)); + at.add(1).write(at.add(2).read()); + let dsite = &mut *(site.direct as *mut DirectSite); + match direct_call_out(s, pc, start, start + 2, dsite, op) { + None => { + let f = at.read(); + at.add(2).write(at.add(1).read()); + at.add(1).write(Object::Unbound); + at.write(builtin); + if let Object::Function(f) = &f { + let fc = f.code(); + if let Some(ext) = crate::code_vm_ext(&fc) { + ext.frame_jit + .warm_switched(&fc, ext, fc.varnames.len().max(1)); + } + } + drop(f); + None + } + Some(0) => { + drop(builtin); + match settle(at.read()) { + Ok(v) => { + at.write(v); + s.len = start + 1; + Some(0) + } + Err(e) => { + s.len = start; + s.pc = pc + 1; + s.err = Some(e); + Some(RAISED) + } + } + } + Some(r) => { + drop(builtin); + Some(r) + } + } + } +} + +/// [`call_leaf_in_place`]'s `hasattr(obj, name)` or `getattr(obj, name, +/// default)` (the `CALL` at `pc`, the builtin at `start` on a `lenu`-deep +/// stack) of an instance the default lookup certainly misses whose class's +/// `__getattr__` is a Python function: the hook called directly +/// ([`direct_call`]) as `[hook, obj, name]`, its result the probe's +/// (`True`, or the value), and an `AttributeError` it raises the probe's +/// miss (`False`, or the default) with nothing unwound for it where the +/// callee never registered (see `records::raise_unseen`). As +/// [`call_leaf_in_place`]'s, `Some(RELOAD)` too (the core loop settles the +/// activation: see `records::MethodOp::HasAttr`). +/// +/// # Safety +/// +/// As [`call_leaf_in_place`]'s, with a non-null switch and the site's +/// direct-call cache. +#[inline(never)] +unsafe fn attr_probe_call( + s: &mut State, + site: &BuiltinSite, + pc: usize, + start: usize, + lenu: usize, +) -> Option { + // SAFETY: the caller's contract. + unsafe { + let at = s.stack.add(start); + let argc = lenu - start - 2; + let probe = argc == 2; + if !matches!(&*at.add(1), Object::Unbound) { + return None; + } + let Object::Instance(inst) = &*at.add(2) else { + return None; + }; + let Object::Str(name) = &*at.add(3) else { + return None; + }; + if crate::object::exotic_str_keys_possible() + || !Interpreter::default_getattribute(inst.cls_raw()) + || !crate::default_lookup_misses(&*at.add(2), name, true) + { + return None; + } + let hook = Interpreter::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::GETATTR_FN), + "__getattr__", + )?; + { + // SAFETY: GIL-serialized raw read of the function's code cell. + let hc = &*hook.code.as_ptr(); + if hc.arg_count != 2 + || hc.kwonly_count != 0 + || hc.has_varargs + || hc.has_varkeywords + || hc.is_generator + || hc.is_coroutine + || hc.is_async_generator + { + return None; + } + } + // `[probe, NULL, obj, name(, default)]` becomes the method call + // `[hook, obj, name]`, the default held here. + let default = (!probe).then(|| at.add(4).read()); + let op = match &default { + None => records::MethodOp::HasAttr, + Some(d) => records::MethodOp::GetAttrOr(d), + }; + let builtin = at.read(); + at.write(Object::Function(hook)); + at.add(1).write(at.add(2).read()); + at.add(2).write(at.add(3).read()); + let dsite = &mut *(site.direct as *mut DirectSite); + // (The probe's answer for the hook's: `miss` its `AttributeError`.) + let answer = |miss: bool, v: Option, default: Option| match (miss, default) + { + (true, None) => Object::Bool(false), + (true, Some(d)) => d, + (false, None) => { + drop(v); + Object::Bool(true) + } + (false, Some(d)) => { + drop(d); + v.unwrap_or(Object::None) + } + }; + match direct_call_out(s, pc, start, start + 3, dsite, Some(op)) { + None => { + let f = at.read(); + at.add(3).write(at.add(2).read()); + at.add(2).write(at.add(1).read()); + at.add(1).write(Object::Unbound); + at.write(builtin); + if let Some(d) = default { + at.add(4).write(d); + } + if let Object::Function(f) = &f { + let fc = f.code(); + if let Some(ext) = crate::code_vm_ext(&fc) { + ext.frame_jit + .warm_switched(&fc, ext, fc.varnames.len().max(2)); + } + } + drop(f); + None + } + Some(0) => { + drop(builtin); + let v = at.read(); + let miss = matches!(v, Object::Unbound); + at.write(answer(miss, Some(v), default)); + s.len = start + 1; + Some(0) + } + Some(RAISED) + if s.err + .as_ref() + .is_some_and(|e| (*s.interp).is_attribute_error(e)) => + { + drop(builtin); + drop(s.err.take()); + at.write(answer(true, None, default)); + s.len = start + 1; + Some(0) + } + Some(r) => { + drop(builtin); + drop(default); + Some(r) + } + } + } +} + +/// The name of `operator.methodcaller`'s native `__call__` (see +/// `stdlib::operator_accel`). +const METHODCALLER_CALL: &str = ".methodcaller.__call__"; + +/// [`call_leaf_in_place`]'s `mc(obj)` (the `CALL` at `pc`, the +/// methodcaller at `start` on a `lenu`-deep stack) of an +/// `operator.methodcaller` whose stored method name names a Python function +/// of `obj`'s plain class, with at most two stored positional arguments and +/// no keywords: the function called directly ([`direct_call`]) with `obj` +/// and those arguments laid over the call's slots, as `obj.name(*args)` +/// calls it. As [`call_leaf_in_place`]'s, `Some(RELOAD)` too. +/// +/// # Safety +/// +/// As [`len_call`]'s (two slots free above the call's). +#[inline(never)] +unsafe fn methodcaller_direct( + s: &mut State, + site: &BuiltinSite, + pc: usize, + start: usize, + lenu: usize, +) -> Option { + // SAFETY: the caller's contract. + unsafe { + let at = s.stack.add(start); + if lenu != start + 3 || !matches!(&*at.add(1), Object::Unbound) { + return None; + } + let Object::Instance(mc) = &*at else { + return None; + }; + if !Interpreter::instance_calls_native(mc, site.f) { + return None; + } + let (f, stored) = crate::stdlib::operator_accel::methodcaller_target(mc, &*at.add(2))?; + let Object::Tuple(stored) = &stored else { + return None; + }; + let k = stored.len(); + { + // SAFETY: GIL-serialized raw read of the function's code cell. + let fc = &*f.code.as_ptr(); + if k > 2 + || fc.arg_count as usize != k + 1 + || fc.kwonly_count != 0 + || fc.has_varargs + || fc.has_varkeywords + || fc.is_generator + || fc.is_coroutine + || fc.is_async_generator + { + return None; + } + } + // `[mc, NULL, obj]` becomes the method call `[f, obj, *args]`. + let mcobj = at.read(); + at.write(Object::Function(f)); + at.add(1).write(at.add(2).read()); + for (j, a) in stored.iter().enumerate() { + at.add(2 + j).write(a.clone()); + } + let dsite = &mut *(site.direct as *mut DirectSite); + match direct_call_out(s, pc, start, start + 2 + k, dsite, None) { + None => { + for j in (0..k).rev() { + crate::drop_hot_at(at.add(2 + j)); + } + let f = at.read(); + at.add(2).write(at.add(1).read()); + at.add(1).write(Object::Unbound); + at.write(mcobj); + if let Object::Function(f) = &f { + let fc = f.code(); + if let Some(ext) = crate::code_vm_ext(&fc) { + ext.frame_jit + .warm_switched(&fc, ext, fc.varnames.len().max(1)); + } + } + drop(f); + None + } + Some(0) => { + drop(mcobj); + s.len = start + 1; + Some(0) + } + Some(r) => { + drop(mcobj); + Some(r) + } + } + } +} + +/// [`len_call`]'s and [`str_call`]'s result `v`, a text the builtin finds +/// natively (see [`Interpreter::native_text`]) or a pure leaf's checked +/// result: the call's three operands from `start` released and `v` in +/// their place. +/// +/// # Safety +/// +/// As [`len_call`]'s. +unsafe fn text_in_place(s: &mut State, pc: usize, start: usize, v: Object) -> u32 { + // SAFETY: the caller's contract. + unsafe { + let at = s.stack.add(start); + crate::release_operands(&*s.interp, at, 3); + at.write(v); + s.len = start + 1; + // A dying argument's finalizer runs before the next instruction. + if (*s.maybe_dead).get() { + return left_marked(s, pc as u32, start + 1); + } + 0 } } @@ -13513,6 +19785,10 @@ unsafe fn call_leaf_in_place( pub(crate) struct TypeSite { cls: Rc, argc: usize, + /// The address of the site's direct-call cache, for `str(obj)` of an + /// instance whose class's `__str__` is a Python function (see + /// [`str_call`]); `0` none. + direct: usize, } /// [`h_call`] at a site settled on a builtin type `site` names: the callee @@ -13550,13 +19826,161 @@ unsafe extern "C" fn h_call_type( crate::release_operands(interp, base.add(start), lenu - start); base.add(start).write(v); s.len = start + 1; + // A dying argument's finalizer runs before the next + // instruction, as after the full call (`bool(Dying())`). + if (*s.maybe_dead).get() { + return left_marked(st, pc as u32, start + 1); + } return 0; } + // `str(obj)` through a Python `__str__` (see `str_call`). + if site.direct != 0 { + if let Some(r) = + str_call(s, site.direct as *mut DirectSite, pc as usize, start, lenu) + { + return r; + } + } + // `list(it)`, `tuple(it)`, `set(it)` ... of anything else + // (`list(map(f, xs))`): straight to the core loop's lane. + if site.argc == 1 && Interpreter::core_type_lane_class(&site.cls) { + if let Some(r) = type_lane_direct(st, pc, lenu, start) { + return r; + } + } } h_call(st, code, ext, pc, len) } } +/// [`h_call_type`]'s `str(obj)` (the `CALL` at `pc`, `str` at `start` on a +/// `lenu`-deep stack) of an instance whose class's `__str__` is a Python +/// function: the method called directly ([`direct_call`]) on the instance, +/// the type's slot taking the method, and its result taken as `str()` +/// takes it ([`crate::str_result`]). `Some(0)` the string in place, +/// `Some(RAISED)` or `Some(RELOAD)` as [`h_call`]'s (the core loop settles +/// a result it finishes: see `records::MethodOp::Str`), `None` declined +/// untouched. +/// +/// # Safety +/// +/// As [`h_call_type`]'s, with the site's direct-call cache. +#[inline(never)] +unsafe fn str_call( + s: &mut State, + dsite: *mut DirectSite, + pc: usize, + start: usize, + lenu: usize, +) -> Option { + // SAFETY: the caller's contract. + unsafe { + if s.sw.is_null() { + return None; + } + let at = s.stack.add(start); + if lenu != start + 3 || !matches!(&*at.add(1), Object::Unbound) { + return None; + } + let Object::Instance(inst) = &*at.add(2) else { + return None; + }; + // (An exception that keeps `BaseException.__str__`: its text, on + // one remembered verdict.) + if inst.cls_raw().flags.is_exception { + if let Some(v) = Interpreter::exc_str_leaf(inst) { + return Some(text_in_place(s, pc, start, v)); + } + } + // (A `str` subclass that keeps `str`'s own `__str__`: its payload, + // on one remembered verdict, ahead of the kinds below.) + if let Some(v) = + Interpreter::str_payload(inst).or_else(|| Interpreter::native_text(inst, false)) + { + return Some(text_in_place(s, pc, start, v)); + } + // (Or the `__repr__` that `object.__str__` calls.) + let f = Interpreter::instance_str_function(inst)?; + { + // SAFETY: GIL-serialized raw read of the function's code cell. + let fc = &*f.code.as_ptr(); + if fc.arg_count != 1 + || fc.kwonly_count != 0 + || fc.has_varargs + || fc.has_varkeywords + || fc.is_generator + || fc.is_coroutine + || fc.is_async_generator + { + return None; + } + // A warm pure leaf evaluates in place, as `dunder_call` runs + // one (the type call's frameless path asks for the method and + // the leaf again, about 200 instructions more). + if crate::code_is_pure_leaf(fc) && crate::pure_leaf_warm(fc) { + let depth = crate::recursion::current_depth(); + if depth >= crate::recursion::recursion_limit() || !droppable(&*at.add(2)) { + return None; + } + let ptrs = [at.add(2).cast_const()]; + let v = (*s.interp).pure_leaf_call(fc, &f, &ptrs, false, depth)?; + return Some(match crate::str_result(v) { + Ok(v) => text_in_place(s, pc, start, v), + Err(e) => { + crate::release_operands(&*s.interp, at, 3); + s.len = start; + s.pc = pc + 1; + s.err = Some(e); + RAISED + } + }); + } + } + // `[str, NULL, obj]` becomes the method call `[f, obj]`. + let ty = at.read(); + at.write(Object::Function(f)); + at.add(1).write(at.add(2).read()); + let dsite = &mut *dsite; + match direct_call_out(s, pc, start, start + 2, dsite, Some(records::MethodOp::Str)) { + None => { + let f = at.read(); + at.add(2).write(at.add(1).read()); + at.add(1).write(Object::Unbound); + at.write(ty); + if let Object::Function(f) = &f { + let fc = f.code(); + if let Some(ext) = crate::code_vm_ext(&fc) { + ext.frame_jit + .warm_switched(&fc, ext, fc.varnames.len().max(1)); + } + } + drop(f); + None + } + Some(0) => { + drop(ty); + match crate::str_result(at.read()) { + Ok(v) => { + at.write(v); + s.len = start + 1; + Some(0) + } + Err(e) => { + s.len = start; + s.pc = pc + 1; + s.err = Some(e); + Some(RAISED) + } + } + } + Some(r) => { + drop(ty); + Some(r) + } + } + } +} + /// [`h_call`] at a site settled on a builtin whose body the core loop's /// lane runs (see `Interpreter::core_native_body`), named by `site`: the /// callee checked to be that builtin by its address (a method with its @@ -13583,10 +20007,91 @@ unsafe extern "C" fn h_call_native( let (pcu, lenu) = (pc as usize, len as usize); let start = lenu - site.argc - 2; let base = s.stack; + // `mc(obj)` of an `operator.methodcaller` whose method is a Python + // function (see `methodcaller_direct`). + if site.direct != 0 && !s.sw.is_null() { + if let Some(r) = methodcaller_direct(s, site, pcu, start, lenu) { + return r; + } + } + // An instance whose class's native `__call__` is the builtin and + // takes it first (a `methodcaller` whose leaf half declined): the + // call rewritten as `h_call` rewrites it, the instance in the self + // slot as the body's first argument. + let mut rewritten = false; + if let (Object::Instance(inst), Object::Unbound) = + (&*base.add(start), &*base.add(start + 1)) + { + if !(*site.f).binds_instance && Interpreter::instance_calls_native(inst, site.f) { + Interpreter::core_instance_callee(base.add(start)); + rewritten = true; + } + } + // A `functools.partial` of the site's builtin (`partial(operator.add, + // 3)`, whose unwrapped call the core loop settled the site on): its + // function and stored argument in place, as `h_call` unwraps it + // first, the argument in the self slot. + // Its fast half settled at the site (`operator.add`'s) runs on the + // stored argument and the call's; a decline goes on to `h_call` + // with the call unwrapped, as `h_call` would leave it. + if !rewritten && !s.sw.is_null() { + if let (Object::Instance(inst), Object::Unbound) = + (&*base.add(start), &*base.add(start + 1)) + { + if !(*site.f).binds_instance && Interpreter::instance_calls_partial(inst) { + // (`core_instance_callee`'s unwrap: the instance leaves + // by a plain decrement, something else holding it.) + if Rc::strong_count(inst) > 1 { + if let Some((func, first)) = + crate::stdlib::functools_mod::partial_inline(inst) + { + drop(base.add(start).read()); + base.add(start).write(func); + base.add(start + 1).write(first); + } + } + if let Object::Builtin(b) = &*base.add(start) { + let args = + std::slice::from_raw_parts(base.add(start + 1), lenu - start - 1); + let kind = (*ext).method_slot(pcu).and_then(|m| m.get_leaf(b)); + if let (true, Some(crate::LeafKind::Fast(fast))) = + (std::ptr::eq(Rc::as_ptr(b), site.f), kind) + { + if Rc::strong_count(b) > 1 + && Rc::strong_count(b) > 1 + && !matches!(args[0], Object::Unbound) + && Interpreter::core_all_droppable(args) + { + match fast(args) { + None => {} + Some(Ok(v)) => { + crate::release_run(base.add(start), lenu - start); + base.add(start).write(v); + s.len = start + 1; + return 0; + } + Some(Err(e)) => { + crate::release_run(base.add(start), lenu - start); + s.len = start; + s.pc = pcu + 1; + s.err = Some(e); + return RAISED; + } + } + } + } + } + return h_call(st, code, ext, pc, len); + } + } + } let hit = match (&*base.add(start), &*base.add(start + 1)) { (Object::Builtin(b), Object::Unbound) => { std::ptr::eq(Rc::as_ptr(b), site.f) && !b.binds_instance } + (Object::Builtin(b), Object::Instance(_)) if rewritten => { + std::ptr::eq(Rc::as_ptr(b), site.f) + } (Object::Builtin(b), recv) => { std::ptr::eq(Rc::as_ptr(b), site.f) && crate::lane_recv_ok(b, recv, site.via_call) } @@ -13605,6 +20110,30 @@ unsafe extern "C" fn h_call_native( if !hit || s.sw.is_null() { return h_call(st, code, ext, pc, len); } + // `super().__init__(message)` of an exception, `BaseException`'s: + // its `args` (and a `StopIteration`'s `value`) stored in place. + if crate::builtin_types::is_exc_init(site.f) { + if let Object::Instance(_) = &*base.add(start + 1) { + let ops = std::slice::from_raw_parts(base.add(start), lenu - start); + if Interpreter::core_all_droppable(ops) { + match crate::builtin_types::exc_init(&ops[1..]) { + Ok(v) => { + crate::release_run(base.add(start), lenu - start); + base.add(start).write(v); + s.len = start + 1; + return 0; + } + Err(e) => { + crate::release_run(base.add(start), lenu - start); + s.len = start; + s.pc = pcu + 1; + s.err = Some(e); + return RAISED; + } + } + } + } + } // `x.__reduce_ex__(proto)` of a plain instance (`copy`'s, // `pickle`'s): the default reduction, in place. if site.argc == 1 && (*site.f).name == ".object_reduce_ex" { @@ -13652,9 +20181,11 @@ unsafe fn native_body_here( frame.stack.set_len(lenu); // A lazily running activation stays so unless something looks while // the body runs, which a body that runs no Python code rarely makes - // happen. (Other threads can look without settling it: it registers - // first once there are any.) - let lazy = !s.lazy.is_null() && !crate::sync::rc_shared_flag().load(Ordering::Relaxed); + // happen. (Another thread looks only once this one releases the + // GIL, which settles it first, see `gil::before_gil_release`; a + // watchdog that reads frames without the GIL makes it register + // first.) + let lazy = !s.lazy.is_null() && !crate::sync::cells_unguarded(); if !lazy { settle(s); *(*s.sw).last = s.last; @@ -13748,11 +20279,43 @@ unsafe fn leaf_call_lane(st: &mut State, pc: usize, start: usize, len: usize) -> if !interp.core_leaf_call_lane(sw) { return CALL_DECLINED; } + lane_outcome(st, pc, start) + } +} + +/// How compiled code goes on after a core-loop lane ran the `CALL` at `pc` +/// (its operands from `start`): `0` the result in place at `start` (see +/// [`finished_in_place`]); `RAISED` for an exception the lane raised in +/// place, the operands gone, which the code's own handler takes (see +/// [`h_catch`]), as a native body's raise is; `RELOAD` for anything else. +/// +/// # Safety +/// +/// As [`finished_in_place`]'s. +unsafe fn lane_outcome(st: &mut State, pc: usize, start: usize) -> u32 { + // SAFETY: the caller's contract. + unsafe { if finished_in_place(st, start) { - 0 - } else { - RELOAD + return 0; + } + let sw = &mut *st.sw; + if std::ptr::eq(sw.cur, st.frame) + && crate::hot_gates::loop_gen() == st.snap_gen + && !(*st.maybe_dead).get() + && (*st.frame).stack.len() == start + { + if let Some(crate::CoreExit::Stop(crate::LeafStop::Raised(_))) = &sw.pending { + let Some(crate::CoreExit::Stop(crate::LeafStop::Raised(e))) = sw.pending.take() + else { + unreachable!("matched above") + }; + st.len = start; + st.pc = pc + 1; + st.err = Some(e); + return RAISED; + } } + RELOAD } } @@ -13970,6 +20533,16 @@ unsafe extern "C" fn h_call_kw(st: *mut State, code: *const CodeObject, pc: u64, } } Interpreter::core_instance_callee(base.add(start)); + // A pure constructor's parameters named (`deque(xs, maxlen=5)`). + if matches!(&*base.add(start), Object::Type(ty) if ty.pure_new_kw.get().is_some()) { + let ops = std::slice::from_raw_parts(base.add(start), len - start); + if let Some(r) = Interpreter::core_pure_new_kw(ops, argc) { + crate::release_run(base.add(start), len - start); + base.add(start).write(r); + st.len = start + 1; + return 0; + } + } // A plain class whose `__init__` has native code: the instance made // and the `__init__` entered directly, its keywords bound. if matches!(&*base.add(start), Object::Type(ty) if ty.native_kind.get() == 0) @@ -13982,7 +20555,8 @@ unsafe extern "C" fn h_call_kw(st: *mut State, code: *const CodeObject, pc: u64, let ops = std::slice::from_raw_parts(base.add(start), len - start); let interp = &*st.interp; let r = match &ops[0] { - Object::Type(ty) if ty.native_kind.get() != 0 => { + // (A natively served class, or an exact `itertools` one.) + Object::Type(ty) if ty.native_kind.get() != 0 || ty.lazy_ctor.get() != 0 => { Interpreter::core_native_ctor_kw(ops, argc, true) } Object::Builtin(_) @@ -13991,8 +20565,54 @@ unsafe extern "C" fn h_call_kw(st: *mut State, code: *const CodeObject, pc: u64, { Interpreter::core_native_method_kw(ops, argc) } + // (A `functools.partial`'s own `__call__` over a pure leaf + // first: see `Interpreter::partial_leaf_kw`.) + Object::Builtin(b) + if matches!(&ops[1], Object::Instance(_)) + && crate::stdlib::functools_mod::is_partial_call(b) => + { + interp + .partial_leaf_kw(ops, argc) + .or_else(|| Interpreter::core_native_kw_call(ops, argc)) + } + // (`s.replace(a, b, count=1)`: keywords naming the next + // parameters in order make the positional call, run as `CALL`'s + // leaf lane runs it, ahead of any registered keyword half; see + // `Interpreter::core_method_kw_positional`.) + Object::Builtin(b) if crate::builtin_method_kw_params(&ops[1], b.name).is_some() => { + interp + .core_method_kw_positional(ops, argc) + .or_else(|| Interpreter::core_native_kw_call(ops, argc)) + } Object::BoundMethod(_) | Object::Builtin(_) => { Interpreter::core_native_kw_call(ops, argc) + .or_else(|| Interpreter::core_dict_update_kw(ops, argc)) + } + // `dict(k=v, ...)`, `dict(d, k=v, ...)`: the keywords' own names + // are the keys, as the core loop's arm builds it. + Object::Type(ty) + if argc <= 1 && Rc::ptr_eq(ty, &crate::builtin_types::builtin_types().dict_) => + { + Interpreter::core_dict_kw(ops) + } + Object::Type(ty) + if argc == 0 + && Rc::ptr_eq(ty, &crate::builtin_types::builtin_types().simple_namespace_) => + { + Interpreter::core_namespace_kw(ops) + } + // `int(text, base=16)`, `enumerate(xs, start=1)`: keywords that + // name the next positional parameters in order, so the operands + // below the names are the positional call's. + Object::Type(ty) if crate::builtin_kw_positional(ty, argc, &ops[len - start - 1]) => { + interp.core_builtin_ctor(base, start, len - 1) + } + // `zip(xs, ys, strict=True)`, `map(f, xs, strict=True)`. + Object::Type(ty) + if Rc::ptr_eq(ty, &crate::builtin_types::builtin_types().zip_) + || Rc::ptr_eq(ty, &crate::builtin_types::builtin_types().map_) => + { + Interpreter::seq_new_strict_kw(ops, argc) } _ if st.depth_cell.is_null() => None, _ => interp.core_pure_kw_call(code, pc, ops, argc, st.depth_cell), @@ -14002,7 +20622,10 @@ unsafe extern "C" fn h_call_kw(st: *mut State, code: *const CodeObject, pc: u64, // (`sorted` with a `key=` lambda, `xs.sort(key=f)`, // `enumerate(xs, start=1)`): the core loop's lane for it, the // activation published, the result in place. - if Interpreter::kw_lane_callee(&ops[0], &ops[1]) && !st.sw.is_null() { + if (Interpreter::kw_lane_callee(&ops[0], &ops[1]) + || interp.native_ctor_kw_callee(&ops[0], &ops[1])) + && !st.sw.is_null() + { let frame = &mut *st.frame; frame.stack.set_len(len); frame.pc = pc as u32; @@ -14131,7 +20754,16 @@ unsafe fn spread_ctor(st: &mut State, pc: usize, start: usize) -> Option { let Object::Type(ty) = &*base.add(start) else { return None; }; - ty.instance_plan.peek().and_then(Option::as_ref)?; + // (A natively served class's constructor, as `h_call` runs a + // `CALL`'s: `datetime(*args)` in `_strptime`, which took the core + // loop's lane and registered its callers.) + let native = !ty.flags.is_builtin + && (ty.native_kind.get() != 0 + || ty.pure_new.get().is_some() + || ty.lazy_ctor.get() != 0); + if !native { + ty.instance_plan.peek().and_then(Option::as_ref)?; + } let n = match &*base.add(start + 2) { Object::Tuple(t) => t.len(), Object::List(l) => l.try_borrow().ok()?.len(), @@ -14150,6 +20782,24 @@ unsafe fn spread_ctor(st: &mut State, pc: usize, start: usize) -> Option { for (k, v) in items.iter().enumerate() { base.add(start + 2 + k).write(crate::clone_hot(v)); } + if native { + let ops = std::slice::from_raw_parts(base.add(start), len - start); + if let Some(v) = Interpreter::core_native_ctor_kw(ops, n, false) { + crate::release_run(base.add(start), len - start); + base.add(start).write(v); + st.len = start + 1; + drop(spread); + return Some(0); + } + if ty.instance_plan.peek().and_then(Option::as_ref).is_none() { + for k in 0..n { + drop(base.add(start + 2 + k).read()); + } + base.add(start + 2).write(spread); + base.add(start + 3).write(Object::Unbound); + return None; + } + } match records::ctor_direct(st, records::CallAt::new(pc, start, n, None), len) { Some(r) => { drop(spread); @@ -14315,12 +20965,58 @@ unsafe fn spread_on_frame(st: &mut State, pc: usize, start: usize) -> Option Option { + // SAFETY: the caller's contract. + unsafe { + let ops = std::slice::from_raw_parts(st.stack.add(start), 4); + let (Object::Instance(inst), Object::Unbound, Object::Tuple(args)) = + (&ops[0], &ops[1], &ops[2]) + else { + return None; + }; + if !Interpreter::core_all_droppable(ops) { + return None; + } + let v = crate::stdlib::functools_mod::lru_hit_if_wrapper(inst, args)?; + crate::release_run(st.stack.add(start), 4); + st.stack.add(start).write(v); + st.len = start + 1; + Some(0) + } +} + unsafe fn spread_native(st: &mut State, pc: usize, start: usize) -> Option { use crate::LeafKind; // SAFETY: the caller's contract: four initialized operand slots, and // room up to `st.cap`. unsafe { let base = st.stack; + // A builtin type whose native constructor builds the value from + // the items with no code run (`zip(*rows)`, `tuple(*a)`), as the + // `CALL` arm builds it. + if let (Object::Type(t), Object::Unbound) = (&*base.add(start), &*base.add(start + 1)) { + match &*base.add(start + 3) { + Object::Unbound => {} + Object::Dict(d) if d.try_borrow().is_ok_and(|d| d.is_empty()) => {} + _ => return None, + } + let v = match &*base.add(start + 2) { + Object::Tuple(items) => crate::seqiter::builtin_ctor_pure(t, items)?, + Object::List(l) => crate::seqiter::builtin_ctor_pure(t, &l.try_borrow().ok()?)?, + _ => return None, + }; + crate::release_run(base.add(start), 4); + base.add(start).write(v); + st.len = start + 1; + return Some(0); + } let (b, recv) = match (&*base.add(start), &*base.add(start + 1)) { (Object::Builtin(b), Object::Unbound) if !b.binds_instance => (b, None), (Object::BoundMethod(bm), Object::Unbound) if !bm.redispatch_descriptor => { @@ -14466,6 +21162,12 @@ unsafe extern "C" fn h_call_ex( return CALL_DECLINED; } let start = len - 4; + // A warm leaf function's call over a tuple that fills its + // parameters (`fn(*args)` in a decorator's forwarder): evaluated in + // place. + if let Some(r) = spread_leaf(st, start) { + return r; + } // A plain function's call over a tuple or list: a direct call. if let Some(r) = spread_direct(st, pc, start, &mut *site) { return r; @@ -14486,6 +21188,61 @@ unsafe extern "C" fn h_call_ex( } } +/// [`h_call_ex`]'s call of a plain function (or a method bound to one) +/// over an exact tuple, with no keywords, that is a warm leaf the items +/// fill exactly (see `Interpreter::leaf_call_spread`): `0` the result in +/// the callee's slot, the operands released; `None` touched nothing. +/// +/// # Safety +/// +/// As [`h_call_ex`]'s, with the four operands from `start`. +#[inline(never)] +unsafe fn spread_leaf(st: &mut State, start: usize) -> Option { + // SAFETY: the caller's contract. + unsafe { + let base = st.stack; + let (Object::Unbound, Object::Tuple(items), kw) = ( + &*base.add(start + 1), + &*base.add(start + 2), + &*base.add(start + 3), + ) else { + return None; + }; + match kw { + Object::Unbound => {} + Object::Dict(d) if d.peek().is_some_and(|d| d.is_empty()) => {} + _ => return None, + } + let (f, head): (&crate::object::PyFunction, &[Object]) = match &*base.add(start) { + Object::Function(f) => (f, &[]), + Object::BoundMethod(bm) if !bm.redispatch_descriptor => match &bm.function { + Object::Function(f) => (f, std::slice::from_ref(&bm.receiver)), + _ => return None, + }, + _ => return None, + }; + let r = (*st.interp).leaf_call_spread(f, head, items)?; + let shared = crate::shared_value::ThinArc::strong_count(items) > 1; + // A tuple another owner keeps (`f(*args)` of a local) frees nothing + // as it leaves: the plain run release. + if shared && matches!(kw, Object::Unbound) { + crate::release_run(base.add(start), 4); + base.add(start).write(r); + st.len = start + 1; + return Some(0); + } + // Otherwise the operands leave last first, as the full call releases + // them (a tuple only they held lets its items go last first too). + let operands: [Object; 4] = base.add(start).cast::<[Object; 4]>().read(); + base.add(start).write(r); + st.len = start + 1; + for o in operands.into_iter().rev() { + (*st.interp).release_hot(o); + } + Some(0) + } +} + /// The rest of [`h_call_ex`] once neither a direct call nor a call on the /// frame alone took the `CALL_FUNCTION_EX` at `pc` (its operands from /// `start`, synced on the frame, `frame.pc` at it): the core loop's arm, @@ -14567,6 +21324,9 @@ unsafe extern "C" fn h_call_forward( }) { st.stack.add(len).write(Object::Unbound); + if let Some(r) = spread_lru_hit(st, start) { + return r; + } if let Some(r) = spread_direct(st, pc + 3, start, &mut *site) { return r; } @@ -14607,7 +21367,7 @@ unsafe extern "C" fn h_call_forward( *sw.last = st.last; let saved_last = sw.last; let interp = &mut *st.interp.cast_mut(); - if !interp.core_call_forward(sw, pc) { + if !interp.core_call_forward(sw, pc, st.snap_gen) { return if sw.pending.is_some() || stack_moved(st) { RELOAD } else { @@ -14688,6 +21448,9 @@ unsafe extern "C" fn h_await_iter(st: *mut State, at: *mut Object, kind: u64) -> .is_some_and(|s| matches!(s, crate::object::GeneratorState::Created(_))), // A `types.coroutine` generator is its own. Object::Generator(g) => g.code_ref().is_some_and(|c| c.is_iterable_coroutine), + // An async generator's `asend` / `athrow` / `aclose` + // awaitable is its own too. + Object::AsyncGenAwait(_) => true, _ => false, } } else { @@ -14701,6 +21464,24 @@ unsafe extern "C" fn h_await_iter(st: *mut State, at: *mut Object, kind: u64) -> if ok { return 0; } + // `yield from xs` of a builtin container: its iterator, in place + // (an iterator is its own). + if kind == 1 + && matches!( + top, + Object::List(_) + | Object::Tuple(_) + | Object::Range(_) + | Object::Str(_) + | Object::Iter(_) + ) + && Interpreter::core_droppable(top) + { + if let Some(Ok(it)) = crate::seqiter::iter_fast(std::slice::from_ref(top)) { + crate::drop_hot(std::mem::replace(&mut *at, it)); + return 0; + } + } if matches!(top, Object::Instance(_)) && Interpreter::core_droppable(top) { let name = if kind == 0 { "__await__" } else { "__iter__" }; if let Some(gen) = (*st.interp).instance_gen_call(top, name) { @@ -14725,12 +21506,102 @@ const SEND_YIELDED: u32 = 2; /// `END_SEND` (`0`), or a fast step's yield ([`SEND_YIELDED`]); anything /// else (another delegate, or a generator's fast step, which never /// switches) declined untouched. +/// The most `yield from` items [`h_send`] folds into a draining +/// consumer's sink in one call. +const SEND_FOLD_RUN: u32 = 256; + +/// The sink of the draining consumer driving `st`'s frame, where its +/// yields fold (see [`h_gen_yield`]). +/// +/// The frame must be the switch's running one *and* this code's own: a +/// generator resumed lazily from the drained one (`for x in inner` in its +/// body) runs on the same switch before it registers, and its items +/// belong to that resume, not the consumer. +/// +/// # Safety +/// +/// `st` is the live state of compiled code. +#[inline] +unsafe fn send_fold_sink(st: &State) -> Option { + // SAFETY: the caller's contract. + unsafe { + if st.sw.is_null() || st.gen_lazy || !(*(*st.sw).inl).is_empty() { + return None; + } + let (ff, sink) = (*st.interp).sum_fold?; + (ff == (*st.sw).cur as usize && ff == st.frame as usize).then_some(sink) + } +} + unsafe extern "C" fn h_send(st: *mut State, pc: u64, len: u64) -> u32 { // SAFETY: the code passes its live state and its stack depth (the // delegate and the sent value on top). unsafe { let st = &mut *st; let len = len as usize; + // A list's or tuple's cursor (`yield from xs`) steps in place: its + // next item takes the sent `None`'s place for this code's + // `YIELD_VALUE`, and at its end the `None` stays as the result for + // the `END_SEND`, as CPython's `SEND` steps an iterator. + if len >= 2 { + if let (Object::Iter(rc), Object::None) = + (&*st.stack.add(len - 2), &*st.stack.add(len - 1)) + { + // (A draining consumer's sink, `sum(g)` say, where this + // frame's yields fold: up to `SEND_FOLD_RUN` items in a row + // fold into it here, as the `YIELD_VALUE` after this would + // fold each, with no yield and resume between them. The + // run is bounded so the resume's checkpoint still comes.) + let mut fold = send_fold_sink(st).map(|sink| (sink, SEND_FOLD_RUN)); + while let Some(cur) = rc.peek_mut() { + let Some(v) = cur.pure_next().or_else(|| { + let v = cur.pure_peek()?; + cur.pure_skip(); + Some(v) + }) else { + break; + }; + let mut v = std::mem::ManuallyDrop::new(v); + if let Some((sink, left @ 1..)) = &mut fold { + if sink.fold(std::ptr::from_mut(&mut *v)) { + *left -= 1; + continue; + } + } + st.stack + .add(len - 1) + .write(std::mem::ManuallyDrop::into_inner(v)); + st.len = len; + return SEND_YIELDED; + } + if let Some(cur) = rc.peek_mut() { + // A plain dict's entries (`yield from` a mapping whose + // `__iter__` is its dict's), or its end. + match cur.dict_step_quiet(true) { + Some(Some(v)) => { + st.stack.add(len - 1).write(v); + st.len = len; + return SEND_YIELDED; + } + Some(None) => { + st.len = len; + return 0; + } + None => {} + } + } + if crate::seqiter::cursor_at_end(&*st.stack.add(len - 2)) { + st.len = len; + return 0; + } + } + } + if len >= 2 + && !st.sw.is_null() + && matches!(&*st.stack.add(len - 2), Object::AsyncGenAwait(_)) + { + return send_agen_await(st, pc as usize, len); + } if st.sw.is_null() || len < 2 || !matches!( @@ -14784,6 +21655,129 @@ unsafe extern "C" fn h_send(st: *mut State, pc: u64, len: u64) -> u32 { } } +/// [`h_send`]'s status for an awaitable's drive that raised in place +/// ([`send_agen_await`]): `State::err`, the state past the `SEND`. +const SEND_RAISED: u32 = 3; + +/// [`h_send`] to an async generator's `asend` / `athrow` / `aclose` +/// awaitable below the sent value (`await anext(g)`, `await g.aclose()`): +/// the awaitable is driven from here (`Interpreter::core_agen_await`), the +/// frame synced as a native call's is (see [`native_body_here`]). Its +/// completion leaves the result in the sent value's place as the `SEND` +/// exits (`0`); a suspension on an inner `await` leaves the passed value +/// there for the code's own `YIELD_VALUE` ([`SEND_YIELDED`]); a raise is +/// the instruction's ([`SEND_RAISED`]); when the drive left the +/// activation's code, the frame is left as the core loop's `SEND` would +/// leave it (`RELOAD`). `1` declined, untouched. +/// +/// # Safety +/// +/// As [`h_send`]'s, with a non-null switch and the awaitable below the +/// sent value. +#[inline(never)] +unsafe fn send_agen_await(st: &mut State, pc: usize, len: usize) -> u32 { + use crate::AgenAwaitStep; + // SAFETY: the caller's contract. + unsafe { + if !(*st.sw).calls_ok + || crate::hot_gates::loop_gen() != st.snap_gen + || (*st.maybe_dead).get() + || crate::trace::any_observers_active() + { + return 1; + } + let base = st.stack; + let Object::AsyncGenAwait(a) = &*base.add(len - 2) else { + return 1; + }; + let a = a.clone(); + // The frame synced, as the core loop's arm syncs it: the sent + // value popped (it moves into the drive). + let sent = base.add(len - 1).read(); + let frame = &mut *st.frame; + frame.stack.set_len(len - 1); + let lazy = !st.lazy.is_null() && !crate::sync::cells_unguarded(); + if !lazy { + settle(st); + *(*st.sw).last = st.last; + } + let sw = &mut *st.sw; + let interp = &mut *st.interp.cast_mut(); + let r = interp.core_agen_await( + sw, + frame, + pc, + &a, + sent, + if lazy { + std::ptr::from_mut(st) + } else { + std::ptr::null_mut() + }, + ); + // (The stack's slot keeps the awaitable.) + drop(a); + let mut in_place = false; + if !st.lazy.is_null() { + in_place = sw.pending.is_none() && crate::hot_gates::loop_gen() == st.snap_gen; + if !in_place { + settle(st); + } + } + let sw = &mut *st.sw; + in_place = in_place + || (sw.pending.is_none() + && std::ptr::eq(sw.cur, st.frame) + && crate::hot_gates::loop_gen() == st.snap_gen); + if in_place { + return match r { + Ok(AgenAwaitStep::Passed(v)) => { + base.add(len - 1).write(v); + st.len = len; + SEND_YIELDED + } + Ok(AgenAwaitStep::Done(v)) => { + base.add(len - 1).write(v.unwrap_or(Object::None)); + st.len = len; + 0 + } + Err(e) => { + st.len = len - 1; + st.pc = pc + 1; + st.err = Some(e); + SEND_RAISED + } + }; + } + // The core loop goes on from the frame, left as its `SEND` leaves + // it. + let frame = &mut *st.frame; + match r { + Ok(AgenAwaitStep::Passed(v)) => { + base.add(len - 1).write(v); + frame.stack.set_len(len); + frame.pc = pc as u32 + 1; + } + Ok(AgenAwaitStep::Done(v)) => { + base.add(len - 1).write(v.unwrap_or(Object::None)); + frame.stack.set_len(len); + frame.pc = pc as u32 + 1 + frame.code.instructions[pc].arg; + } + Err(e) => { + frame.stack.set_len(len - 1); + frame.pc = pc as u32 + 1; + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Raised(e))); + return RELOAD; + } + } + *sw.last = pc; + if sw.pending.is_none() && (*sw.maybe_dead).get() { + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Marked)); + } + RELOAD + } +} + /// [`h_send`]'s lazy resume ([`lazy_gen_resume`]) of the generator or /// coroutine below the sent value: its yield takes the sent value's slot /// ([`SEND_YIELDED`]), or its return value does as the `SEND` exits @@ -14892,102 +21886,463 @@ unsafe fn h_send_step(st: &mut State, pc: u64, len: usize) -> Option { frame.pc = to as u32; *sw.last = pc as usize; sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Marked)); - return Some(RELOAD); + return Some(RELOAD); + } + st.len = len; + Some(if exit { 0 } else { SEND_YIELDED }) + } +} + +/// `YIELD_VALUE` in a generator's fast step whose draining consumer's +/// sink is `fold`: the value at `top` folded into the sink, the sent +/// `None` in its slot (`1`), or `0` for the step to hand it back. +unsafe extern "C" fn h_fold_yield(fold: *const crate::FoldSink, top: *mut Object) -> u32 { + // SAFETY: the step's sink, live while it runs, and the stack's top + // slot, initialized; a folded value moved out (or is a scalar). + unsafe { + if (*fold).fold(top) { + top.write(Object::None); + 1 + } else { + 0 + } + } +} + +/// `YIELD_VALUE` at `pc` of the running activation, an inline generator +/// resume (its stack `len` deep, the value on top), as the core loop's arm +/// runs it: the generator parks and its consumer, the value delivered, is +/// switched to (`RELOAD`); for a root activation, folded into its draining +/// consumer's sink ([`GEN_FOLDED`]); declined untouched for a generator's +/// fast step, any other root activation, or a yield the switch doesn't +/// take. +/// [`h_gen_yield`]'s status for a yield the draining consumer's sink took: +/// the body goes on, the sent `None` in the value's slot. +const GEN_FOLDED: u32 = 2; + +unsafe extern "C" fn h_gen_yield(st: *mut State, pc: u64, len: u64) -> u32 { + // SAFETY: the code passes its live state and its stack depth. + unsafe { + let st = &mut *st; + if st.sw.is_null() { + return 1; + } + if (*(*st.sw).inl).is_empty() { + // A draining consumer driving this frame: the yield folds into + // its sink, as the core loop's arm folds it. + if let Some((ff, sink)) = (*st.interp).sum_fold { + if ff == (*st.sw).cur as usize && len > 0 { + let top = st.stack.add(len as usize - 1); + if sink.fold(top) { + top.write(Object::None); + return GEN_FOLDED; + } + } + } + return 1; + } + settle(st); + let sw = &mut *st.sw; + let frame = &mut *st.frame; + frame.stack.set_len(len as usize); + frame.pc = pc as u32; + *sw.last = st.last; + let interp = &mut *st.interp.cast_mut(); + if !interp.core_gen_yield(sw, st.snap_gen) { + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Step)); + } else { + // A `yield from` chain passes the value straight up. + while sw.pending.is_none() + && interp.core_yield_chains(sw) + && interp.core_gen_yield(sw, st.snap_gen) + {} + } + RELOAD + } +} + +/// `RETURN_VALUE` at `pc` of the running activation, an inline generator +/// resume, as the core loop's arm runs it (see [`h_return`]); declined +/// untouched for a generator's fast step or a root activation. +unsafe extern "C" fn h_gen_return(st: *mut State, pc: u64, len: u64) -> u32 { + // SAFETY: the code passes its live state and its stack depth. + unsafe { + let st = &mut *st; + if st.sw.is_null() || (*(*st.sw).inl).is_empty() { + return 1; + } + settle(st); + let sw = &mut *st.sw; + let frame = &mut *st.frame; + frame.stack.set_len(len as usize); + frame.pc = pc as u32; + *sw.last = st.last; + let interp = &mut *st.interp.cast_mut(); + if !interp.core_return(sw, st.snap_gen) { + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Step)); + } + RELOAD + } +} + +/// [`h_anext`] of the plain instance atop the `len`-deep stack whose +/// class's `__anext__` is a coroutine function with native code: its body +/// runs as an awaited call's does ([`lazy_await_to`]), with no bound method +/// and no coroutine made unless something needs it. `AWAITED` leaves +/// `[None, result]` above the iterator for the `END_SEND`; `RELOAD` leaves +/// the rest to the core loop, the frame at the `SEND` as the instructions +/// would leave it; [`ANEXT_DECLINED`] touched nothing. +/// +/// # Safety +/// +/// As [`h_anext`]'s, its guards passed. +#[inline(never)] +unsafe fn anext_method(st: &mut State, pc: usize, len: usize) -> u32 { + // SAFETY: the caller's contract: two free slots above the iterator. + unsafe { + let base = st.stack; + let Some(f) = Interpreter::anext_dunder(&*base.add(len - 1)) else { + return ANEXT_DECLINED; + }; + let code: &Rc = &*f.code.as_ptr(); + if !code.is_coroutine || code.is_async_generator { + return ANEXT_DECLINED; + } + // The operands as a call's: the function, then the instance as its + // first argument. + base.add(len).write(Object::Function(f)); + base.add(len + 1) + .write(crate::clone_hot(&*base.add(len - 1))); + match lazy_await_to(st, pc + 2, len, len + 2) { + Some(r) => r, + None => { + drop(base.add(len + 1).read()); + drop(base.add(len).read()); + ANEXT_DECLINED + } + } + } +} + +/// `GET_AITER` of the value at `at`: an async generator is its own +/// iterator, and so is a plain instance whose class's `__aiter__` is a +/// leaf that returns it (evaluated here) and whose class has a Python +/// `__anext__`: `0`, the value standing as its iterator. Anything else +/// declined (`1`), untouched. +unsafe extern "C" fn h_get_aiter(st: *mut State, at: *const Object) -> u32 { + // SAFETY: the code passes its live state and an initialized stack slot; + // a leaf's evaluation runs no other Python code. + unsafe { + match &*at { + Object::AsyncGenerator(_) => 0, + v @ Object::Instance(inst) => { + let Some(f) = Interpreter::aiter_dunder(v) else { + return 1; + }; + if Interpreter::anext_dunder(v).is_none() { + return 1; + } + match (*(*st).interp).call_pure_leaf_with(&f, Some(v), &[]) { + // (The slot keeps it: a plain decrement.) + Some(Object::Instance(r)) if Rc::ptr_eq(&r, inst) => 0, + Some(other) => { + (*(*st).interp).release(other); + 1 + } + None => 1, + } + } + _ => 1, + } + } +} + +/// `END_ASYNC_FOR` at the site's pc, the iterator at the site's slot and +/// the exception above it: a `StopAsyncIteration` and the iterator leave +/// the stack and are released (`0`), or a status (see [`LEFT_INTERP`]); +/// any other exception is the core loop's to raise again. +unsafe extern "C" fn h_end_async_for(st: *mut State, site: SlotWord) -> u32 { + // SAFETY: the code passes its live state and a site whose two stack + // slots are initialized. + unsafe { + let at = (*st).stack.add(site.slot()); + if !crate::is_stop_async_iteration_obj(&*at.add(1)) + || !droppable(&*at) + || !droppable(&*at.add(1)) + { + return left(st, site.pc(), site.last(), site.slot() + 2); + } + crate::drop_hot_at(at.add(1)); + crate::drop_hot_at(at); + if (*(*st).maybe_dead).get() { + return left_marked(st, site.pc(), site.slot()); + } + } + 0 +} + +/// [`h_anext`] declined, untouched. +const ANEXT_DECLINED: u32 = 1; +/// [`h_anext`]'s generator suspended on an inner `await`: the awaitable +/// and the value passed through atop the stack, for the code's own +/// `YIELD_VALUE`. +const ANEXT_PASSED: u32 = 3; + +/// `GET_ANEXT` at `pc` of the running activation, its stack `len` deep +/// with an async generator on top, in the shape whose `END_SEND` is at +/// `exit` (see `crate::anext_send_exit`): the generator resumes from here +/// (`Interpreter::core_anext`), the frame synced as a native call's is (see +/// [`native_body_here`]). Its item is pushed for the code to go on past +/// the `END_SEND` (`0`); a suspension on an inner `await` pushes the +/// awaitable and the passed value for the code's own `YIELD_VALUE` +/// ([`ANEXT_PASSED`]); a raise (the generator's end among them) is the +/// instruction's (`RAISED`); when the resume left the activation's code, +/// the frame is left as the core loop's instructions would leave it +/// (`RELOAD`). [`ANEXT_DECLINED`] touched nothing (another iterator, an +/// observer owed the `StopIteration`, a fast step). +unsafe extern "C" fn h_anext(st: *mut State, pc: u64, len: u64, exit: u64) -> u32 { + use crate::AnextStep; + // SAFETY: the code passes its live state, one of its `GET_ANEXT`s and + // its stack depth (the iterator on top, with room for two more above + // it: the awaitable and the sent value of the `SEND` that follows). + unsafe { + let st = &mut *st; + let (pc, len, exit) = (pc as usize, len as usize, exit as usize); + if st.sw.is_null() + || !(*st.sw).calls_ok + || len + 2 > st.cap + || crate::hot_gates::loop_gen() != st.snap_gen + || (*st.maybe_dead).get() + || crate::trace::any_observers_active() + { + return ANEXT_DECLINED; + } + let base = st.stack; + if matches!(&*base.add(len - 1), Object::Instance(_)) { + return anext_method(st, pc, len); + } + let Object::AsyncGenerator(g) = &*base.add(len - 1) else { + return ANEXT_DECLINED; + }; + // (The stack's slot keeps the generator alive while it runs.) + let aiter = crate::clone_hot(&*base.add(len - 1)); + // The frame synced, as the core loop's arm syncs it. + let frame = &mut *st.frame; + frame.stack.set_len(len); + let lazy = !st.lazy.is_null() && !crate::sync::cells_unguarded(); + if !lazy { + settle(st); + *(*st.sw).last = st.last; + } + let sw = &mut *st.sw; + let interp = &mut *st.interp.cast_mut(); + let r = interp.core_anext( + sw, + frame, + pc, + g, + &aiter, + if lazy { + std::ptr::from_mut(st) + } else { + std::ptr::null_mut() + }, + ); + crate::drop_hot(aiter); + let mut in_place = false; + if !st.lazy.is_null() { + in_place = sw.pending.is_none() && crate::hot_gates::loop_gen() == st.snap_gen; + if !in_place { + settle(st); + } + } + let sw = &mut *st.sw; + in_place = in_place + || (sw.pending.is_none() + && std::ptr::eq(sw.cur, st.frame) + && crate::hot_gates::loop_gen() == st.snap_gen); + if in_place { + return match r { + Ok(AnextStep::Item(v)) => { + base.add(len).write(v); + st.len = len + 1; + 0 + } + Ok(AnextStep::Passed(aw, v)) => { + base.add(len).write(aw); + base.add(len + 1).write(v); + st.len = len + 2; + ANEXT_PASSED + } + Err(e) => { + st.len = len; + st.pc = pc + 1; + st.err = Some(e); + RAISED + } + }; + } + // The core loop goes on from the frame, left as its instructions + // leave it. + let frame = &mut *st.frame; + match r { + Ok(AnextStep::Item(v)) => { + base.add(len).write(v); + frame.stack.set_len(len + 1); + frame.pc = exit as u32 + 1; + *sw.last = exit; + } + Ok(AnextStep::Passed(aw, v)) => { + base.add(len).write(aw); + base.add(len + 1).write(v); + frame.stack.set_len(len + 2); + frame.pc = pc as u32 + 3; + *sw.last = pc + 2; + } + Err(e) => { + frame.stack.set_len(len); + frame.pc = pc as u32 + 1; + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Raised(e))); + return RELOAD; + } + } + if sw.pending.is_none() && (*sw.maybe_dead).get() { + sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Marked)); } - st.len = len; - Some(if exit { 0 } else { SEND_YIELDED }) + RELOAD } } -/// `YIELD_VALUE` in a generator's fast step whose draining consumer's -/// sink is `fold`: the value at `top` folded into the sink, the sent -/// `None` in its slot (`1`), or `0` for the step to hand it back. -unsafe extern "C" fn h_fold_yield(fold: *const crate::FoldSink, top: *mut Object) -> u32 { - // SAFETY: the step's sink, live while it runs, and the stack's top - // slot, initialized; a folded value moved out (or is a scalar). +/// `MATCH_SEQUENCE` (`kind` 0), `MATCH_MAPPING` (1) or `GET_LEN` (2) of +/// the value at `at` (the stack's top, which stays): the answer in the +/// free slot above it (`0`). A length that isn't an exact builtin +/// container's is the object's own to give (`1`, nothing written). +unsafe extern "C" fn h_match_probe(at: *mut Object, kind: u64) -> u32 { + // SAFETY: the code passes its initialized top slot, with room for one + // more above it; nothing here runs code. unsafe { - if (*fold).fold(top) { - top.write(Object::None); - 1 - } else { - 0 - } + let v = &*at; + let answer = match kind { + 0 => Object::Bool(crate::object_is_match_sequence(v)), + 1 => Object::Bool(crate::object_is_match_mapping(v)), + _ => match len_fast(std::slice::from_ref(v)) { + Some(Ok(n)) => n, + _ => return 1, + }, + }; + at.add(1).write(answer); + 0 } } -/// `YIELD_VALUE` at `pc` of the running activation, an inline generator -/// resume (its stack `len` deep, the value on top), as the core loop's arm -/// runs it: the generator parks and its consumer, the value delivered, is -/// switched to (`RELOAD`); for a root activation, folded into its draining -/// consumer's sink ([`GEN_FOLDED`]); declined untouched for a generator's -/// fast step, any other root activation, or a yield the switch doesn't -/// take. -/// [`h_gen_yield`]'s status for a yield the draining consumer's sink took: -/// the body goes on, the sent `None` in the value's slot. -const GEN_FOLDED: u32 = 2; - -unsafe extern "C" fn h_gen_yield(st: *mut State, pc: u64, len: u64) -> u32 { - // SAFETY: the code passes its live state and its stack depth. +/// `UNPACK_SEQUENCE 0` of the value at `at` (the stack's top): an empty +/// tuple, which a class pattern with no sub-patterns leaves to unpack, +/// goes (`0`); anything else declined untouched (`1`). +unsafe extern "C" fn h_unpack_empty(at: *mut Object) -> u32 { + // SAFETY: the code passes its initialized top slot; an empty tuple's + // release runs nothing. unsafe { - let st = &mut *st; - if st.sw.is_null() { + if !matches!(&*at, Object::Tuple(t) if t.is_empty()) { return 1; } - if (*(*st.sw).inl).is_empty() { - // A draining consumer driving this frame: the yield folds into - // its sink, as the core loop's arm folds it. - if let Some((ff, sink)) = (*st.interp).sum_fold { - if ff == (*st.sw).cur as usize && len > 0 { - let top = st.stack.add(len as usize - 1); - if sink.fold(top) { - top.write(Object::None); - return GEN_FOLDED; - } - } + crate::drop_hot_at(at); + 0 + } +} + +/// `MATCH_KEYS` of the subject at `at` and the keys tuple above it (both +/// stay): the values tuple, or `None`, in the free slot above them (`0`), +/// for an exact dict and plain keys (`Interpreter::match_keys_plain`); +/// anything else declined untouched (`1`). +unsafe extern "C" fn h_match_keys(at: *mut Object) -> u32 { + // SAFETY: the code passes two initialized slots atop its stack, with + // room for one more; nothing here runs code. + unsafe { + match Interpreter::match_keys_plain(&*at, &*at.add(1)) { + Some(v) => { + at.add(2).write(v); + 0 } - return 1; + None => 1, } - settle(st); - let sw = &mut *st.sw; - let frame = &mut *st.frame; - frame.stack.set_len(len as usize); - frame.pc = pc as u32; - *sw.last = st.last; - let interp = &mut *st.interp.cast_mut(); - if !interp.core_gen_yield(sw, st.snap_gen) { - sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Step)); - } else { - // A `yield from` chain passes the value straight up. - while sw.pending.is_none() - && interp.core_yield_chains(sw) - && interp.core_gen_yield(sw, st.snap_gen) - {} + } +} + +/// `MATCH_CLASS nargs` of the subject at `at`, the class above it and the +/// keyword names above that: for a match that runs no code +/// (`Interpreter::match_class_plain`), the three leave and the tuple of +/// sub-pattern subjects, or `None`, takes the subject's slot (`0`); +/// anything else declined untouched (`1`). +unsafe extern "C" fn h_match_class(at: *mut Object, nargs: u64) -> u32 { + // SAFETY: the code passes three initialized slots atop its stack; + // nothing here runs code, and the operands leave by plain releases. + unsafe { + let ops = std::slice::from_raw_parts(at, 3); + if !Interpreter::core_all_droppable(ops) { + return 1; } - RELOAD + let Some(v) = Interpreter::match_class_plain(&ops[0], &ops[1], nargs as usize, &ops[2]) + else { + return 1; + }; + crate::release_run(at, 3); + at.write(v); + 0 } } -/// `RETURN_VALUE` at `pc` of the running activation, an inline generator -/// resume, as the core loop's arm runs it (see [`h_return`]); declined -/// untouched for a generator's fast step or a root activation. -unsafe extern "C" fn h_gen_return(st: *mut State, pc: u64, len: u64) -> u32 { - // SAFETY: the code passes its live state and its stack depth. +/// `STORE_GLOBAL` of the value at `at` (the stack's top) to +/// `co_names[name]` of `code` in the running frame's globals, as the core +/// loop's arm stores it: an existing binding's value replaced in place +/// (the key layout, and with it every cached global load, standing; the +/// value epoch moved), the value it displaces leaving by a plain drop, or +/// a new name bound. `0` the value moved in; anything else (a watched +/// dict, a guard on the globals, an exotic key) declined untouched. +unsafe extern "C" fn h_store_global( + st: *mut State, + code: *const CodeObject, + name: u64, + at: *mut Object, +) -> u32 { + // SAFETY: the code passes its live state, its own code, one of its + // names and its initialized top slot; nothing here runs code. unsafe { - let st = &mut *st; - if st.sw.is_null() || (*(*st.sw).inl).is_empty() { + if crate::capi_watchers::dicts_active() { return 1; } - settle(st); - let sw = &mut *st.sw; - let frame = &mut *st.frame; - frame.stack.set_len(len as usize); - frame.pc = pc as u32; - *sw.last = st.last; - let interp = &mut *st.interp.cast_mut(); - if !interp.core_return(sw, st.snap_gen) { - sw.pending = Some(crate::CoreExit::Stop(crate::LeafStop::Step)); + let code = &*code; + let Some(probe) = crate::code_name_leaf_probe(code, name as u32) else { + return 1; + }; + let frame = &*(*st).frame; + let Some(g) = frame.globals.peek_mut() else { + return 1; + }; + match g.get_index_of(&probe) { + Some(_) if probe.saw_exotic() => 1, + Some(i) => { + if !g.get_index(i).is_some_and(|(_, old)| droppable(old)) { + return 1; + } + let Some((_, slot)) = g.map_mut_value_store().get_index_mut(i) else { + return 1; + }; + crate::object::bump_global_value_epoch(); + let old = std::mem::replace(slot, at.read()); + crate::drop_hot(old); + 0 + } + None => { + let (Some(key @ Object::Str(_)), false) = + (crate::code_name_obj(code, name as u32), probe.saw_exotic()) + else { + return 1; + }; + let displaced = g.insert(crate::object::DictKey(key.clone()), at.read()); + debug_assert!(displaced.is_none()); + 0 + } } - RELOAD } } @@ -14998,7 +22353,15 @@ unsafe extern "C" fn h_end_send(at: *mut Object) -> u32 { // SAFETY: the code passes two initialized slots atop its stack. unsafe { if !Interpreter::core_droppable(&*at) { - return 1; + // (An async generator's awaitable that was driven has nothing + // to warn of as it goes.) + let driven = matches!( + &*at, + Object::AsyncGenAwait(a) if a.started.get() || a.consumed.get() + ) && Interpreter::core_drops_plain(); + if !driven { + return 1; + } } let v = at.add(1).read(); crate::drop_hot(std::mem::replace(&mut *at, v)); @@ -15067,6 +22430,27 @@ unsafe extern "C" fn h_raise(st: *mut State, pc: u64, len: u64, n: u64) -> u32 { if !exc_ok || !cause_ok { return CALL_DECLINED; } + // `raise X` or `raise X(...)` under a clause that can't observe + // the exception (see `blind_raise`): a built-in class is never + // instantiated, and an instance nothing else holds is released + // after the clause's body with no context or traceback given it. + if n == 1 { + let cls: Option<*const crate::types::TypeObject> = match &*st.stack.add(len - 1) { + Object::Instance(i) if Rc::strong_count(i) == 1 => Some(i.cls_raw()), + Object::Type(t) => Some(Rc::as_ptr(t)), + _ => None, + }; + if let Some(cls) = cls { + let arg = st.stack.add(len - 1).read(); + st.len = len - 1; + st.pc = pc as usize + 1; + if blind_raise(st, &*cls) { + (*st.interp.cast_mut()).release(arg); + return RAISED; + } + st.stack.add(len - 1).write(arg); + } + } let cause = (n == 2).then(|| st.stack.add(len - 1).read()); let arg = st.stack.add(len - n).read(); let interp = &mut *st.interp.cast_mut(); @@ -15131,6 +22515,21 @@ unsafe extern "C" fn h_with_except_start( Some(r) => r, None => { crate::release_run(base.add(len), 5); + // A leaf has no body until it's hot (the core loop evaluates + // it frameless): this exit warms it, as compiled code's + // calls of a leaf do, so it's entered directly once it has. + if let Object::Function(f) = &*base.add(len - 5) { + let code_rc: &Rc = &*f.code.as_ptr(); + if crate::fn_is_leaf(f) { + if let Some(ext) = crate::code_vm_ext(code_rc) { + ext.frame_jit.warm_switched( + code_rc, + ext, + code_rc.varnames.len().max(4), + ); + } + } + } CALL_DECLINED } } @@ -15221,6 +22620,79 @@ unsafe extern "C" fn h_delete_fast(st: *mut State, slot: *mut Object) -> u32 { } } +/// The exception in `st.err`, raised by the instruction before `st.pc`, +/// caught by a clause of the running activation that can't observe it +/// (see `Interpreter::blind_catch`), when nothing else holds it: the +/// clause's body run and the exception released, as the clause's +/// `POP_EXCEPT` releases it, with no traceback entry, no frame record and +/// none of the handler's own instructions. `0` the state past the clause, +/// `MARKED` the same with a finalizer queued; `None` touched nothing. +#[inline(never)] +unsafe fn blind_caught(st: &mut State) -> Option { + // SAFETY: per `h_catch`. + unsafe { + let Some(RuntimeError::PyException(exc)) = &st.err else { + return None; + }; + let Object::Instance(inst) = &exc.instance else { + return None; + }; + if Rc::strong_count(inst) != 1 { + return None; + } + let cls: *const crate::types::TypeObject = inst.cls_raw(); + let (len, end) = (*st.interp).blind_catch( + &mut *st.frame, + st.locals, + st.stack, + st.len, + st.cap, + st.pc as u32 - 1, + &*cls, + )?; + st.len = len; + st.pc = end as usize + 1; + st.last = end as usize; + if let Some(RuntimeError::PyException(mut exc)) = st.err.take() { + let instance = std::mem::replace(&mut exc.instance, Object::None); + (*st.interp.cast_mut()).release(instance); + } + Some(if (*st.maybe_dead).get() { MARKED } else { 0 }) + } +} + +/// An exception of the built-in class `cls` that the instruction before +/// `st.pc` is about to raise, the stack `st.len` deep, when a clause that +/// can't observe it catches it (see `Interpreter::blind_catch`): the +/// clause's body run with no exception built. `true` leaves the state +/// past the clause and marks it caught, for the raise's status to reach +/// [`h_catch`] as any raise's does; `false` touched nothing. +#[inline(never)] +unsafe fn blind_raise(st: &mut State, cls: &crate::types::TypeObject) -> bool { + if !st.inl_call.is_null() || st.sw.is_null() || st.pc == 0 { + return false; + } + // SAFETY: per the raising helper (its live state). + unsafe { + let Some((len, end)) = (*st.interp).blind_catch( + &mut *st.frame, + st.locals, + st.stack, + st.len, + st.cap, + st.pc as u32 - 1, + cls, + ) else { + return false; + }; + st.len = len; + st.pc = end as usize + 1; + st.last = end as usize; + st.caught = true; + true + } +} + /// The exception a helper raised (`RAISED`, `st` synced past the raising /// instruction) caught by a handler of the running activation, as the /// quiet loop catches it (`Interpreter::quiet_catch`): `0` the state at @@ -15231,9 +22703,33 @@ unsafe extern "C" fn h_catch(st: *mut State) -> u32 { // SAFETY: the code passes its live state. unsafe { let st = &mut *st; + // A clause that ignores its exception, already run (see + // `blind_raise`): what its body released may have queued a + // finalizer. + if st.caught { + st.caught = false; + return if (*st.maybe_dead).get() { MARKED } else { 0 }; + } if st.sw.is_null() { return RAISED; } + // A record's callee nothing looked at yet, with no handler for the + // raise: its call's end unwinds it as it stands (see + // `records::raise_unseen`). + if !st.lazy.is_null() + && st.in_rec + && !st.gen_lazy + && st.inl_call.is_null() + && st.pc != 0 + && crate::find_handler(&(&*st.frame).code.exception_table, st.pc as u32 - 1).is_none() + { + return RAISED; + } + if st.inl_call.is_null() && st.pc != 0 { + if let Some(r) = blind_caught(st) { + return r; + } + } let Some(err) = st.err.take() else { return RAISED; }; @@ -15252,7 +22748,7 @@ unsafe extern "C" fn h_catch(st: *mut State) -> u32 { let mut tmp = None; let (_, _, shell) = sw.activation(depth, &mut tmp); let raise_pc = st.pc - 1; - match interp.quiet_catch(frame, &mut *shell.cast::>(), err) { + match interp.quiet_catch_seen(frame, &mut *shell.cast::>(), err) { Ok(()) => { *sw.last = raise_pc; st.pc = frame.pc as usize; @@ -15509,6 +23005,80 @@ unsafe extern "C" fn h_list_to_tuple(at: *mut Object) -> u32 { } } +/// `LIST_EXTEND 1` fused with the `LIST_TO_TUPLE` after it (a call's +/// spread arguments, `f(a, *rest)`): the list at stack slot `at`, which +/// only the stack holds, and the exact tuple or list above it become one +/// tuple of both's items in the list's slot, the source released. `0` +/// done, anything else declined untouched (the unfused steps take it). +unsafe extern "C" fn h_extend_to_tuple(at: *mut Object) -> u32 { + // SAFETY: the code passes two initialized slots. + unsafe { + let Object::List(l) = &*at else { + return 1; + }; + if Rc::strong_count(l) != 1 { + return 1; + } + let Some(head) = l.peek_mut() else { + return 1; + }; + let tail: &[Object] = match &*at.add(1) { + Object::Tuple(t) => t, + Object::List(src) if !Rc::ptr_eq(src, l) => match src.peek() { + Some(xs) => xs, + None => return 1, + }, + _ => return 1, + }; + // (One allocation, the tuple's own.) + let t = crate::object::TupleStorage::from_cloned_pair(head, tail); + // (Both runs' items live on in the tuple, so releasing the list's + // and the source frees at most their storage.) + head.clear(); + crate::drop_hot(at.add(1).read()); + crate::drop_hot(std::mem::replace(&mut *at, Object::Tuple(t))); + 0 + } +} + +/// Whether the `BUILD_MAP` at `pc` of `code` makes 1 to 8 pairs that the +/// next instruction, a plain `DICT_UPDATE`, merges into the dict below +/// them (`{**d, "k": v}`): one step through [`h_map_into`]. +fn fused_map_update_at(code: &CodeObject, pc: usize) -> bool { + let op = |pc: usize| code.instructions.get(pc).map(|i| (i.op, i.arg)); + matches!(op(pc), Some((OpCode::BuildMap, 1..=8))) + && matches!(op(pc + 1), Some((OpCode::DictUpdate, 0))) + && pc + 2 < code.instructions.len() +} + +/// Whether the `LIST_EXTEND` at `pc` of `code` spreads one source into a +/// list the `LIST_TO_TUPLE` after it converts, which [`h_extend_to_tuple`] +/// fuses. +fn fused_extend_tuple_at(code: &CodeObject, pc: usize) -> bool { + let op = |pc: usize| code.instructions.get(pc).map(|i| (i.op, i.arg)); + matches!(op(pc), Some((OpCode::ListExtend, 1))) + && matches!(op(pc + 1), Some((OpCode::ListToTuple, _))) + && pc + 2 < code.instructions.len() +} + +/// Whether the `BUILD_LIST` at `pc` of `code` only collects a call's +/// spread arguments: one load, then a [`fused_extend_tuple_at`] pair, so +/// that only the stack holds the list until it becomes a tuple. +fn spread_list_at(code: &CodeObject, pc: usize) -> bool { + matches!( + code.instructions.get(pc + 1).map(|i| i.op), + Some( + OpCode::LoadConst + | OpCode::LoadFast + | OpCode::LoadFastBorrow + | OpCode::LoadFastCheck + | OpCode::LoadDeref + | OpCode::LoadGlobal + | OpCode::LoadName + ) + ) && fused_extend_tuple_at(code, pc + 2) +} + /// `GET_ITER` of the value at stack slot `at`, as the core loop's arm /// runs it: `0` the iterator in its place, anything else declined /// untouched. @@ -15516,12 +23086,113 @@ unsafe extern "C" fn h_get_iter(at: *mut Object) -> u32 { // SAFETY: the code passes an initialized stack slot. unsafe { let v = &*at; + // A list or a tuple, the commonest loops' (a short inner loop + // pays this once an outer step): its iterator built here, ahead + // of the other kinds' tests. + let it = match v { + Object::List(items) => Some(PyIterator::List { + items: items.clone(), + index: 0, + owner: None, + }), + Object::Tuple(items) => Some(PyIterator::Tuple { + items: items.clone(), + index: 0, + }), + _ => None, + }; + if let Some(it) = it { + if !droppable(v) { + return 1; + } + let it = Object::Iter(Rc::new(crate::sync::RefCell::new(it))); + crate::drop_hot(std::mem::replace(&mut *at, it)); + return 0; + } if matches!( v, Object::Iter(_) | Object::LazyIter(_) | Object::Generator(_) ) { return 0; } + // An open file is its own iterator (a closed one's `ValueError` is + // the core loop's to raise). + if let Object::File(f) = v { + return u32::from(f.is_closed()); + } + // An enum class (`for m in Color`): its members as `EnumType`'s + // own `__iter__` yields them (see `Interpreter::enum_iter_lazy`). + if let Object::Type(t) = v { + let Some(it) = Interpreter::enum_iter_lazy(t) else { + return 1; + }; + crate::drop_hot(std::mem::replace(&mut *at, it)); + return 0; + } + // A list, tuple or dict subclass inheriting `__iter__` (a + // `defaultdict`, a `Counter`): its value's iterator, as + // `Interpreter::make_iter` makes it. + if let Object::Instance(inst) = v { + let Some( + native @ (Object::List(_) + | Object::Tuple(_) + | Object::Dict(_) + | Object::Set(_) + | Object::FrozenSet(_)), + ) = inst.native.get() + else { + // A deque (`for x in d`): the iterator its native + // `__iter__` builds, which runs no code. + // An array, or a view of an `OrderedDict` + // (`for k, v in od.items()`), likewise; and an `xml.etree` + // element (`for child in elem`), which has no `__iter__`: + // the iterator that reads its children as `elem[i]` does. + // (A class whose `__iter__` is a Python function has none + // of these: its memo answers that before the lanes' class + // tests, the `OrderedDict` one a lookup by name.) + if droppable(v) && !inst.class_dunder(crate::types::Dunder::Iter).is_function() { + // An `os.scandir` iterator is its own (its native + // `__iter__` returns it): left in place. + // So is a `csv.reader`. + if crate::stdlib::os::is_scandir(inst) + || crate::stdlib::csv_mod::is_plain_reader(inst) + { + return 0; + } + if let Some(it) = crate::stdlib::collections_native::deque_iter_lane(v) + .or_else(|| crate::stdlib::struct_mod::array_iter_lane(v)) + .or_else(|| crate::stdlib::collections_odict::iter_lane(v)) + .or_else(|| crate::stdlib::elementtree_native::sequence_iter(v)) + { + crate::drop_hot(std::mem::replace(&mut *at, it)); + return 0; + } + } + return 1; + }; + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || !cls.dunder(crate::types::Dunder::Iter).builtin_owner() + || !droppable(v) + { + // An `OrderedDict` (`for k in od`): the order iterator its + // native `__iter__` builds, which runs no code. + if droppable(v) && matches!(native, Object::Dict(_)) { + if let Some(it) = crate::stdlib::collections_odict::iter_lane(v) { + crate::drop_hot(std::mem::replace(&mut *at, it)); + return 0; + } + } + return 1; + } + let Ok(it) = native.make_iter() else { + return 1; + }; + let it = Object::Iter(Rc::new(crate::sync::RefCell::new(it))); + crate::drop_hot(std::mem::replace(&mut *at, it)); + return 0; + } if !matches!( v, Object::List(_) @@ -16115,7 +23786,7 @@ fn op_ir(op: OpCode) -> u32 { OpCode::LoadAttr | OpCode::LoadGlobal => 6, OpCode::LoadFast | OpCode::LoadFastBorrow | OpCode::PushNull => 3, OpCode::LoadConst | OpCode::LoadSmallInt | OpCode::Nop | OpCode::NotTaken => 1, - OpCode::Resume => 0, + OpCode::Resume | OpCode::AsyncGenWrap => 0, _ => 12, } } @@ -16151,10 +23822,10 @@ fn lower_range( need: usize, ) -> Option { engine.func.clear(); - // (About 18 IR instructions and 4 blocks per instruction lowered: the - // function is handed to code generation, so each lowering starts from - // empty tables.) - let span = range.len().min(code.instructions.len()); + // (About 18 IR instructions and 4 blocks per instruction lowered, the + // inlined callees' included: the function is handed to code + // generation, so each lowering starts from empty tables.) + let span = range.len().min(code.instructions.len()) + plans.total; engine.func.reserve(span * 18, span * 4); let ptr = engine.ptr; let sig = &mut engine.func.signature; @@ -16377,6 +24048,7 @@ impl Parts { chunk_at: self.chunk_at.into(), nlocals: self.nlocals, fails: self.entries.iter().map(|_| AtomicU8::new(0)).collect(), + lean_cap: std::sync::atomic::AtomicUsize::new(usize::MAX), entries: self.entries.into_iter().map(AtomicBool::new).collect(), name: self.name, ops: self.ops, @@ -16515,11 +24187,18 @@ fn block_starts(code: &CodeObject, depths: &[i64]) -> Vec { if ins.op == OpCode::Send && next < n { starts[next] = true; } + // And past the `END_SEND` that an `async for`'s `GET_ANEXT` skips + // with an async generator's item (`h_anext`). + if ins.op == OpCode::GetAnext { + if let Some(exit) = crate::anext_send_exit(code, pc).filter(|&e| e + 1 < n) { + starts[exit + 1] = true; + } + } if let Some(t) = target { if t < n { starts[t] = true; } - if fused_pair_at(code, pc) { + if fused_pair_at(code, pc) || fused_tuple_at(code, pc).is_some() { // Past the `UNPACK_SEQUENCE` a fused step skips. starts[pc + 2] = true; } @@ -16543,6 +24222,14 @@ fn block_starts(code: &CodeObject, depths: &[i64]) -> Vec { if next < n && (target.is_some() || !native_at(code, pc)) { starts[next] = true; } + // A fused spread continues after its `LIST_TO_TUPLE`. + if fused_extend_tuple_at(code, pc) { + starts[pc + 2] = true; + } + // A fused map merge continues after its `DICT_UPDATE`. + if fused_map_update_at(code, pc) { + starts[pc + 2] = true; + } // A fused attribute store continues after its `STORE_ATTR`. if ins.op == OpCode::LoadFast && code.instructions.get(next).map(|i| i.op) == Some(OpCode::StoreAttr) @@ -16588,11 +24275,18 @@ fn block_starts(code: &CodeObject, depths: &[i64]) -> Vec { } } } - // A handler, entered from a helper's raise (see `h_catch`). + // A handler, entered from a helper's raise (see `h_catch`); one that + // ignores its exception is left at the instruction after its clause + // (see `Interpreter::blind_catch`). for h in &code.exception_table { if (h.handler as usize) < n { starts[h.handler as usize] = true; } + if let Some(b) = crate::blind_handler(code, h) { + if (b.end as usize + 1) < n { + starts[b.end as usize + 1] = true; + } + } } for (pc, s) in starts.iter_mut().enumerate() { if *s && depths[pc] < 0 { @@ -16781,6 +24475,11 @@ struct Lower<'a> { held_codes: Vec>, /// A fused call just lowered: the last instruction it covers. skip_to: Option, + /// A fused `FOR_ITER`'s stored path (see [`h_for_iter_store`]): the + /// `STORE_FAST` it skipped and the block it waits in, which the store's + /// own path joins once lowered (no block start past the store, which + /// would cost every loop of the kind a store of its last instruction). + store_join: Option<(usize, Block)>, /// The IR instructions of the callees lowered in line. inline_ir: usize, /// The stack capacity the code needs. @@ -16808,6 +24507,7 @@ fn native_op(op: OpCode) -> bool { | OpCode::NotTaken | OpCode::Resume | OpCode::CopyFreeVars + | OpCode::AsyncGenWrap | OpCode::LoadFast | OpCode::LoadFastBorrow | OpCode::LoadConst @@ -16891,6 +24591,20 @@ fn native_at(code: &CodeObject, pc: usize) -> bool { OpCode::UnaryOp => ins.arg <= 3, OpCode::RaiseVarargs => matches!(ins.arg, 1 | 2), OpCode::Reraise | OpCode::WithExceptStart => true, + // An `async for`'s step (`h_anext`), start and end. + OpCode::GetAnext => crate::anext_send_exit(code, pc).is_some(), + OpCode::GetAiter | OpCode::EndAsyncFor => true, + // A module global's store (`h_store_global`). + OpCode::StoreGlobal => true, + // A module scope's names (`h_global`, `h_store_name`). + OpCode::LoadName | OpCode::StoreName => !code.is_class_body, + // A `match` statement's probes (`h_match_probe`, `h_match_keys`, + // `h_match_class`). + OpCode::MatchSequence + | OpCode::MatchMapping + | OpCode::GetLen + | OpCode::MatchKeys + | OpCode::MatchClass => true, // A prologue `MAKE_CELL`: the activation's cells are built with it. OpCode::MakeCell => prologue_cell(code, pc), // (A slot shared with a cell saves the cell itself.) @@ -17007,6 +24721,7 @@ impl<'a> Lower<'a> { method_notes: Vec::new(), held_codes: Vec::new(), skip_to: None, + store_join: None, inline_ir: 0, need, enter_sig: None, @@ -17110,6 +24825,16 @@ impl<'a> Lower<'a> { /// Whether `tag` is `None`'s, `bool`'s, `int`'s, `float`'s or /// `Unbound`'s: copied by value, dropped by forgetting. + /// Whether the value tagged `tag` is one a fresh instance can hold + /// untracked (see [`crate::object::ATOMIC_TAGS`]). + fn is_atomic(&mut self, tag: Value) -> Value { + self.b.ins().icmp_imm( + IntCC::UnsignedLessThan, + tag, + i64::from(crate::object::ATOMIC_TAGS), + ) + } + fn is_scalar(&mut self, tag: Value) -> Value { self.b.ins().icmp_imm( IntCC::UnsignedLessThan, @@ -17998,10 +25723,26 @@ impl<'a> Lower<'a> { self.sizes[start] = (self.b.func.dfg.num_insts() - before) as u32; } } + if let Some((at, join)) = self.store_join.take() { + self.close_store_join(at, join); + } self.side_exits(); true } + /// A fused `FOR_ITER`'s stored path (see [`Self::store_join`]) whose + /// `STORE_FAST` didn't go on in line: the core loop's past the store. + fn close_store_join(&mut self, at: usize, join: Block) { + let (depth, last) = (self.depth, self.last_pc); + self.b.switch_to_block(join); + self.vs.clear(); + // (The iterator alone, the item stored.) + self.depth = (self.depth_at(at) - 1).max(0) as usize; + self.last_pc = Some(at); + self.exit(INTERP, at + 1); + (self.depth, self.last_pc) = (depth, last); + } + /// Lower `blk`, from the instruction at `start` until the block ends or /// the next one starts. fn lower_block(&mut self, start: usize, blk: Block) { @@ -18021,6 +25762,19 @@ impl<'a> Lower<'a> { loop { let before = (self.b.func.dfg.num_insts(), self.b.func.dfg.num_blocks()); let goes_on = self.instruction(pc); + // A fused `FOR_ITER`'s stored path joins its `STORE_FAST`'s + // (the block after the `FOR_ITER`'s, lowered next). + if let Some((at, join)) = self.store_join { + if at == pc && !self.inlining() { + self.store_join = None; + if goes_on { + self.b.ins().jump(join, &[]); + self.b.switch_to_block(join); + } else { + self.close_store_join(at, join); + } + } + } if stats::enabled() { stats::lowered( format!("{:?}", self.code.instructions[pc].op), @@ -18057,7 +25811,11 @@ impl<'a> Lower<'a> { return r; } let cont = match ins.op { - OpCode::Nop | OpCode::NotTaken | OpCode::Resume | OpCode::CopyFreeVars => true, + OpCode::Nop + | OpCode::NotTaken + | OpCode::Resume + | OpCode::CopyFreeVars + | OpCode::AsyncGenWrap => true, OpCode::MakeCell if prologue_cell(self.code, pc) => true, OpCode::LoadFast | OpCode::LoadFastBorrow => self.load_fast(pc, ins.arg), OpCode::LoadConst if (ins.arg as usize) < self.ext.objects.len() => { @@ -18265,7 +26023,24 @@ impl<'a> Lower<'a> { return false; } OpCode::ForIter => return self.for_iter(pc, ins.arg), + OpCode::BinarySubscr if self.layout.is_some() && self.plan_at(pc).is_some() => { + let plans = self.plan_at(pc).expect("checked"); + return self.inline_subscr(pc, plans); + } OpCode::BinarySubscr if self.subscr_ref(pc) => true, + // (Nothing to unpack: a class pattern with no sub-patterns.) + OpCode::UnpackSequence if ins.arg == 0 && self.depth >= 1 && !self.inlining() => { + let s = self.top_to_mem(); + let at = self.slot_addr(s); + let r = self + .call(h_unpack_empty as *const () as usize, &[at], true) + .expect("returns"); + let out = self.exit_with(pc, &[], INTERP); + self.branch_out(r, out); + self.pop(); + self.set_last(pc); + true + } OpCode::UnpackSequence if self.unpack_ref(pc, ins.arg as usize) => true, OpCode::StoreSubscr if self.store_subscr_ref(pc) => true, OpCode::LoadSpecial => return self.load_special(pc), @@ -18378,6 +26153,15 @@ impl<'a> Lower<'a> { OpCode::ListAppend if ins.arg != 0 && (ins.arg as usize) < self.depth => { return self.list_append(pc, ins.arg as usize) } + OpCode::MapAdd if ins.arg != 0 && (ins.arg as usize) + 2 <= self.depth => { + return self.map_add(pc, ins.arg as usize) + } + OpCode::SetAdd if ins.arg != 0 && (ins.arg as usize) < self.depth => { + return self.set_add(pc, ins.arg as usize) + } + OpCode::ListExtend if fused_extend_tuple_at(self.code, pc) => { + return self.extend_to_tuple(pc) + } OpCode::ListAppend | OpCode::ListExtend | OpCode::SetAdd @@ -18391,6 +26175,7 @@ impl<'a> Lower<'a> { OpCode::ContainsOp => return self.contains(pc, ins.arg), OpCode::LoadAttr => return self.load_attr(pc, ins.arg), OpCode::LoadGlobal => return self.load_global(pc), + OpCode::LoadName if !self.inlining() => return self.load_name(pc), OpCode::PushNull => { let s = self.depth; let dst = self.slot_addr(s); @@ -18634,7 +26419,47 @@ impl<'a> Lower<'a> { .call(h_get_iter as *const () as usize, &[at], true) .expect("returns"); let out = self.exit_with(pc, &[], INTERP); - self.branch_out(r, out); + // An instance whose class's `__iter__` is a Python function, + // at a site that has run one: the method, called directly + // (it can raise or switch, which leaves the whole stack on + // the frame's). + let raisable = + !self.inlining() && self.vs.iter().all(|i| matches!(i, Item::Mem(_))); + if raisable && crate::instance_site(self.ext, pc) { + let dunder = self.b.create_block(); + let ok = self.b.create_block(); + self.b.ins().brif(r, dunder, &[], ok, &[]); + self.b.switch_to_block(dunder); + let site: Box = Box::default(); + let site_at = self + .b + .ins() + .iconst(self.ptr, std::ptr::from_ref::(&site) as i64); + self.direct_sites.push(site); + let pcv = self.b.ins().iconst(types::I64, pc as i64); + let slotv = self.b.ins().iconst(types::I64, s as i64); + let d = self + .call( + h_iter_dunder as *const () as usize, + &[self.st, pcv, slotv, site_at], + true, + ) + .expect("returns"); + let other = self.b.create_block(); + self.b.ins().brif(d, other, &[], ok, &[]); + self.b.switch_to_block(other); + let declined = self + .b + .ins() + .icmp_imm(IntCC::Equal, d, i64::from(CALL_DECLINED)); + let leave = self.b.create_block(); + self.b.ins().brif(declined, out, &[], leave, &[]); + self.b.switch_to_block(leave); + self.leave(d); + self.b.switch_to_block(ok); + } else { + self.branch_out(r, out); + } self.set_last(pc); self.check_released(pc + 1); true @@ -18663,6 +26488,193 @@ impl<'a> Lower<'a> { self.check_released(pc + 1); true } + // A `match` statement's probes of its subject, which stays: + // the answer pushed (`h_match_probe`). + OpCode::MatchSequence | OpCode::MatchMapping | OpCode::GetLen + if self.depth >= 1 && !self.inlining() => + { + let s = self.top_to_mem(); + let at = self.slot_addr(s); + let kind = self.b.ins().iconst( + types::I64, + match ins.op { + OpCode::MatchSequence => 0, + OpCode::MatchMapping => 1, + _ => 2, + }, + ); + let r = self + .call(h_match_probe as *const () as usize, &[at, kind], true) + .expect("returns"); + let out = self.exit_with(pc, &[], INTERP); + self.branch_out(r, out); + self.push(Item::Mem(s + 1)); + self.set_last(pc); + true + } + // A mapping pattern's keys: the values tuple or `None` pushed + // above the subject and the keys (`h_match_keys`). + OpCode::MatchKeys if self.depth >= 2 && !self.inlining() => { + self.flush(); + let at = self.slot_addr(self.depth - 2); + let r = self + .call(h_match_keys as *const () as usize, &[at], true) + .expect("returns"); + let out = self.exit_with(pc, &[], INTERP); + self.branch_out(r, out); + self.push(Item::Mem(self.depth)); + self.set_last(pc); + true + } + // A class pattern: the subject, the class and the names give + // way to the sub-patterns' subjects or `None` + // (`h_match_class`). + OpCode::MatchClass if self.depth >= 3 && !self.inlining() => { + self.flush(); + let at = self.slot_addr(self.depth - 3); + let nargs = self.b.ins().iconst(types::I64, i64::from(ins.arg)); + let r = self + .call(h_match_class as *const () as usize, &[at, nargs], true) + .expect("returns"); + let out = self.exit_with(pc, &[], INTERP); + self.branch_out(r, out); + self.pop(); + self.pop(); + self.pop(); + self.push(Item::Mem(self.depth)); + self.set_last(pc); + self.check_released(pc + 1); + true + } + // A module global's store, as the core loop's arm makes it + // (`h_store_global`): the frame's own globals, so not an + // inlined body's. + OpCode::StoreGlobal | OpCode::StoreName if self.depth >= 1 && !self.inlining() => { + let s = self.top_to_mem(); + let at = self.slot_addr(s); + let code = self.code_ptr(); + let name = self.b.ins().iconst(types::I64, i64::from(ins.arg)); + let helper = if ins.op == OpCode::StoreName { + h_store_name as *const () as usize + } else { + h_store_global as *const () as usize + }; + let r = self + .call(helper, &[self.st, code, name, at], true) + .expect("returns"); + let out = self.exit_with(pc, &[], INTERP); + self.branch_out(r, out); + // (The value moved into the binding; the one it displaced + // may have queued a finalizer.) + self.pop(); + self.set_last(pc); + self.check_released(pc + 1); + true + } + // An async generator is its own async iterator, as is an + // instance whose `__aiter__` is a leaf returning it + // (`h_get_aiter`); anything else is the core loop's. + OpCode::GetAiter if self.depth >= 1 && !self.inlining() => { + self.flush(); + let at = self.slot_addr(self.depth - 1); + let r = self + .call(h_get_aiter as *const () as usize, &[self.st, at], true) + .expect("returns"); + let out = self.exit_with(pc, &[], INTERP); + self.branch_out(r, out); + self.set_last(pc); + true + } + // An `async for`'s end: the `StopAsyncIteration` and the + // iterator leave (`h_end_async_for`); another exception is the + // core loop's. + OpCode::EndAsyncFor if self.depth >= 2 && !self.inlining() => { + self.flush(); + let site = SlotWord::new(0, self.depth - 2, pc, self.last_pc); + let w = self.b.ins().iconst(types::I64, site.0 as i64); + let r = self + .call(h_end_async_for as *const () as usize, &[self.st, w], true) + .expect("returns"); + self.after_helper(r); + self.pop(); + self.pop(); + self.set_last(pc); + true + } + // An `async for`'s step of an async generator resumes it from + // here (`h_anext`): its item goes on past the `END_SEND`, and a + // suspension on an inner `await` at this code's own + // `YIELD_VALUE`; the block ends either way. + OpCode::GetAnext if self.depth >= 1 && !self.inlining() => { + let Some(exit) = crate::anext_send_exit(self.code, pc) else { + self.exit(INTERP, pc); + return false; + }; + self.flush(); + self.store_last(); + let before = self.last_pc; + let depth = self.depth; + let pcv = self.b.ins().iconst(types::I64, pc as i64); + let len = self.b.ins().iconst(types::I64, depth as i64); + let exitv = self.b.ins().iconst(types::I64, exit as i64); + let r = self + .call( + h_anext as *const () as usize, + &[self.st, pcv, len, exitv], + true, + ) + .expect("returns"); + let item = self.b.create_block(); + let other = self.b.create_block(); + self.b.ins().brif(r, other, &[], item, &[]); + self.b.switch_to_block(item); + self.depth = depth + 1; + self.set_last(exit); + self.goto(exit + 1); + self.depth = depth; + self.b.switch_to_block(other); + let passed = self + .b + .ins() + .icmp_imm(IntCC::Equal, r, i64::from(ANEXT_PASSED)); + let passed_b = self.b.create_block(); + let rest = self.b.create_block(); + self.b.ins().brif(passed, passed_b, &[], rest, &[]); + self.b.switch_to_block(passed_b); + self.depth = depth + 2; + self.set_last(pc + 2); + self.goto(pc + 3); + self.depth = depth; + self.b.switch_to_block(rest); + // A class's `__anext__` awaited to its return + // (`anext_method`): on at the `END_SEND`. + if self.depths.get(exit).copied() == Some(depth as i64 + 2) { + let awaited = self.b.ins().icmp_imm(IntCC::Equal, r, i64::from(AWAITED)); + let awaited_b = self.b.create_block(); + let rest = self.b.create_block(); + self.b.ins().brif(awaited, awaited_b, &[], rest, &[]); + self.b.switch_to_block(awaited_b); + self.depth = depth + 2; + self.set_last(pc + 2); + self.goto(exit); + self.depth = depth; + self.b.switch_to_block(rest); + } + let declined = self + .b + .ins() + .icmp_imm(IntCC::Equal, r, i64::from(ANEXT_DECLINED)); + let left = self.b.create_block(); + let decl = self.b.create_block(); + self.b.ins().brif(declined, decl, &[], left, &[]); + // Raised, or the core loop's from the synced frame. + self.b.switch_to_block(left); + self.leave(r); + self.b.switch_to_block(decl); + self.last_pc = before; + self.exit(INTERP, pc); + return false; + } // The delegate resumes as the running activation (`h_send`): // the block ends either way. OpCode::Send if self.depth >= 2 => { @@ -18695,6 +26707,18 @@ impl<'a> Lower<'a> { self.set_last(pc); self.goto(next); self.b.switch_to_block(rest); + // An awaitable's drive raised in place (`send_agen_await`). + let raised = self + .b + .ins() + .icmp_imm(IntCC::Equal, r, i64::from(SEND_RAISED)); + let raised_b = self.b.create_block(); + let rest = self.b.create_block(); + self.b.ins().brif(raised, raised_b, &[], rest, &[]); + self.b.switch_to_block(raised_b); + let s = self.b.ins().iconst(types::I32, i64::from(RAISED)); + self.leave(s); + self.b.switch_to_block(rest); self.b.ins().brif(r, out, &[], returned, &[]); // The delegate returned into this `SEND`: its result took the // sent value's place. @@ -18898,7 +26922,10 @@ impl<'a> Lower<'a> { // an inlined body runs only what can't see its frame.) if !self.method_inlined(pc + 1) { self.method_kernel(pc); - if !self.inlining() { + if !self.inlining() + && self.simple_call_ahead(pc + 2) + && !self.inst_native_call_ahead(pc) + { self.method_call(pc) } } @@ -18949,6 +26976,41 @@ impl<'a> Lower<'a> { false } + /// Whether the instructions from `pc` are argument loads the fused + /// method call can take (locals, constants, small ints, and binary + /// operations it may fold) up to a positional `CALL`: every shape + /// `Interpreter::core_local_method` serves is one of these, so a call + /// with any other argument (an attribute, a subscript, a keyword) + /// skips the fused attempt, which would walk the instructions, decline + /// and leave the call to the method site anyway (about 450 + /// instructions a call for a native method with a keyword). + fn simple_call_ahead(&self, pc: usize) -> bool { + for i in self.code.instructions.iter().skip(pc).take(16) { + match i.op { + OpCode::LoadFast + | OpCode::LoadFastBorrow + | OpCode::LoadConst + | OpCode::LoadSmallInt + | OpCode::BinaryOp => {} + OpCode::Call => return true, + _ => return false, + } + } + false + } + + /// Whether the method call `LOAD_FAST x; x.m(...)` at `pc` (its + /// arguments as [`Self::simple_call_ahead`] takes them) is of a native + /// method an instance's site cached: the method load and the call + /// site's native lane serve it in about half what the fused call's + /// general native call takes (`od.move_to_end(i % n)`). + fn inst_native_call_ahead(&self, pc: usize) -> bool { + let call_pc = (pc + 2..self.code.instructions.len()) + .take(16) + .find(|&k| self.code.instructions[k].op == OpCode::Call); + call_pc.is_some_and(|k| crate::inst_builtin_method_site(self.ext, pc + 1, k).is_some()) + } + /// Whether the code is a generator's, coroutine's or async generator's /// body: its resume can't raise from here (its calls are the general /// loop's). @@ -19014,13 +27076,38 @@ impl<'a> Lower<'a> { Arg::Small(v) => (false, u32::MAX - v.min(u32::MAX - 1)), }) .collect(); - if args.iter().all(|&(local, v)| local || v < u32::MAX / 2) { - self.inst_native_call(pc, call_pc, &args, ver, fast, f); - } + let want = self.tags.instance; + self.native_method_call(pc, call_pc, &args, ver, want, fast, f); } return; }; let Some(kernel) = kernel_for(tag, kind, args.len()) else { + // A fast half, `pop(i)`, or a body that's a leaf whole, through + // the native method site (whose call can raise), the receiver's + // tag checked in line. + let fast = match (tag, kind) { + (_, crate::LeafKind::Fast(fast)) => Some(fast), + (1, crate::LeafKind::ListPop) | (1..=3, crate::LeafKind::Opaque) => None, + _ => return, + }; + if self.inlining() { + return; + } + let args: Vec<(bool, u32)> = args + .iter() + .map(|a| match *a { + Arg::Local(i) => (true, i), + Arg::Const(c) => (false, c), + Arg::Small(v) => (false, u32::MAX - v.min(u32::MAX - 1)), + }) + .collect(); + let want = match tag { + 1 => self.tags.list, + 2 => self.tags.dict, + 3 => self.tags.set, + _ => self.tags.str, + }; + self.native_method_call(pc, call_pc, &args, BUILTIN_RECV, want, fast, f); return; }; let want = match tag { @@ -19072,10 +27159,8 @@ impl<'a> Lower<'a> { let r = self .call(kernel as *const () as usize, &[out, recv, a, b, fp], true) .expect("returns"); - let ran = self.b.create_block(); - self.b.ins().brif(r, declined, &[], ran, &[]); + self.kernel_status(r, declined, call_pc); // Ran: the result in the receiver's slot, as after the `CALL`. - self.b.switch_to_block(ran); let (depth, last) = (self.depth, self.last_pc); self.push(Item::Mem(slot)); self.set_last(call_pc); @@ -19086,18 +27171,68 @@ impl<'a> Lower<'a> { self.b.switch_to_block(declined); } - /// `LOAD_FAST x; x.m(); CALL` on an - /// instance whose method site cached a native method: the receiver's - /// tag checked in line and the method called through [`h_inst_native`] - /// on the operands in place, continuing after the `CALL`. Lowering - /// continues (at the general fused call) where the receiver is - /// something else or the helper declines. - fn inst_native_call( + /// After a [`Kernel`] returned `r` for the `CALL` at `call_pc` (the + /// stack written out, as deep as `self.depth`): go on in a fresh block + /// where it ran; where its body raised ([`KERNEL_RAISED`]) raise the + /// error it kept through this code's handlers ([`h_kernel_raised`]), + /// or in an inlined body, which raises only through its caller's + /// paths, drop it for the full call at `declined`; there for anything + /// else too. + fn kernel_status(&mut self, r: Value, declined: Block, call_pc: usize) { + let ran = self.b.create_block(); + let not_ran = self.b.create_block(); + self.b.set_cold_block(not_ran); + self.b.ins().brif(r, not_ran, &[], ran, &[]); + self.b.switch_to_block(not_ran); + let raised = self + .b + .ins() + .icmp_imm(IntCC::Equal, r, i64::from(KERNEL_RAISED)); + let raise_b = self.b.create_block(); + self.b.set_cold_block(raise_b); + self.b.ins().brif(raised, raise_b, &[], declined, &[]); + self.b.switch_to_block(raise_b); + if self.inlining() { + self.call(h_kernel_forget as *const () as usize, &[], false); + self.b.ins().jump(declined, &[]); + } else { + let pcv = self.b.ins().iconst(types::I32, call_pc as i64); + let lenv = self.b.ins().iconst(types::I32, self.depth as i64); + let s = self + .call( + h_kernel_raised as *const () as usize, + &[self.st, pcv, lenv], + true, + ) + .expect("returns"); + let is_raise = self.b.ins().icmp_imm(IntCC::Equal, s, i64::from(RAISED)); + let leave_b = self.b.create_block(); + self.b.set_cold_block(leave_b); + self.b.ins().brif(is_raise, leave_b, &[], declined, &[]); + self.b.switch_to_block(leave_b); + let s = self.b.ins().iconst(types::I32, i64::from(RAISED)); + self.leave(s); + } + self.b.switch_to_block(ran); + } + + /// `LOAD_FAST x; x.m(); CALL` + /// on an instance whose method site cached a native method (or on an + /// exact builtin receiver whose method has a fast half, `ver` + /// [`BUILTIN_RECV`] and `want` its tag): the + /// receiver's tag checked in line and the method called through + /// [`h_inst_native`] on the operands in place (a small int, `(false, + /// u32::MAX - v)` in `args`, in the slot it would take), continuing + /// after the `CALL`. Lowering continues (at the general fused call) + /// where the receiver is something else or the helper declines. + #[allow(clippy::too_many_arguments)] + fn native_method_call( &mut self, pc: usize, call_pc: usize, args: &[(bool, u32)], ver: u64, + want: u8, fast: Option, f: Rc, ) { @@ -19106,13 +27241,10 @@ impl<'a> Lower<'a> { let declined = self.b.create_block(); let recv = self.local_addr(self.code.instructions[pc].arg); let t = self.tag_at(recv); - let other = self - .b - .ins() - .icmp_imm(IntCC::NotEqual, t, i64::from(self.tags.instance)); + let other = self.b.ins().icmp_imm(IntCC::NotEqual, t, i64::from(want)); self.branch_out(other, declined); let mut addrs = Vec::with_capacity(2); - for &(local, i) in args { + for (j, &(local, i)) in args.iter().enumerate() { let at = if local { let at = self.local_addr(i); if self.maybe_unbound[i as usize] && !self.bound[i as usize] { @@ -19124,17 +27256,32 @@ impl<'a> Lower<'a> { self.branch_out(unbound, declined); } at + } else if i >= u32::MAX / 2 { + // A small int, in the slot the argument would take. + let at = self.slot_addr(slot + 2 + j); + self.write_tag(at, self.tags.int); + let v = self.b.ins().iconst(types::I64, i64::from(u32::MAX - i)); + self.b.ins().store(FLAGS, v, at, 8); + at } else { self.const_addr(i) }; addrs.push(at); } + let name: Box = self + .code + .names + .get(self.code.instructions[pc + 1].arg as usize) + .map_or_else(|| Box::from(""), |n| Box::from(n.as_str())); + let hash = crate::object::py_str_hash(&name); let site = Box::new(InstMethodSite { f, fast, ver, nargs: args.len() as u32, call_pc: call_pc as u32, + name, + hash, }); let sp = self .b @@ -19450,9 +27597,10 @@ impl<'a> Lower<'a> { if native { return self.binary_helper(pc, kind, ai, bi); } + // (A small int operand, `b * 3`, is boxed onto the stack.) if crate::heap_site(self.ext, pc) - && matches!(ai, Item::Local(_) | Item::Const(_)) - && matches!(bi, Item::Local(_) | Item::Const(_)) + && !matches!(ai, Item::Mem(_)) + && !matches!(bi, Item::Mem(_)) { return self.binary_helper(pc, kind, ai, bi); } @@ -19730,6 +27878,20 @@ impl<'a> Lower<'a> { /// the values in registers written there here, the helper copying the /// rest. `arg` is the helper's operation. fn operand_site(&mut self, pc: usize, arg: u32, ai: Item, bi: Item, dunder: bool) -> Value { + self.operand_site_growing(pc, arg, ai, bi, dunder, NO_GROW) + } + + /// [`Self::operand_site`], with the local a `BINARY_OP`'s result is + /// stored into next (see [`BinopSite::grow_local`]). + fn operand_site_growing( + &mut self, + pc: usize, + arg: u32, + ai: Item, + bi: Item, + dunder: bool, + grow_local: u32, + ) -> Value { let slot = self.depth; let mut copies = Vec::new(); // (No method runs in an inlined body, whose locals aren't in the @@ -19779,6 +27941,9 @@ impl<'a> Lower<'a> { last: self.last_pc.map_or(NO_LAST, |l| l as u32), direct, dunder, + raisable: !in_line, + // (An inlined body's locals aren't in the state's array.) + grow_local: if in_line { NO_GROW } else { grow_local }, }); let c = self .b @@ -19791,7 +27956,24 @@ impl<'a> Lower<'a> { /// [`Self::operand_site`] for a `BINARY_OP`. fn binop_site(&mut self, pc: usize, kind: u8, ai: Item, bi: Item) -> Value { let flag = self.code.instructions[pc].arg & weavepy_compiler::BINARY_OP_INPLACE_FLAG; - self.operand_site(pc, u32::from(kind) | flag, ai, bi, true) + // `x = x + t` with the store next: `x` may grow in place. (Not + // when a load of `x` further down the stack is still to be made: + // it must see the old value.) + let grow = match self.code.instructions.get(pc + 1) { + Some(next) + if kind == BinOpKind::Add as u8 + && next.op == OpCode::StoreFast + && (next.arg as usize) < self.nlocals + && !self + .vs + .iter() + .any(|i| matches!(i, Item::Local(x) if *x == next.arg)) => + { + next.arg + } + _ => NO_GROW, + }; + self.operand_site_growing(pc, u32::from(kind) | flag, ai, bi, true, grow) } /// The other shapes of a `BINARY_OP` whose in-line arithmetic declined @@ -19901,6 +28083,7 @@ impl<'a> Lower<'a> { .iconst(self.ptr, std::ptr::from_ref(self.code) as i64); let pcv = self.b.ins().iconst(types::I64, pc as i64); let len = self.b.ins().iconst(types::I64, self.depth as i64); + let mut super_site = None; let n = if self.code.instructions[pc].op == OpCode::LoadSuperAttr { // `super().name`, through its site's cache. let site: Box = Box::default(); @@ -19908,6 +28091,7 @@ impl<'a> Lower<'a> { .b .ins() .iconst(self.ptr, std::ptr::from_ref::(&site) as i64); + super_site = Some(at); self.supers.push(site); self.call_typed( h_super_attr as *const () as usize, @@ -19915,6 +28099,20 @@ impl<'a> Lower<'a> { Some(types::I64), ) .expect("returns") + } else if let Some(kind) = match self.code.instructions[pc].op { + OpCode::PushExcInfo => Some(0), + OpCode::CheckExcMatch => Some(1), + OpCode::PopExcept => Some(2), + _ => None, + } { + // A handler's own instructions, by their helper. + let kind = self.b.ins().iconst(types::I64, kind); + self.call_typed( + h_exc_op as *const () as usize, + &[self.st, kind, len], + Some(types::I64), + ) + .expect("returns") } else { let raises = i64::from(!self.inlining()); let can_raise = self.b.ins().iconst(types::I64, raises); @@ -19930,11 +28128,24 @@ impl<'a> Lower<'a> { // A slice of an instance whose class's `__getitem__` is a Python // function, at a site that has sliced one: the method, called // directly (see `h_slice_dunder`). - if !self.inlining() - && self.code.instructions[pc].op == OpCode::BinarySlice - && self.depth >= 3 - && crate::instance_site(self.ext, pc) - { + // `super().name` of a property likewise: its getter, called + // directly (see `h_super_property`). + let ins_at = self.code.instructions[pc]; + // (The helper, and how many operands the instruction takes.) + let dunder_helper = match ins_at.op { + OpCode::BinarySlice if crate::instance_site(self.ext, pc) => { + Some((h_slice_dunder as *const () as usize, 3)) + } + OpCode::LoadSuperAttr if ins_at.arg & 1 == 0 => { + Some((h_super_property as *const () as usize, 3)) + } + // A deletion from an instance whose class's `__delitem__` is a + // Python function (see `h_delitem_dunder`). + OpCode::DeleteSubscr => Some((h_delitem_dunder as *const () as usize, 2)), + _ => None, + } + .filter(|&(_, nops)| self.depth >= nops); + if let (false, Some((helper, nops))) = (self.inlining(), dunder_helper) { let dunder = self.b.create_block(); let fine = self.b.create_block(); self.b.ins().brif(declined, dunder, &[], fine, &[]); @@ -19945,14 +28156,10 @@ impl<'a> Lower<'a> { .ins() .iconst(self.ptr, std::ptr::from_ref::(&site) as i64); self.direct_sites.push(site); - let slotv = self.b.ins().iconst(types::I64, self.depth as i64 - 3); - let d = self - .call( - h_slice_dunder as *const () as usize, - &[self.st, code, pcv, slotv, site_at], - true, - ) - .expect("returns"); + let slotv = self.b.ins().iconst(types::I64, (self.depth - nops) as i64); + let mut args = vec![self.st, code, pcv, slotv, site_at]; + args.extend(super_site); + let d = self.call(helper, &args, true).expect("returns"); let done = self.b.create_block(); let other = self.b.create_block(); self.b.ins().brif(d, other, &[], done, &[]); @@ -20038,12 +28245,13 @@ impl<'a> Lower<'a> { let restore: Vec = (slot..slot + n).map(Item::Mem).collect(); let out = self.exit_with(pc, &restore, INTERP); // A subscript of an instance whose class's `__getitem__` is a - // Python function, at a site that has run one: the method, called - // directly (it can raise or switch, which leaves the whole stack - // on the frame's). + // Python function, at a site that has run one (or that no run has + // settled: code compiled at its loop's first back edges): the + // method, called directly (it can raise or switch, which leaves + // the whole stack on the frame's). if raisable && self.code.instructions[pc].op == OpCode::BinarySubscr - && crate::instance_site(self.ext, pc) + && (crate::instance_site(self.ext, pc) || !crate::native_site(self.ext, pc)) { let dunder = self.b.create_block(); let ok = self.b.create_block(); @@ -20058,7 +28266,41 @@ impl<'a> Lower<'a> { let slotv = self.b.ins().iconst(types::I64, slot as i64); let d = self .call( - h_subscr_dunder as *const () as usize, + h_subscr_dunder as *const () as usize, + &[self.st, code, pcv, slotv, site_at], + true, + ) + .expect("returns"); + let other = self.b.create_block(); + self.b.ins().brif(d, other, &[], ok, &[]); + self.b.switch_to_block(other); + let declined = self + .b + .ins() + .icmp_imm(IntCC::Equal, d, i64::from(CALL_DECLINED)); + let leave = self.b.create_block(); + self.b.ins().brif(declined, out, &[], leave, &[]); + self.b.switch_to_block(leave); + self.leave(d); + self.b.switch_to_block(ok); + } else if raisable && self.code.instructions[pc].op == OpCode::StoreSubscr { + // A store into an instance whose class's `__setitem__` is a + // Python function: the method, called directly, as above. + let dunder = self.b.create_block(); + let ok = self.b.create_block(); + self.b.ins().brif(declined, dunder, &[], ok, &[]); + self.b.set_cold_block(dunder); + self.b.switch_to_block(dunder); + let site: Box = Box::default(); + let site_at = self + .b + .ins() + .iconst(self.ptr, std::ptr::from_ref::(&site) as i64); + self.direct_sites.push(site); + let slotv = self.b.ins().iconst(types::I64, slot as i64); + let d = self + .call( + h_setitem_dunder as *const () as usize, &[self.st, code, pcv, slotv, site_at], true, ) @@ -20075,6 +28317,37 @@ impl<'a> Lower<'a> { self.b.switch_to_block(leave); self.leave(d); self.b.switch_to_block(ok); + } else if !raisable + && !self.inlining() + && self.code.instructions[pc].op == OpCode::BinarySubscr + && n == 2 + { + // A dict's missing key or a sequence's index out of range under + // virtual items: the virtual stack written out (on this path + // only), the raise is the handlers' (see `h_subscr_raise`). + let miss = self.b.create_block(); + let ok = self.b.create_block(); + self.b.ins().brif(declined, miss, &[], ok, &[]); + self.b.set_cold_block(miss); + self.b.switch_to_block(miss); + let (vs, depth) = (self.vs.clone(), self.depth); + self.flush(); + let raised = self + .call( + h_subscr_raise as *const () as usize, + &[self.st, pcv, lenv], + true, + ) + .expect("returns"); + let raise_b = self.b.create_block(); + let back = self.exit_with(pc, &restore, INTERP); + self.b.ins().brif(raised, raise_b, &[], back, &[]); + self.b.switch_to_block(raise_b); + let s = self.b.ins().iconst(types::I32, i64::from(RAISED)); + self.leave(s); + self.vs = vs; + self.depth = depth; + self.b.switch_to_block(ok); } else { self.branch_out(declined, out); } @@ -20168,12 +28441,12 @@ impl<'a> Lower<'a> { let h = self.b.ins().load(types::I64, FLAGS, k, l.str_hash); let unknown = self.b.ins().icmp_imm(IntCC::Equal, h, -1); self.branch_out(unknown, helper_block); - let nslots = self.b.ins().load(types::I64, FLAGS, obj, l.slots_len); - let small = self.b.ins().icmp_imm(IntCC::Equal, nslots, 0); + // (A table without slots keeps 64 for its shift.) + let shift = self.b.ins().uload32(FLAGS, obj, l.shift); + let small = self.b.ins().icmp_imm(IntCC::Equal, shift, 64); self.branch_out(small, helper_block); // The home slot: the mixed hash's top bits. let m = self.b.ins().imul_imm(h, l.mix); - let shift = self.b.ins().uload32(FLAGS, obj, l.shift); let pos = self.b.ins().ushr(m, shift); let slots = self.b.ins().load(self.ptr, FLAGS, obj, l.slots); let at = self.b.ins().ishl_imm(pos, 3); @@ -20480,13 +28753,17 @@ impl<'a> Lower<'a> { let key = self.pop(); let cont = self.pop(); let slot = self.depth; - // A site that has run an instance's Python `__getitem__`: that - // first, the native containers' paths only when it declines. + // A site that has run an instance's Python `__getitem__` (or a + // dict subclass's `__missing__`): that first, the native + // containers' paths only when it declines. The call can switch, so + // the copies below (`d[k] += 1`'s) go to the frame's stack first. if !self.inlining() && self.code.instructions[pc].op == OpCode::BinarySubscr && crate::instance_site(self.ext, pc) - && self.vs.iter().all(|i| matches!(i, Item::Mem(_))) { + if !self.vs.iter().all(|i| matches!(i, Item::Mem(_))) { + self.flush(); + } return self.subscr_dunder_first(pc, slot, cont, key); } let tuple = self.seq_index_site(pc, cont); @@ -20750,6 +29027,27 @@ impl<'a> Lower<'a> { /// `LIST_APPEND` through [`h_list_append`] (the value leaves the stack /// into the list `arg` below it). fn list_append(&mut self, pc: usize, arg: usize) -> bool { + // A local's or constant's value is read in place (no copy to the + // stack first) when the list is on the frame's stack. + if self.slot_on_stack(self.depth - 1 - arg) && !self.inlining() { + let list = self.slot_addr(self.depth - 1 - arg); + let vi = self.pop(); + let slot = self.depth; + let (value, own) = self.ref_or_own(vi, slot); + let owned = self.b.ins().iconst(types::I32, i64::from(own)); + let r = self + .call( + h_list_append_ref as *const () as usize, + &[list, value, owned], + true, + ) + .expect("returns"); + let restore = if own { Item::Mem(slot) } else { vi }; + let out = self.exit_with(pc, &[restore], INTERP); + self.branch_out(r, out); + self.set_last(pc); + return true; + } self.flush(); let list = self.slot_addr(self.depth - 1 - arg); let value = self.slot_addr(self.depth - 1); @@ -20763,6 +29061,65 @@ impl<'a> Lower<'a> { true } + /// Whether stack slot `s` holds its value on the frame's stack (not a + /// virtual item waiting to be written there). + fn slot_on_stack(&self, s: usize) -> bool { + let base = self.depth - self.vs.len(); + s < base || matches!(self.vs.get(s - base), Some(Item::Mem(m)) if *m == s) + } + + /// `SET_ADD` through [`h_set_add`], or out to the core loop with the + /// operands as they were. + fn set_add(&mut self, pc: usize, arg: usize) -> bool { + if !self.slot_on_stack(self.depth - 1 - arg) || self.inlining() { + self.flush(); + } + let set = self.slot_addr(self.depth - 1 - arg); + let vi = self.pop(); + let slot = self.depth; + let (value, own) = self.ref_or_own(vi, slot); + let owned = self.b.ins().iconst(types::I32, i64::from(own)); + let r = self + .call(h_set_add as *const () as usize, &[set, value, owned], true) + .expect("returns"); + let restore = if own { Item::Mem(slot) } else { vi }; + let out = self.exit_with(pc, &[restore], INTERP); + self.branch_out(r, out); + self.set_last(pc); + true + } + + /// `MAP_ADD` through [`h_map_add`], or out to the core loop with the + /// operands as they were. + fn map_add(&mut self, pc: usize, arg: usize) -> bool { + if !self.slot_on_stack(self.depth - 2 - arg) || self.inlining() { + self.flush(); + } + let dict = self.slot_addr(self.depth - 2 - arg); + let vi = self.pop(); + let ki = self.pop(); + let slot = self.depth; + let (key, own_k) = self.ref_or_own(ki, slot); + let (value, own_v) = self.ref_or_own(vi, slot + 1); + let owned = self.b.ins().iconst( + types::I32, + i64::from(u8::from(own_k) | u8::from(own_v) << 1), + ); + let r = self + .call( + h_map_add as *const () as usize, + &[dict, key, value, owned], + true, + ) + .expect("returns"); + let rk = if own_k { Item::Mem(slot) } else { ki }; + let rv = if own_v { Item::Mem(slot + 1) } else { vi }; + let out = self.exit_with(pc, &[rk, rv], INTERP); + self.branch_out(r, out); + self.set_last(pc); + true + } + /// An operand for a helper that reads it in place: a local's or a /// constant's own value (borrowed, `false`), or anything else on the /// stack at `slot` (owned there, `true`). @@ -20812,7 +29169,54 @@ impl<'a> Lower<'a> { let r = self.b.block_params(done)[0]; let declined = self.b.ins().icmp_imm(IntCC::UnsignedGreaterThan, r, 1); let out = self.exit_with(pc, &[Item::Mem(slot), Item::Mem(slot + 1)], INTERP); - self.branch_out(declined, out); + // An instance's Python `__contains__`, called directly where both + // operands are on the stack and nothing below them is virtual (see + // `h_contains_dunder`). + // (A declined test leaves both operands owned in their slots.) + let r = if !self.inlining() && self.vs.iter().all(|i| matches!(i, Item::Mem(_))) { + let dunder = self.b.create_block(); + let found_b = self.b.create_block(); + self.b.append_block_param(found_b, types::I32); + self.b + .ins() + .brif(declined, dunder, &[], found_b, &[r.into()]); + self.b.set_cold_block(dunder); + self.b.switch_to_block(dunder); + let site: Box = Box::default(); + let site_at = self + .b + .ins() + .iconst(self.ptr, std::ptr::from_ref::(&site) as i64); + self.direct_sites.push(site); + let code = self.code_ptr(); + let pcv = self.b.ins().iconst(types::I64, pc as i64); + let slotv = self.b.ins().iconst(types::I64, slot as i64); + let inv = self.b.ins().iconst(types::I64, i64::from(arg == 1)); + let d = self + .call( + h_contains_dunder as *const () as usize, + &[self.st, code, pcv, slotv, site_at, inv], + true, + ) + .expect("returns"); + let other = self.b.create_block(); + let more = self.b.ins().icmp_imm(IntCC::UnsignedGreaterThan, d, 1); + self.b.ins().brif(more, other, &[], found_b, &[d.into()]); + self.b.switch_to_block(other); + let no = self + .b + .ins() + .icmp_imm(IntCC::Equal, d, i64::from(CALL_DECLINED)); + let leave = self.b.create_block(); + self.b.ins().brif(no, out, &[], leave, &[]); + self.b.switch_to_block(leave); + self.leave(d); + self.b.switch_to_block(found_b); + self.b.block_params(found_b)[0] + } else { + self.branch_out(declined, out); + r + }; let found = self.b.ins().icmp_imm(IntCC::NotEqual, r, 0); let found = if arg == 1 { self.b.ins().bxor_imm(found, 1) @@ -21247,6 +29651,68 @@ impl<'a> Lower<'a> { self.depth = depth; self.b.switch_to_block(single); } + // A loop that stores a fresh pair whole (`for t in enumerate(xs)`): + // refilled into the local's previous pair when that tuple is the + // local's alone (a tuple there, counted once, checked in line first: + // a list of pairs' loop holds a shared one). + if let (Some(i), Some(sl), false, None) = ( + store_fusion_at(self.code, pc), + self.tags.seq_layout, + self.inlining(), + self.store_join, + ) { + let local = self.local_addr(i); + let tag = self.tag_at(local); + let is_tuple = self + .b + .ins() + .icmp_imm(IntCC::Equal, tag, i64::from(sl.tuple_tag)); + let try_b = self.b.create_block(); + let single = self.b.create_block(); + self.b.ins().brif(is_tuple, try_b, &[], single, &[]); + self.b.switch_to_block(try_b); + if sl.tuple_counted { + let w = self.b.ins().load(self.ptr, FLAGS, local, 8); + let count = self.b.ins().load(self.ptr, FLAGS, w, 0); + let sole = self.b.ins().icmp_imm(IntCC::Equal, count, 1); + let call_b = self.b.create_block(); + self.b.ins().brif(sole, call_b, &[], single, &[]); + self.b.switch_to_block(call_b); + } + let r = self + .call( + h_for_iter_store as *const () as usize, + &[self.st, it, local], + true, + ) + .expect("returns"); + let join = self.b.create_block(); + self.b.ins().brif(r, single, &[], join, &[]); + self.store_join = Some((pc + 1, join)); + self.b.switch_to_block(single); + } + // Likewise a loop that unpacks three or four (`for a, b, c in + // zip(xs, ys, zs)`). + if let Some(n) = fused_tuple_at(self.code, pc) { + let nv = self.b.ins().iconst(types::I64, i64::from(n)); + let r = self + .call( + h_for_iter_tuple as *const () as usize, + &[it, out_slot, nv], + true, + ) + .expect("returns"); + let tuple_b = self.b.create_block(); + let single = self.b.create_block(); + self.b.ins().brif(r, single, &[], tuple_b, &[]); + self.b.switch_to_block(tuple_b); + let depth = self.depth; + self.depth += n as usize; + self.set_last(pc + 1); + self.goto(pc + 2); + self.depth = depth; + self.b.switch_to_block(single); + } let pcv = self.b.ins().iconst(types::I64, pc as i64); // An inlined `list(...)`, `tuple(...)`, `all(...)` or `any(...)` of a // generator expression may drain its generator (see @@ -21255,6 +29721,12 @@ impl<'a> Lower<'a> { inline::h_inline_for_iter as *const () as usize } else if drain_shape(self.code, pc) { h_for_iter_drain as *const () as usize + } else if matches!( + self.code.caches.get(pc as u32), + weavepy_compiler::InlineCache::ForIterDict + ) { + // (A site that settled on a dict's iterator: its step first.) + h_for_iter_dict as *const () as usize } else { h_for_iter as *const () as usize }; @@ -21359,7 +29831,7 @@ impl<'a> Lower<'a> { }; if !matches!( self.code.caches.get(pc as u32), - IC::Empty | IC::ForIterList | IC::ForIterRange + IC::Empty | IC::ForIterList | IC::ForIterRange | IC::ForIterTuple ) { return; } @@ -21403,13 +29875,50 @@ impl<'a> Lower<'a> { self.b.ins().store(FLAGS, next, obj, l.range_current); self.b.ins().store(FLAGS, cur, self.st, S_OUT); self.b.ins().jump(int_b, &[]); - // A list: its next item. self.b.switch_to_block(maybe_list); - let not_list = self + let list_b = self.b.create_block(); + let maybe_tuple = self.b.create_block(); + let is_list = self + .b + .ins() + .icmp_imm(IntCC::Equal, disc, i64::from(l.list_disc)); + self.b.ins().brif(is_list, list_b, &[], maybe_tuple, &[]); + // A tuple: its next item (nothing to borrow: it never changes). + self.b.switch_to_block(maybe_tuple); + let not_tuple = self .b .ins() - .icmp_imm(IntCC::NotEqual, disc, i64::from(l.list_disc)); - self.branch_out(not_list, helper_b); + .icmp_imm(IntCC::NotEqual, disc, i64::from(l.tuple_disc)); + self.branch_out(not_tuple, helper_b); + { + let items = self.b.ins().load(self.ptr, FLAGS, obj, l.tuple_items); + let i = self.b.ins().load(types::I64, FLAGS, obj, l.tuple_index); + let len = self.b.ins().load(types::I64, FLAGS, items, s.tuple_len); + let end = self.b.ins().icmp(IntCC::UnsignedGreaterThanOrEqual, i, len); + self.branch_out(end, helper_b); + let byte = self.b.ins().ishl_imm(i, 4); + let first = self.b.ins().iadd_imm(items, i64::from(s.tuple_items)); + let src = self.b.ins().iadd(first, byte); + let next = self.b.ins().iadd_imm(i, 1); + self.b.ins().store(FLAGS, next, obj, l.tuple_index); + let itag = self.tag_at(src); + let is_int = self + .b + .ins() + .icmp_imm(IntCC::Equal, itag, i64::from(self.tags.int)); + let int_item = self.b.create_block(); + let boxed = self.b.create_block(); + self.b.ins().brif(is_int, int_item, &[], boxed, &[]); + self.b.switch_to_block(int_item); + let v = self.b.ins().load(types::I64, FLAGS, src, 8); + self.b.ins().store(FLAGS, v, self.st, S_OUT); + self.b.ins().jump(int_b, &[]); + self.b.switch_to_block(boxed); + self.copy_value(out, src); + self.b.ins().jump(pushed_b, &[]); + } + // A list: its next item. + self.b.switch_to_block(list_b); let items = self.b.ins().load(self.ptr, FLAGS, obj, l.list_items); let lb = self.b.ins().load(types::I32, FLAGS, items, s.list_borrow); let held = self.b.ins().icmp_imm(IntCC::SignedLessThan, lb, 0); @@ -21459,9 +29968,13 @@ impl<'a> Lower<'a> { }; let field = self.field_slots.get(pc); let slots = field.is_some_and(|f| f.get().1 & crate::SLOT_FIELD != 0); + // (A polymorphic site's split fields: helpers of their own.) + let poly = self.ext.attr_poly_slot(pc).is_some() && !crate::property_site(self.ext, pc); let (helper, local) = match item { Item::Local(i) if slots => (h_attr_local_slot as *const () as usize, i), + Item::Local(i) if poly => (h_attr_local_poly as *const () as usize, i), Item::Local(i) => (h_attr_local as *const () as usize, i), + _ if poly => (h_attr_stack_poly as *const () as usize, 0), _ => (h_attr_stack as *const () as usize, 0), }; let site = Box::new(AttrSite { @@ -21473,12 +29986,14 @@ impl<'a> Lower<'a> { last: self.last_pc.map_or(NO_LAST, |l| l as u32), property: !in_line && crate::property_site(self.ext, pc), field: field.map_or(std::ptr::null(), std::ptr::from_ref), - field2: Cell::new((0, 0)), + field2: [const { Cell::new((0, 0)) }; FIELD_MORE], direct, cache: SlotCache::default(), class_attr: Cell::new(false), descr: Cell::new(false), no_descr: Cell::new(0), + py_hook: Cell::new(0), + py_hook_call: Cell::new(0), hook: std::cell::RefCell::new(None), type_attr: std::cell::RefCell::new(None), class_poly: Default::default(), @@ -21486,6 +30001,11 @@ impl<'a> Lower<'a> { no_shadow_keys: Cell::new(0), no_shadow_limit: Cell::new(0), builtin_attr: std::cell::RefCell::new(None), + prop_leaf: [const { Cell::new((0, 0, 0, 0)) }; PROP_LEAVES], + pub_hint: Cell::new((0, 0)), + exc_slot: Cell::new(0), + exc_default: Cell::new(EXC_DEFAULT_ABSENT), + exc_which: Cell::new(EXC_SLOT_OTHER), }); let c = self .b @@ -21605,11 +30125,15 @@ impl<'a> Lower<'a> { let r = match item { Item::Local(i) if in_line => { let at = self.local_addr(i); - self.call( - inline::h_inline_attr_local as *const () as usize, - &[self.st, c, at], - true, - ) + // (A polymorphic site's split fields: its own helper.) + let f = if self.ext.attr_poly_slot(pc).is_some() + && !crate::property_site(self.ext, pc) + { + inline::h_inline_attr_poly as *const () as usize + } else { + inline::h_inline_attr_local as *const () as usize + }; + self.call(f, &[self.st, c, at], true) } _ => self.call(helper, &[self.st, c], true), } @@ -21621,6 +30145,11 @@ impl<'a> Lower<'a> { } self.push(Item::Mem(slot)); self.set_last(pc); + // (A receiver `h_class_read` released last may have queued a + // finalizer.) + if class_read { + self.check_released(pc + 1); + } true } @@ -21692,41 +30221,204 @@ impl<'a> Lower<'a> { if may_fuse { self.flush(); } - let s = self.depth; - let cache: Box = Box::new(GlobalCache { - code: std::ptr::from_ref(self.code) as u64, - ext: std::ptr::from_ref(self.ext) as u64, - pc: pc as u32, - nlocals: self.nlocals as u32, - len: s as u64, - last: self.last_pc.map_or(NO_LAST, |l| l as u32), - ..GlobalCache::default() - }); - let c = self - .b - .ins() - .iconst(self.ptr, std::ptr::from_ref::(&cache) as i64); - self.global_caches.push(cache); + let s = self.depth; + let cache: Box = Box::new(GlobalCache { + code: std::ptr::from_ref(self.code) as u64, + ext: std::ptr::from_ref(self.ext) as u64, + pc: pc as u32, + nlocals: self.nlocals as u32, + len: s as u64, + last: self.last_pc.map_or(NO_LAST, |l| l as u32), + ..GlobalCache::default() + }); + let c = self + .b + .ins() + .iconst(self.ptr, std::ptr::from_ref::(&cache) as i64); + self.global_caches.push(cache); + let r = self + .call(h_global as *const () as usize, &[self.st, c], true) + .expect("returns"); + self.after_helper(r); + self.push(Item::Mem(s)); + self.set_last(pc); + true + } + + /// A module scope's `LOAD_NAME` at `pc`: a global's load through + /// [`h_global`], its cache marked for [`name_miss`]. + fn load_name(&mut self, pc: usize) -> bool { + let s = self.depth; + let cache: Box = Box::new(GlobalCache { + code: std::ptr::from_ref(self.code) as u64, + ext: std::ptr::from_ref(self.ext) as u64, + pc: pc as u32, + nlocals: self.nlocals as u32, + len: s as u64, + last: self.last_pc.map_or(NO_LAST, |l| l as u32), + name: true, + ..GlobalCache::default() + }); + let c = self + .b + .ins() + .iconst(self.ptr, std::ptr::from_ref::(&cache) as i64); + self.global_caches.push(cache); + let r = self + .call(h_global as *const () as usize, &[self.st, c], true) + .expect("returns"); + self.after_helper(r); + self.push(Item::Mem(s)); + self.set_last(pc); + true + } + + /// `LOAD_ATTR` with the method flag through [`h_method`]: the + /// method and its self slot in place of the receiver. + fn load_method(&mut self, pc: usize) -> bool { + if self.depth == 0 { + self.exit(INTERP, pc); + return false; + } + if let Some(r) = self.inline_method(pc) { + return r; + } + if !self.is_gen() && crate::method_site_in_place(self.ext, pc) { + self.stack_method_kernel(pc); + } + self.load_method_site(pc) + } + + /// [`Self::method_kernel`] for a receiver on the stack rather than in a + /// local (`self.items.append(x)`, `d[k].append(v)`): `x.m(); CALL` at the method load + /// `pc` on an exact `list`, `dict`, `set` or `str`, its tag checked in + /// line and the kernel called with the result in the slot above it; + /// the receiver then released as `POP_TOP` releases one (checked + /// droppable first, so nothing declines after the kernel ran) and the + /// result moved into its slot, continuing after the `CALL`. Lowering + /// continues (at the general method load) where the receiver is + /// something else or the kernel declines. + fn stack_method_kernel(&mut self, pc: usize) { + #[derive(Clone, Copy)] + enum Arg { + Local(u32), + Const(u32), + Small(u32), + } + let code = self.code; + let ins = &code.instructions; + let n = ins.len(); + let mut args: Vec = Vec::new(); + let mut k = pc + 1; + let call_pc = loop { + let Some(i) = ins.get(k) else { + return; + }; + match i.op { + OpCode::LoadFast | OpCode::LoadFastBorrow if (i.arg as usize) < self.nlocals => { + args.push(Arg::Local(i.arg)); + } + OpCode::LoadConst if (i.arg as usize) < self.ext.objects.len() => { + args.push(Arg::Const(i.arg)); + } + OpCode::LoadSmallInt => args.push(Arg::Small(i.arg)), + OpCode::Call if i.arg as usize == args.len() => break k, + _ => return, + } + if args.len() > 2 { + return; + } + k += 1; + }; + if call_pc + 1 >= n || !self.starts.get(call_pc + 1).copied().unwrap_or(false) { + return; + } + let Some((tag, kind, f)) = crate::builtin_method_site(self.ext, pc, call_pc) else { + return; + }; + let Some(kernel) = kernel_for(tag, kind, args.len()) else { + return; + }; + let want = match tag { + 1 => self.tags.list, + 2 => self.tags.dict, + 3 => self.tags.set, + _ => self.tags.str, + }; + self.flush(); + let slot = self.depth - 1; + let declined = self.b.create_block(); + let recv = self.slot_addr(slot); + let t = self.tag_at(recv); + let other = self.b.ins().icmp_imm(IntCC::NotEqual, t, i64::from(want)); + self.branch_out(other, declined); + let mut addrs = Vec::with_capacity(2); + for (j, arg) in args.iter().enumerate() { + let at = match *arg { + Arg::Local(i) => { + let at = self.local_addr(i); + if self.maybe_unbound[i as usize] && !self.bound[i as usize] { + let t = self.tag_at(at); + let unbound = + self.b + .ins() + .icmp_imm(IntCC::Equal, t, i64::from(self.tags.unbound)); + self.branch_out(unbound, declined); + } + at + } + Arg::Const(c) => self.const_addr(c), + // A scalar in a slot above the result's. + Arg::Small(v) => { + let at = self.slot_addr(slot + 2 + j); + self.write_tag(at, self.tags.int); + let v = self.b.ins().iconst(types::I64, i64::from(v)); + self.b.ins().store(FLAGS, v, at, 8); + at + } + }; + addrs.push(at); + } + // (The receiver leaves after the kernel runs: one whose release + // could run code takes the general path.) + let keep = self + .call(h_droppable as *const () as usize, &[recv], true) + .expect("returns"); + self.branch_out(keep, declined); + let null = self.b.ins().iconst(self.ptr, 0); + let a = addrs.first().copied().unwrap_or(null); + let b = addrs.get(1).copied().unwrap_or(null); + let fp = self.b.ins().iconst(self.ptr, Rc::as_ptr(&f) as i64); + self.held.push(f); + let out = self.slot_addr(slot + 1); let r = self - .call(h_global as *const () as usize, &[self.st, c], true) + .call(kernel as *const () as usize, &[out, recv, a, b, fp], true) + .expect("returns"); + self.kernel_status(r, declined, call_pc); + // Ran: the receiver released and the result moved into its slot, + // as after the `CALL`. + let recv = self.slot_addr(slot); + let out = self.slot_addr(slot + 1); + let pcv = self.b.ins().iconst(types::I32, call_pc as i64); + let lenv = self.b.ins().iconst(types::I32, (slot + 1) as i64); + let r = self + .call( + h_kernel_result as *const () as usize, + &[self.st, recv, out, pcv, lenv], + true, + ) .expect("returns"); self.after_helper(r); - self.push(Item::Mem(s)); - self.set_last(pc); - true - } - - /// `LOAD_ATTR` with the method flag through [`h_method`]: the - /// method and its self slot in place of the receiver. - fn load_method(&mut self, pc: usize) -> bool { - if self.depth == 0 { - self.exit(INTERP, pc); - return false; - } - if let Some(r) = self.inline_method(pc) { - return r; - } - self.load_method_site(pc) + let (depth, last) = (self.depth, self.last_pc); + self.depth = slot; + self.push(Item::Mem(slot)); + self.set_last(call_pc); + self.goto(call_pc + 1); + self.depth = depth; + self.last_pc = last; + self.vs.clear(); + self.b.switch_to_block(declined); } /// `LOAD_ATTR` with the method flag at `pc` through [`h_method`]. @@ -21757,6 +30449,8 @@ impl<'a> Lower<'a> { own: (0, 0, 0), desc: None, desc_miss: 0, + type_attr: None, + stream: None, }); let c = self .b @@ -21807,7 +30501,7 @@ impl<'a> Lower<'a> { let ver = self .b .ins() - .load(types::I64, FLAGS, cls, l.type_attr_version); + .load(types::I64, FLAGS, cls, inline::type_bind_version(&l)); let want = self.b.ins().load(types::I64, FLAGS, c, MC_VER); let flag = self.b.ins().iconst(ptr, l.cells_unguarded as i64); let unguarded = self.b.ins().uload8(types::I64, FLAGS, flag, 0); @@ -21951,6 +30645,69 @@ impl<'a> Lower<'a> { true } + /// [`Self::field_store_in_line`]'s replacement of the value at `place` + /// (an instance's laid-out value, `inst` the instance) by the one at + /// `value`, going on to `done`: the value there now a scalar or a heap + /// one another owner keeps (not an unset one), and the new one a + /// scalar or the instance tracked; anything else to `helper`, + /// untouched. (The release gates were checked clear.) + fn replace_field_in_line( + &mut self, + place: Value, + value: Value, + inst: Value, + deferred_at: i32, + done: Block, + helper: Block, + ) { + let old = self.tag_at(place); + let unset = self + .b + .ins() + .icmp_imm(IntCC::Equal, old, i64::from(self.tags.unbound)); + self.branch_out(unset, helper); + let plain_old = self.is_scalar(old); + let heap = self.b.create_block(); + let checked = self.b.create_block(); + self.b.ins().brif(plain_old, checked, &[], heap, &[]); + self.b.switch_to_block(heap); + let word = self.b.ins().load(self.ptr, FLAGS, place, 8); + let n = self.b.ins().load(types::I64, FLAGS, word, 0); + let last = self.b.ins().icmp_imm(IntCC::SignedLessThanOrEqual, n, 1); + self.branch_out(last, helper); + self.b.ins().jump(checked, &[]); + self.b.switch_to_block(checked); + let new = self.tag_at(value); + let atomic_new = self.is_atomic(new); + let deferred = self.b.ins().uload8(types::I32, FLAGS, inst, deferred_at); + let tracked = self.b.ins().icmp_imm(IntCC::Equal, deferred, 0); + let ok = self.b.ins().bor(atomic_new, tracked); + let barrier = self.b.ins().icmp_imm(IntCC::Equal, ok, 0); + self.branch_out(barrier, helper); + self.release_checked_old(Some(plain_old), place); + self.copy16(place, value); + self.b.ins().jump(done, &[]); + } + + /// The plain decrement [`Self::field_store_in_line`] checked for the + /// heap value at `place` (`plain_old` its scalar test), if it isn't a + /// scalar. + fn release_checked_old(&mut self, plain_old: Option, place: Value) { + let Some(plain_old) = plain_old else { + return; + }; + let heap = self.b.create_block(); + let done = self.b.create_block(); + self.b.ins().brif(plain_old, done, &[], heap, &[]); + self.b.switch_to_block(heap); + let word = self.b.ins().load(self.ptr, FLAGS, place, 8); + let n = self.b.ins().load(types::I64, FLAGS, word, 0); + let n = self.b.ins().iadd_imm(n, -1); + self.b.ins().store(FLAGS, n, word, 0); + self.b.ins().jump(done, &[]); + self.b.switch_to_block(done); + } + /// `STORE_ATTR` at `pc` of the value at `value` into the instance at /// `recv` (a local's slot, or with `release_recv` the stack's, whose /// reference then goes), in line when the site settled on one field of @@ -22009,6 +30766,22 @@ impl<'a> Lower<'a> { // The next value of values laid out over the class's names, // with room for it, of an instance with no native body. inline::FieldMemo::Split { block, len } if append => { + // (Already there, from an earlier pass over the same + // instances: replaced in place, as a replacing site's.) + if !release_recv && !cfg!(debug_assertions) { + let present = + self.b + .ins() + .icmp_imm(IntCC::UnsignedGreaterThan, len, i64::from(idx)); + let replace = self.b.create_block(); + let add = self.b.create_block(); + self.b.ins().brif(present, replace, &[], add, &[]); + self.b.switch_to_block(replace); + let off = i64::from(idx) * 16 + i64::from(l.split_values); + let place = self.b.ins().iadd_imm(block, off); + self.replace_field_in_line(place, value, inst, deferred_at, done, helper); + self.b.switch_to_block(add); + } let cap = self.b.ins().uload32(FLAGS, block, l.split_cap); let body = self.b.ins().uload8(types::I64, FLAGS, inst, l.inst_c_body); let next = self.b.ins().icmp_imm(IntCC::NotEqual, len, i64::from(idx)); @@ -22030,29 +30803,60 @@ impl<'a> Lower<'a> { } memo => (self.field_place(memo, idx, helper), None), }; - if grown.is_none() { + // A heap value there now goes by a plain decrement (another owner + // keeping it, no release gate): checked here, before anything is + // written, and given up as the new value moves in. + let heap_old = if grown.is_none() && !cfg!(debug_assertions) { let old = self.tag_at(place); let plain_old = self.is_scalar(old); - let held = self.b.ins().icmp_imm(IntCC::Equal, plain_old, 0); + let heap = self.b.create_block(); + let checked = self.b.create_block(); + self.b.ins().brif(plain_old, checked, &[], heap, &[]); + self.b.switch_to_block(heap); + let word = self.b.ins().load(ptr, FLAGS, place, 8); + let n = self.b.ins().load(types::I64, FLAGS, word, 0); + let last = self.b.ins().icmp_imm(IntCC::SignedLessThanOrEqual, n, 1); + let held = self.b.ins().bor(last, gates); self.branch_out(held, helper); - } + self.b.ins().jump(checked, &[]); + self.b.switch_to_block(checked); + Some(plain_old) + } else { + if grown.is_none() { + let old = self.tag_at(place); + let plain_old = self.is_scalar(old); + let held = self.b.ins().icmp_imm(IntCC::Equal, plain_old, 0); + self.branch_out(held, helper); + } + None + }; let new = self.tag_at(value); - let plain_new = self.is_scalar(new); + let atomic_new = self.is_atomic(new); let deferred = self.b.ins().uload8(types::I32, FLAGS, inst, deferred_at); let tracked = self.b.ins().icmp_imm(IntCC::Equal, deferred, 0); - let ok = self.b.ins().bor(plain_new, tracked); - let barrier = self.b.ins().icmp_imm(IntCC::Equal, ok, 0); - self.branch_out(barrier, helper); + let ok = self.b.ins().bor(atomic_new, tracked); + // The write barrier: a container stored into an instance the + // collector doesn't track yet tracks it first (`h_track_instance`). + let barrier = self.b.create_block(); + let stored = self.b.create_block(); + self.b.ins().brif(ok, stored, &[], barrier, &[]); + self.b.set_cold_block(barrier); + self.b.switch_to_block(barrier); + self.call(h_track_instance as *const () as usize, &[recv], false); + self.b.ins().jump(stored, &[]); + self.b.switch_to_block(stored); if release_recv { // The receiver's reference goes by a plain decrement: another // owner holds the instance. let n = self.b.ins().load(types::I64, FLAGS, inst, 0); let last = self.b.ins().icmp_imm(IntCC::SignedLessThanOrEqual, n, 1); self.branch_out(last, helper); + self.release_checked_old(heap_old, place); self.copy16(place, value); let n = self.b.ins().iadd_imm(n, -1); self.b.ins().store(FLAGS, n, inst, 0); } else { + self.release_checked_old(heap_old, place); self.copy16(place, value); } if let Some(block) = grown { @@ -22085,13 +30889,32 @@ impl<'a> Lower<'a> { self.b.switch_to_block(tried); let code = self.code_ptr(); let rel = self.b.ins().iconst(types::I64, i64::from(release_recv)); + // The store's direct-call cache (see `setter_call`), but in a body + // inlined into its caller's code, whose leaving takes the exit. + let inlined = self.inlining(); + let site_at = if inlined { + self.b.ins().iconst(self.ptr, 0) + } else { + let site: Box = Box::default(); + let at = self + .b + .ins() + .iconst(self.ptr, std::ptr::from_ref::(&site) as i64); + self.direct_sites.push(site); + at + }; let r = self .call( h_setter_store as *const () as usize, - &[self.st, code, store_pc, recv, value, rel], + &[self.st, code, store_pc, recv, value, rel, site_at], true, ) .expect("returns"); + if !inlined { + // A direct call that raised or left the rest to the core loop. + let left = self.b.ins().icmp_imm(IntCC::UnsignedGreaterThan, r, 1); + self.after_helper_if(left, r); + } self.b.ins().brif(r, out, &[], done, &[]); self.b.switch_to_block(done); } @@ -22104,12 +30927,24 @@ impl<'a> Lower<'a> { Item::Mem(s) => (h_truth_stack as *const () as usize, 0, s), _ => unreachable!("a local or a stack value"), }; + // An instance's Python `__bool__` is called directly where nothing + // below the value is virtual (see `truth_call`). + let direct = if !self.inlining() && self.vs.iter().all(|i| matches!(i, Item::Mem(_))) { + let d: Box = Box::default(); + let at = std::ptr::from_ref::(&d) as usize; + self.direct_sites.push(d); + at + } else { + 0 + }; let site = Box::new(TruthSite { ver: std::cell::Cell::new(0), + native: std::cell::Cell::new((0, crate::NativeTruthPlan::NONE)), pc: pc as u32, slot: slot as u32, local, last: self.last_pc.map_or(NO_LAST, |l| l as u32), + direct, }); let c = self .b @@ -22407,8 +31242,10 @@ impl<'a> Lower<'a> { /// The `CALL` at `pc` of `argc` arguments, straight to the callee's /// native code (see [`records`]) when the callee is a function with a - /// direct entry. The block its status goes to, which takes it as a - /// parameter; lowering goes on for anything else. + /// direct entry, or a class whose construction runs a framed + /// `__init__` with one (see [`records::ctor_enter`]). The block its + /// status goes to, which takes it as a parameter; lowering goes on for + /// anything else. fn direct_native_call(&mut self, pc: usize, argc: usize) -> Block { let joined = self.b.create_block(); self.b.append_block_param(joined, types::I32); @@ -22416,6 +31253,18 @@ impl<'a> Lower<'a> { let slow = self.b.create_block(); let start = self.depth - argc - 2; let callee = self.slot_addr(start); + // A class goes to its own helper, a function's stays lean. + let tag = self.tag_at(callee); + let is_class = self + .b + .ins() + .icmp_imm(IntCC::Equal, tag, i64::from(self.tags.class)); + let class_b = self.b.create_block(); + let other_b = self.b.create_block(); + let got = self.b.create_block(); + self.b.append_block_param(got, self.ptr); + self.b.append_block_param(got, self.ptr); + self.b.ins().brif(is_class, class_b, &[], other_b, &[]); let sig = *self.enter_sig.get_or_insert_with(|| { let conv = records::ENTER_CONV.unwrap_or(self.b.func.signature.call_conv); let mut sig = Signature::new(conv); @@ -22426,19 +31275,38 @@ impl<'a> Lower<'a> { sig.returns.push(AbiParam::new(self.ptr)); self.b.import_signature(sig) }); - let helper = self.b.ins().iconst( - self.ptr, - records::h_direct_enter_regs as *const () as usize as i64, - ); - let call = self.b.ins().iconst( - types::I64, - records::CallAt::new(pc, start, argc, self.last_pc).bits(), - ); - let inst = self - .b - .ins() - .call_indirect(sig, helper, &[self.st, callee, call]); - let (cst, entry) = (self.b.inst_results(inst)[0], self.b.inst_results(inst)[1]); + let call_bits = records::CallAt::new(pc, start, argc, self.last_pc).bits(); + for (block, helper) in [ + (other_b, records::h_direct_enter_regs as *const () as usize), + (class_b, records::ctor_enter_regs as *const () as usize), + ] { + self.b.switch_to_block(block); + let helper = self.b.ins().iconst(self.ptr, helper as i64); + let call = self.b.ins().iconst(types::I64, call_bits); + let inst = self + .b + .ins() + .call_indirect(sig, helper, &[self.st, callee, call]); + let (cst, entry) = (self.b.inst_results(inst)[0], self.b.inst_results(inst)[1]); + if block == class_b { + // A construction finished in the helper (see + // `records::CTOR_DONE`): the instance in the class's slot. + let done = self + .b + .ins() + .icmp_imm(IntCC::Equal, cst, records::CTOR_DONE_ST as i64); + let fin = self.b.create_block(); + let cont = self.b.create_block(); + self.b.ins().brif(done, fin, &[], cont, &[]); + self.b.switch_to_block(fin); + let zero = self.b.ins().iconst(types::I32, 0); + self.b.ins().jump(joined, &[zero.into()]); + self.b.switch_to_block(cont); + } + self.b.ins().jump(got, &[cst.into(), entry.into()]); + } + self.b.switch_to_block(got); + let (cst, entry) = (self.b.block_params(got)[0], self.b.block_params(got)[1]); self.b.ins().brif(cst, run, &[], slow, &[]); self.b.switch_to_block(run); let sig = self.sig(&[self.ptr], Some(types::I32)); @@ -22487,7 +31355,17 @@ impl<'a> Lower<'a> { use crate::LeafKind; let Some((f, kind, via_call)) = crate::call_site_builtin(self.ext, pc) else { let cls = crate::call_site_type(self.ext, pc)?; - let site = Box::new(TypeSite { cls, argc }); + // `str(obj)` calls a Python `__str__` directly (see `str_call`). + let direct = + if argc == 1 && Rc::ptr_eq(&cls, &crate::builtin_types::builtin_types().str_) { + let d: Box = Box::default(); + let at = std::ptr::from_ref::(&d) as usize; + self.direct_sites.push(d); + at + } else { + 0 + }; + let site = Box::new(TypeSite { cls, argc, direct }); let at = std::ptr::from_ref::(&site).cast_mut().cast(); self.type_sites.push(site); return Some((h_site_type as *const () as usize, at)); @@ -22532,6 +31410,33 @@ impl<'a> Lower<'a> { } _ => None, }; + // `len(obj)`, `repr(obj)`, `abs(obj)`, `iter(obj)`, `format(obj)`, + // `hash(obj)` and `next(obj)` call a Python `__len__`, `__repr__`, + // `__abs__`, `__iter__`, `__str__` (for `object.__format__`), + // `__hash__` or `__next__` directly (see `len_call`). + // `hasattr(obj, name)` and `getattr(obj, name, default)` call a + // Python `__getattr__` directly (see `attr_probe_call`). + let probe = !f.binds_instance + && match kind { + Some(LeafKind::Fast(_)) => f.name == "hasattr" && argc == 2, + Some(LeafKind::GetAttr) => f.name == "getattr" && argc == 3, + _ => false, + }; + let direct = if probe + || argc == 1 + && (matches!(kind, Some(LeafKind::Len)) + || (matches!(kind, Some(LeafKind::Fast(_))) + && !f.binds_instance + && matches!(f.name, "repr" | "abs" | "iter" | "format" | "hash" | "next")) + || f.name == METHODCALLER_CALL) + { + let d: Box = Box::default(); + let at = std::ptr::from_ref::(&d) as usize; + self.direct_sites.push(d); + at + } else { + 0 + }; let site = Box::new(BuiltinSite { f: Rc::as_ptr(&f), argc, @@ -22540,6 +31445,7 @@ impl<'a> Lower<'a> { recv_tag, via_call, lane, + direct, }); self.held.push(f); let at = std::ptr::from_ref::(&site).cast_mut().cast(); @@ -22705,6 +31611,31 @@ impl<'a> Lower<'a> { } /// `BUILD_TUPLE n` / `BUILD_LIST n` through [`h_build`]. + /// `LIST_EXTEND 1` and the `LIST_TO_TUPLE` after it through + /// [`h_extend_to_tuple`], continuing past both; the unfused + /// `LIST_EXTEND` when it declines. + fn extend_to_tuple(&mut self, pc: usize) -> bool { + if self.depth < 2 { + return self.container(pc); + } + self.flush(); + let at = self.slot_addr(self.depth - 2); + let r = self + .call(h_extend_to_tuple as *const () as usize, &[at], true) + .expect("returns"); + let fused = self.b.create_block(); + let unfused = self.b.create_block(); + self.b.ins().brif(r, unfused, &[], fused, &[]); + self.b.switch_to_block(fused); + let depth = self.depth; + self.depth -= 1; + self.set_last(pc + 1); + self.goto(pc + 2); + self.depth = depth; + self.b.switch_to_block(unfused); + self.container(pc) + } + fn build(&mut self, pc: usize, n: usize, list: bool) -> bool { if n > self.depth { self.exit(INTERP, pc); @@ -22713,7 +31644,13 @@ impl<'a> Lower<'a> { self.flush(); let at = self.slot_addr(self.depth - n); let nv = self.b.ins().iconst(types::I64, n as i64); - let lv = self.b.ins().iconst(types::I32, i64::from(list)); + // (`2`: a call's spread arguments, a list left untracked.) + let kind = match list { + true if spread_list_at(self.code, pc) => 2, + true => 1, + false => 0, + }; + let lv = self.b.ins().iconst(types::I32, kind); let r = self .call(h_build as *const () as usize, &[self.st, at, nv, lv], true) .expect("returns"); @@ -22728,10 +31665,11 @@ impl<'a> Lower<'a> { /// f-string's pieces) through [`h_fstring`], which runs the core /// loop's arm; the core loop takes any other shape. fn fstring_op(&mut self, pc: usize, op: OpCode, arg: u32) -> bool { - let n = if op == OpCode::BuildString { - arg as usize - } else { - 1 + let n = match op { + OpCode::BuildString => arg as usize, + // (The value and its spec.) + OpCode::FormatValue if arg & 4 != 0 => 2, + _ => 1, }; if n == 0 || n > self.depth || !fstring_native(op, arg) { self.exit(INTERP, pc); @@ -22741,6 +31679,7 @@ impl<'a> Lower<'a> { let at = self.slot_addr(self.depth - n); let kind = match op { OpCode::ConvertValue => FSTRING_CONVERT | u64::from(arg) << 8, + OpCode::FormatValue if arg & 4 != 0 => FSTRING_FORMAT_SPEC, OpCode::FormatValue => FSTRING_FORMAT, _ => FSTRING_JOIN | (n as u64) << 8, }; @@ -22749,7 +31688,47 @@ impl<'a> Lower<'a> { .call(h_fstring as *const () as usize, &[at, kv], true) .expect("returns"); let out = self.exit_with(pc, &[], INTERP); - self.branch_out(r, out); + if matches!(op, OpCode::FormatValue | OpCode::ConvertValue) && !self.inlining() { + // An instance's Python `__format__`, `__str__` or `__repr__`, + // called directly (see `h_format_dunder`, `h_convert_dunder`). + let dunder = self.b.create_block(); + let done = self.b.create_block(); + self.b.ins().brif(r, dunder, &[], done, &[]); + self.b.set_cold_block(dunder); + self.b.switch_to_block(dunder); + let site: Box = Box::default(); + let site_at = self + .b + .ins() + .iconst(self.ptr, std::ptr::from_ref::(&site) as i64); + self.direct_sites.push(site); + let code = self.code_ptr(); + let pcv = self.b.ins().iconst(types::I64, pc as i64); + let slotv = self.b.ins().iconst(types::I64, (self.depth - n) as i64); + let (helper, last) = if op == OpCode::ConvertValue { + (h_convert_dunder as *const () as usize, i64::from(arg & 3)) + } else { + (h_format_dunder as *const () as usize, i64::from(n == 2)) + }; + let last = self.b.ins().iconst(types::I64, last); + let d = self + .call(helper, &[self.st, code, pcv, slotv, site_at, last], true) + .expect("returns"); + let other = self.b.create_block(); + self.b.ins().brif(d, other, &[], done, &[]); + self.b.switch_to_block(other); + let no = self + .b + .ins() + .icmp_imm(IntCC::Equal, d, i64::from(CALL_DECLINED)); + let leave = self.b.create_block(); + self.b.ins().brif(no, out, &[], leave, &[]); + self.b.switch_to_block(leave); + self.leave(d); + self.b.switch_to_block(done); + } else { + self.branch_out(r, out); + } self.depth = self.depth - n + 1; self.set_last(pc); true @@ -22781,11 +31760,30 @@ impl<'a> Lower<'a> { self.exit(INTERP, pc); return false; } + // `{**d, "k": v}`: the pairs merged into the dict below at once + // (the core loop runs both instructions when the helper declines). + if fused_map_update_at(self.code, pc) + && 2 * n < self.depth + && self.starts.get(pc + 2).copied().unwrap_or(false) + { + self.flush(); + let at = self.slot_addr(self.depth - 2 * n - 1); + let nv = self.b.ins().iconst(types::I64, n as i64); + let r = self + .call(h_map_into as *const () as usize, &[at, nv], true) + .expect("returns"); + let out = self.exit_with(pc, &[], INTERP); + self.branch_out(r, out); + self.depth -= 2 * n; + self.set_last(pc + 1); + self.goto(pc + 2); + return false; + } self.flush(); let at = self.slot_addr(self.depth - 2 * n); let nv = self.b.ins().iconst(types::I64, n as i64); let r = self - .call(h_build_map as *const () as usize, &[at, nv], true) + .call(h_build_map as *const () as usize, &[self.st, at, nv], true) .expect("returns"); let out = self.exit_with(pc, &[], INTERP); self.branch_out(r, out); @@ -22794,10 +31792,58 @@ impl<'a> Lower<'a> { true } + /// [`Self::unary`] at a site that has run on instances, through + /// [`h_unary_dunder`] (anything it declines leaves for the core loop). + fn unary_dunder(&mut self, pc: usize, item: Item) -> bool { + self.flush(); + let slot = self.depth; + self.materialize(item, slot); + let code = self.code_ptr(); + let pcv = self.b.ins().iconst(types::I64, pc as i64); + let slotv = self.b.ins().iconst(types::I64, slot as i64); + let site: Box = Box::default(); + let site_at = self + .b + .ins() + .iconst(self.ptr, std::ptr::from_ref::(&site) as i64); + self.direct_sites.push(site); + let d = self + .call( + h_unary_dunder as *const () as usize, + &[self.st, code, pcv, slotv, site_at], + true, + ) + .expect("returns"); + let out = self.exit_with(pc, &[Item::Mem(slot)], INTERP); + let other = self.b.create_block(); + let done = self.b.create_block(); + self.b.ins().brif(d, other, &[], done, &[]); + self.b.set_cold_block(other); + self.b.switch_to_block(other); + let no = self + .b + .ins() + .icmp_imm(IntCC::Equal, d, i64::from(CALL_DECLINED)); + let leave = self.b.create_block(); + self.b.ins().brif(no, out, &[], leave, &[]); + self.b.switch_to_block(leave); + self.leave(d); + self.b.switch_to_block(done); + self.push(Item::Mem(slot)); + self.set_last(pc); + self.check_released(pc + 1); + true + } + /// `UNARY_OP` of a scalar (the leaf arm's shapes): `not` of a `bool`, /// `int` or `None`; `-`, `+` of an `int` or `float`; `~` of an `int`. fn unary(&mut self, pc: usize, arg: u32) -> bool { let item = self.pop(); + // A site that has run on instances: the operand on the stack, where + // its operator method's direct call takes it (see `h_unary_dunder`). + if arg != 2 && !self.inlining() && crate::instance_site(self.ext, pc) { + return self.unary_dunder(pc, item); + } let Some(o) = self.operand(item) else { self.push(item); self.exit(INTERP, pc); diff --git a/crates/weavepy-vm/src/frame_jit/inline.rs b/crates/weavepy-vm/src/frame_jit/inline.rs index 6b8878027..2859a2794 100644 --- a/crates/weavepy-vm/src/frame_jit/inline.rs +++ b/crates/weavepy-vm/src/frame_jit/inline.rs @@ -51,11 +51,11 @@ use super::{ attr_hit, attr_miss, block_starts, call_kernel_in_place, call_leaf_in_place, ctor_store_init, direct_call, droppable, field_hit, h_call_kw, h_for_iter, h_stack_store_attr, kernel_for, left, left_marked, maybe_unbound_locals, never_ran_blocks, plain_release, settle, stats, truth_at, - type_of_call, AttrSite, BinOpKind, Block, BuiltinSite, Cell, CodeConstObjects, CodeObject, - DirectSite, FieldSlot, GlobalCache, IntCC, Interpreter, Item, Lower, Object, OpCode, - PyIterator, Rc, SlotWord, State, TruthSite, Value, CALL_DECLINED, DICT_STAMP, EXIT_LAST_SHIFT, - EXIT_PC_SHIFT, FLAGS, INTERP, LEFT_MARKED, MARKED, NO_LAST, RAISED, RELOAD, S_LAST, S_SNAP, - S_SW, + tuple_stamp_hit, type_of_call, AttrSite, BinOpKind, Block, BuiltinSite, Cell, CodeConstObjects, + CodeObject, DirectSite, FieldSlot, GlobalCache, IntCC, Interpreter, Item, Lower, Object, + OpCode, PyIterator, Rc, SlotWord, State, TruthSite, Value, CALL_DECLINED, DICT_STAMP, + EXIT_LAST_SHIFT, EXIT_PC_SHIFT, FLAGS, INTERP, LEFT_MARKED, MARKED, NO_LAST, RAISED, RELOAD, + S_LAST, S_SNAP, S_SW, }; use super::{fill_method_cache, MethodCache, MC_VER}; use weavepy_codegen::types; @@ -214,7 +214,8 @@ pub(super) struct Plan { classes: usize, } -/// A `BINARY_OP` site's guard on the operands (see `dunder_note`). +/// A `BINARY_OP` site's guard on the operands (see `dunder_note`), or a +/// `BINARY_SUBSCR`'s on its container (see `getitem_note`). #[derive(Clone, Copy)] struct Dunder { ver: u64, @@ -222,6 +223,14 @@ struct Dunder { arg: u32, } +impl Dunder { + /// Whether it's a subscript's `__getitem__` (any key, and its result + /// taken as it is). + fn subscr(self) -> bool { + self.right == Some(crate::DUNDER_ANY_KEY) + } +} + /// The `property` getter of the `LOAD_ATTR` at `pc`, to lower in line. fn getter_plan( ext: &CodeConstObjects, @@ -542,26 +551,34 @@ fn callees_at( depths: &[i64], pc: usize, ) -> Vec<(Rc, bool, usize)> { - let mut found = crate::call_site_callees(ext, pc); - let start = call_start(code, ext, pc, depths[pc]); - if let Some(attr) = call_method_pc(code, depths, pc, start) { - found.extend( - crate::method_site_callees(ext, attr) - .into_iter() - .map(|f| (f, true)), - ); - } + // (A method the call site recorded too is one of the method site's + // classes, not one more.) let mut seen: Vec<(Rc, bool, usize)> = Vec::new(); - for (f, has_self) in found { + for (f, has_self) in crate::call_site_callees(ext, pc) { let c = f.code(); - match seen - .iter_mut() - .find(|(g, s, _)| *s == has_self && Rc::ptr_eq(&g.code(), &c)) + if !seen + .iter() + .any(|(g, s, _)| *s == has_self && Rc::ptr_eq(&g.code(), &c)) { - Some(entry) => entry.2 += 1, - None => seen.push((f, has_self, 1)), + seen.push((f, has_self, 0)); + } + } + let start = call_start(code, ext, pc, depths[pc]); + if let Some(attr) = call_method_pc(code, depths, pc, start) { + for (f, classes) in crate::method_site_callees(ext, attr) { + let c = f.code(); + match seen + .iter_mut() + .find(|(g, s, _)| *s && Rc::ptr_eq(&g.code(), &c)) + { + Some(entry) => entry.2 += classes, + None => seen.push((f, true, classes)), + } } } + for entry in &mut seen { + entry.2 = entry.2.max(1); + } seen } @@ -591,7 +608,10 @@ pub(super) fn plan( // (A generator's body takes its calls in line, not a property's // getter or an operator's method.) let plain = !code.is_generator; - (plain && i.op == OpCode::BinaryOp && depths[pc] >= 2 && crate::dunder_known(ext, pc)) + (plain + && matches!(i.op, OpCode::BinaryOp | OpCode::BinarySubscr) + && depths[pc] >= 2 + && crate::dunder_known(ext, pc)) || (plain && i.op == OpCode::LoadAttr && depths[pc] >= 1 @@ -627,7 +647,7 @@ pub(super) fn plan( } continue; } - if i.op == OpCode::BinaryOp { + if matches!(i.op, OpCode::BinaryOp | OpCode::BinarySubscr) { match dunder_plan(code, ext, pc, &mut path, &mut left) { Ok(p) => { note(code, pc, "inlined", &p.code.qualname); @@ -845,8 +865,11 @@ fn admit( return Err("no dispatch"); } // A callee that has barely run doesn't pay for its compile time here, and - // shows little of what it does. - if !crate::callee_warm(code, ext) { + // shows little of what it does. (A callee of a callee lowered in line, + // `path` holding the root and that caller, counts once the frameless + // evaluator has run it: a warm helper's own helper runs there, nested + // in its caller's evaluation, and leaves no other count.) + if !crate::callee_warm(code, ext) && !(path.len() > 1 && crate::leaf_plan_built(ext)) { return Err("not warm"); } // A callee whose loops tier 2 compiled and runs better than this @@ -1515,7 +1538,10 @@ impl<'a> Lower<'a> { for plan in plans.iter().filter(|p| binds_in_place(p, &items, 0)) { let next = self.b.create_block(); let mut caches = Vec::new(); - for _ in 0..plan.classes.min(2) { + // (One to spare at a site that has seen a single class: a + // second class arriving later then costs one miss, not one + // per call.) + for _ in 0..plan.classes.clamp(2, METHOD_GUARD_CLASSES) { let mut cache: Box = Box::default(); caches.push(std::ptr::from_mut::(&mut cache)); self.method_caches.push(cache); @@ -1577,7 +1603,11 @@ impl<'a> Lower<'a> { /// The guards of a fused method call: the receiver an instance of a class /// one of the caches read, which holds no dictionary and no value that /// could shadow the method (a mismatch of either kind goes to `slow`). - /// The values to test: the site's being off, and a value false. + /// The values to test: the site's being off, and a value false. (A body + /// has a cache for each class its site recorded, up to + /// [`METHOD_GUARD_CLASSES`]: with fewer than the site's classes, the + /// last cache changes hands on every miss, and each miss is a method + /// load and an ordinary call.) fn method_guards( &mut self, recv: Item, @@ -1601,7 +1631,7 @@ impl<'a> Lower<'a> { let ver = self .b .ins() - .load(types::I64, FLAGS, cls, l.type_attr_version); + .load(types::I64, FLAGS, cls, type_bind_version(&l)); let c = self.b.ins().iconst(ptr, caches[0]); let want = self.b.ins().load(types::I64, FLAGS, c, MC_VER); let lazy = self.b.ins().load(ptr, FLAGS, inst, l.inst_dict_lazy); @@ -1613,17 +1643,30 @@ impl<'a> Lower<'a> { let other = self.b.ins().icmp_imm(IntCC::NotEqual, other, 0); let ckeys = self.b.ins().load(types::I64, FLAGS, c, MC_KEYS); let before = self.b.ins().uload32(FLAGS, c, MC_BEFORE); - let (stale, ckeys, before) = if let Some(&second) = caches.get(1) { - let c2 = self.b.ins().iconst(ptr, second); + let (stale, ckeys, before) = if caches.len() > 1 { + // (The first cache that reads the version decides: the walk + // runs from the last to the first.) + let (&last, rest) = caches[1..].split_last().expect("more than one"); + let c2 = self.b.ins().iconst(ptr, last); let want2 = self.b.ins().load(types::I64, FLAGS, c2, MC_VER); - let keys2 = self.b.ins().load(types::I64, FLAGS, c2, MC_KEYS); - let before2 = self.b.ins().uload32(FLAGS, c2, MC_BEFORE); + let mut hit = self.b.ins().icmp(IntCC::Equal, ver, want2); + let mut keys_at = self.b.ins().load(types::I64, FLAGS, c2, MC_KEYS); + let mut before_at = self.b.ins().uload32(FLAGS, c2, MC_BEFORE); + for &other in rest.iter().rev() { + let c2 = self.b.ins().iconst(ptr, other); + let want2 = self.b.ins().load(types::I64, FLAGS, c2, MC_VER); + let keys2 = self.b.ins().load(types::I64, FLAGS, c2, MC_KEYS); + let before2 = self.b.ins().uload32(FLAGS, c2, MC_BEFORE); + let same = self.b.ins().icmp(IntCC::Equal, ver, want2); + keys_at = self.b.ins().select(same, keys2, keys_at); + before_at = self.b.ins().select(same, before2, before_at); + hit = self.b.ins().bor(hit, same); + } let first = self.b.ins().icmp(IntCC::Equal, ver, want); - let second = self.b.ins().icmp(IntCC::Equal, ver, want2); - let hit = self.b.ins().bor(first, second); + let hit = self.b.ins().bor(hit, first); let stale = self.b.ins().bxor_imm(hit, 1); - let ckeys = self.b.ins().select(first, ckeys, keys2); - let before = self.b.ins().select(first, before, before2); + let ckeys = self.b.ins().select(first, ckeys, keys_at); + let before = self.b.ins().select(first, before, before_at); (stale, ckeys, before) } else { (self.b.ins().icmp(IntCC::NotEqual, ver, want), ckeys, before) @@ -1707,8 +1750,12 @@ impl<'a> Lower<'a> { base, nlocals, borrowed: Vec::new(), - method: no_callable - .then(|| (borrowed_function(&plan.func), plan.dunder.map(|d| d.arg))), + method: no_callable.then(|| { + ( + borrowed_function(&plan.func), + plan.dunder.filter(|d| !d.subscr()).map(|d| d.arg), + ) + }), }); let site_at = std::ptr::from_ref::(&site) as i64; let method_at = site @@ -2189,6 +2236,8 @@ impl<'a> Lower<'a> { let key = self.b.ins().load(types::I64, FLAGS, sv, IS_KEY); let other = self.b.ins().icmp(IntCC::NotEqual, ver, key); let wrong = match (d.right, args[1]) { + // (A subscript's key, any value.) + _ if d.subscr() => self.b.ins().iconst(types::I8, 0), (Some(t), Item::Int(_)) => self .b .ins() @@ -2275,6 +2324,45 @@ impl<'a> Lower<'a> { true } + /// `BINARY_SUBSCR` at `pc` of the Python `__getitem__` `plans` lowers + /// in line, as [`Self::inline_binop`] lowers an operator method: the + /// container's guard and the body, with the instruction's other shapes + /// for anything the guard doesn't take. + pub(super) fn inline_subscr(&mut self, pc: usize, plans: &'a [Plan]) -> bool { + let before = self.b.func.dfg.num_insts(); + let nested = self.inlining(); + let ki = self.pop(); + let ci = self.pop(); + let args = [ci, ki]; + self.flush(); + let start = self.depth; + let call_last = self.last_pc; + let join = self.b.create_block(); + let slow = self.b.create_block(); + self.inline_body(pc, &plans[0], &args, start, slow, join, None); + self.b.switch_to_block(slow); + self.b.set_cold_block(slow); + self.vs = args.to_vec(); + self.depth = start + 2; + self.last_pc = call_last; + // (The method called directly, as the site's ordinary lowering + // calls it, when the guard fails: a class whose version moves.) + if nested { + self.exit(INTERP, pc); + } else if self.subscr_ref(pc) || self.container(pc) { + self.flush(); + self.b.ins().jump(join, &[]); + } + self.b.switch_to_block(join); + self.vs.clear(); + self.depth = start + 1; + self.set_last(pc); + if !nested { + self.inline_ir += self.b.func.dfg.num_insts() - before; + } + true + } + /// The address of the running inlined body's function's `Object`. fn inline_callable(&mut self) -> Value { let f = self.inl.last().expect("in an inlined body"); @@ -2368,6 +2456,7 @@ impl<'a> Lower<'a> { let slot = self.depth; let cache: Box = Box::new(GlobalCache { code: std::ptr::from_ref(self.code) as u64, + ext: std::ptr::from_ref(self.ext) as u64, pc: pc as u32, len: slot as u64, last: self.last_pc.map_or(NO_LAST, |l| l as u32), @@ -2379,6 +2468,50 @@ impl<'a> Lower<'a> { .iconst(self.ptr, std::ptr::from_ref::(&cache) as i64); self.global_caches.push(cache); let callee = self.inline_callable(); + // `Cls.CONST`: the constant the attribute site's stamp holds, in one + // call; the global's value, and the attribute read below, when the + // stamp doesn't hold for it. + let attr = pc + 1; + if self.code.instructions.get(attr).map(|i| i.op) == Some(OpCode::LoadAttr) + && !self.starts.get(attr).copied().unwrap_or(true) + && self.ext.stamp_slot(attr).is_some() + && !crate::property_site(self.ext, attr) + && self.plan_at(attr).is_none() + { + // (The code's site table never moves once allocated.) + if let (Some(cache), Some(s)) = + (self.global_caches.last_mut(), self.ext.stamp_slot(attr)) + { + cache.attr_slot = std::ptr::from_ref(s) as u64; + } + let r = self + .call( + h_inline_global_attr as *const () as usize, + &[self.st, callee, c], + true, + ) + .expect("returns"); + let pending = self.b.ins().icmp_imm(IntCC::Equal, r, 1); + let read = self.b.create_block(); + let fused = self.b.create_block(); + let done = self.b.create_block(); + self.b.ins().brif(pending, read, &[], fused, &[]); + self.b.set_cold_block(read); + self.b.switch_to_block(fused); + let (vs, depth) = (self.vs.clone(), self.depth); + self.after_helper(r); + self.push(Item::Mem(slot)); + self.set_last(attr); + self.b.ins().jump(done, &[]); + self.b.switch_to_block(read); + self.vs = vs; + self.depth = depth; + self.load_attr_shared(attr, Item::Mem(slot)); + self.b.ins().jump(done, &[]); + self.b.switch_to_block(done); + self.skip_to = Some(attr); + return true; + } let r = self .call( h_inline_global as *const () as usize, @@ -2450,6 +2583,7 @@ impl<'a> Lower<'a> { // (An inlined body's declined call leaves through its caller's // paths.) lane: None, + direct: 0, }); self.held.push(f); let at = self @@ -2493,6 +2627,16 @@ impl<'a> Lower<'a> { } } +/// Where a class keeps [`crate::types::TypeObject::bind_version`], from +/// its pointer (measured as `layout`'s `type_attr_version` is): what a +/// [`MethodCache`] is keyed by. +pub(super) fn type_bind_version(l: &weavepy_jit::ObjLayout) -> i32 { + use crate::types::TypeObject; + let base = + l.type_attr_version as isize - std::mem::offset_of!(TypeObject, attr_version) as isize; + (base + std::mem::offset_of!(TypeObject, bind_version) as isize) as i32 +} + /// Where a class keeps [`crate::types::TypeObject::slot_layout_word`], /// from its pointer (measured as `layout`'s `type_attr_version` is). fn type_slot_layout(l: &weavepy_jit::ObjLayout) -> i32 { @@ -2862,6 +3006,10 @@ pub(super) unsafe extern "C" fn h_inline_store_attr( } } +/// The receiver classes a fused method call's body guards in line (see +/// `Lower::method_guards`): as many as a method site records. +const METHOD_GUARD_CLASSES: usize = 4; + /// A fused method call's slow path loaded the method at `callee`, its /// receiver above it: if it's one of the bodies' functions, called on an /// instance, the guards take the receiver's class from now on. @@ -2878,7 +3026,7 @@ unsafe extern "C" fn h_inline_method_note(callee: *const Object, notes: *const M return; }; let cls = inst.cls_raw(); - let ver = cls.attr_version.get(); + let ver = cls.bind_version.get(); let target = caches .iter() .find(|&&c| (*c).ver == 0 || (*c).ver == ver) @@ -2922,7 +3070,7 @@ unsafe extern "C" fn h_inline_global( && (c.builtins == 0 || (std::ptr::from_ref(&f.builtins).cast::().read() == c.builtins && stamp(c.bdata) == c.bstamp - && !(*(*st).interp).globals_missing_any.get())) + && !(*(*st).interp).globals_missing_gate())) { let v = &*(c.value as *const Object); (*st).stack.add(c.len as usize).write(crate::clone_hot(v)); @@ -2937,6 +3085,66 @@ unsafe extern "C" fn h_inline_global( } } +/// [`h_inline_global`] at a `LOAD_GLOBAL` its `LOAD_ATTR` follows: `0` the +/// constant the attribute site's stamp holds for the global, a class, at +/// its version (see `global_cls_attr`), past both; `1` the global's value +/// pushed, for the attribute read to follow; anything else a status, as +/// [`h_inline_global`]'s. +/// +/// # Safety +/// +/// As [`h_inline_global`]'s; the site's `attr_slot` is its `LOAD_ATTR`'s +/// stamp slot, in its code's site table. +#[allow(clippy::cast_ptr_alignment)] // (Word fields, at their offsets.) +unsafe extern "C" fn h_inline_global_attr( + st: *mut State, + callee: *const Object, + site: *mut GlobalCache, +) -> u32 { + // SAFETY: as `h_inline_global`'s. + unsafe { + let c = &*site; + if let Object::Function(f) = &*callee { + let stamp = |data: u64| { + (data as *const u8) + .add(DICT_STAMP as usize) + .cast::() + .read() + }; + let hit = std::ptr::from_ref(&f.globals).cast::().read() == c.globals + && stamp(c.gdata) == c.gstamp + && (c.builtins == 0 + || (std::ptr::from_ref(&f.builtins).cast::().read() == c.builtins + && stamp(c.bdata) == c.bstamp + && !(*(*st).interp).globals_missing_gate())); + if hit || inline_global_miss(st, f, site) { + let c = &*site; + let at = (*st).stack.add(c.len as usize); + let v = &*(c.value as *const Object); + if let Object::Type(cls) = v { + debug_assert!(c.attr_slot != 0, "a fused global site without its slot"); + if let Some(r) = + crate::class_attr_hit(&*(c.attr_slot as *const crate::StampSlot), cls) + { + if !hit { + // (The miss pushed the class.) + std::ptr::drop_in_place(at); + } + at.write(r); + return 0; + } + } + if hit { + at.write(crate::clone_hot(v)); + } + return 1; + } + } + let c = &*site; + left(st, c.pc, c.last, c.len as usize) + } +} + /// [`h_inline_global`] past the cached read, by name: a body that only ever /// ran in line or as a frameless leaf never filled the instruction's inline /// cache. Whether the value is in the site's slot. @@ -2967,7 +3175,7 @@ unsafe fn inline_global_miss( let b_stamp = (*bdict).mutation_stamp(); let (v, builtin) = match g.get_full(&probe) { Some((_, _, v)) => (v, false), - None if interp.globals_missing_any.get() => return false, + None if interp.globals_missing_gate() => return false, None => match b.get_full(&probe) { Some((_, _, v)) => (v, true), None => return false, @@ -3060,11 +3268,25 @@ pub(super) unsafe extern "C" fn h_inline_attr_local( (*st).stack.add(slot).write(crate::clone_hot(v)); return 0; } + if let Some(v) = tuple_stamp_hit(s, inst) { + (*st).stack.add(slot).write(v); + return 0; + } } if let Some(v) = attr_hit(s, &*at) { (*st).stack.add(slot).write(crate::clone_hot(v)); return 0; } + // A polymorphic site's other classes, ahead of the miss chain: an + // instance field the site's table places, or a `__slots__` member. + if let Object::Instance(inst) = &*at { + if let Some(v) = + super::field_hit_slow(s, inst).or_else(|| super::slot_field_resolve(s, inst)) + { + (*st).stack.add(slot).write(crate::clone_hot(v)); + return 0; + } + } let r = attr_miss(st, s, at, true); if r != CALL_DECLINED { return r; @@ -3074,6 +3296,34 @@ pub(super) unsafe extern "C" fn h_inline_attr_local( } } +/// [`h_inline_attr_local`] at a polymorphic site: an instance's split +/// field at the position one of the site's entries (its own, then the +/// code's shared slot) names for its class, straight off its split values +/// (none while its dict is published); anything else through +/// [`h_inline_attr_local`]. +/// +/// # Safety +/// +/// As [`h_inline_attr_local`]'s. +pub(super) unsafe extern "C" fn h_inline_attr_poly( + st: *mut State, + site: *const AttrSite, + at: *mut Object, +) -> u32 { + // SAFETY: as `h_inline_attr_local`'s; the site's field slot, when set, + // lives as long as its code. + unsafe { + let s = &*site; + if let Object::Instance(inst) = &*at { + if let Some(v) = super::poly_split_hit(s, inst) { + (*st).stack.add(s.slot as usize).write(crate::clone_hot(v)); + return 0; + } + } + h_inline_attr_local(st, site, at) + } +} + /// `CALL` (the `pc`th instruction, operands up a `len`-deep stack) in an /// inlined body, of the builtin `site` settled on: `0` the result in place, /// `RAISED` the operands released with the error in the state and its pc @@ -3089,8 +3339,16 @@ unsafe extern "C" fn h_inline_builtin( unsafe { let s = &mut *st; let site = &*site; - if site.kernel.is_some() && call_kernel_in_place(s, site, len as usize) { - return 0; + if site.kernel.is_some() { + match call_kernel_in_place(s, site, len as usize) { + 0 => return 0, + super::KERNEL_RAISED => { + if let Some(r) = super::kernel_raise_in_place(s, site, pc, len as usize) { + return r; + } + } + _ => {} + } } if site.kind.is_some_and(crate::LeafKind::runs_in_core) { if let Some(r) = call_leaf_in_place(s, site, pc, len as usize) { @@ -3149,20 +3407,15 @@ unsafe extern "C" fn h_inline_left(st: *mut State, site: *const InlineSite, r: u } } -/// An inlined body stops at `pc` with `depth` operands, its last instruction -/// `last` and the status `status`: its and its callers' activations built. -/// `RELOAD`, always. -unsafe fn leave_body( - st: &mut State, - site: *const InlineSite, - depth: usize, - pc: usize, - last: usize, - status: u32, -) -> u32 { - // SAFETY: the callers' contract. +/// The body at `site` leaves for the core loop: a site that keeps leaving +/// takes the ordinary call from now on. +/// +/// # Safety +/// +/// `site` is a live site. +unsafe fn note_exit(site: *const InlineSite) { + // SAFETY: the caller's contract. unsafe { - // A site that keeps leaving takes the ordinary call from now on. let root = root_site(site); let exits = root.exits.get().saturating_add(1); root.exits.set(exits); @@ -3176,6 +3429,23 @@ unsafe fn leave_body( ); } } + } +} + +/// An inlined body stops at `pc` with `depth` operands, its last instruction +/// `last` and the status `status`: its and its callers' activations built. +/// `RELOAD`, always. +unsafe fn leave_body( + st: &mut State, + site: *const InlineSite, + depth: usize, + pc: usize, + last: usize, + status: u32, +) -> u32 { + // SAFETY: the callers' contract. + unsafe { + note_exit(site); crate::burst_stats::note_call(crate::burst_stats::CALL_INLINE_EXIT); bind_levels(st, site, depth, pc, false); let sw = &mut *st.sw; @@ -3352,6 +3622,10 @@ pub(super) unsafe fn spill(st: &mut State) -> *mut crate::Frame { unsafe { let call = &*std::mem::replace(&mut st.inl_call, std::ptr::null()); st.inl_gone = true; + // (The body goes on in the core loop from here, as after any other + // exit: a callee that registers call after call, one that raises + // or catches, costs the site its place.) + note_exit(call.site); let count = call.start - (*call.site).base; bind_levels(st, call.site, count, call.pc + 1, true) } diff --git a/crates/weavepy-vm/src/frame_jit/records.rs b/crates/weavepy-vm/src/frame_jit/records.rs index 75e23ccc8..1c033bbea 100644 --- a/crates/weavepy-vm/src/frame_jit/records.rs +++ b/crates/weavepy-vm/src/frame_jit/records.rs @@ -56,6 +56,35 @@ pub(super) enum MethodOp<'a> { /// A `COMPARE_OP`'s first method, the instruction's oparg: the /// operands wait under the call on the caller's stack. Compare(u32), + /// A `GET_ITER`'s `__iter__`: its result must be an iterator. + Iter, + /// A `STORE_ATTR`'s setter or a `STORE_SUBSCR`'s `__setitem__`: its + /// result is dropped. + Store, + /// A `TO_BOOL`'s `__bool__` (`true`: its `__len__`): its result becomes + /// the truth. + Truth(bool), + /// A `CONTAINS_OP`'s `__contains__` (`true`: `not in`). + Contains(bool), + /// `len(obj)`'s `__len__`: its result becomes the length. + Len, + /// An augmented assignment's in-place method, on these operands: its + /// `NotImplemented` goes on to the regular operator. + Inplace(weavepy_compiler::BinOpKind, &'a Object, &'a Object), + /// A `FORMAT_VALUE`'s `__format__`: its result must be a string. + Format, + /// `str(obj)`'s `__str__`: its result must be a string. + Str, + /// `repr(obj)`'s `__repr__`: its result must be a string. + Repr, + /// `hash(obj)`'s `__hash__`: its result must be an integer. + Hash, + /// `hasattr(obj, name)`'s `__getattr__`: any result is `True`, an + /// `AttributeError` `False`. + HasAttr, + /// `getattr(obj, name, default)`'s `__getattr__`: an `AttributeError` + /// is the default. + GetAttrOr(&'a Object), } impl MethodOp<'_> { @@ -66,6 +95,18 @@ impl MethodOp<'_> { crate::MethodOp::Binary(op, inplace, l.clone(), r.clone()) } MethodOp::Compare(arg) => crate::MethodOp::Compare(arg), + MethodOp::Iter => crate::MethodOp::Iter, + MethodOp::Store => crate::MethodOp::Store, + MethodOp::Truth(from_len) => crate::MethodOp::Truth(from_len), + MethodOp::Contains(invert) => crate::MethodOp::Contains(invert), + MethodOp::Len => crate::MethodOp::Len, + MethodOp::Inplace(op, a, b) => crate::MethodOp::Inplace(op, a.clone(), b.clone()), + MethodOp::Format => crate::MethodOp::Format, + MethodOp::Str => crate::MethodOp::Str, + MethodOp::Repr => crate::MethodOp::Repr, + MethodOp::Hash => crate::MethodOp::Hash, + MethodOp::HasAttr => crate::MethodOp::HasAttr, + MethodOp::GetAttrOr(d) => crate::MethodOp::GetAttrOr(d.clone()), } } } @@ -199,6 +240,7 @@ impl DirectRecs { wait_pending: None, outer_lazy: 0, fold: std::ptr::null(), + caught: false, }, frame: std::ptr::null_mut(), locals: std::ptr::null_mut(), @@ -406,6 +448,10 @@ struct Shape(u32); impl Shape { const CLOSURE: u32 = 1 << 31; + /// The code takes `*args` (and neither `**kwargs` nor keyword-only + /// parameters): its local after the positional parameters is the + /// tuple of the surplus. + const VARARGS: u32 = 1 << 17; #[inline(always)] fn params(self) -> usize { @@ -414,7 +460,7 @@ impl Shape { #[inline(always)] fn room(self) -> u32 { - self.0 >> 4 & 0x3fff + self.0 >> 4 & 0x1fff } #[inline(always)] @@ -426,6 +472,18 @@ impl Shape { fn closure(self) -> bool { self.0 & Self::CLOSURE != 0 } + + #[inline(always)] + fn varargs(self) -> bool { + self.0 & Self::VARARGS != 0 + } +} + +/// Whether `code`'s only extended parameter is `*args` (see +/// [`Shape::VARARGS`]). +#[inline] +fn varargs_only(code: &CodeObject) -> bool { + code.has_varargs && !code.has_varkeywords && code.kwonly_count == 0 } /// The most arguments [`h_direct_enter`] moves. @@ -440,7 +498,7 @@ pub(super) fn note_direct(code: &CodeObject, native: &super::Native, packed: usi let hint = &code.jit_hint; let nlocals = code.varnames.len(); let room = nlocals.max(native.need); - if packed & super::EXTENDED_BIT as usize != 0 + if (packed & super::EXTENDED_BIT as usize != 0 && !varargs_only(code)) || !code.cellvars.is_empty() || !native.chunks.is_empty() || !native.enters_at(0) @@ -456,7 +514,8 @@ pub(super) fn note_direct(code: &CodeObject, native: &super::Native, packed: usi let shape = code.arg_count | (room as u32) << 4 | (nlocals as u32) << 18 - | if closure { Shape::CLOSURE } else { 0 }; + | if closure { Shape::CLOSURE } else { 0 } + | if code.has_varargs { Shape::VARARGS } else { 0 }; hint.set_direct(native.func as usize, shape); } @@ -512,6 +571,18 @@ const NOT_ENTERED: Entered = Entered { entry: 0, }; +/// [`ctor_enter`]'s state word for a construction it finished itself +/// (see [`CTOR_DONE`]). +pub(super) const CTOR_DONE_ST: usize = 1; + +/// [`ctor_enter`] built the instance itself: it's in the class's slot, the +/// call's operands gone, as a direct call's clean return leaves its +/// result (status `0`), with nothing to run. +const CTOR_DONE: Entered = Entered { + st: CTOR_DONE_ST as *mut State, + entry: 0, +}; + /// A `CALL`'s callee entered from compiled code, the function at `slot` on /// the stack and `call` the `CALL`'s own: its arguments bound and its record /// armed, for the code to call the native code and pass the status to @@ -557,7 +628,7 @@ pub(super) unsafe extern "C" fn h_direct_enter( } let has_self = !matches!(&*slot.add(1), Object::Unbound); let n = call.argc() + usize::from(has_self); - if n != shape.params() || shape.closure() { + if n != shape.params() || shape.0 & (Shape::CLOSURE | Shape::VARARGS) != 0 { return enter_more(st, slot, call, entry); } // Committed. (The native code's entry marks the other locals unbound @@ -607,8 +678,9 @@ pub(super) const ENTER_CONV: Option = None }; -/// [`h_direct_enter`] for a callee `entry` with defaults to take or a closure -/// to read, or with the wrong number of arguments, the other checks passed. +/// [`h_direct_enter`] for a callee `entry` with defaults to take, a closure +/// to read or a `*args` tuple to make, or with the wrong number of +/// arguments, the other checks passed. /// /// # Safety /// @@ -634,13 +706,13 @@ unsafe extern "C" fn enter_more( let interp = &*s.interp; let rec = &mut *interp.recs.top(); let params = shape.params(); - if n > params { + if n > params && !shape.varargs() { return NOT_ENTERED; } - let missing = params - n; + let missing = params.saturating_sub(n); let defaults = &(*fp).defaults; if missing != 0 - && (crate::sync::release_gates() != 0 + && (crate::sync::release_gates() & crate::sync::RELEASE_OBSERVER_GATES != 0 || defaults.len() < missing || (*fp).defaults_maybe_overridden()) { @@ -658,18 +730,37 @@ unsafe extern "C" fn enter_more( let dc = &*s.depth_cell; dc.set(dc.get() + 1); let dst = rec.st.locals; - move_args(slot.add(2 - usize::from(has_self)), dst, n); + let src = slot.add(2 - usize::from(has_self)); + move_args(src, dst, n.min(params)); + // (The surplus moves into the tuple.) + if shape.varargs() { + let star = if n > params { + Object::Tuple(crate::tuple_storage::TupleStorage::from_moved_raw( + src.add(params), + n - params, + )) + } else { + Object::new_tuple(Vec::new()) + }; + dst.add(params).write(star); + } if missing != 0 { let defaults = defaults.as_ptr().add(defaults.len() - missing); + let shared = crate::sync::release_gates() != 0; for k in 0..missing { let d = defaults.add(k); - // While the gates are off this thread alone updates counts. + // While the gates are off this thread alone updates counts; + // with counts shared, a locked update. if let Some(word) = (*d).strong_word() { let w = &*word; - w.store( - w.load(std::sync::atomic::Ordering::Relaxed) + 1, - std::sync::atomic::Ordering::Relaxed, - ); + if shared { + w.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } else { + w.store( + w.load(std::sync::atomic::Ordering::Relaxed) + 1, + std::sync::atomic::Ordering::Relaxed, + ); + } } let (a, b) = (d.cast::(), dst.add(n + k).cast::()); let (x, y) = (a.read(), a.add(1).read()); @@ -689,6 +780,313 @@ unsafe extern "C" fn enter_more( } } +/// Whether [`h_direct_enter`] enters the function `fp` (running `code_rc`) +/// with `n` positional arguments, the instance among them: the checks it +/// and [`enter_more`] make before committing, made first. +/// +/// # Safety +/// +/// As `h_direct_enter`'s. +#[inline(always)] +unsafe fn direct_enters( + s: &State, + fp: *const crate::object::PyFunction, + code_rc: &CodeObject, + n: usize, +) -> bool { + // SAFETY: the caller's contract. + unsafe { + let shape = Shape(code_rc.jit_hint.direct_shape()); + let rec = &*(*s.interp).recs.top(); + if code_rc.jit_hint.direct_entry() == 0 + || rec.st.lazy.is_null() + || s.no_direct + || rec.room < shape.room() + || crate::hot_gates::loop_gen() != s.snap_gen + || (*s.depth_cell).get() + 1 > crate::recursion::recursion_limit() + { + return false; + } + let params = shape.params(); + if n == params && !shape.closure() { + return true; + } + let missing = params.saturating_sub(n); + let defaults = &(*fp).defaults; + (n <= params || shape.varargs()) + && (missing == 0 + || (crate::sync::release_gates() & crate::sync::RELEASE_OBSERVER_GATES == 0 + && defaults.len() >= missing + && !(*fp).defaults_maybe_overridden())) + && (!shape.closure() || (*fp).closure_cells.get().is_some()) + } +} + +/// Whether a class whose plan is `plan` constructs through a framed +/// `__init__` (running `code`) that compiled code enters directly: no +/// Python `__new__`, a plain allocation, an `__init__` with neither a +/// store-only nor a leaf form (verdicts that never turn; an exception's +/// construction takes neither) and with a direct entry (see +/// [`ctor_enter`]). +#[inline] +fn ctor_framed(plan: &crate::types::InstancePlan, code: &CodeObject) -> bool { + code.jit_hint.direct_entry() != 0 + && plan.user_new.is_none() + && plan.abstract_error.is_none() + && matches!(plan.native, crate::types::NativeKind::Plain) + && (plan.seeds_exception_args + || plan.store_init.load(std::sync::atomic::Ordering::Relaxed) == 2 + // (An `__init__` with `*args` runs as no leaf.) + && (varargs_only(code) + || code.jit_hint.pure_leaf() == Some(false) && !code.jit_hint.effect_leaf())) +} + +/// [`h_direct_enter`]'s counterpart for a `CALL` of a Python class (at +/// `slot`, its self slot empty), which compiled code calls for a callee +/// with a class's tag, +/// whose memoized plan settled on running a plain `__init__` in a frame of +/// its own (no Python `__new__`, and neither a store-only nor a leaf form, +/// verdicts that never turn) that has a direct entry: the instance made, +/// and the `__init__` entered on the call's operands as [`ctor_direct`] +/// enters it, the caller taking the instance when it returns `None` (see +/// [`DirectRec::finish_extra`]). The compiled code's call then costs what +/// a function's does. Null touched nothing. +/// +/// # Safety +/// +/// As `h_direct_enter`'s. +#[inline(never)] +pub(super) unsafe extern "C" fn ctor_enter( + st: *mut State, + slot: *mut Object, + call: CallAt, +) -> Entered { + // SAFETY: the caller's contract. + unsafe { + // A class `ctor_direct` found to construct through a framed + // `__init__` with a direct entry, at its current version: most + // classes decline on this alone. + match &*slot { + Object::Type(ty) if ty.framed_ctor.get() == ty.attr_version.get() => { + ctor_enter_framed(st, slot, call) + } + Object::Type(ty) if ty.store_ctor.get() == ty.attr_version.get() => { + if ctor_store_lean(st, slot, call) { + CTOR_DONE + } else { + NOT_ENTERED + } + } + _ => NOT_ENTERED, + } + } +} + +/// [`ctor_enter`] for a class stamped store-only at its version (see +/// `TypeObject::store_ctor`): `frame_jit::ctor_store_init`'s +/// construction, from the class's slot, without the general call's +/// dispatch before it. `true` built the instance into the class's slot +/// (`st.len` past it); `false` touched nothing. +/// +/// # Safety +/// +/// As `h_direct_enter`'s, with a class at `slot`. +#[inline(never)] +unsafe fn ctor_store_lean(st: *mut State, slot: *mut Object, call: CallAt) -> bool { + // SAFETY: the caller's contract. + unsafe { + let s = &mut *st; + let (Object::Type(ty), Object::Unbound) = (&*slot, &*slot.add(1)) else { + return false; + }; + let interp = &*s.interp; + let argc = call.argc(); + // (The checks `ctor_store_init` makes; the class leaves the slot + // below, never its last reference.) + if s.sw.is_null() + || Rc::strong_count(ty) < 2 + || interp.lean_snapshot() != Some(s.snap_gen) + || !interp.inline_calls_ok() + || crate::stdlib::tracemalloc_real::is_tracking() + || crate::stdlib::testinternalcapi_mod::reftrace_print_active() + || crate::stdlib::testinternalcapi_mod::nomem_alloc_fails() + || !Interpreter::metaclass_calls_like_type(ty) + { + return false; + } + // SAFETY: a guard-free read of the memoized plan; the class (held + // by the slot) keeps it, and nothing below changes the class. + let Some((ver, plan)) = ty.instance_plan.peek().and_then(Option::as_ref) else { + return false; + }; + let plan = interp.call_plan(plan, ty, argc); + if *ver != ty.attr_version.get() + || plan.store_init.load(std::sync::atomic::Ordering::Relaxed) != 1 + { + return false; + } + let Some((init, init_code)) = plan.lean_init.as_ref() else { + return false; + }; + // SAFETY: GIL-serialized raw read of the function's code cell; only + // the pointer is compared. + if !std::ptr::eq(Rc::as_ptr(&*init.code.as_ptr()), Rc::as_ptr(init_code)) { + return false; + } + let Some(missing) = Interpreter::missing_defaults(init, init_code, argc + 1) else { + return false; + }; + let args = slot.add(2); + let Some(inst) = interp.store_init_build( + ty, + plan, + init, + init_code, + false, + argc, + missing, + s.depth_cell, + |j, last| { + let a = args.add(j - 1); + if last { + std::ptr::replace(a, Object::Unbound) + } else { + (*a).clone() + } + }, + ) else { + return false; + }; + // The arguments the stores left, then the class (the self slot is + // empty). + for k in 0..argc { + let o = args.add(k).read(); + if !matches!(o, Object::Unbound) { + interp.release(o); + } + } + crate::drop_hot(std::ptr::replace(slot, inst)); + s.len = call.start() + 1; + true + } +} + +/// [`ctor_enter`] as compiled code calls it on Windows (see +/// [`h_direct_enter_regs`]). +/// +/// # Safety +/// +/// As `ctor_enter`'s. +#[cfg(all(windows, target_arch = "x86_64"))] +pub(super) unsafe extern "sysv64" fn ctor_enter_regs( + st: *mut State, + slot: *mut Object, + call: CallAt, +) -> Entered { + // SAFETY: per the caller. + unsafe { ctor_enter(st, slot, call) } +} + +/// [`ctor_enter`] as compiled code calls it. +#[cfg(not(all(windows, target_arch = "x86_64")))] +pub(super) use ctor_enter as ctor_enter_regs; + +/// [`ctor_enter`] past its stamp check. +/// +/// # Safety +/// +/// As `h_direct_enter`'s, with a class at `slot`. +#[inline(never)] +unsafe extern "C" fn ctor_enter_framed(st: *mut State, slot: *mut Object, call: CallAt) -> Entered { + // SAFETY: the caller's contract. + unsafe { + let s = &*st; + let (Object::Type(ty), Object::Unbound) = (&*slot, &*slot.add(1)) else { + return NOT_ENTERED; + }; + // The plan's verdicts first: most classes decline on them. + // SAFETY: a guard-free read of the memoized plan; nothing runs + // before its last use. + let Some((ver, plan)) = ty.instance_plan.peek().and_then(Option::as_ref) else { + return NOT_ENTERED; + }; + let plan = (*s.interp).call_plan(plan, ty, call.argc()); + let Some((init, code)) = plan.lean_init.as_ref() else { + return NOT_ENTERED; + }; + // SAFETY: GIL-serialized raw read of the function's code cell; only + // the pointer is compared. + if *ver != ty.attr_version.get() + || !ctor_framed(plan, code) + || !std::ptr::eq(Rc::as_ptr(&*init.code.as_ptr()), Rc::as_ptr(code)) + { + return NOT_ENTERED; + } + let interp = &mut *s.interp.cast_mut(); + // (The class leaves the slot below: never its last reference.) + if s.sw.is_null() + || ty.flags.is_builtin + || ty.native_kind.get() != 0 + || Rc::strong_count(ty) < 2 + || (*s.maybe_dead).get() + || interp.recs.full_at(interp.recs.top()) + || crate::stdlib::tracemalloc_real::is_tracking() + || crate::stdlib::testinternalcapi_mod::reftrace_print_active() + || crate::stdlib::testinternalcapi_mod::nomem_alloc_fails() + || crate::gc_trace::auto_collect_due() + || ty.instances_need_finalize() + || !direct_enters(s, Rc::as_ptr(init), code, call.argc() + 1) + || !Interpreter::metaclass_calls_like_type(ty) + { + return NOT_ENTERED; + } + // Committed: the instance made (no collection is due), the function + // in the class's slot and the instance in the self slot, entered as + // a method call of them, which the checks above proved it takes. + let init = Rc::clone(init); + let (inst, _) = interp.alloc_lean_instance_obj(ty, &plan.native); + // Room for the class's names, which the constructor's stores then + // append in line (see `Lower::field_store_in_line`). + // (A pooled instance keeps its last tenant's.) + if let Object::Instance(i) = &inst { + // SAFETY: the instance is fresh and unshared. + if let Some(split) = i.dict.split_cell().peek_mut().filter(|s| !s.has_block()) { + if let (None, Some(keys)) = ( + ty.slot_layout.get().and_then(Option::as_ref), + ty.shared_keys.get(), + ) { + split.reserve_for(|| ty.shared_keys.share(), keys.len()); + } + } + } + // (An exception's `args` are the call's, as `BaseException.__new__` + // seeds them.) + if plan.seeds_exception_args { + let args = std::slice::from_raw_parts(slot.add(2), call.argc()); + Interpreter::seed_exception_args(&inst, args.iter().cloned()); + } + slot.add(1).write(inst.clone()); + let cls = slot.replace(Object::Function(init)); + let rec_at = interp.recs.top(); + let entered = h_direct_enter(st, slot, call); + if entered.st.is_null() { + // An allocation above raised a gate (a collection due) that + // ended the generation the checks saw: the call goes back as it + // was, its fresh instance (no finalizer) gone unseen. + crate::drop_hot(slot.replace(cls)); + crate::drop_hot(slot.add(1).replace(Object::Unbound)); + drop(inst); + return NOT_ENTERED; + } + let rec = &mut *rec_at; + std::ptr::write(&raw mut (*rec.st.lazy).init_inst, Some(inst)); + rec.extra = true; + rec.st.clean = false; + crate::drop_hot(cls); + entered + } +} + /// `CALL` (`call`, atop a `len`-deep stack) of a Python class whose memoized /// plan runs a plain `__init__` that has a native body, as /// `Interpreter::core_new_n` runs one: the instance allocated and that body @@ -728,7 +1126,19 @@ pub(super) unsafe fn ctor_direct(st: &mut State, call: CallAt, len: usize) -> Op if *ver != ty.attr_version.get() { return None; } + let outer = Rc::as_ptr(plan); + let plan = interp.call_plan(plan, ty, argc); + // (Whether the plan with `object.__new__` stands in, which nothing + // below changes.) + let shadow = !std::ptr::eq(Rc::as_ptr(plan), outer); if plan.user_new.is_some() { + // (`Path(...)`: a call of the class its `__new__` picks.) + if plan.trivial_new.is_some() { + if let Some(m) = interp.trivial_new_retarget(plan, ty, argc) { + crate::drop_hot(slot.replace(Object::Type(m))); + return ctor_direct(st, call, len); + } + } return new_direct(st, call, len); } // What runs on the frame alone (a store-only or leaf `__init__`, the @@ -747,6 +1157,10 @@ pub(super) unsafe fn ctor_direct(st: &mut State, call: CallAt, len: usize) -> Op return None; }; let (_, plan) = ty.instance_plan.peek().and_then(Option::as_ref)?; + let plan = match &plan.trivial_new { + Some(tn) if shadow => &tn.plan, + _ => plan, + }; let (init, code) = plan.lean_init.as_ref()?; // SAFETY: GIL-serialized raw read of the function's code cell; only // the pointer is compared. @@ -772,6 +1186,15 @@ pub(super) unsafe fn ctor_direct(st: &mut State, call: CallAt, len: usize) -> Op if dc.get() + 1 > crate::recursion::recursion_limit() { return None; } + // (Compiled callers enter it straight from here on, see + // `ctor_enter`, once it's past the warm-up hooks.) + if code.jit_hint.direct_entry() == 0 && (!extended || varargs_only(code)) { + let packed = missing | if cells { super::CELLS_BIT as usize } else { 0 }; + note_direct(code, native, packed); + } + if ty.framed_ctor.get() != ty.attr_version.get() && ctor_framed(plan, code) { + ty.framed_ctor.set(ty.attr_version.get()); + } // Committed: the frame as the core loop's arm has it at the call, // the instance made (a collection it sets off may run finalizers). let frame = &mut *st.frame; @@ -823,6 +1246,61 @@ pub(super) unsafe fn ctor_direct(st: &mut State, call: CallAt, len: usize) -> Op } } +/// [`crate::specialize::kw_perm`] for a constructor's `__init__`, through +/// a per-thread memo by function, code, names tuple and argument count: +/// the site has no cache of its own, and the permutation compares every +/// keyword's name (about 330 instructions for three). A function whose +/// defaults may have been reassigned asks afresh; another function at a +/// freed one's address with the same code and as many defaults binds the +/// same way. +fn ctor_kw_perm( + init: &Rc, + code: &CodeObject, + argc: usize, + names: &crate::tuple_storage::TupleStorage, +) -> Option<(u32, u32)> { + type Key = (usize, usize, usize, usize, usize); + const WAYS: usize = 32; + thread_local! { + static MEMO: [std::cell::Cell<(Key, (u32, u32))>; WAYS] = + const { [const { std::cell::Cell::new(((0, 0, 0, 0, 0), (0, 0))) }; WAYS] }; + } + let memo_ok = !init.defaults_maybe_overridden(); + let key: Key = ( + Rc::as_ptr(init) as usize, + std::ptr::from_ref(code) as usize, + std::ptr::from_ref(names).cast::() as usize, + argc, + (init.defaults.len() << 16) | init.kw_defaults.len(), + ); + let way = (key.0 >> 4 ^ key.2 >> 4) % WAYS; + if memo_ok { + let hit = MEMO + .try_with(|m| { + let e = m[way].get(); + (e.0 == key).then_some(e.1) + }) + .ok() + .flatten(); + if hit.is_some() { + return hit; + } + } + let r = crate::specialize::kw_perm( + init, + code, + argc, + names.iter().map(|n| match n { + Object::Str(s) => &**s, + _ => "", + }), + )?; + if memo_ok { + let _ = MEMO.try_with(|m| m[way].set((key, r))); + } + Some(r) +} + /// [`ctor_direct`] for a `CALL_KW` of a plain class (`C(i, b=2)`), its /// operands from `start` up a `len`-deep stack (the class, its empty self /// slot, `argc` positionals, `kwc` keyword values and the names tuple): @@ -898,15 +1376,7 @@ pub(super) unsafe fn ctor_direct_kw( if names.len() != kwc || !names.iter().all(|n| matches!(n, Object::Str(_))) { return None; } - let (perm, covered) = crate::specialize::kw_perm( - init, - code, - argc + 1, - names.iter().map(|n| match n { - Object::Str(s) => &**s, - _ => "", - }), - )?; + let (perm, covered) = ctor_kw_perm(init, code, argc + 1, names)?; let dc = &*st.depth_cell; if dc.get() + 1 > crate::recursion::recursion_limit() { return None; @@ -994,7 +1464,10 @@ unsafe fn new_direct(st: &mut State, call: CallAt, len: usize) -> Option { // `Interpreter::core_new_user` declines them; a named tuple's is // its own lane's.) if plan.abstract_error.is_some() - || !matches!(plan.native, crate::types::NativeKind::Plain) + || !matches!( + plan.native, + crate::types::NativeKind::Plain | crate::types::NativeKind::Value { .. } + ) || plan.seeds_exception_args || plan.tuple_new.is_some() || ty.is_type_subclass() @@ -1312,10 +1785,12 @@ pub(super) unsafe extern "C" fn h_direct_leave( || (*rec.locals_count).load(std::sync::atomic::Ordering::Relaxed) > 1 || interp.gil_countdown <= 2 || crate::hot_gates::loop_gen() != rec.st.snap_gen - || crate::sync::release_gates() != 0 + || crate::sync::release_gates() & crate::sync::RELEASE_OBSERVER_GATES != 0 { return left_slowly(s, rec, status); } + // (With counts shared, each release below is a locked update.) + let shared = crate::sync::release_gates() != 0; interp.lazy_top.set(rec.outer); (*rec.frame).stack.set_len(0); let n = (*rec.locals).len(); @@ -1328,6 +1803,12 @@ pub(super) unsafe extern "C" fn h_direct_leave( k -= 1; if let Some(word) = (*locals.add(k)).strong_word() { // While the gates are off this thread alone updates counts. + if shared { + if !crate::rc::release_unless_last(word) { + return release_rest(s, rec, k + 1); + } + continue; + } let w = &*word; let c = w.load(std::sync::atomic::Ordering::Relaxed); if c == 1 { @@ -1342,11 +1823,17 @@ pub(super) unsafe extern "C" fn h_direct_leave( } // (A function's second word is its count's address.) let word = &**slot.cast::<*const std::sync::atomic::AtomicUsize>().add(1); - let c = word.load(std::sync::atomic::Ordering::Relaxed); - if c == 1 { - return finish_rest(s, rec); + if shared { + if !crate::rc::release_unless_last(word) { + return finish_rest(s, rec); + } + } else { + let c = word.load(std::sync::atomic::Ordering::Relaxed); + if c == 1 { + return finish_rest(s, rec); + } + word.store(c - 1, std::sync::atomic::Ordering::Relaxed); } - word.store(c - 1, std::sync::atomic::Ordering::Relaxed); let (a, b) = (rec.st.stack.cast::(), slot.cast::()); let (x, y) = (a.read(), a.add(1).read()); b.write(x); @@ -1429,6 +1916,11 @@ unsafe fn finalizers_after(st: &mut State, call: CallAt, interp: &mut Interprete unsafe fn left_slowly(s: &mut State, rec: &mut DirectRec, status: u32) -> u32 { // SAFETY: as `h_direct_leave`'s. unsafe { + if status == super::DIRECT_RET && rec.extra { + if let Some(r) = ctor_left(s, rec) { + return r; + } + } let status = rec.unpack(status); if status == super::INTERP { // An entry that got nowhere counts against the entry. @@ -1442,6 +1934,81 @@ unsafe fn left_slowly(s: &mut State, rec: &mut DirectRec, status: u32) -> u32 { } } +/// [`left_slowly`] for a constructor's `__init__` (see +/// [`ctor_enter_framed`]) that returned `None`: [`leave`]'s clean finish +/// with nothing else to do, the instance taking the call's slot and the +/// function released as [`h_direct_leave`] releases it. `None` touched +/// nothing. +/// +/// # Safety +/// +/// As `h_direct_leave`'s, the record's return a `DIRECT_RET`. +#[inline(always)] +unsafe fn ctor_left(s: &mut State, rec: &mut DirectRec) -> Option { + // SAFETY: the caller's contract. + unsafe { + let interp = &mut *s.interp.cast_mut(); + if rec.st.lazy.is_null() || rec.st.len != 1 { + return None; + } + let act = &mut *rec.st.lazy; + if act.init_inst.is_none() + || !matches!(&*rec.st.stack, Object::None) + || act.back_for.is_some() + || act.new_init.is_some() + || act.lru.is_some() + || (*rec.frame).locals.is_shared() + || interp.countdown_out(2) + || crate::hot_gates::loop_gen() != rec.st.snap_gen + { + return None; + } + interp.lazy_top.set(rec.outer); + let frame = &mut *rec.frame; + frame.stack.set_len(0); + let owns_cells = act.owns_cells; + crate::release_activation_locals(frame, owns_cells); + if owns_cells { + act.owns_cells = false; + drop(std::ptr::read(&raw const frame.cells)); + } + let dc = &*s.depth_cell; + dc.set(dc.get() - 1); + // (Over the `None` it returned.) + rec.st.stack.write(act.init_inst.take()?); + rec.extra = false; + rec.st.clean = true; + let slot = s.stack.add(rec.call.start()); + if !matches!(&*slot, Object::Function(_)) + || crate::sync::release_gates() & crate::sync::RELEASE_OBSERVER_GATES != 0 + { + return Some(finish_rest(s, rec)); + } + // (A function's second word is its count's address; the class + // holds it.) + let word = &**slot.cast::<*const std::sync::atomic::AtomicUsize>().add(1); + if crate::sync::release_gates() != 0 { + if !crate::rc::release_unless_last(word) { + return Some(finish_rest(s, rec)); + } + } else { + let c = word.load(std::sync::atomic::Ordering::Relaxed); + if c == 1 { + return Some(finish_rest(s, rec)); + } + word.store(c - 1, std::sync::atomic::Ordering::Relaxed); + } + slot.write(rec.st.stack.read()); + interp.gil_countdown -= 1; + interp.recs.set_top(std::ptr::from_mut(rec)); + if (*s.maybe_dead).get() && s.inl_call.is_null() { + return Some(finalizers_after(s, rec.call, interp)); + } + s.len = rec.call.start() + 1; + Some(0) + } +} + /// The end of a call on `rec`, whose native code returned `status`: its /// return finished here when clean, or whatever it left synced for the /// core loop. `op` is an instance operator's (see @@ -1492,6 +2059,9 @@ unsafe fn leave(st: &mut State, rec: &mut DirectRec, status: u32, op: Op<'_>) -> // first. (The record stays this level's until that's done: anything // the core loop's paths run nests above it.) let r = left_uncleanly(st, rec, status, op); + // (An inlined body's frames built during this call were this + // call's: the record's next call starts without them.) + rec.st.inl_gone = false; interp.recs.set_top(rec_at); r } @@ -1513,22 +2083,34 @@ unsafe fn chain_init(st: &mut State, rec: &mut DirectRec, interp: &mut Interpret // SAFETY: the caller's contract. unsafe { let act = &mut *rec.st.lazy; - if act.init_inst.is_some() || act.lru.is_some() { + if act.init_inst.is_some() || act.lru.is_some() || act.back_for.is_some() { return None; } let ni: &crate::NewInit = act.new_init.as_deref()?; - if ni.plan.init_from_object { - return None; - } let Object::Instance(made) = &*rec.st.stack else { return None; }; - if !std::ptr::eq(made.cls_raw(), Rc::as_ptr(&ni.ty)) { + // `type(obj).__init__` runs: the class's own, or, for an instance of + // a subclass `__new__` made (`Path.__new__`'s `PosixPath`), that + // subclass's, from its own plan. + let sub_plan; + let plan: &crate::types::InstancePlan = if std::ptr::eq(made.cls_raw(), Rc::as_ptr(&ni.ty)) + { + &ni.plan + } else { + let made_cls = made.cls(); + if !made_cls.is_subclass_of(&ni.ty) { + return None; + } + sub_plan = interp.instance_plan(&made_cls); + &sub_plan + }; + if plan.init_from_object { return None; } // (The plan's `__init__` as `Interpreter::core_push_init` takes it: // a class with its own `__new__` keeps no lean form of it.) - let Some(Object::Function(init)) = &ni.plan.init_fn else { + let Some(Object::Function(init)) = &plan.init_fn else { return None; }; // SAFETY: GIL-serialized raw read of the function's code cell. @@ -1688,7 +2270,8 @@ impl DirectRec { unsafe { let act = &*self.st.lazy; let made = &*self.st.stack; - (act.init_inst.is_none() || matches!(made, Object::None)) + act.back_for.is_none() + && (act.init_inst.is_none() || matches!(made, Object::None)) && act.new_init.as_ref().is_none_or(|ni| { // An instance of the class itself whose `__init__` is // `object`'s, which a `__new__` override skips. @@ -1716,12 +2299,268 @@ impl DirectRec { } } +/// [`leave`] for a callee that never registered, whose raise none of its +/// handlers covers, while nothing observes frames: its unwinding done here +/// (`Interpreter::unwind_unseen`: the traceback's entry, and a departed +/// shell that keeps its locals), the record back at rest, and the error +/// the caller's to catch (`RAISED`, its state past the call) or the core +/// loop's (`RELOAD`, a finalizer or a breaker being due). The departed +/// shell's caller link is the caller's shell, or waits for it on a caller +/// that runs lazily too (`InlineAct::back_for`). `None` touched nothing. +/// +/// # Safety +/// +/// As [`leave`]'s, the callee's native code having returned `RAISED`. +#[inline(never)] +unsafe fn raise_unseen(st: &mut State, rec: &mut DirectRec, op: Op<'_>) -> Option { + // SAFETY: the caller's contract. + unsafe { + let act = rec.st.lazy; + if act.is_null() + || rec.st.gen_lazy + || !rec.st.inl_call.is_null() + || rec.st.inl_gone + || rec.st.wait_pc != usize::MAX + || !rec.st.fold.is_null() + || rec.st.pc == 0 + || st.sw.is_null() + || !st.inl_call.is_null() + || crate::trace::any_observers_active() + { + return None; + } + let act = &mut *act; + if act.new_init.is_some() || act.lru.is_some() || act.owns_cells || act.lazy_coro { + return None; + } + let fr = &mut *rec.frame; + let interp = &mut *st.interp.cast_mut(); + let raise_pc = rec.st.pc as u32 - 1; + if fr.locals.is_shared() + || interp.exc_info_len() != rec.exc_depth + || !matches!( + &rec.st.err, + Some(crate::RuntimeError::PyException(e)) if !e.suppress_tb_once + ) + || crate::find_handler(&fr.code.exception_table, raise_pc).is_some() + { + return None; + } + // A probe's hook (`hasattr`, `getattr` with a default) raised an + // `AttributeError` nothing else holds: the probe drops it, so no + // traceback is built for it and the frame's locals go now. The + // record's result is left unbound for the probe to read as the + // miss (see `super::attr_probe_call`). + if matches!(op, Some(MethodOp::HasAttr | MethodOp::GetAttrOr(_))) + && act.back_for.is_none() + && !rec.extra + && matches!( + &rec.st.err, + Some(crate::RuntimeError::PyException(e)) + if matches!(&e.instance, Object::Instance(i) + if Rc::strong_count(i) == 1 + && std::ptr::eq( + i.cls_raw(), + Rc::as_ptr(&crate::builtin_types::builtin_types().attribute_error), + )) + ) + { + let err = rec.st.err.take(); + let n = rec.st.len; + rec.st.len = 0; + fr.stack.set_len(0); + crate::release_run(rec.st.stack, n); + crate::release_activation_locals(fr, false); + let dc = &*st.depth_cell; + dc.set(dc.get() - 1); + drop(err); + rec.st.stack.write(Object::Unbound); + let r = finish_rest(st, rec); + if r != 0 { + if let Some(op) = op { + super::op_after_reload(st, op); + } + } + return Some(r); + } + // A plain call whose caller catches the raise in a clause that + // can't observe it (see `blind_swallow`). + if op.is_none() && act.back_for.is_none() && !rec.extra && act.init_inst.is_none() { + if let Some(r) = blind_swallow(st, rec) { + return Some(r); + } + } + let (pc, start) = (rec.call.pc(), rec.call.start()); + let caller_frame = &mut *st.frame; + // An attribute hook's error takes the read's name and receiver on + // the way (as `Interpreter::attr_hook_context` gives them): the + // receiver, held across the unwinding. + let ins = caller_frame.code.instructions.get(pc as usize)?; + let hook = if ins.op == weavepy_compiler::OpCode::LoadAttr && fr.code.arg_count == 2 { + match fr.locals.slots().first() { + Some(recv @ Object::Instance(_)) => caller_frame + .code + .names + .get(ins.arg as usize) + .map(|name| (recv.clone(), name)), + _ => None, + } + } else { + None + }; + // The caller's shell, or a caller that has none to have yet. + let caller_shell = if st.lazy.is_null() { + if !std::ptr::eq((*st.sw).cur, st.frame) { + return None; + } + Some(interp.spine_top_for(caller_frame)?) + } else { + if !st.in_rec || st.gen_lazy || (*st.lazy).back_for.is_some() { + return None; + } + None + }; + // Committed. + let Some(crate::RuntimeError::PyException(mut exc)) = rec.st.err.take() else { + std::hint::unreachable_unchecked() + }; + let shell = interp.unwind_unseen(fr, &mut exc, raise_pc); + if let Some((departed, _)) = act.back_for.take() { + departed.depart(Some(&shell)); + } + match &caller_shell { + Some(caller) => { + caller.lasti.store(pc, std::sync::atomic::Ordering::Relaxed); + shell.depart(Some(caller)); + } + None => { + shell.depart(None); + (*st.lazy).back_for = Some((shell.clone(), pc)); + let caller_rec = &mut *std::ptr::from_mut(st).cast::(); + caller_rec.extra = true; + st.clean = false; + } + } + drop(shell); + drop(caller_shell); + // The record back at rest, on the frame's fresh locals. + rec.locals = fr.locals.storage(); + rec.locals_count = crate::rc::strong_word(Rc::as_ptr(fr.locals.shared())); + let n = rec.st.len; + rec.st.len = 0; + fr.stack.set_len(0); + rec.note_buffers(); + rec.extra = false; + rec.st.clean = true; + let dc = &*st.depth_cell; + dc.set(dc.get() - 1); + if let Some(last) = rec.call.last() { + st.last = last; + } + // What the call still held: its operands, a constructor's instance, + // the function. + crate::release_run(rec.st.stack, n); + if let Some(inst) = act.init_inst.take() { + interp.release(inst); + } + let callable = st.stack.add(start).read(); + interp.release(callable); + let err = crate::RuntimeError::PyException(exc); + if let Some((recv, name)) = hook { + interp.attr_error_context(&err, &recv, name); + interp.release(recv); + } + if (*st.maybe_dead).get() || crate::hot_gates::loop_gen() != st.snap_gen { + caller_frame.stack.set_len(start); + caller_frame.pc = pc + 1; + super::settle(st); + (*st.sw).pending = Some(crate::CoreExit::Stop(crate::LeafStop::Raised(err))); + return Some(super::RELOAD); + } + st.err = Some(err); + st.len = start; + st.pc = pc as usize + 1; + Some(super::RAISED) + } +} + +/// [`raise_unseen`] for a plain `CALL` whose caller catches the raise in +/// a clause that can't observe the exception (see +/// `Interpreter::blind_catch`), when nothing else holds it: no traceback +/// entry and no shell are built for the callee. The caller's clause runs +/// first, then the callee's stack, the exception and the callee's locals +/// go, in the order the unwinding, the clause's `POP_EXCEPT` and the +/// traceback's end would have released them. The caller's state is left +/// past the clause and marked caught (`RAISED`, for `super::h_catch` to +/// go on from); `None` touched nothing. +/// +/// # Safety +/// +/// As [`raise_unseen`]'s, past its checks. +#[inline(never)] +unsafe fn blind_swallow(st: &mut State, rec: &mut DirectRec) -> Option { + // SAFETY: the caller's contract. + unsafe { + let Some(crate::RuntimeError::PyException(e)) = &rec.st.err else { + return None; + }; + let Object::Instance(inst) = &e.instance else { + return None; + }; + if Rc::strong_count(inst) != 1 { + return None; + } + let cls: *const crate::types::TypeObject = inst.cls_raw(); + let (pc, start) = (rec.call.pc(), rec.call.start()); + let caller_frame = &mut *st.frame; + if caller_frame.code.instructions.get(pc as usize)?.op != weavepy_compiler::OpCode::Call { + return None; + } + let interp = &mut *st.interp.cast_mut(); + // (The caller's stack still holds the callable at `start`: the + // catch releases it with whatever else lies above the handler's + // depth.) + let (len, end) = interp.blind_catch( + caller_frame, + st.locals, + st.stack, + start + 1, + st.cap, + pc, + &*cls, + )?; + let fr = &mut *rec.frame; + let err = rec.st.err.take(); + let n = rec.st.len; + rec.st.len = 0; + fr.stack.set_len(0); + crate::release_run(rec.st.stack, n); + if let Some(crate::RuntimeError::PyException(mut exc)) = err { + let instance = std::mem::replace(&mut exc.instance, Object::None); + interp.release(instance); + } + crate::release_activation_locals(fr, false); + let dc = &*st.depth_cell; + dc.set(dc.get() - 1); + st.len = len; + st.pc = end as usize + 1; + st.last = end as usize; + st.caught = true; + Some(super::RAISED) + } +} + /// [`leave`] when the return isn't clean. #[cold] #[inline(never)] unsafe fn left_uncleanly(st: &mut State, rec: &mut DirectRec, status: u32, op: Op<'_>) -> u32 { // SAFETY: as `leave`'s. unsafe { + if status == super::RAISED { + if let Some(r) = raise_unseen(st, rec, op) { + return r; + } + } super::register_lazy(&mut rec.st); let (pc, start) = (rec.call.pc(), rec.call.start()); let callee = rec.st.frame; diff --git a/crates/weavepy-vm/src/frame_slots.rs b/crates/weavepy-vm/src/frame_slots.rs index ec22c69c9..2474815c9 100644 --- a/crates/weavepy-vm/src/frame_slots.rs +++ b/crates/weavepy-vm/src/frame_slots.rs @@ -559,15 +559,16 @@ fn release_held_cells_and_locals( return release_values(locals); }; // The slot of each cell variable that is an argument (its value moved - // out of the slot into the cell). - let args: &[u32] = crate::code_vm_ext(code).map_or(&[], |ext| &ext.cell_args); + // out of the slot into the cell), and the inverse. + let (args, of_slot): (&[u32], &[u32]) = + crate::code_vm_ext(code).map_or((&[], &[]), |ext| (&ext.cell_args, &ext.cell_of_slot)); let args = &args[..args.len().min(held.len())]; - let Some(top_arg) = args.iter().copied().filter(|&s| s != u32::MAX).max() else { + if of_slot.is_empty() { while let Some(cell) = held.pop() { drop(cell); } return release_values(locals); - }; + } let ncells = held.len(); let cell_base = held.as_mut_ptr(); let nlocals = locals.len(); @@ -585,9 +586,10 @@ fn release_held_cells_and_locals( } for k in (0..nlocals).rev() { std::ptr::drop_in_place(local_base.add(k)); - if k <= top_arg as usize { - if let Some(i) = args.iter().position(|&s| s as usize == k) { - std::ptr::drop_in_place(cell_base.add(i)); + // (`u32::MAX`, a slot with no cell, is past `args`.) + if let Some(&i) = of_slot.get(k) { + if (i as usize) < args.len() { + std::ptr::drop_in_place(cell_base.add(i as usize)); } } } diff --git a/crates/weavepy-vm/src/frozen_code_cache.rs b/crates/weavepy-vm/src/frozen_code_cache.rs index 2238650f8..567de2a30 100644 --- a/crates/weavepy-vm/src/frozen_code_cache.rs +++ b/crates/weavepy-vm/src/frozen_code_cache.rs @@ -153,10 +153,58 @@ fn disk_dir() -> Option<&'static PathBuf> { .as_ref() } -/// The artifact path for a frozen module. Frozen names are dotted -/// identifiers (`os.path`), safe as single filename components. -fn disk_path(name: &str) -> Option { - Some(disk_dir()?.join(name)) +/// The artifact path for a frozen module's source: its name and the +/// source's hash, so two builds whose frozen sources differ (a developer's +/// branches, a benchmark's merge-base build run between the PR's) keep an +/// artifact each instead of compiling and replacing the other's at every +/// start. Frozen names are dotted identifiers (`os.path`), safe as single +/// filename components. +fn disk_path(name: &str, source: &str) -> Option { + let hash = crate::stdlib::frozen_source_hash(name, source); + Some(disk_dir()?.join(format!("{name}.{hash:016x}"))) +} + +/// After a write of `keep`, remove `name`'s artifacts for other sources +/// (and its unhashed one, an earlier layout's) that no start has replaced +/// for a day, so the directory doesn't grow with every source change. (A +/// fresher one may belong to a build still in use.) +fn prune_stale(name: &str, keep: &std::path::Path) { + let Some(dir) = keep.parent() else { + return; + }; + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + let day = std::time::Duration::from_hours(24); + for entry in entries.flatten() { + let file = entry.file_name(); + let Some(file) = file.to_str() else { + continue; + }; + // (An unhashed name is an earlier layout's artifact.) + let Some(rest) = file.strip_prefix(name) else { + continue; + }; + let hashed = rest + .strip_prefix('.') + .is_some_and(|h| h.len() == 16 && h.bytes().all(|b| b.is_ascii_hexdigit())); + if !(rest.is_empty() || hashed) { + continue; + } + let path = entry.path(); + if path == keep { + continue; + } + let old = entry + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.elapsed().ok()) + .is_some_and(|age| age > day); + if old { + let _ = std::fs::remove_file(&path); + } + } } /// Try the on-disk cache for a frozen module. On a healthy hit the @@ -166,7 +214,7 @@ fn disk_path(name: &str) -> Option { pub fn get_disk(name: &str, source: &str, filename: &str) -> Option { use std::io::Read; use weavepy_compiler::native_code; - let mut file = std::fs::File::open(disk_path(name)?).ok()?; + let mut file = std::fs::File::open(disk_path(name, source)?).ok()?; let size = usize::try_from(file.metadata().ok()?.len()).ok()?; let mut head = [0u8; FROZEN_HEADER_LEN]; file.read_exact(&mut head).ok()?; @@ -245,19 +293,36 @@ impl weavepy_compiler::CodeBytes for Payload { return; } read(weavepy_compiler::CodeBytes::bytes(self)); + // (Every [`LINUX_READS_PER_DROP`]th read: a run reads most bodies in + // bursts from one module, and dropping the pages after each read + // faults them back in for the next.) #[cfg(target_os = "linux")] - // SAFETY: a read-only file mapping: dropping its page table entries - // loses nothing, and the next read faults the pages back in. - unsafe { - libc::madvise( - self.map.as_ptr().cast_mut().cast(), - self.map.len(), - libc::MADV_DONTNEED, - ); + { + use std::sync::atomic::{AtomicU32, Ordering}; + static READS: AtomicU32 = AtomicU32::new(0); + if READS.fetch_add(1, Ordering::Relaxed) % LINUX_READS_PER_DROP + == LINUX_READS_PER_DROP - 1 + { + // SAFETY: a read-only file mapping: dropping its page table + // entries loses nothing, and the next read faults the pages + // back in. + unsafe { + libc::madvise( + self.map.as_ptr().cast_mut().cast(), + self.map.len(), + libc::MADV_DONTNEED, + ); + } + } } } } +/// The body reads between drops of a mapping's pages on Linux (see +/// `Payload::read`). +#[cfg(target_os = "linux")] +const LINUX_READS_PER_DROP: u32 = 64; + #[cfg(target_os = "macos")] impl Drop for Payload { fn drop(&mut self) { @@ -396,7 +461,7 @@ fn discard_disk_cache() { } pub fn write_disk(name: &str, source: &str, code: &CodeObject) { - let Some(path) = disk_path(name) else { + let Some(path) = disk_path(name, source) else { return; }; if let Some(parent) = path.parent() { @@ -416,7 +481,9 @@ pub fn write_disk(name: &str, source: &str, code: &CodeObject) { // half-written artifact. let tmp = path.with_extension(format!("tmp.{}", std::process::id())); if std::fs::write(&tmp, &bytes).is_ok() { - let _ = std::fs::rename(&tmp, &path); + if std::fs::rename(&tmp, &path).is_ok() { + prune_stale(name, &path); + } } else { let _ = std::fs::remove_file(&tmp); } diff --git a/crates/weavepy-vm/src/gc_trace.rs b/crates/weavepy-vm/src/gc_trace.rs index 4474c4a77..8906db3ac 100644 --- a/crates/weavepy-vm/src/gc_trace.rs +++ b/crates/weavepy-vm/src/gc_trace.rs @@ -961,6 +961,12 @@ impl GcState { /// collector already holds it. `false` leaves it to eager registration. #[inline] fn nurse_own(&self, set: &RefCell>, obj: &crate::Rc) -> bool { + self.nurse_ref(set, obj) + } + + /// [`Self::nurse_own`] given the object itself (alive, in an `Rc`). + #[inline(always)] + fn nurse_ref(&self, set: &RefCell>, obj: &T) -> bool { // SAFETY: nothing below runs code while the set is borrowed. let Some(young) = (unsafe { set.peek_mut() }) else { // A flush is walking the set, or cells are shared. @@ -971,7 +977,7 @@ impl GcState { return true; } slot.set(YOUNG_BIT | young.0.len() as u32); - young.0.push(crate::Rc::as_ptr(obj)); + young.0.push(std::ptr::from_ref(obj)); self.note_gen0_alloc(); true } @@ -1186,35 +1192,56 @@ impl GcState { /// garbage can appear, and nothing deferred here can be part of a /// cycle. A population that genuinely accumulates is paced by /// `DEFERRED_CAP` instead. + #[inline] fn defer_container(&self, obj: &Object) -> bool { let Some(weak) = DeferredContainer::new(obj) else { return false; }; + // SAFETY: nothing below runs code while the list is viewed (a dead + // predecessor's release only frees memory). + let Some(deferred) = (unsafe { self.deferred.peek_mut() }) else { + return self.defer_container_slow(weak); + }; + Self::push_deferred(deferred, weak); + if deferred.len() >= self.deferred_limit.load(Ordering::Relaxed) { + self.sweep_deferred(false); + } + true + } + + /// Queue `weak`, first reclaiming the dead predecessors just below the + /// tail: the churn shape (a loop that builds a container and drops the + /// previous one) leaves them there, so steady churn neither grows the + /// list nor parks dead allocations until a sweep. + #[inline(always)] + fn push_deferred(deferred: &mut Vec, weak: DeferredContainer) { + // (The last two, the last first, unrolled: a range loop over them + // cost a third of every deferral.) + if deferred.last().is_some_and(DeferredContainer::is_dead) { + deferred.pop(); + if deferred.last().is_some_and(DeferredContainer::is_dead) { + deferred.pop(); + } + } else if let Some(i) = deferred.len().checked_sub(2) { + if deferred[i].is_dead() { + deferred.swap_remove(i); + } + } + deferred.push(weak); + } + + /// [`Self::defer_container`] when the list is held by a guard: through + /// a borrow of its own, or (a sweep is already walking the list, which + /// upgrades and can re-enter through a promotion) not at all, the + /// container then tracked eagerly. + #[cold] + #[inline(never)] + fn defer_container_slow(&self, weak: DeferredContainer) -> bool { let over = { - // SAFETY: nothing below runs code while the list is borrowed - // (a dead predecessor's release only frees memory). - let mut guard = None; - let deferred = match unsafe { self.deferred.peek_mut() } { - Some(d) => d, - None => match self.deferred.try_borrow_mut() { - Ok(g) => &mut **guard.insert(g), - // A sweep is already walking the list (it upgrades and - // can re-enter through a promotion). Track eagerly - // rather than queue onto a list we cannot touch. - Err(_) => return false, - }, + let Ok(mut deferred) = self.deferred.try_borrow_mut() else { + return false; }; - // The churn shape — a loop that builds a container and drops - // the previous one — leaves its dead predecessors just below - // the tail: reclaim them here, so steady churn neither grows - // the list nor parks dead allocations until a sweep. - let n = deferred.len(); - for i in (n.saturating_sub(2)..n).rev() { - if deferred[i].is_dead() { - deferred.swap_remove(i); - } - } - deferred.push(weak); + Self::push_deferred(&mut deferred, weak); deferred.len() >= self.deferred_limit.load(Ordering::Relaxed) }; if over { @@ -1861,7 +1888,9 @@ impl GcState { /// structure and drops the previous one thus seldom collects, as in /// CPython; the pruning costs a few steps per allocation.) pub fn maybe_auto_collect(&self) -> bool { - if !self.is_enabled() || self.collecting.load(Ordering::Acquire) { + // (The gauge settles the common answer, not due yet, from one + // load: no borrow of the counts or thresholds.) + if !self.auto_collect_due() { return false; } // How many collections in a row have found nothing (see `wanted` @@ -3504,6 +3533,13 @@ fn traverse_impl(obj: &Object, visit: &mut visit_rc::(visit, meta, Object::Type); } } + // The `__mro__`/`__bases__` tuples the class keeps (see + // `TypeObject::links_tuple`), the MRO's one holding the class. + if let Ok(links) = t.link_tuples.try_borrow() { + for tuple in [&links.0, &links.1].into_iter().flatten() { + visit.visit(tuple); + } + } // The cached instantiation plan holds strong refs to the // resolved `__new__`/`__init__` (usually aliases of the dict // entries visited above, but still *extra* edges). Without @@ -3889,6 +3925,9 @@ pub fn clear_object_fields(obj: &Object) -> bool { if let Ok(mut mro) = t.mro.try_borrow_mut() { mro.clear(); } + if let Ok(mut links) = t.link_tuples.try_borrow_mut() { + *links = (None, None); + } if let Ok(mut meta) = t.metaclass.try_borrow_mut() { *meta = None; } @@ -3971,6 +4010,15 @@ pub fn track(obj: &Object) { return; } } + // A frozenset of atomic values (`frozenset((1, 2, 3))`) can never be + // part of a cycle, whatever happens later: it can't change. It isn't + // registered (`gc.is_tracked` registers it on asking, as CPython tracks + // every frozenset). + if let Object::FrozenSet(fs) = obj { + if fs.len() <= 64 && fs.iter().all(|k| is_atomic(&k.0)) { + return; + } + } if let Object::Instance(inst) = obj { // The instance may have been born with deferred tracking; its // `__dict__` no longer needs to guard it. @@ -4091,6 +4139,16 @@ pub fn track_deferred_owner(owner: usize) { track(&Object::Instance(inst)); } +/// [`track`] for the deferred instance `inst` once its records are +/// cleared (see `PyInstance::ensure_gc_tracked`): into the young set +/// directly when it's open, as `track` puts it there. +#[inline] +pub(crate) fn track_cleared_instance(inst: &crate::types::PyInstance) { + if !GC_STATE.nurse_ref(&GC_STATE.young, inst) { + track_deferred_owner(std::ptr::from_ref(inst) as usize); + } +} + /// True while a collection (mark/sweep or weakref-only pass) is in /// flight on the process-global collector. Used by the capi boundary to /// suppress side-effectful bookkeeping (e.g. the C-drop reap queue) for diff --git a/crates/weavepy-vm/src/gen_fast.rs b/crates/weavepy-vm/src/gen_fast.rs index 65b75f961..c1ba0e122 100644 --- a/crates/weavepy-vm/src/gen_fast.rs +++ b/crates/weavepy-vm/src/gen_fast.rs @@ -128,10 +128,23 @@ fn op_native(code: &CodeObject, pc: usize) -> bool { | OpCode::Swap | OpCode::PopJumpIfNone | OpCode::PopJumpIfNotNone + // (An exact tuple's or list's items, or the step stops + // there untouched: `for k, v in pairs: yield ...`.) + | OpCode::UnpackSequence ), } } +/// Native steps of one body that stopped partway, net of those that ran to +/// a yield, past which [`Interpreter::gen_native_next`] declines the body's +/// steps (a `for` loop over a generator whose body calls a Python +/// `__getitem__`: the loop's switched resume calls it, where each step +/// would stop at it and finish on the general path). One step in +/// [`STALL_RETRY`] past the limit runs again, and one that reaches a yield +/// starts the count over. +pub(crate) const STALL_LIMIT: u32 = 64; +const STALL_RETRY: u32 = 256; + /// [`code_ok`]'s verdicts (kept in the code's extension table). const CODE_NO: u8 = 1; const CODE_OK: u8 = 2; @@ -141,6 +154,12 @@ const CODE_NATIVE: u8 = 3; /// [`verdicts`]) sits above them. const CODE_MASK: u8 = 0x0f; const PROLOGUE_SHIFT: u32 = 4; +/// Beside the verdicts in the table's byte: nothing here ever steps the +/// body (its steady state is [`CODE_NO`], it has no `yield from` whose +/// delegate could step in its place, and it's no sequence walk), so a +/// resume declines on this bit alone (see +/// [`Interpreter::gen_native_next`]). +const NEVER_STEPS: u8 = 0x80; /// Whether `code` is a plain generator whose steady state, everything a /// resume can reach from a `yield`, is instructions a fast step runs @@ -166,8 +185,218 @@ fn code_ok(code: &CodeObject) -> u8 { fn verdicts(code: &CodeObject, ext: &crate::CodeConstObjects) -> u8 { match ext.gen_fast.load(std::sync::atomic::Ordering::Relaxed) { 0 => code_ok_scan(code, ext), - v => v, + v => v & !NEVER_STEPS, + } +} + +/// The sequence walk of `code`, if it is one (see +/// `Interpreter::gen_walk_step`): the pc `k` of a loop body +/// +/// ```text +/// k LOAD_FAST seq v = seq[i] +/// k+1 LOAD_FAST i +/// k+2 BINARY_SUBSCR +/// k+3 STORE_FAST v +/// k+4 LOAD_FAST v yield v +/// k+5 YIELD_VALUE +/// k+6 RESUME +/// k+7 POP_TOP +/// k+8 LOAD_FAST i i += 1 +/// k+9 LOAD_SMALL_INT 1 +/// k+10 BINARY_OP += +/// k+11 STORE_FAST i +/// k+12 JUMP_BACKWARD k +/// ``` +/// +/// over three distinct plain locals, the body's only `yield` +/// (`collections.abc.Sequence.__iter__`'s loop). Recorded in `ext` as +/// `k + 2`, or 1 for none, with [`WALK_FIRST`] when the body comes to the +/// loop by `i = 0` alone and [`WALK_END`] when an `IndexError` from the +/// read lands in `except IndexError: return` (see [`walk_ends_at`]). +#[cfg(feature = "jit")] +#[cold] +#[inline(never)] +fn walk_scan(code: &CodeObject, ext: &crate::CodeConstObjects) -> u32 { + let ins = &code.instructions; + let site = || { + if !code.is_generator + || code.is_coroutine + || code.is_async_generator + || code.is_iterable_coroutine + || !code.cellvars.is_empty() + || !code.freevars.is_empty() + { + return None; + } + let mut yields = ins + .iter() + .enumerate() + .filter(|(_, i)| matches!(i.op, OpCode::YieldValue)); + let (at, _) = yields.next()?; + if yields.next().is_some() { + return None; + } + let k = at.checked_sub(5)?; + let w = ins.get(k..k + 13)?; + let (seq, i, v) = (w[0].arg, w[1].arg, w[3].arg); + let load = |x: &weavepy_compiler::Instruction, n: u32| { + matches!(x.op, OpCode::LoadFast | OpCode::LoadFastBorrow) && x.arg == n + }; + let back = (k + 13).checked_sub(w[12].arg as usize)?; + let shape = load(&w[0], seq) + && load(&w[1], i) + && w[2].op == OpCode::BinarySubscr + && w[3].op == OpCode::StoreFast + && load(&w[4], v) + && w[6].op == OpCode::Resume + && w[7].op == OpCode::PopTop + && load(&w[8], i) + && w[9].op == OpCode::LoadSmallInt + && w[9].arg == 1 + && w[10].op == OpCode::BinaryOp + && w[10].arg == (BinOpKind::Add as u32 | weavepy_compiler::BINARY_OP_INPLACE_FLAG) + && w[11].op == OpCode::StoreFast + && w[11].arg == i + && w[12].op == OpCode::JumpBackward + && back <= k + && ins[back..k].iter().all(|x| x.op == OpCode::Nop); + let n = code.varnames.len() as u32; + if !(shape && seq != i && seq != v && i != v && seq < n && i < n && v < n && k < 0xfff0) { + return None; + } + // `RETURN_GENERATOR; POP_TOP; RESUME; i = 0`, then the loop. + let first = k >= 5 + && ins[0].op == OpCode::ReturnGenerator + && ins[1].op == OpCode::PopTop + && ins[2].op == OpCode::Resume + && ins[3].op == OpCode::LoadSmallInt + && ins[3].arg == 0 + && ins[4].op == OpCode::StoreFast + && ins[4].arg == i + && ins[5..k].iter().all(|x| x.op == OpCode::Nop); + let mut walk = k as u32 + 2; + if first { + walk |= WALK_FIRST; + } + if walk_ends_at(code, ext, k + 2) { + walk |= WALK_END; + } + Some(walk) + }; + let walk = site().unwrap_or(1); + ext.gen_walk + .store(walk, std::sync::atomic::Ordering::Relaxed); + walk +} + +/// [`walk_scan`]'s flags, above the walk's pc. +#[cfg(feature = "jit")] +const WALK_FIRST: u32 = 1 << 16; +#[cfg(feature = "jit")] +const WALK_END: u32 = 1 << 17; + +/// Whether an `IndexError` raised at `pc` of `code` (with nothing on the +/// stack) only ends the generator: its handler is `except IndexError: +/// return`, +/// +/// ```text +/// h PUSH_EXC_INFO +/// h+1 LOAD_GLOBAL IndexError +/// h+2 CHECK_EXC_MATCH +/// h+3 POP_JUMP_IF_FALSE +/// h+4 NOT_TAKEN +/// h+5 POP_TOP +/// h+6 POP_EXCEPT +/// h+7 LOAD_CONST None +/// h+8 RETURN_VALUE +/// ``` +/// +/// (The name must still resolve to the builtin class when a walk ends: +/// see `Interpreter::walk_catches`.) +#[cfg(feature = "jit")] +fn walk_ends_at(code: &CodeObject, ext: &crate::CodeConstObjects, pc: usize) -> bool { + let Some(entry) = code + .exception_table + .iter() + .find(|h| pc as u32 >= h.start && (pc as u32) < h.end) + else { + return false; + }; + if entry.depth != 0 || entry.push_lasti { + return false; + } + let h = entry.handler as usize; + let Some(w) = code.instructions.get(h..h + 9) else { + return false; + }; + w[0].op == OpCode::PushExcInfo + && w[1].op == OpCode::LoadGlobal + && code + .names + .get(w[1].arg as usize) + .is_some_and(|n| n.as_str() == "IndexError") + && w[2].op == OpCode::CheckExcMatch + && w[3].op == OpCode::PopJumpIfFalse + && w[4].op == OpCode::NotTaken + && w[5].op == OpCode::PopTop + && w[6].op == OpCode::PopExcept + && w[7].op == OpCode::LoadConst + && matches!(ext.objects.get(w[7].arg as usize), Some(Object::None)) + && w[8].op == OpCode::ReturnValue +} + +/// What [`Interpreter::gen_walk_step`] came to. +#[cfg(feature = "jit")] +enum Walk { + /// The next item, the frame suspended at the walk's `yield`. + Item(Object), + /// The sequence's end, which only finishes the generator (nothing + /// touched: the caller retires it). + End, + /// Neither, nothing touched. + No, +} + +/// Whether a generator suspended at `pc` of the code `ext` describes has +/// resumed there by its native code and come to a `yield` or `return` +/// (see `Interpreter::gen_native_next`): what that resume checked of the +/// code and the pc alone holds for every later one. The table keeps four +/// such pcs (a body with more resume points takes the long path at the +/// others), and none past 16 bits. +#[cfg(feature = "jit")] +#[inline(always)] +fn lean_pc(ext: &crate::CodeConstObjects, pc: usize) -> bool { + let m = ext.gen_lean.load(std::sync::atomic::Ordering::Relaxed); + let p = pc as u64; + m != 0 + && p.wrapping_sub(1) < 0xffff + && (m & 0xffff == p || (m >> 16) & 0xffff == p || (m >> 32) & 0xffff == p || m >> 48 == p) +} + +/// Note a clean resume at `pc` (see [`lean_pc`]), or (`on` false) take +/// the note back. +#[cfg(feature = "jit")] +#[cold] +#[inline(never)] +fn note_lean_pc(ext: &crate::CodeConstObjects, pc: usize, on: bool) { + use std::sync::atomic::Ordering::Relaxed; + let p = pc as u64; + if p.wrapping_sub(1) >= 0xffff { + return; } + let mut m = ext.gen_lean.load(Relaxed); + let slot = |m: u64, i: u32| (m >> (16 * i)) & 0xffff; + let held = (0..4).find(|&i| slot(m, i) == p); + match (on, held) { + (true, Some(_)) | (false, None) => return, + (false, Some(i)) => m &= !(0xffff << (16 * i)), + (true, None) => { + // (A free slot, else the one the pc's low bits pick.) + let i = (0..4).find(|&i| slot(m, i) == 0).unwrap_or(pc as u32 & 3); + m = (m & !(0xffff << (16 * i))) | (p << (16 * i)); + } + } + ext.gen_lean.store(m, Relaxed); } /// Whether a fast step may run `g`'s body at all (see [`code_ok`]). @@ -218,7 +447,16 @@ fn code_ok_scan(code: &CodeObject, ext: &crate::CodeConstObjects) -> u8 { (_, Some(at)) => verdict(&[at + 1], true), }; let v = v | (first << PROLOGUE_SHIFT); - ext.gen_fast.store(v, Ordering::Relaxed); + #[cfg(feature = "jit")] + let walks = match ext.gen_walk.load(Ordering::Relaxed) { + 0 => walk_scan(code, ext), + walk => walk, + } > 1; + #[cfg(not(feature = "jit"))] + let walks = false; + let never = v & CODE_MASK == CODE_NO && !walks && !instrs.iter().any(|i| i.op == OpCode::Send); + ext.gen_fast + .store(v | if never { NEVER_STEPS } else { 0 }, Ordering::Relaxed); v } @@ -404,6 +642,91 @@ fn scalar_truth(v: &Object) -> Option { }) } +/// A `SEND` of `None` to `it`, a `yield from`'s range, tuple or list +/// iterator: `Some(Some(item))` its next item, `Some(None)` its end (a +/// range's or tuple's, which frees nothing), `None` for the general path +/// (another iterator, or a list's end, which detaches the list and may free +/// a subclass's owner). Nothing here runs code. +#[inline] +pub(crate) fn send_iter_step(it: &Rc>) -> Option> { + let mut it = it.try_borrow_mut().ok()?; + // A plain dict's entries, the dict unchanged: the checked step's item, + // or its end (see `PyIterator::dict_step_quiet`). + if matches!(&*it, PyIterator::DictKeys { .. }) { + return it.dict_step_quiet(true); + } + match &mut *it { + PyIterator::Range { .. } | PyIterator::Tuple { .. } => Some(it.next_value()), + PyIterator::List { items, index, .. } => { + let v = items.try_borrow().ok()?.get(*index).cloned()?; + *index += 1; + Some(Some(v)) + } + _ => None, + } +} + +/// [`send_iter_step`] for a whole run: the remaining items of a range, +/// tuple or list iterator (up to a bound) appended to `out`, the cursor +/// left past them, for a `yield from` whose every yield a collecting +/// consumer would take. `false`, nothing taken, for any other iterator. +pub(crate) fn send_iter_drain( + it: &Rc>, + out: &mut Vec, +) -> bool { + const MAX: usize = 1 << 16; + let Ok(mut it) = it.try_borrow_mut() else { + return false; + }; + // (A plain dict's entries, as `send_iter_step` takes them one by one.) + if matches!(&*it, PyIterator::DictKeys { .. }) { + let mut n = 0; + while n < MAX { + match it.dict_step_quiet(false) { + Some(Some(k)) => out.push(k), + _ => break, + } + n += 1; + } + return n > 0; + } + match &mut *it { + PyIterator::Tuple { items, index } => { + let rest = items.get(*index..).unwrap_or(&[]); + let rest = &rest[..rest.len().min(MAX)]; + out.extend_from_slice(rest); + *index += rest.len(); + } + PyIterator::List { + items, + index, + owner: None, + } => { + let Ok(v) = items.try_borrow() else { + return false; + }; + let rest = v.get(*index..).unwrap_or(&[]); + let rest = &rest[..rest.len().min(MAX)]; + out.extend_from_slice(rest); + *index += rest.len(); + } + PyIterator::Range { + current, + stop, + step, + } if *step > 0 => { + let mut n = 0; + while *current < *stop && n < MAX { + out.push(Object::Int(*current)); + *current = current.wrapping_add(*step); + n += 1; + } + } + _ => return false, + } + true +} + /// How deep a chain of `yield from` delegations steps directly (see /// `Interpreter::gen_chain_step`). #[cfg(feature = "jit")] @@ -521,7 +844,8 @@ impl Interpreter { if stack.capacity() < want { stack.reserve(want - stack.len()); } - let (base, cap) = (stack.as_mut_ptr(), stack.capacity()); + #[cfg_attr(not(feature = "jit"), allow(unused_mut))] + let (mut base, mut cap) = (stack.as_mut_ptr(), stack.capacity()); let mut len = stack.len(); let mut pc = frame.pc as usize; if pc >= ninstrs { @@ -580,6 +904,7 @@ impl Interpreter { wait_pending: None, outer_lazy: 0, fold: fold.as_ref().map_or(std::ptr::null(), std::ptr::from_ref), + caught: false, }); nst.len = len; nst.pc = pc; @@ -761,6 +1086,20 @@ impl Interpreter { ext.frame_jit .warm(code, ext, nlocals, crate::frame_jit::Heat::Step); native = ext.frame_jit.get(nlocals); + // The native form arrived in the middle of the + // step, whose stack was sized without it: it grows + // now, as the next step's would (no view of it is + // built yet). Left small, every entry of a fold + // that drains the body in this one step would get + // nowhere, and the entries would be given up. + if let Some(n) = native.filter(|n| cap < n.need()) { + // SAFETY: the first `len` slots are initialized, + // as at the step's end. + unsafe { frame.stack.set_len(len) }; + frame.stack.reserve(n.need() - len); + base = frame.stack.as_mut_ptr(); + cap = frame.stack.capacity(); + } } } // `iter()` of an iterator or a generator is itself. @@ -964,6 +1303,7 @@ impl Interpreter { wait_pending: None, outer_lazy: 0, fold: std::ptr::null(), + caught: false, }; // SAFETY: the body's activation state, as `gen_fast_step` holds it. let status = unsafe { native.run(&mut st) }; @@ -1052,7 +1392,7 @@ impl Interpreter { return ForNext::Bail; } if !unique { - *items = Rc::new(crate::sync::RefCell::new(Vec::new())); + *items = crate::object::detached_store(); } return ForNext::Exhausted; }; @@ -1215,6 +1555,16 @@ impl Interpreter { level: u8, ) -> GenNext { use std::sync::atomic::Ordering; + // A body nothing below steps (a call in its loop, say), whatever + // its state: declined on its code's cached verdict, before any + // of the checks (160 instructions a resume otherwise, each ending + // in the same answer). + if g.code_ref().is_some_and(|code| { + crate::code_vm_ext_existing(code) + .is_some_and(|ext| ext.gen_fast.load(Ordering::Relaxed) & NEVER_STEPS != 0) + }) { + return GenNext::Declined; + } 'lean: { if g.chain.get() != 0 || depth_cell.is_null() { break 'lean; @@ -1224,31 +1574,82 @@ impl Interpreter { let Some(state) = (unsafe { g.state_raw().peek_mut() }) else { break 'lean; }; + // SAFETY: the running thread's own depth cell, not null. + if let Some(next) = + unsafe { self.gen_lean_resume(g, state, snap_gen, dead, depth_cell) } + { + return next; + } let first = match &*state { GeneratorState::Suspended(_) => false, GeneratorState::Created(_) => true, _ => break 'lean, }; - let (GeneratorState::Suspended(boxed) | GeneratorState::Created(boxed)) = &mut *state + let (GeneratorState::Suspended(boxed) | GeneratorState::Created(boxed)) = &*state else { break 'lean; }; - let frame: &mut Frame = boxed; // SAFETY: the frame's code outlives the step (as in // `gen_fast_step`). - let code: &CodeObject = unsafe { &*Rc::as_ptr(&frame.code) }; + let code: &CodeObject = unsafe { &*Rc::as_ptr(&boxed.code) }; let Some(ext) = crate::code_vm_ext(code) else { break 'lean; }; + // A fresh sequence walk's first step, on its frame. + if first { + let walk = ext.gen_walk.load(Ordering::Relaxed); + if walk != 1 { + if let Some(next) = self.gen_walk_apply(g, state, code, ext, walk) { + return next; + } + } + } + let (GeneratorState::Suspended(boxed) | GeneratorState::Created(boxed)) = &mut *state + else { + break 'lean; + }; + let frame: &mut Frame = boxed; + // A fresh body whose start no fast step runs (a call building + // its loop's iterator) declines at once, as the fast step's + // `gen_fast_ok` would after every check below: its first resume + // is the lazy one's. + if first && verdicts(code, ext) >> PROLOGUE_SHIFT == CODE_NO { + return GenNext::Declined; + } let pc = frame.pc as usize; - // Resting in a `yield from` over a generator (its delegate tops - // its stack): the delegate steps directly (see - // `gen_chain_step`). - if level < CHAIN_LEVELS - && matches!(frame.stack.last(), Some(Object::Generator(_))) - && crate::yield_from_resend(&code.instructions, pc).is_some() - { - return self.gen_chain_step(g, snap_gen, dead, depth_cell, level); + // (A loop's iterator tops the stack at most plain yields: the + // shortcuts below are for a `yield from`'s resume point alone.) + let resend = crate::yield_from_resend(&code.instructions, pc).is_some(); + if resend { + match frame.stack.last() { + // Resting in a `yield from` over a generator (its + // delegate tops its stack): the delegate steps directly + // (see `gen_chain_step`). + Some(Object::Generator(_)) if level < CHAIN_LEVELS => { + return self.gen_chain_step(g, snap_gen, dead, depth_cell, level); + } + // Resting in a `yield from` over a range, tuple or list + // iterator with an item left: the item, the frame + // untouched (a `SEND` of `None` to it and the + // `YIELD_VALUE` after are just that). Its end, and every + // other iterator, take the general resume. + Some(Object::Iter(it)) => { + if let Some(v) = Self::yield_from_iter_item(frame, code, pc, it) { + return GenNext::Yielded(v); + } + } + _ => {} + } + } + // A body whose steps keep stopping partway: declined untouched, + // for the caller's resume (but one in `STALL_RETRY`). + let stalls = ext.gen_stalls.load(Ordering::Relaxed); + if stalls >= STALL_LIMIT { + ext.gen_stalls + .store(stalls.saturating_add(1), Ordering::Relaxed); + if !(stalls - STALL_LIMIT).is_multiple_of(STALL_RETRY) { + return GenNext::Declined; + } } let Some(native) = ext.frame_jit.get(frame.locals.len()) else { break 'lean; @@ -1304,16 +1705,34 @@ impl Interpreter { frame.stack.push_fast(Object::None); // SAFETY: the checks above. let ran = unsafe { self.gen_native_run(frame, native, locals, snap_gen, 0, dead) }; + let stalls = ext.gen_stalls.load(Ordering::Relaxed); return match ran { - Ok((v, false)) => { - Self::park_stepped(g, boxed); - GenNext::Yielded(v) - } - Ok((v, true)) => { - self.retire_gen(g, boxed); - GenNext::Exhausted(v) + Ok((v, done)) => { + if stalls != 0 { + // (A retry past the limit that ran clean starts over.) + let next = if stalls >= STALL_LIMIT { 0 } else { stalls - 1 }; + ext.gen_stalls.store(next, Ordering::Relaxed); + } + // A suspended body's clean resume: the next one here + // is `gen_lean_resume`'s. + if !first && !resend { + if let Some(s) = code.stacksize { + native.note_lean_cap(s as usize); + note_lean_pc(ext, start as usize, true); + } + } + if done { + self.retire_gen(g, boxed); + GenNext::Exhausted(v) + } else { + Self::park_stepped(g, boxed); + GenNext::Yielded(v) + } } Err(at) => { + if stalls < STALL_LIMIT { + ext.gen_stalls.store(stalls + 1, Ordering::Relaxed); + } self.gen_resume_rest(g, boxed, ext, start, false, at, snap_gen, 0, None, dead) } }; @@ -1321,6 +1740,359 @@ impl Interpreter { self.gen_fast_next(g, snap_gen, 0, dead) } + /// [`Self::gen_walk_step`] of `g`, suspended or fresh in `state` + /// (its body `code`, whose recorded walk is `walk`, scanned here if it + /// isn't yet): the step's item with `g` left suspended at the walk's + /// `yield`, or its end with `g` finished. `None` with nothing touched + /// when the body is no walk or the step declines. + #[cfg(feature = "jit")] + #[inline(never)] + fn gen_walk_apply( + &self, + g: &Rc, + state: &mut GeneratorState, + code: &CodeObject, + ext: &crate::CodeConstObjects, + walk: u32, + ) -> Option { + let walk = if walk == 0 { + walk_scan(code, ext) + } else { + walk + }; + if walk <= 1 { + return None; + } + let first = matches!(state, GeneratorState::Created(_)); + let (GeneratorState::Suspended(boxed) | GeneratorState::Created(boxed)) = &mut *state + else { + return None; + }; + match self.gen_walk_step(boxed, code, walk, first) { + Walk::No => None, + Walk::Item(v) => { + if first { + let GeneratorState::Created(boxed) = + std::mem::replace(state, GeneratorState::Running) + else { + unreachable!("checked above"); + }; + Self::park_stepped(g, boxed); + } + Some(GenNext::Yielded(v)) + } + Walk::End => { + let (GeneratorState::Suspended(boxed) | GeneratorState::Created(boxed)) = + std::mem::replace(state, GeneratorState::Running) + else { + unreachable!("checked above"); + }; + self.retire_gen(g, boxed); + Some(GenNext::Exhausted(Object::None)) + } + } + } + + /// [`Self::gen_walk_apply`] for a consumer with only the generator in + /// hand (a drain, whose folding resume would run the walk's reads as + /// calls): `None` with nothing touched for any other generator. + #[cfg(feature = "jit")] + pub(crate) fn gen_walk_next(&self, g: &Rc) -> Option { + if g.chain.get() != 0 { + return None; + } + // SAFETY: nothing below reaches the cell again until `state`'s + // last use (`peek_mut` rejects a live guard or shared cells). + let state = unsafe { g.state_raw().peek_mut() }?; + let (GeneratorState::Suspended(boxed) | GeneratorState::Created(boxed)) = &*state else { + return None; + }; + // SAFETY: the frame's code outlives the step. + let code: &CodeObject = unsafe { &*Rc::as_ptr(&boxed.code) }; + let ext = crate::code_vm_ext_existing(code)?; + let walk = ext.gen_walk.load(std::sync::atomic::Ordering::Relaxed); + if walk == 1 { + return None; + } + self.gen_walk_apply(g, state, code, ext, walk) + } + + /// One step of a generator in a sequence walk (`walk`, see + /// [`walk_scan`]) taken on its frame, with no resume: suspended at the + /// walk's `yield`, what its resume would do up to the next `yield` + /// (`i += 1; v = seq[i]; yield v`); fresh (`first`), what its first + /// would (`i = 0; v = seq[0]; yield v`); parked at the walk's read by + /// a fast step that stopped there (its operands on the stack, the sent + /// value consumed), the read and what follows it. The frame is left + /// at the walk's `yield`. Only where `seq[i]` is a pure leaf + /// `__getitem__`'s to answer (see [`Self::leaf_item`]): the frame's + /// locals are left as the body's own stores leave them. A plain + /// sequence's own index miss there is [`Walk::End`] when the body's + /// handler only returns (the `IndexError` raised, caught and dropped + /// unseen). [`Walk::No`] with nothing touched for anything else: + /// another receiver, a frame with state of its own, an observer. + #[cfg(feature = "jit")] + #[inline(always)] + fn gen_walk_step(&self, frame: &mut Frame, code: &CodeObject, walk: u32, first: bool) -> Walk { + use std::sync::atomic::Ordering; + let k = (walk & 0xffff) as usize - 2; + let pc = frame.pc as usize; + let at_read = !first && pc == k + 2; + let placed = if first { + pc == 1 && walk & WALK_FIRST != 0 && frame.stack.is_empty() && !frame.sent_consumed + } else if at_read { + frame.sent_consumed && frame.stack.len() == 2 + } else { + pc == k + 6 && !frame.sent_consumed + }; + if !placed + || frame.py_frame.is_some() + || frame.has_saved_exc_info() + || frame.parked_native.is_some() + || frame + .shell_cache + .as_ref() + .is_some_and(|c| c.has_materialized.load(Ordering::Relaxed)) + || crate::trace::eval_frame_record_active() + { + return Walk::No; + } + let ins = &code.instructions; + let (seq, i, v) = ( + ins[k].arg as usize, + ins[k + 1].arg as usize, + ins[k + 3].arg as usize, + ); + // SAFETY: a suspended generator's frame, which nothing else holds; + // the evaluation below is pure, and what the step displaces (whose + // release may run a finalizer) leaves after the views' last use. + let Some(locals) = (unsafe { frame.locals.peek_mut() }) else { + return Walk::No; + }; + if locals.len() < code.varnames.len() { + return Walk::No; + } + // The read's operands: the stack's when the frame rests there. + let (recv, next) = if at_read { + let Object::Int(n) = frame.stack[1] else { + return Walk::No; + }; + (&frame.stack[0], n) + } else if first { + (&locals[seq], 0) + } else { + let Object::Int(now) = locals[i] else { + return Walk::No; + }; + match now.checked_add(1) { + Some(n) => (&locals[seq], n), + None => return Walk::No, + } + }; + if next < 0 { + return Walk::No; + } + match self.leaf_item(recv, next, false) { + Some(Some(item)) => { + let old = std::mem::replace(&mut locals[v], crate::clone_hot(&item)); + let mut popped = None; + if at_read { + popped = frame.stack.pop().zip(frame.stack.pop()); + frame.sent_consumed = false; + } else { + locals[i] = Object::Int(next); + } + frame.pc = (k + 6) as u32; + drop(popped); + drop(old); + Walk::Item(item) + } + Some(None) if walk & WALK_END != 0 && self.walk_catches(frame) => Walk::End, + _ => Walk::No, + } + } + + /// Whether `IndexError`, as `frame`'s body reads the name, is the + /// builtin class (see [`walk_ends_at`]): its plain globals don't hold + /// the name and its builtins hold the class. + #[cfg(feature = "jit")] + fn walk_catches(&self, frame: &Frame) -> bool { + let key = crate::object::StrKey("IndexError"); + if self.globals_missing_owner(&frame.globals).is_some() { + return false; + } + let Ok(globals) = frame.globals.try_borrow() else { + return false; + }; + if globals.get(&key).is_some() { + return false; + } + let Ok(builtins) = frame.builtins.try_borrow() else { + return false; + }; + matches!(builtins.get(&key), Some(Object::Type(t)) + if Rc::ptr_eq(t, &crate::builtin_types::builtin_types().index_error)) + } + + /// [`Self::gen_native_next`] for a generator suspended where its body's + /// native code has resumed before and come to a `yield` or `return` + /// ([`lean_pc`]). That resume settled everything about the code + /// and the pc (no `yield from` rests there, the native code enters + /// there, the body's verdict), so this one asks only what can change + /// between two resumes: the frame's own extra state, the room on its + /// stack, the recorder, the recursion depth, and a body that lately + /// stopped partway (its stalls are the long path's to count). `None` + /// with nothing touched for anything else. + /// + /// # Safety + /// + /// `state` is `g`'s state, which nothing else borrows, and + /// `depth_cell` the running thread's depth cell. + #[cfg(feature = "jit")] + #[inline(always)] + unsafe fn gen_lean_resume( + &mut self, + g: &Rc, + state: &mut GeneratorState, + snap_gen: u64, + dead: *const std::cell::Cell, + depth_cell: *const std::cell::Cell, + ) -> Option { + use std::sync::atomic::Ordering; + let GeneratorState::Suspended(boxed) = &*state else { + return None; + }; + // SAFETY: the frame's code outlives the step (as in + // `gen_fast_step`). + let code: &CodeObject = unsafe { &*Rc::as_ptr(&boxed.code) }; + let ext = crate::code_vm_ext_existing(code)?; + // A sequence walk steps on its frame, with no resume. + let walk = ext.gen_walk.load(Ordering::Relaxed); + if walk != 1 { + if let Some(next) = self.gen_walk_apply(g, state, code, ext, walk) { + return Some(next); + } + } + let GeneratorState::Suspended(boxed) = &mut *state else { + return None; + }; + let frame: &mut Frame = boxed; + let pc = frame.pc as usize; + // (First what turns most others away: a generator resting in a + // `yield from`, or one whose body has yet to resume clean.) + if !lean_pc(ext, pc) { + return None; + } + // SAFETY: as in `gen_fast_step`. + let locals = unsafe { frame.locals.peek_mut() }?; + let native = ext.frame_jit.get(locals.len())?; + let (depth, cap) = (frame.stack.len(), frame.stack.capacity()); + if frame.sent_consumed + || frame.py_frame.is_some() + || frame.has_saved_exc_info() + || frame.parked_native.is_some() + || frame + .shell_cache + .as_ref() + .is_some_and(|c| c.has_materialized.load(Ordering::Relaxed)) + || crate::trace::eval_frame_record_active() + || ext.gen_stalls.load(Ordering::Relaxed) != 0 + || depth + 2 > cap + || cap < native.lean_cap() + // SAFETY: the caller's contract. + || unsafe { (*depth_cell).get() } + 2 >= crate::recursion::recursion_limit() + { + return None; + } + let locals = locals.as_mut_ptr(); + // Committed: the generator runs. + let GeneratorState::Suspended(mut boxed) = + std::mem::replace(state, GeneratorState::Running) + else { + unreachable!("checked above"); + }; + let frame: &mut Frame = &mut boxed; + frame.gen_first_resume = false; + frame.stack.push_fast(Object::None); + // SAFETY: the checks above, and the resume that set the note. + let ran = unsafe { self.gen_native_run(frame, native, locals, snap_gen, 0, dead) }; + Some(match ran { + Ok((v, false)) => { + Self::park_stepped(g, boxed); + GenNext::Yielded(v) + } + Ok((v, true)) => { + self.retire_gen(g, boxed); + GenNext::Exhausted(v) + } + // Stopped partway: the long path's again, until a resume here + // runs clean. + Err(at) => { + note_lean_pc(ext, pc, false); + ext.gen_stalls.store(1, Ordering::Relaxed); + self.gen_resume_rest(g, boxed, ext, pc as u32, false, at, snap_gen, 0, None, dead) + } + }) + } + + /// The next item of `it`, the native iterator a generator's suspended + /// `frame` (at `pc` of `code`) rests on in a `yield from`, when stepping + /// it runs no code and doesn't end it (see `gen_native_next`). + #[inline] + pub(crate) fn yield_from_iter_item( + frame: &Frame, + code: &CodeObject, + pc: usize, + it: &Rc>, + ) -> Option { + // (A loop's iterator tops the stack at a plain yield: only a + // `yield from`'s resume point goes on.) + let send = crate::yield_from_resend(&code.instructions, pc)?; + Self::yield_from_iter_step(frame, code, send, it) + } + + /// [`Self::yield_from_iter_item`] past its resume-point check (`send` + /// is the `SEND`'s pc). + #[inline(never)] + fn yield_from_iter_step( + frame: &Frame, + code: &CodeObject, + send: usize, + it: &Rc>, + ) -> Option { + use std::sync::atomic::Ordering; + if code.instructions[send].arg & crate::GEN_SEND != 0 + || frame.sent_consumed + || frame.py_frame.is_some() + || frame.has_saved_exc_info() + || frame.parked_native.is_some() + || frame + .shell_cache + .as_ref() + .is_some_and(|c| c.has_materialized.load(Ordering::Relaxed)) + || crate::trace::eval_frame_record_active() + { + return None; + } + let mut it = it.try_borrow_mut().ok()?; + // A plain dict's entries, the dict unchanged and one left + // (`KeysView.__iter__` over a mapping whose `__iter__` is its + // dict's): the checked step's item. + if matches!(&*it, PyIterator::DictKeys { .. }) { + return it.dict_step_quiet(false).flatten(); + } + match &mut *it { + PyIterator::Range { .. } | PyIterator::Tuple { .. } => it.next_value(), + // (A list's end detaches it and may free a subclass owner.) + PyIterator::List { items, index, .. } => { + let v = items.try_borrow().ok()?.get(*index).cloned()?; + *index += 1; + Some(v) + } + _ => None, + } + } + /// [`Self::gen_native_next`] for a generator resting in a `yield from` /// over another generator: the delegate steps directly (itself through /// `gen_native_next`, one level deeper), and what it yields is what `g` @@ -1375,7 +2147,10 @@ impl Interpreter { .is_some_and(|c| c.has_materialized.load(Ordering::Relaxed)) || crate::trace::eval_frame_record_active() || Rc::ptr_eq(d, g) - || !may_step(d) + // (A delegate whose body no fast step runs may still rest in + // a `yield from` of its own, which steps it the same way; one + // that doesn't declines at once, touching nothing.) + || d.chain.get() != 0 { break 'chain; } diff --git a/crates/weavepy-vm/src/gil.rs b/crates/weavepy-vm/src/gil.rs index 23b38aac9..397e92a92 100644 --- a/crates/weavepy-vm/src/gil.rs +++ b/crates/weavepy-vm/src/gil.rs @@ -279,8 +279,11 @@ impl GilState { self.note_acquired(); let me = current_thread_id(); crate::sync::note_vm_thread(me); + crate::sync::note_gil_thread(me); self.holder.store(me, Ordering::Release); - self.depth.fetch_add(1, Ordering::AcqRel); + if self.depth.fetch_add(1, Ordering::AcqRel) == 0 { + crate::sync::gil_taken(); + } // We must hold the parking_lot guard for the lifetime // of the GilGuard. Stash a transmuted-lifetime guard // inside the result, paired with a clone of the Arc to @@ -310,8 +313,11 @@ impl GilState { self.note_acquired(); let me = current_thread_id(); crate::sync::note_vm_thread(me); + crate::sync::note_gil_thread(me); self.holder.store(me, Ordering::Release); - self.depth.fetch_add(1, Ordering::AcqRel); + if self.depth.fetch_add(1, Ordering::AcqRel) == 0 { + crate::sync::gil_taken(); + } // SAFETY: as in `acquire`. let static_guard: parking_lot::ReentrantMutexGuard<'static, ()> = unsafe { std::mem::transmute(lock_guard) }; @@ -335,8 +341,11 @@ impl GilState { self.note_acquired(); let me = current_thread_id(); crate::sync::note_vm_thread(me); + crate::sync::note_gil_thread(me); self.holder.store(me, Ordering::Release); - self.depth.fetch_add(1, Ordering::AcqRel); + if self.depth.fetch_add(1, Ordering::AcqRel) == 0 { + crate::sync::gil_taken(); + } let static_guard: parking_lot::ReentrantMutexGuard<'static, ()> = unsafe { std::mem::transmute(lock_guard) }; Some(GilGuard { @@ -451,8 +460,10 @@ impl Drop for GilGuard { // Never touched holder/depth on acquire. return; } - self.state.depth.fetch_sub(1, Ordering::AcqRel); - if self.state.depth.load(Ordering::Acquire) == 0 { + // (Still under the lock: the field that releases it drops after + // this body.) + if self.state.depth.fetch_sub(1, Ordering::AcqRel) == 1 { + crate::sync::gil_given_up(); self.state.holder.store(0, Ordering::Release); } } @@ -701,12 +712,35 @@ pub fn push_gil_guard(g: GilGuard) { GIL_GUARD_STACK.with(|cell| cell.borrow_mut().push(g)); } +/// Register the calling thread's guard stack for destruction now, ahead +/// of its other thread-locals. A thread's destructors run in the reverse +/// of the order its thread-locals were first used, so a guard a thread +/// leaves on a stack armed first keeps the GIL through every other +/// destructor of that thread, and gives it back in the stack's own. +pub(crate) fn arm_guard_stack() { + let _ = GIL_GUARD_STACK.try_with(|_| ()); +} + /// Pop and return the top guard. Returns `None` when the calling /// thread doesn't hold the GIL through this stack. pub fn pop_gil_guard() -> Option { GIL_GUARD_STACK.with(|cell| cell.borrow_mut().pop()) } +/// [`current_thread_holds_gil`] for a caller that may run in a +/// thread-local destructor (`false` once the guard stack is gone). +pub(crate) fn try_current_thread_holds_gil() -> bool { + GIL_GUARD_STACK + .try_with(|cell| cell.try_borrow().is_ok_and(|v| !v.is_empty())) + .unwrap_or(false) +} + +/// Whether the calling thread owns the GIL's lock, through the guard +/// stack or not (a thread-local destructor's own acquire, say). +pub(crate) fn holds_gil_lock() -> bool { + global_gil_ref().lock.is_owned_by_current_thread() +} + /// `True` if the calling thread holds the GIL via this stack. pub fn current_thread_holds_gil() -> bool { GIL_GUARD_STACK.with(|cell| !cell.borrow().is_empty()) @@ -765,6 +799,10 @@ impl GilScope { impl Drop for GilScope { fn drop(&mut self) { if self.engaged { + // This thread may touch objects after its outermost scope + // (an embedder reading a result): with other threads + // running, counts are atomic from here on. + crate::sync::counts_leave_gil(); // The cooperative hand-off may have replaced the stack's // guards meanwhile, but it restores as many as it took. drop(GIL_GUARD_STACK.try_with(|cell| cell.borrow_mut().pop())); @@ -819,6 +857,20 @@ impl Drop for ReleaseUnderGil { } } +/// What a thread does before it releases the GIL to block: other threads +/// may look at its frames meanwhile, so lean activations waiting for their +/// shells and lazily running ones get them first. With no other thread (a +/// second thread is recorded before it starts) and no dump armed, nothing can look until this thread runs again, and whatever +/// looks then makes the spine whole first (an event loop's `select` blocks +/// once a step). Every release of the GIL by a thread with frames goes +/// through here (C code's `PyEval_SaveThread` too). +#[inline] +pub fn before_gil_release() { + if crate::sync::threads_started() || crate::stdlib::faulthandler_mod::may_read_frames() { + crate::builtins::sync_frame_spine(); + } +} + /// RFC 0025: drop the GIL, run `f`, re-acquire the GIL, then /// return `f`'s result. Used by every blocking-I/O / lock-acquire /// path that would otherwise prevent other threads from running. @@ -832,17 +884,7 @@ impl Drop for ReleaseUnderGil { /// Py_END_ALLOW_THREADS`. The C-API macros' expansion /// (`PyEval_SaveThread()` / `PyEval_RestoreThread()`) lands here. pub fn allow_threads_then(f: impl FnOnce() -> R) -> R { - // Other threads may look at this one's frames while it blocks: lean - // activations waiting for their shells get them first. With no other - // thread (a second thread turns shared reference counts on before it - // starts) and no dump armed, nothing can look until this thread runs - // again, and whatever looks then makes the spine whole first (an event - // loop's `select` blocks once a step). - if crate::sync::rc_shared_flag().load(Ordering::Relaxed) - || crate::stdlib::faulthandler_mod::may_read_frames() - { - crate::builtins::sync_frame_spine(); - } + before_gil_release(); // Pop every guard we currently hold (a worker calls // `start_new_thread` -> builtin -> `allow_threads_then` with // exactly one guard; nested cases pop them all). @@ -1090,8 +1132,13 @@ fn maybe_yield_gil() { // shared counter (the `test_release_task_refs` race). Both clocks must // have run out: the holder has held for the interval *and* the waiter // has waited for it (`WAITER_SEEN_SINCE`), which is what CPython's - // waiter-timed drop request amounts to. - if !switch_interval_elapsed() || !waiter_interval_elapsed() { + // waiter-timed drop request amounts to. The two run side by side: + // the waiter's clock starts at the first checkpoint that sees it, + // whatever the holder's says (started only once the holder's had run + // out, it made a thread back from a blocking call wait two intervals + // for a busy one, 10 ms where CPython waits 5). + let waited = waiter_interval_elapsed(); + if !switch_interval_elapsed() || !waited { return; } // The next holder may look at this thread's frames (see diff --git a/crates/weavepy-vm/src/import.rs b/crates/weavepy-vm/src/import.rs index a13e172d1..82260b35b 100644 --- a/crates/weavepy-vm/src/import.rs +++ b/crates/weavepy-vm/src/import.rs @@ -62,7 +62,7 @@ pub struct ModuleCache { /// import from another thread block until the body finishes, like /// CPython's per-module import lock (bpo-34572, /// test_pickle test_unpickle_module_race). - pub initializing: Rc>>, + pub initializing: Rc>>, /// Names currently inside `load_one`'s find+create+exec sequence, /// mapped to the loading thread — CPython's per-module /// `_ModuleLockManager` window, which is *wider* than @@ -116,7 +116,7 @@ impl Default for ModuleCache { builtins: Rc::new(RefCell::new(HashMap::new())), frozen: Rc::new(FrozenRegistry::default()), frozen_tests_override: Rc::new(crate::sync::Cell::new(0)), - initializing: Rc::new(RefCell::new(std::collections::HashMap::new())), + initializing: Rc::new(RefCell::new(crate::fasthash::FxHashMap::default())), loading: Rc::new(RefCell::new(std::collections::HashMap::new())), import_waiting: Rc::new(RefCell::new(std::collections::HashMap::new())), startup_path0: Rc::new(RefCell::new(None)), @@ -149,6 +149,15 @@ impl ModuleCache { self.modules.borrow().get(&StrKey(full_name)).cloned() } + /// [`Self::get`] with `hash`, which must be `py_str_hash(full_name)` + /// (a `str` object's memoized hash), so the probe doesn't hash it. + pub fn get_hashed(&self, full_name: &str, hash: i64) -> Option { + self.modules + .borrow() + .get(&crate::object::StrKeyHashed { s: full_name, hash }) + .cloned() + } + /// Install a loaded module in the cache. CPython treats /// `sys.modules` writes as authoritative — subsequent imports /// of the same name return whatever is in the cache, regardless diff --git a/crates/weavepy-vm/src/inst_dict.rs b/crates/weavepy-vm/src/inst_dict.rs index 4980859c8..95bc63d49 100644 --- a/crates/weavepy-vm/src/inst_dict.rs +++ b/crates/weavepy-vm/src/inst_dict.rs @@ -590,6 +590,21 @@ impl SplitValues { /// [`Self::append_over`] and compiled code's new-key stores). Nothing /// when a block exists (values, or a recycled one) or `cap` is zero. pub(crate) fn reserve_for(&mut self, keys: impl FnOnce() -> Rc, cap: usize) { + if self.block.is_some() || cap == 0 { + return; + } + self.reserve_new(keys, cap); + } + + /// Whether the values have a block (values, or a recycled one). + #[inline] + pub(crate) fn has_block(&self) -> bool { + self.block.is_some() + } + + /// [`Self::reserve_for`] past its checks. + #[inline(never)] + fn reserve_new(&mut self, keys: impl FnOnce() -> Rc, cap: usize) { if self.block.is_some() || cap == 0 { return; } @@ -1262,6 +1277,30 @@ fn note_materialize(at: &'static std::panic::Location<'static>) { } impl crate::types::PyInstance { + /// The value at position `i` of the instance's published dictionary + /// (one its `__dict__` made), when the key there is still `name`. + /// + /// # Safety + /// + /// As [`crate::sync::GilCell::peek`]: the view ends before anything + /// that could store an attribute runs. + #[inline] + pub unsafe fn published_field(&self, i: usize, name: &Object) -> Option<&Object> { + let Object::Str(name) = name else { + return None; + }; + // SAFETY: forwarded contract. + let d = unsafe { self.dict.published()?.peek() }?; + match d.get_index(i)? { + (DictKey(Object::Str(k)), v) + if std::ptr::eq(k.as_ptr(), name.as_ptr()) || **k == **name => + { + Some(v) + } + _ => None, + } + } + /// The attribute at position `i` of the class's shared names, while /// this instance's values are still split over its own class's names: /// the name there is fixed for as long as the class lives, so a @@ -1539,6 +1578,45 @@ impl crate::types::PyInstance { } } + /// [`Self::attr_get_str`] of a name whose Python hash is `hash`: the + /// split layout finds it by the hash first, a name no instance of the + /// class set answering without a comparison. + pub fn attr_get_hashed(&self, name: &str, hash: i64) -> Option { + match self.dict.published() { + Some(d) => d + .try_borrow() + .ok()? + .get(&crate::object::StrKeyHashed { s: name, hash }) + .cloned(), + None => { + let s = self.dict.split_cell().try_borrow().ok()?; + let i = s.position_hashed(name, hash)?; + s.get_index(i).map(|(_, v)| v.clone()) + } + } + } + + /// Attribute `name` (Python hash `hash`) read in place from either + /// layout, with no code run: a published dict probed by the hash, a + /// split layout at the position `memo` last found it (see + /// [`SplitValues::get_memo`]). `None` when absent or borrowed. + pub fn attr_get_memo(&self, name: &str, hash: i64, memo: &PosMemo) -> Option { + match self.dict.published() { + Some(d) => d + .try_borrow() + .ok()? + .get(&crate::object::StrKeyHashed { s: name, hash }) + .cloned(), + None => self + .dict + .split_cell() + .try_borrow() + .ok()? + .get_memo(name, hash, memo) + .cloned(), + } + } + /// Attribute `name`'s value (either layout), without materializing /// a split layout and without running code. pub fn attr_get_str(&self, name: &str) -> Option { @@ -1573,6 +1651,29 @@ impl crate::types::PyInstance { u32::try_from(i).ok() } + /// [`Self::attr_position_str`] of a name whose Python hash is `hash` + /// (a `str` object's memoised one): a split layout's miss answers from + /// the names' filter, without comparing each name. + pub fn attr_position_hashed(&self, name: &str, hash: i64) -> Option { + let i = match self.dict.published() { + Some(d) => { + let probe = crate::object::LeafNameProbe::new(name, hash); + let i = d.try_borrow().ok()?.get_index_of(&probe); + if probe.saw_exotic() { + return None; + } + i? + } + None => self + .dict + .split_cell() + .try_borrow() + .ok()? + .position_hashed(name, hash)?, + }; + u32::try_from(i).ok() + } + /// How many attributes are set (either layout, no materializing). pub fn attr_count(&self) -> usize { match self.dict.published() { diff --git a/crates/weavepy-vm/src/leaf_plan.rs b/crates/weavepy-vm/src/leaf_plan.rs index 92e0476ef..09a98d0e7 100644 --- a/crates/weavepy-vm/src/leaf_plan.rs +++ b/crates/weavepy-vm/src/leaf_plan.rs @@ -93,6 +93,7 @@ pub(crate) fn compare(a: V, b: V, kind: CompareKind) -> Option { // the evaluator's scratch; no Python runs. (V::R(p), V::R(q)) => match (unsafe { &*p }, unsafe { &*q }) { (Object::Str(s), Object::Str(t)) => (**s).cmp(&**t), + (Object::Tuple(s), Object::Tuple(t)) => return tuple_compare(s, t, kind), _ => return None, }, _ => return None, @@ -107,11 +108,90 @@ pub(crate) fn compare(a: V, b: V, kind: CompareKind) -> Option { }) } +/// `s t` for two tuples, as CPython's tuple comparison takes it: the +/// first pair of items that differ (identity first, then `==`) decides, +/// else the lengths do. Only items [`compare`] settles take part (scalars +/// and strings, a nested tuple declining), so nothing runs. +fn tuple_compare(s: &[Object], t: &[Object], kind: CompareKind) -> Option { + for (x, y) in s.iter().zip(t) { + if std::ptr::eq(x, y) { + continue; + } + let (vx, vy) = (norm(x), norm(y)); + if let (V::R(px), V::R(py)) = (vx, vy) { + // SAFETY: items of live tuples, with nothing running. + if !matches!(unsafe { (&*px, &*py) }, (Object::Str(_), Object::Str(_))) { + return None; + } + } + if !compare(vx, vy, CompareKind::Eq)? { + return match kind { + CompareKind::Eq => Some(false), + CompareKind::NotEq => Some(true), + _ => compare(vx, vy, kind), + }; + } + } + let ord = s.len().cmp(&t.len()); + Some(match kind { + CompareKind::Lt => ord.is_lt(), + CompareKind::LtE => ord.is_le(), + CompareKind::Eq => ord.is_eq(), + CompareKind::NotEq => ord.is_ne(), + CompareKind::Gt => ord.is_gt(), + CompareKind::GtE => ord.is_ge(), + }) +} + +/// The first `n` of `s` against the first `n` of `t`, as +/// [`tuple_compare`] takes two tuples of that length: the same items take +/// part (scalars and strings; two operands that are the same object count +/// as equal, as CPython's identity test has them). +#[inline] +pub(super) fn items_compare(s: [V; 3], t: [V; 3], n: u8, kind: CompareKind) -> Option { + for (x, y) in s.into_iter().zip(t).take(usize::from(n)) { + if let (V::R(p), V::R(q)) = (x, y) { + if std::ptr::eq(p, q) { + continue; + } + // SAFETY: as `norm` (live registers, nothing running). + if !matches!(unsafe { (&*p, &*q) }, (Object::Str(_), Object::Str(_))) { + return None; + } + } + if !compare(x, y, CompareKind::Eq)? { + return match kind { + CompareKind::Eq => Some(false), + CompareKind::NotEq => Some(true), + _ => compare(x, y, kind), + }; + } + } + Some(matches!( + kind, + CompareKind::LtE | CompareKind::Eq | CompareKind::GtE + )) +} + +/// What a `Tuple` op, or a `Seq` op building a list of one to three +/// items, builds: its register, its item registers (the first repeated +/// past `n`), `n`, and whether it's a list. +fn built_items(op: Op) -> Option<(u8, [u8; 3], u8, bool)> { + match op { + Op::Tuple { dst, a, b, c, n } => Some((dst, [a, b, c], n, false)), + Op::Seq { at, n, list: true } if (1..=3).contains(&n) => { + let item = |k: u8| if k < n { at.checked_add(k) } else { Some(at) }; + Some((at, [at, item(1)?, item(2)?], n, true)) + } + _ => None, + } +} + /// Registers a plan may address: the locals, then the operand stack. const REGS: usize = 32; /// Nested leaf calls evaluated within one evaluation at most this deep. -const NEST: u8 = 3; +pub(crate) const NEST: u8 = 3; /// One plan operation. Registers are `u8` indices below [`REGS`]; `pc` /// is the source instruction (its inline caches and site slots), and @@ -179,12 +259,67 @@ enum Op { b: u8, kind: u8, }, + /// `regs[dst] = (regs[item] in regs[cont]) != invert` (see + /// [`contains`]). + Contains { + dst: u8, + item: u8, + cont: u8, + invert: bool, + }, /// `regs[dst] = regs[a][regs[b]]` (see [`subscr`]). Subscr { dst: u8, a: u8, b: u8, }, + /// `regs[dst] = format(regs[src], "")` (an f-string's plain + /// `FORMAT_VALUE`) for a string, an int, a float, a bool or `None` (see + /// [`text`]). + Text { + dst: u8, + src: u8, + }, + /// `regs[dst]` the `!s` (`kind` 1) or `!r` (2) conversion of + /// `regs[src]`, an f-string's `CONVERT_VALUE` (see [`convert`]). + Convert { + dst: u8, + src: u8, + kind: u8, + }, + /// Decline unless `regs[src]` is an exact tuple or list of `n` items + /// (an `UNPACK_SEQUENCE`'s check, before its [`Op::Item`]s). + Unpack { + src: u8, + n: u8, + }, + /// `regs[dst] = regs[src][idx]` of a sequence [`Op::Unpack`] checked. + Item { + dst: u8, + src: u8, + idx: u8, + }, + /// `regs[at]` a new list (`list`) or tuple of `regs[at..at + n]` (a + /// `BUILD_LIST`, or a `BUILD_TUPLE` past [`Op::Tuple`]'s three items; + /// at most [`SEQ_MAX`]; see [`new_seq`]). + Seq { + at: u8, + n: u8, + list: bool, + }, + /// `regs[at]` a new dict of the `n` key and value pairs + /// `regs[at..at + 2 * n]` (a dict literal's `BUILD_MAP`, at most + /// [`MAP_MAX`] pairs; see [`new_map`]). + Map { + at: u8, + n: u8, + }, + /// `regs[at]` the strings `regs[at..at + n]` joined (an f-string's + /// `BUILD_STRING`, at most [`JOIN_MAX`] pieces; see [`join`]). + Join { + at: u8, + n: u8, + }, /// `regs[dst]` a new tuple of the first `n` (one to three) of /// `regs[a]`, `regs[b]`, `regs[c]`, held by the owned scratch (see /// [`new_tuple`]). @@ -195,6 +330,15 @@ enum Op { c: u8, n: u8, }, + /// `slice(regs[a], regs[b][, regs[c]])` (`n` bounds), its bounds + /// plain ints or `None`, held by the owned scratch. + Slice { + dst: u8, + a: u8, + b: u8, + c: u8, + n: u8, + }, /// Exchange two registers. Swap { a: u8, @@ -234,13 +378,252 @@ enum Op { /// Abandon the evaluation: the path reached an instruction the plan /// can't run. Decline, + /// `raise X` (`RAISE_VARARGS 1`): declines, unless this is the step + /// `Interpreter::leaf_python_step` asked for (see [`stop_ends_step`]), + /// where a bare `raise StopIteration` ends it as exhausted. + StopIter { + src: u8, + }, /// An effect leaf's buffered `recv.name = val`. + /// An effect leaf's `cont[key] = val` (see [`store_item`]), which + /// lands at once: only where nothing after it can decline (`last`, set + /// when the plan is built) and no attribute store waits in the buffer; + /// anywhere else it declines. + StoreItem { + cont: u8, + key: u8, + val: u8, + last: bool, + }, StoreAttr { recv: u8, val: u8, pc: u16, name: u16, }, + /// `regs[a].__class__ is regs[b].__class__` (`is not` with `invert`), + /// the two reads (at `pa` and `pb`, of name `name`) fused with the + /// test: two instances whose classes keep `object`'s `__class__` + /// compare their classes, building no class objects (a dataclass's + /// `__eq__`); anything else reads both and tests them as the three ops + /// would. + SameClass { + dst: u8, + a: u8, + b: u8, + invert: bool, + pa: u16, + pb: u16, + name: u16, + }, + /// `hash((regs[a], regs[b], regs[c]))` of the first `n` (see + /// [`hash_items`]) with `regs[at]` the builtin `hash`, its result in + /// `regs[at]`, building no tuple: a `Call` of a global named `hash` on + /// the tuple the op before built. Any other callee declines. + HashItems { + at: u8, + a: u8, + b: u8, + c: u8, + n: u8, + }, + /// `regs[dst] = (regs[a0], ..) (regs[b0], ..)`, the first `n` + /// (one to three) registers of each, as a comparison of two tuples + /// (see [`items_compare`]) building neither: two `BUILD_TUPLE n`s a + /// `COMPARE_OP` reads. + ItemsCompare { + dst: u8, + a0: u8, + a1: u8, + a2: u8, + b0: u8, + b1: u8, + b2: u8, + n: u8, + kind: u8, + }, +} + +impl Op { + /// The registers this op writes (at most two). + fn writes(self) -> [Option; 2] { + match self { + Op::Move { dst, .. } + | Op::Const { dst, .. } + | Op::Global { dst, .. } + | Op::Deref { dst, .. } + | Op::Attr { dst, .. } + | Op::Compare { dst, .. } + | Op::ItemsCompare { dst, .. } + | Op::Is { dst, .. } + | Op::Truth { dst, .. } + | Op::Unary { dst, .. } + | Op::Binary { dst, .. } + | Op::Contains { dst, .. } + | Op::Subscr { dst, .. } + | Op::Text { dst, .. } + | Op::Convert { dst, .. } + | Op::Item { dst, .. } + | Op::Tuple { dst, .. } + | Op::Slice { dst, .. } + | Op::New { dst, .. } + | Op::SameClass { dst, .. } => [Some(dst), None], + Op::Method { dst, .. } => [Some(dst), dst.checked_add(1)], + Op::Swap { a, b } => [Some(a), Some(b)], + Op::Call { at, .. } + | Op::HashItems { at, .. } + | Op::Join { at, .. } + | Op::Seq { at, .. } + | Op::Map { at, .. } => [Some(at), None], + Op::BranchIf { .. } + | Op::BranchNone { .. } + | Op::Jump { .. } + | Op::Return { .. } + | Op::Unpack { .. } + | Op::Decline + | Op::StopIter { .. } + | Op::StoreAttr { .. } + | Op::StoreItem { .. } => [None, None], + } + } + + /// This op with every register `r` it names replaced by `f(r)`, for + /// the ops that name only single registers (no runs); `None` for any + /// other op or when `f` refuses a register. + fn map_regs(self, f: impl Fn(u8) -> Option) -> Option { + Some(match self { + Op::Move { dst, src } => Op::Move { + dst: f(dst)?, + src: f(src)?, + }, + Op::Const { dst, k } => Op::Const { dst: f(dst)?, k }, + Op::Global { dst, pc } => Op::Global { dst: f(dst)?, pc }, + Op::Deref { dst, idx } => Op::Deref { dst: f(dst)?, idx }, + Op::Attr { dst, src, pc, name } => Op::Attr { + dst: f(dst)?, + src: f(src)?, + pc, + name, + }, + Op::Compare { dst, a, b, kind } => Op::Compare { + dst: f(dst)?, + a: f(a)?, + b: f(b)?, + kind, + }, + Op::Is { dst, a, b, invert } => Op::Is { + dst: f(dst)?, + a: f(a)?, + b: f(b)?, + invert, + }, + Op::Truth { dst, src } => Op::Truth { + dst: f(dst)?, + src: f(src)?, + }, + Op::Unary { dst, src, kind } => Op::Unary { + dst: f(dst)?, + src: f(src)?, + kind, + }, + Op::Binary { dst, a, b, kind } => Op::Binary { + dst: f(dst)?, + a: f(a)?, + b: f(b)?, + kind, + }, + Op::Subscr { dst, a, b } => Op::Subscr { + dst: f(dst)?, + a: f(a)?, + b: f(b)?, + }, + Op::Text { dst, src } => Op::Text { + dst: f(dst)?, + src: f(src)?, + }, + Op::Tuple { dst, a, b, c, n } => Op::Tuple { + dst: f(dst)?, + a: f(a)?, + b: f(b)?, + c: f(c)?, + n, + }, + _ => return None, + }) + } +} + +impl Interpreter { + /// Whether plan value `v` is the builtin `hash`. + #[inline] + pub(super) fn is_builtin_hash(&self, v: V) -> bool { + // SAFETY: as `norm`. + matches!(v, V::R(p) if self.is_builtin_hash_obj(unsafe { &*p })) + } +} + +/// The Python hash of a tuple of the first `n` of `items` when each item +/// hashes natively, running no code (see [`hash_item`]); `None` otherwise. +#[inline] +pub(super) fn hash_items(items: [V; 3], n: u8) -> Option { + let mut h = crate::object::TupleHasher::new(); + for v in &items[..usize::from(n)] { + h.push(hash_item(*v)?); + } + Some(h.finish(usize::from(n))) +} + +/// One tuple item's hash, when it runs no code and can't fail: a native +/// scalar (not a NaN, which hashes by identity), a `str` or `bytes`, a +/// tuple of such ([`crate::seqiter::plain_hashable`]), or an instance +/// hashed by identity. +#[inline] +pub(super) fn hash_item(v: V) -> Option { + match v { + V::I(i) => Some(crate::object::py_hash_long_i64(i)), + V::B(b) => Some(i64::from(b)), + V::N => crate::object::py_hash_value(&Object::None), + V::F(x) if !x.is_nan() => Some(crate::object::py_hash_double(x)), + // SAFETY: as `norm` (a register's borrowed object outlives the + // evaluation). + V::R(p) => match unsafe { &*p } { + Object::Int(i) => Some(crate::object::py_hash_long_i64(*i)), + Object::Str(s) => Some(crate::shared_value::SharedStr::hash_cached(s)), + o @ Object::Instance(i) => (i.native.get().is_none() + && i.class_dunder(crate::types::Dunder::Hash).object_owner()) + .then(|| crate::object::identity_hash(o)), + o if crate::seqiter::plain_hashable(o, 1) => crate::object::py_hash_value(o), + _ => None, + }, + _ => None, + } +} + +/// `len(v)` of an exact `str`, `list`, `tuple` or `dict`, read in line as +/// the `Len` leaf kind reads it (anything else: `None`, for that call). +#[inline] +pub(super) fn len_item(v: V) -> Option { + // SAFETY: as `norm` (a register's borrowed object outlives the + // evaluation). + let n = match v { + V::R(p) => match unsafe { &*p } { + Object::Str(s) => crate::object::str_char_len(s), + // SAFETY (both peeks): guard-free reads that run no code, as + // the evaluation's other reads are. + Object::List(l) => match unsafe { l.peek() } { + Some(xs) => xs.len(), + None => l.try_borrow().ok()?.len(), + }, + Object::Tuple(t) => t.len(), + Object::Dict(d) => match unsafe { d.peek() } { + Some(m) => m.len(), + None => d.try_borrow().ok()?.len(), + }, + _ => return None, + }, + _ => return None, + }; + i64::try_from(n).ok() } /// A leaf body, translated (see the module docs). @@ -407,6 +790,187 @@ impl Builder<'_> { Some(()) } + /// At an `IS_OP`: the two ops just emitted, when they read `__class__` + /// of two locals into the two operands (`other.__class__ is + /// self.__class__`), as `(a, b, pa, pb, name)` for a `SameClass`. + fn class_reads(&self) -> Option<(u8, u8, u16, u16, u16)> { + let n = self.ops.len(); + let depth = self.stack.len(); + if n < 2 || depth < 2 { + return None; + } + let ( + Op::Attr { + dst: d1, + src: s1, + pc: p1, + name: n1, + }, + Op::Attr { + dst: d2, + src: s2, + pc: p2, + name: n2, + }, + ) = (self.ops[n - 2], self.ops[n - 1]) + else { + return None; + }; + let locals = usize::from(s1) < self.nl && usize::from(s2) < self.nl; + let operands = self.stack[depth - 2] == d1 && self.stack[depth - 1] == d2; + let class = n1 == n2 + && self + .code + .names + .get(usize::from(n1)) + .is_some_and(|n| n.as_str() == "__class__"); + (locals && operands && class).then_some((s1, s2, p1, p2, n1)) + } + + /// At a `COMPARE_OP` (bytecode `pc`) of registers `a` and `b`: when + /// each is a tuple (or each a list) of the same length a `Tuple` op + /// (a `Seq` op) built, the second the op just emitted and the ops since the first straight-line code + /// that renaming can move (no jump, branch or jump target between), + /// replace the first with nothing and the second with an + /// [`Op::ItemsCompare`] into `dst`. The ops between move up past the + /// registers the first tuple's items may sit in, so those stay put. + /// Whether it fused. + fn fuse_items_compare(&mut self, pc: usize, dst: u8, a: u8, b: u8, kind: u8) -> bool { + let Some((bd, [b0, b1, b2], items, blist)) = self.ops.last().copied().and_then(built_items) + else { + return false; + }; + let n = self.ops.len(); + if bd != b || a >= b { + return false; + } + let Some(ai) = self.ops[..n - 1] + .iter() + .rposition(|op| op.writes().contains(&Some(a))) + else { + return false; + }; + let Some((_, [a0, a1, a2], an, alist)) = built_items(self.ops[ai]) else { + return false; + }; + // (Two lists, or two tuples, of one length: their comparisons are + // the same item by item.) + if an != items || alist != blist { + return false; + } + // (The first tuple's items sit in locals or the `items` registers + // from `a`; what the ops between write moves above those.) + let by = items - 1; + let read = [a0, a1, a2]; + let read = &read[..usize::from(items)]; + let jumps = self.ops[ai..].iter().any(|op| { + matches!( + op, + Op::Jump { .. } | Op::BranchIf { .. } | Op::BranchNone { .. } + ) + }); + let landing = self + .targets + .keys() + .any(|&t| t <= pc && self.starts.get(t).is_some_and(|&s| usize::from(s) > ai)); + if jumps || landing { + return false; + } + // (Registers above `a` move up `by`; the tuple's own register, + // read nowhere now, may not appear.) + let top = std::cell::Cell::new(0usize); + let shift = |r: u8| match r.cmp(&a) { + std::cmp::Ordering::Less => Some(r), + std::cmp::Ordering::Equal => None, + std::cmp::Ordering::Greater => { + let r = r.checked_add(by).filter(|&r| usize::from(r) < REGS)?; + top.set(top.get().max(usize::from(r) + 1)); + Some(r) + } + }; + let mut moved = Vec::with_capacity(n - 1 - ai); + for op in &self.ops[ai + 1..n - 1] { + let Some(op) = op.map_regs(shift) else { + return false; + }; + // (A walrus store into a local the first tuple read.) + if op.writes().iter().flatten().any(|r| read.contains(r)) { + return false; + } + moved.push(op); + } + let (Some(b0), Some(b1), Some(b2)) = (shift(b0), shift(b1), shift(b2)) else { + return false; + }; + self.top.set(self.top.get().max(top.get())); + self.ops[ai] = Op::Move { dst: a, src: a }; + self.ops.truncate(ai + 1); + self.ops.extend(moved); + self.ops.push(Op::ItemsCompare { + dst, + a0, + a1, + a2, + b0, + b1, + b2, + n: items, + kind, + }); + true + } + + /// At a one-argument `CALL` (bytecode `pc`): the `Tuple` op just + /// emitted, when it built the argument and the callee is the global + /// `hash` loaded (with its empty self slot) in straight-line code since + /// (no jump, branch or jump target between), so the two fuse into a + /// `HashItems`. + fn hash_of_tuple(&self, pc: usize) -> Option { + let depth = self.stack.len(); + let tuple = *self.ops.last()?; + let Op::Tuple { dst, .. } = tuple else { + return None; + }; + if self.stack.last() != Some(&dst) || depth < 3 { + return None; + } + let callee = self.stack[depth - 3]; + let body = &self.ops[..self.ops.len() - 1]; + let gi = body + .iter() + .rposition(|op| op.writes().contains(&Some(callee)))?; + let Op::Global { pc: gpc, .. } = body[gi] else { + return None; + }; + let gpc = usize::from(gpc); + let ins = self.code.instructions.get(gpc)?; + let straight = body[gi..].iter().all(|op| { + !matches!( + op, + Op::Jump { .. } | Op::BranchIf { .. } | Op::BranchNone { .. } + ) + }) && !self.targets.keys().any(|&t| gpc < t && t <= pc); + // (The self slot the empty one: `PUSH_NULL`'s constant, or the one + // a `LOAD_GLOBAL` pushed with its null.) + let null_slot = self.stack[depth - 2]; + let null = body + .iter() + .rposition(|op| op.writes().contains(&Some(null_slot))) + .is_some_and(|i| { + matches!(body[i], Op::Const { k, .. } + if matches!(self.consts.get(usize::from(k)), Some(V::Null))) + }); + (matches!(ins.op, OpCode::LoadGlobal | OpCode::LoadGlobalPushNull) + && self + .code + .names + .get(ins.arg as usize) + .is_some_and(|n| n.as_str() == "hash") + && straight + && null) + .then_some(tuple) + } + /// Translate the instruction at `pc`: whether control falls through /// to the next one. `None` for one the plan can't express (the /// caller rolls back what it emitted and declines on that path). @@ -450,6 +1014,38 @@ impl Builder<'_> { dict: ins.op == OpCode::BuildMap, }); } + // A list literal, or a tuple past `Op::Tuple`'s three items, + // built from their own registers. + OpCode::BuildList | OpCode::BuildTuple + if (1..=SEQ_MAX).contains(&(arg as usize)) + && (ins.op == OpCode::BuildList || arg > 3) => + { + let n = arg as usize; + let depth = self.stack.len(); + if depth < n { + return None; + } + self.canonicalize()?; + self.stack.truncate(depth - n); + let at = self.push_new()?; + self.ops.push(Op::Seq { + at, + n: n as u8, + list: ins.op == OpCode::BuildList, + }); + } + // A dict literal's pairs, built from their own registers. + OpCode::BuildMap if (1..=MAP_MAX).contains(&(arg as usize)) => { + let n = arg as usize; + let depth = self.stack.len(); + if depth < 2 * n { + return None; + } + self.canonicalize()?; + self.stack.truncate(depth - 2 * n); + let at = self.push_new()?; + self.ops.push(Op::Map { at, n: n as u8 }); + } OpCode::LoadGlobal => { let dst = self.push_new()?; self.ops.push(Op::Global { @@ -494,9 +1090,39 @@ impl Builder<'_> { if kind > CompareKind::GtE as u8 { return None; } - self.ops.push(Op::Compare { dst, a, b, kind }); + if !self.fuse_items_compare(pc, dst, a, b, kind) { + self.ops.push(Op::Compare { dst, a, b, kind }); + } + } + // (`x in self.items`, a `__contains__`'s body.) + OpCode::ContainsOp => { + let cont = self.pop()?; + let item = self.pop()?; + let dst = self.push_new()?; + self.ops.push(Op::Contains { + dst, + item, + cont, + invert: arg == 1, + }); } OpCode::IsOp => { + if let Some((a, b, pa, pb, name)) = self.class_reads() { + self.ops.truncate(self.ops.len() - 2); + self.pop()?; + self.pop()?; + let dst = self.push_new()?; + self.ops.push(Op::SameClass { + dst, + a, + b, + invert: arg == 1, + pa, + pb, + name, + }); + return Some(true); + } let b = self.pop()?; let a = self.pop()?; let dst = self.push_new()?; @@ -540,6 +1166,73 @@ impl Builder<'_> { let dst = self.push_new()?; self.ops.push(Op::Subscr { dst, a, b }); } + // An f-string's `!s` or `!r`. + OpCode::ConvertValue if arg == 1 || arg == 2 => { + let src = self.pop()?; + let dst = self.push_new()?; + self.ops.push(Op::Convert { + dst, + src, + kind: arg as u8, + }); + } + // `a, b = pair` of an exact tuple or list: its length checked, + // then its items read into the registers they take, the + // highest first (the lowest is the sequence's own when it sat + // on the stack, read last). + OpCode::UnpackSequence if (1..=UNPACK_MAX).contains(&(arg as usize)) => { + let n = arg as usize; + let src = self.pop()?; + self.ops.push(Op::Unpack { src, n: n as u8 }); + let mut dsts = [0u8; UNPACK_MAX]; + for d in dsts.iter_mut().take(n) { + *d = self.push_new()?; + } + // (The stack's top is the first item.) + for k in (0..n).rev() { + self.ops.push(Op::Item { + dst: dsts[k], + src, + idx: (n - 1 - k) as u8, + }); + } + } + // An f-string's plain conversion (no `!r`, no spec). + OpCode::FormatValue if arg == 0 => { + // (A conversion's string, `!r` or `!s` just before, is + // its own text: nothing to do.) + let converted = matches!( + (self.ops.last(), self.stack.last()), + (Some(Op::Convert { dst, .. }), Some(top)) if dst == top + ); + if !converted { + let src = self.pop()?; + let dst = self.push_new()?; + self.ops.push(Op::Text { dst, src }); + } + } + // An f-string's pieces (each a string: a constant or a + // `FORMAT_VALUE`'s text), joined from their own registers. + OpCode::BuildString if (1..=JOIN_MAX).contains(&(arg as usize)) => { + let n = arg as usize; + let depth = self.stack.len(); + if depth < n { + return None; + } + if n == 1 { + let src = self.pop()?; + let dst = self.push_new()?; + self.ops.push(Op::Text { dst, src }); + } else { + self.canonicalize()?; + self.stack.truncate(depth - n); + let at = self.push_new()?; + self.ops.push(Op::Join { + at, + n: u8::try_from(n).ok()?, + }); + } + } // (`return (x, 1)`, a key function's pair: the items are read // before the tuple's register, their lowest, is written.) OpCode::BuildTuple if (1..=3).contains(&arg) => { @@ -557,6 +1250,42 @@ impl Builder<'_> { n: n as u8, }); } + // (`w[::-1]`, a key function's reversal.) + // `seq[a:b]` of bounds the compiler didn't fold: the slice made + // in the register above the sequence's, then the sequence + // subscripted by it (each op reads its operands before writing + // its result). + OpCode::BinarySlice => { + let stop = self.pop()?; + let start = self.pop()?; + let sl = self.push_new()?; + self.ops.push(Op::Slice { + dst: sl, + a: start, + b: stop, + c: start, + n: 2, + }); + let sl = self.pop()?; + let seq = self.pop()?; + let dst = self.push_new()?; + self.ops.push(Op::Subscr { dst, a: seq, b: sl }); + } + OpCode::BuildSlice if matches!(arg, 2 | 3) => { + let n = arg as usize; + let at = self.stack.len().checked_sub(n)?; + let items: Vec = self.stack[at..].to_vec(); + self.stack.truncate(at); + let dst = self.push_new()?; + let item = |k: usize| items.get(k).copied().unwrap_or(items[0]); + self.ops.push(Op::Slice { + dst, + a: item(0), + b: item(1), + c: item(2), + n: n as u8, + }); + } OpCode::CopyTop => { let n = (arg as usize).max(1); let depth = self.stack.len(); @@ -640,6 +1369,16 @@ impl Builder<'_> { if depth < argc + 2 { return None; } + if argc == 1 { + if let Some(Op::Tuple { a, b, c, n, .. }) = self.hash_of_tuple(pc) { + self.ops.pop(); + self.canonicalize()?; + self.stack.truncate(depth - 3); + let at = self.push_new()?; + self.ops.push(Op::HashItems { at, a, b, c, n }); + return Some(true); + } + } self.canonicalize()?; let at = depth - argc - 2; self.stack.truncate(at); @@ -655,6 +1394,23 @@ impl Builder<'_> { self.ops.push(Op::Return { src }); return Some(false); } + OpCode::RaiseVarargs if arg == 1 => { + let src = self.pop()?; + self.ops.push(Op::StopIter { src }); + return Some(false); + } + // `cont[key] = val` (stack: value, container, key on top). + OpCode::StoreSubscr => { + let key = self.pop()?; + let cont = self.pop()?; + let val = self.pop()?; + self.ops.push(Op::StoreItem { + cont, + key, + val, + last: false, + }); + } OpCode::StoreAttr => { let recv = self.pop()?; let val = self.pop()?; @@ -740,6 +1496,16 @@ impl Builder<'_> { _ => return None, } } + // (A subscript store lands only where nothing after it declines, + // decided once the jumps know their targets.) + for i in 0..self.ops.len() { + if matches!(self.ops[i], Op::StoreItem { .. }) { + let after = infallible_after(&self.ops, i); + if let Op::StoreItem { last, .. } = &mut self.ops[i] { + *last = after; + } + } + } let calls = self.ops.iter().any(|op| matches!(op, Op::Call { .. })); Some(LeafPlan { calls, @@ -822,6 +1588,12 @@ impl Owned { } } + /// Whether another value can be held. + #[inline(always)] + fn has_room(&self) -> bool { + self.n < self.buf.len() + } + /// Whether `p` names one of the held values. #[inline(always)] fn holds(&self, p: *const Object) -> bool { @@ -897,6 +1669,16 @@ impl Pending { }) } + /// The value of the latest buffered store to `recv.name`, if any. + fn latest_to(&self, recv: &Object, name: u32) -> Option<&Object> { + (0..self.n) + .rev() + .map(|k| self.get(k)) + // SAFETY: stable receivers (see `Store`). + .find(|(r, _, n, _)| *n == name && unsafe { (**r).is_same(recv) }) + .map(|(_, _, _, v)| v) + } + /// Whether entry `k` is the last store to its attribute. fn latest(&self, k: usize) -> bool { let (r0, _, n0, _) = self.get(k); @@ -954,6 +1736,81 @@ pub(crate) enum LeafRet { Owned(Object), } +/// Whether a `raise` of `v` at the top of an evaluation of `code` (at +/// call nesting `nest`, on `args`) ends the frameless iterator step +/// [`Interpreter::leaf_python_step`] is running as exhausted: `v` is the +/// builtin `StopIteration` class, and the evaluation is that step's own. +/// Its caller then answers as the exception's catcher would, the +/// exception never built (nothing could observe it: the step is +/// frameless), once the stores buffered ahead of the raise have landed. +pub(super) fn stop_ends_step( + interp: &Interpreter, + code: &CodeObject, + nest: u8, + args: &[*const Object], + v: V, +) -> bool { + let (want_code, want_it, _) = interp.leaf_stop.get(); + if nest != 0 + || want_code != std::ptr::from_ref(code) as usize + || args.first().map(|&a| a as usize) != Some(want_it) + { + return false; + } + let V::R(p) = v else { + return false; + }; + // SAFETY: as `norm`. + // (A legacy sequence's `__getitem__` ends at `IndexError` too.) + matches!(unsafe { &*p }, Object::Type(t) + if t.flags.is_builtin && (t.name.as_str() == "StopIteration" + || (interp.leaf_stop_index.get() && t.name.as_str() == "IndexError"))) +} + +/// Whether the miss of `a[b]` (see [`subscr`]) at the top of an +/// evaluation of `code` ends the legacy sequence step +/// [`Interpreter::seqiter_step`] is running as exhausted: an `int` past +/// either end of a plain list, tuple or string raises the `IndexError` +/// that ends the iteration (`return self.items[i]`), with no handler +/// between the read and the iterator (a leaf has none) and nothing to +/// observe the exception (the step is frameless). +#[cold] +#[inline(never)] +pub(super) fn miss_ends_step( + interp: &Interpreter, + code: &CodeObject, + nest: u8, + args: &[*const Object], + a: V, + b: V, +) -> bool { + if !interp.leaf_stop_index.get() { + return false; + } + let (want_code, want_it, _) = interp.leaf_stop.get(); + if nest != 0 + || want_code != std::ptr::from_ref(code) as usize + || args.first().map(|&a| a as usize) != Some(want_it) + { + return false; + } + let (V::R(c), V::I(i)) = (a, b) else { + return false; + }; + // SAFETY: as `norm`. + let n = match unsafe { &*c } { + // SAFETY: a view that ends here. + Object::List(l) => match unsafe { l.peek() } { + Some(xs) => xs.len(), + None => return false, + }, + Object::Tuple(t) => t.len(), + Object::Str(s) => crate::object::str_char_len(s), + _ => return false, + } as i64; + i >= n || i < -n +} + /// The value of `f`'s closure cell `idx`, borrowed: nothing an evaluation /// runs can rebind a cell (a leaf has no `STORE_DEREF`), and the function /// holds its closure. `None` for an empty cell (the read raises). @@ -1057,6 +1914,86 @@ impl Interpreter { Some(r) } + /// A native caller's positional call of `f` (after `recv`, when + /// given) straight in its plan's native code, when `f`'s code is a + /// warm general pure leaf called with exactly its parameters: the + /// checks `Interpreter::call_pure_leaf_with` and + /// `Interpreter::pure_leaf_call` make, each made once and in one + /// place (a callback's call, `map(f, xs)` or `key=f`, is then the + /// native code and little else). The outer `None` leaves the call to + /// that path, nothing decided (with `part`, a code whose part shape + /// isn't settled as none too: see `lambda_part`); otherwise the + /// result, or `None` inside having done nothing observable. + #[cfg(feature = "jit")] + #[inline(never)] + pub(crate) fn leaf_fast_call( + &self, + f: &crate::object::PyFunction, + recv: Option<&Object>, + args: &[Object], + part: bool, + ) -> Option> { + use std::sync::atomic::Ordering::Relaxed; + const MAX_ARGS: usize = 6; + // SAFETY: a function's code is only replaced under the GIL, and + // nothing here runs code that could replace it. + let code = unsafe { &*f.code.as_ptr() }; + let n = args.len() + usize::from(recv.is_some()); + if code.jit_hint.pure_leaf() != Some(true) + || n != code.arg_count as usize + || n > MAX_ARGS + || code.jit_hint.lean_entries() <= crate::tier2::LEAN_WARM_COMPILE_THRESHOLD_CAP + { + return None; + } + let ext = crate::code_vm_ext_existing(code)?; + if ext.pure_leaf.load(Relaxed) != 2 || (part && !matches!(ext.part_shape.get(), Some(None))) + { + return None; + } + let plan = ext.leaf_plan.get()?.as_deref()?; + if n != usize::from(plan.nargs) || n != crate::leaf_arity(code) { + return None; + } + // (A code whose evaluations gave up counts its skips and retries + // on the general path.) + let tries = ext.leaf_tries.load(Relaxed); + let (bails, done) = (tries >> 32, tries & 0xFFFF_FFFF); + if (bails >= crate::LEAF_BAIL_LIMIT && bails > done) + || crate::trace::any_observers_active() + || !self.inline_calls_ok() + { + return None; + } + let mut ptrs = [std::ptr::null::(); 8]; + let mut k = 0; + if let Some(r) = recv { + ptrs[0] = r; + k = 1; + } + for a in args { + ptrs[k] = a; + k += 1; + } + let depth = crate::recursion::current_depth(); + let r = match jit::run_compiled::(self, code, ext, plan, f, &ptrs[..n], depth)? { + Some(LeafRet::Borrowed(v)) => to_object(v), + Some(LeafRet::Owned(o)) => Some(o), + None => None, + }; + let bump = if r.is_some() { + code.jit_hint.note_leaf_hit(); + 1 + } else { + code.jit_hint.note_leaf_miss(); + 1 << 32 + }; + if bails < u64::from(u32::MAX) && done < u64::from(u32::MAX) { + ext.leaf_tries.store(tries + bump, Relaxed); + } + Some(r) + } + /// [`Self::leaf_run`] with its result borrowed when the caller may /// (see [`LeafRet`]). #[inline(never)] @@ -1164,18 +2101,144 @@ impl Interpreter { // SAFETY: the translation checked `kind` names a // comparison. let kind: CompareKind = unsafe { std::mem::transmute(kind) }; - set!(dst, V::B(compare(get!(a), get!(b), kind)?)); + let (x, y) = (get!(a), get!(b)); + let r = match compare(x, y, kind) { + Some(r) => r, + // Two plain instances: their comparison method as + // a nested leaf call (none while a store waits). + None => match (x, y) { + (V::R(p), V::R(q)) if !(EFFECT && pend.n > 0) => { + // SAFETY: as `compare`'s. + let (p, q) = unsafe { (&*p, &*q) }; + self.leaf_compare_nested(p, q, kind, nest + depth as u8)? + } + _ => return None, + }, + }; + set!(dst, V::B(r)); + } + Op::ItemsCompare { + dst, + a0, + a1, + a2, + b0, + b1, + b2, + n, + kind, + } => { + // SAFETY: the translation checked `kind` names a + // comparison. + let kind: CompareKind = unsafe { std::mem::transmute(kind) }; + let s = [get!(a0), get!(a1), get!(a2)]; + let r = items_compare(s, [get!(b0), get!(b1), get!(b2)], n, kind)?; + set!(dst, V::B(r)); } Op::Is { dst, a, b, invert } => { set!(dst, V::B(is_same(get!(a), get!(b)) != invert)) } + Op::SameClass { + dst, + a, + b, + invert, + pa, + pb, + name, + } => { + let (x, y) = (get!(a), get!(b)); + let fast = if EFFECT && pend.n > 0 { + None + } else { + same_plain_class(x, y) + }; + let same = match fast { + Some(same) => same, + None => { + let nest = nest + depth as u8; + let cx = self.plan_attr::( + code, ext, stamps, &mut owned, &pend, x, pa, name, nest, + )?; + let cy = self.plan_attr::( + code, ext, stamps, &mut owned, &pend, y, pb, name, nest, + )?; + is_same(cx, cy) + } + }; + set!(dst, V::B(same != invert)); + } Op::Truth { dst, src } => set!(dst, V::B(truth(get!(src))?)), Op::Unary { dst, src, kind } => set!(dst, unary(get!(src), kind)?), - Op::Binary { dst, a, b, kind } => set!(dst, binary(get!(a), get!(b), kind)?), - Op::Subscr { dst, a, b } => set!(dst, subscr(&mut owned, get!(a), get!(b))?), + Op::Binary { dst, a, b, kind } => { + let (x, y) = (get!(a), get!(b)); + match binary(x, y, kind) { + Some(v) => set!(dst, v), + None => set!(dst, str_add(&mut owned, x, y, kind)?), + } + } + Op::Contains { + dst, + item, + cont, + invert, + } => set!(dst, V::B(contains(get!(item), get!(cont))? != invert)), + Op::Subscr { dst, a, b } => { + let (x, y) = (get!(a), get!(b)); + match subscr(&mut owned, x, y) { + Some(v) => set!(dst, v), + // (A legacy sequence step's end: see + // `miss_ends_step`.) + None if depth == 0 + && !FRESH + && pend.n == 0 + && miss_ends_step(self, code, nest, args, x, y) => + { + return Some(LeafRet::Owned(Object::Unbound)); + } + None => return None, + } + } + Op::Text { dst, src } => set!(dst, text(&mut owned, get!(src))?), + Op::Convert { dst, src, kind } => set!(dst, convert(&mut owned, get!(src), kind)?), + Op::Unpack { src, n } => unpack_ok(get!(src), n)?, + Op::Item { dst, src, idx } => { + set!(dst, subscr(&mut owned, get!(src), V::I(i64::from(idx)))?) + } + Op::Seq { at, n, list } => { + let mut items = [V::N; SEQ_MAX]; + for (j, item) in items.iter_mut().enumerate().take(usize::from(n)) { + *item = get!(usize::from(at) + j); + } + set!(at, new_seq(&mut owned, &items[..usize::from(n)], list)?) + } + Op::Map { at, n } => { + let mut items = [V::N; 2 * MAP_MAX]; + let k = 2 * usize::from(n); + for (j, item) in items.iter_mut().enumerate().take(k) { + *item = get!(usize::from(at) + j); + } + set!(at, new_map(&mut owned, &items[..k])?) + } + Op::Join { at, n } => { + let mut pieces = [V::N; JOIN_MAX]; + for (k, piece) in pieces.iter_mut().enumerate().take(usize::from(n)) { + *piece = get!(usize::from(at) + k); + } + set!(at, join(&mut owned, &pieces[..usize::from(n)])?) + } Op::Tuple { dst, a, b, c, n } => { set!(dst, new_tuple(&mut owned, [get!(a), get!(b), get!(c)], n)?) } + Op::HashItems { at, a, b, c, n } => { + if !self.is_builtin_hash(get!(at)) { + return None; + } + set!(at, V::I(hash_items([get!(a), get!(b), get!(c)], n)?)) + } + Op::Slice { dst, a, b, c, n } => { + set!(dst, new_slice(&mut owned, [get!(a), get!(b), get!(c)], n)?) + } Op::Swap { a, b } => { let (x, y) = (get!(a), get!(b)); set!(a, y); @@ -1194,6 +2257,22 @@ impl Interpreter { Op::Jump { target } => ip = usize::from(target), Op::New { dst, dict } => set!(dst, new_container(&mut owned, dict)?), Op::Decline => return None, + Op::StopIter { src } => { + if depth == 0 && !FRESH && stop_ends_step(self, code, nest, args, get!(src)) { + // The stores made before the raise land first, as + // a return lands them (`self.i += 1` ahead of the + // exhaustion test); one that can't declines with + // nothing done. + if pend.n > 0 { + if !self.leaf_stop.get().2 { + return None; + } + self.plan_finish::(code, ext, plan, &owned, &mut pend, V::N)?; + } + return Some(LeafRet::Owned(Object::Unbound)); + } + return None; + } Op::Call { at, argc, pc } => { // A pure-leaf callee, evaluated in place: only while // no store is buffered (it would not see one). @@ -1221,6 +2300,17 @@ impl Interpreter { if n > 8 { return None; } + // `hash(x)` of a value that hashes natively (a + // `__hash__`'s `return hash(self.a)`): its hash, with no + // call. + if let Callee::Native(b, _) = callee { + if n == 1 && self.is_builtin_hash_fn(b) { + if let Some(h) = hash_item(get!(first)) { + set!(at, V::I(h)); + continue; + } + } + } let fp = match callee { Callee::Py(fp) => fp, Callee::Native(..) | Callee::Ctor(_) => { @@ -1377,6 +2467,17 @@ impl Interpreter { } return self.plan_finish::(code, ext, plan, &owned, &mut pend, v); } + Op::StoreItem { + cont, + key, + val, + last, + } => { + if !EFFECT || !last || pend.n > 0 { + return None; + } + store_item(&mut owned, get!(cont), get!(key), get!(val))?; + } Op::StoreAttr { recv, val, @@ -1416,6 +2517,28 @@ impl Interpreter { } } +/// `a.__class__ is b.__class__` for two instances whose classes keep +/// `object`'s `__class__` and `__getattribute__` (so each read is just the +/// class): whether the classes are one. `None` for anything else. +#[inline] +pub(super) fn same_plain_class(a: V, b: V) -> Option { + let (V::R(p), V::R(q)) = (a, b) else { + return None; + }; + if crate::gil::free_threading_enabled() { + return None; + } + // SAFETY: as `norm`. + let (Object::Instance(x), Object::Instance(y)) = (unsafe { &*p }, unsafe { &*q }) else { + return None; + }; + let (cx, cy) = (x.cls_raw(), y.cls_raw()); + if std::ptr::eq(cx, cy) { + return cx.class_attr_is_plain().then_some(true); + } + (cx.class_attr_is_plain() && cy.class_attr_is_plain()).then_some(false) +} + /// `a is b` on two leaf values. #[inline(always)] pub(crate) fn is_same(a: V, b: V) -> bool { @@ -1456,8 +2579,201 @@ pub(crate) fn unary(v: V, kind: u8) -> Option { /// result the interpreter must produce (an overflow, a negative operand /// of a floor division). #[inline(always)] +/// `a + b` of two strings (what [`binary`] leaves): a new string, held +/// by `owned`. `None` for anything else. +fn str_add(owned: &mut Owned, a: V, b: V, kind: u8) -> Option { + let V::R(p) = a else { + return None; + }; + // SAFETY: as `norm`. + let left = unsafe { &*p }; + let Object::Str(x) = left else { + return None; + }; + if kind == BinOpKind::Add as u8 { + let V::R(q) = b else { + return None; + }; + // SAFETY: as `norm`. + let Object::Str(y) = (unsafe { &*q }) else { + return None; + }; + return owned.own(Object::Str(crate::shared_value::SharedStr::concat(&[x, y]))); + } + // `str % args` over scalars and strings (or a tuple of them) and a + // short `str * int`, as the core loop's string arms run them (no code + // runs; anything else, an error included, declines): a `__str__` or + // `__repr__` that formats its fields (`"Q%d" % self.n`). + let op = match kind { + k if k == BinOpKind::Mod as u8 => BinOpKind::Mod, + k if k == BinOpKind::Mult as u8 => BinOpKind::Mult, + _ => return None, + }; + let scalar; + let right: &Object = match b { + // SAFETY: as `norm`. + V::R(q) => unsafe { &*q }, + V::I(i) => { + scalar = Object::Int(i); + &scalar + } + V::F(f) => { + scalar = Object::Float(f); + &scalar + } + V::B(t) => { + scalar = Object::Bool(t); + &scalar + } + V::N => { + scalar = Object::None; + &scalar + } + V::Fn(_) | V::Bi(_) | V::Null => return None, + }; + owned.own(crate::Interpreter::core_str_binop(left, right, op)?) +} + +/// `format(v, "")` (an f-string's plain `FORMAT_VALUE`) of a string +/// (itself), an int, a float, a bool or `None` (its `str()`); `None` +/// (declined) for anything else, whose `__format__` or `__str__` could run +/// code. +fn text(owned: &mut Owned, v: V) -> Option { + let s = match v { + // SAFETY: as `norm`. + V::R(p) => return matches!(unsafe { &*p }, Object::Str(_)).then_some(v), + V::I(i) => i.to_string(), + V::F(x) => crate::object::float_repr(x), + V::B(true) => "True".to_owned(), + V::B(false) => "False".to_owned(), + V::N => "None".to_owned(), + V::Fn(_) | V::Bi(_) | V::Null => return None, + }; + owned.own(Object::from_str(s)) +} + +/// Whether nothing after op `i` of `ops` can decline the evaluation: every +/// later op is a move, a constant, a return or a forward jump. +fn infallible_after(ops: &[Op], i: usize) -> bool { + ops.iter().enumerate().skip(i + 1).all(|(k, op)| match *op { + Op::Move { .. } | Op::Const { .. } | Op::Return { .. } => true, + Op::Jump { target } => usize::from(target) > k, + _ => false, + }) +} + +/// [`Op::StoreItem`]: `cont[key] = val` of an exact dict by a key that +/// compares natively, or of an exact list at an in-range int, as compiled +/// stores run it (`Interpreter::dict_set_hot`, `list_set_hot`: a value it +/// displaces is one whose release runs nothing). The displaced value is +/// held by the evaluation until it ends, not released: registers may +/// still borrow from inside it (`rc = self.first[1][0]` before +/// `self.first[1] = self.first[1][1]`, then `return rc`). `None`, nothing +/// done, for anything else (no room to hold it, say). +fn store_item(owned: &mut Owned, cont: V, key: V, val: V) -> Option<()> { + let V::R(cp) = cont else { + return None; + }; + if !owned.has_room() { + return None; + } + let v = to_object(val)?; + // SAFETY: as `norm`; the stores run no code. + let old = unsafe { + match &*cp { + Object::Dict(d) => { + let k = to_object(key)?; + Interpreter::dict_set_hot(d, &k, || v)? + } + Object::List(xs) => { + let V::I(i) = key else { + return None; + }; + Interpreter::list_set_hot(xs, i, || v)? + } + _ => return None, + } + }; + owned.own(old).map(|_| ()) +} + +/// The most items an `UNPACK_SEQUENCE` evaluates frameless (see +/// [`Op::Unpack`]). +pub(crate) const UNPACK_MAX: usize = 8; + +/// [`Op::Convert`]: `!s` (`kind` 1) of what [`text`] takes, or `!r` (2) of +/// a string, an int, a float, a bool or `None` (its native repr); `None` +/// (declined) for anything else, whose `__repr__` could run code. +fn convert(owned: &mut Owned, v: V, kind: u8) -> Option { + if kind == 1 { + return text(owned, v); + } + let r = match v { + // SAFETY: as `norm`. + V::R(p) => match unsafe { &*p } { + s @ Object::Str(_) => s.repr(), + _ => return None, + }, + V::I(i) => i.to_string(), + V::F(x) => crate::object::float_repr(x), + V::B(true) => "True".to_owned(), + V::B(false) => "False".to_owned(), + V::N => "None".to_owned(), + V::Fn(_) | V::Bi(_) | V::Null => return None, + }; + owned.own(Object::from_str(r)) +} + +/// [`Op::Unpack`]'s check: `Some` when `v` is an exact tuple or list of +/// `n` items. +fn unpack_ok(v: V, n: u8) -> Option<()> { + let V::R(p) = v else { + return None; + }; + // SAFETY: as `norm`; a length read between instructions. + let len = match unsafe { &*p } { + Object::Tuple(t) => t.len(), + Object::List(l) => unsafe { l.peek() }?.len(), + _ => return None, + }; + (len == usize::from(n)).then_some(()) +} + +/// The most pieces an f-string's join evaluates frameless (see +/// [`Op::Join`]). +pub(crate) const JOIN_MAX: usize = 16; + +/// [`Op::Join`]: the strings `pieces` (at most [`JOIN_MAX`]) joined into a +/// new string, held by the evaluation; `None` if any piece isn't a string. +fn join(owned: &mut Owned, pieces: &[V]) -> Option { + let mut parts = [""; JOIN_MAX]; + for (part, piece) in parts.iter_mut().zip(pieces) { + let V::R(p) = *piece else { + return None; + }; + // SAFETY: as `norm`. + let Object::Str(s) = (unsafe { &*p }) else { + return None; + }; + *part = s; + } + owned.own(Object::Str(crate::shared_value::SharedStr::concat( + &parts[..pieces.len()], + ))) +} + pub(crate) fn binary(a: V, b: V, kind: u8) -> Option { Some(match (a, b) { + // `int / int` of operands a double holds exactly (at most `2**53` + // in magnitude): their quotient is correctly rounded, as CPython's + // `long_true_divide` gives it (`Fraction.__float__`). + (V::I(a), V::I(b)) if kind == BinOpKind::Div as u8 => { + const EXACT: i64 = 1 << 53; + if b == 0 || !(-EXACT..=EXACT).contains(&a) || !(-EXACT..=EXACT).contains(&b) { + return None; + } + V::F(a as f64 / b as f64) + } (V::I(a), V::I(b)) => V::I(match kind { k if k == BinOpKind::Add as u8 => a.checked_add(b)?, k if k == BinOpKind::Sub as u8 => a.checked_sub(b)?, @@ -1469,8 +2785,26 @@ pub(crate) fn binary(a: V, b: V, kind: u8) -> Option { k if k == BinOpKind::LShift as u8 && (0..63).contains(&b) && ((a << b) >> b) == a => { a << b } - k if k == BinOpKind::FloorDiv as u8 && b > 0 && a >= 0 => a / b, - k if k == BinOpKind::Mod as u8 && b > 0 && a >= 0 => a % b, + // Floored, as Python's are, for any signs (`-x % 3`); a zero + // divisor (the raise) and `MIN // -1` decline. + k if k == BinOpKind::FloorDiv as u8 => { + let q = a.checked_div(b)?; + if (a % b != 0) && ((a < 0) != (b < 0)) { + q - 1 + } else { + q + } + } + k if k == BinOpKind::Mod as u8 => { + let r = a.checked_rem(b)?; + if r != 0 && ((r < 0) != (b < 0)) { + r + b + } else { + r + } + } + // (A negative exponent gives a float: the full arm's.) + k if k == BinOpKind::Pow as u8 && (0..64).contains(&b) => a.checked_pow(b as u32)?, _ => return None, }), (x, y) => { @@ -1497,10 +2831,54 @@ pub(crate) fn binary(a: V, b: V, kind: u8) -> Option { /// key type), or an ASCII string's character (held by `owned`). Anything /// else, a miss included, declines. #[inline] +/// `item in cont` when the test runs no code (see +/// `Interpreter::leaf_contains`): a native container, never an instance, +/// whose own `__contains__` could reach this evaluation again. `None` +/// declines. +pub(super) fn contains(item: V, cont: V) -> Option { + let V::R(c) = cont else { + return None; + }; + // SAFETY: as `norm`. + let c = unsafe { &*c }; + if matches!(c, Object::Instance(_)) { + return None; + } + let scalar; + let item: &Object = match item { + // SAFETY: as above. + V::R(p) => unsafe { &*p }, + V::I(i) => { + scalar = Object::Int(i); + &scalar + } + V::B(b) => { + scalar = Object::Bool(b); + &scalar + } + V::N => &Object::None, + V::F(_) | V::Fn(_) | V::Bi(_) | V::Null => return None, + }; + Interpreter::leaf_contains(c, item) +} + fn subscr(owned: &mut Owned, a: V, b: V) -> Option { let V::R(c) = a else { return None; }; + // An item of a container the evaluation holds itself (the list + // `s.split(".")` made): held too, since the container goes with the + // scratch and a pointer into it would outlive it (a borrowed result + // read after the evaluation, `return s.split(".")[0]`). + let held = owned.holds(c); + let item = |owned: &mut Owned, p: *const Object| { + if held { + // SAFETY: an item of a live held container. + owned.own(crate::clone_hot(unsafe { &*p })) + } else { + Some(norm(p)) + } + }; let index = |i: i64, n: usize| { let n = n as i64; let i = if i < 0 { i + n } else { i }; @@ -1508,18 +2886,54 @@ fn subscr(owned: &mut Owned, a: V, b: V) -> Option { }; // SAFETY: as `norm`; the borrows end before anything could change the // containers (no Python runs during an evaluation). - match (unsafe { &*c }, b) { + let mut cont = unsafe { &*c }; + // A built-in subclass's instance that keeps its base's `__getitem__` + // (`self[key]` in an attribute dict's `__getattr__`): its payload's + // item, as the native subscript reads it. A dict's miss declines like + // any other (the full path calls `__missing__` or raises). + if let Object::Instance(inst) = cont { + match inst.native.get() { + Some(p @ (Object::Dict(_) | Object::List(_) | Object::Tuple(_))) + if Interpreter::native_payload_getitem(inst) => + { + cont = p; + } + _ => return None, + } + } + match (cont, b) { (Object::List(l), V::I(i)) => { let xs = unsafe { l.peek() }?; - Some(norm(&raw const xs[index(i, xs.len())?])) + let p = &raw const xs[index(i, xs.len())?]; + item(owned, p) + } + (Object::Tuple(t), V::I(i)) => { + let p = &raw const t[index(i, t.len())?]; + item(owned, p) } - (Object::Tuple(t), V::I(i)) => Some(norm(&raw const t[index(i, t.len())?])), (Object::Str(s), V::I(i)) => { if crate::object::str_char_len(s) != s.len() { return None; } owned.own(Object::from_char(s.as_bytes()[index(i, s.len())?] as char)) } + // A plain sequence sliced by a slice of plain bounds (as the core + // loop's container step slices it). + (Object::List(_) | Object::Tuple(_) | Object::Str(_) | Object::Bytes(_), V::R(k)) + if matches!(unsafe { &*k }, Object::Slice(_)) => + { + let Object::Slice(sl) = (unsafe { &*k }) else { + return None; + }; + if ![&sl.start, &sl.stop, &sl.step] + .iter() + .all(|v| matches!(v, Object::None | Object::Int(_))) + || matches!(sl.step, Object::Int(0)) + { + return None; + } + owned.own(crate::Interpreter::core_slice(cont, sl)?) + } (Object::Dict(d), V::I(_) | V::R(_)) => { let int; let key = match b { @@ -1532,8 +2946,8 @@ fn subscr(owned: &mut Owned, a: V, b: V) -> Option { _ => return None, }; let probe = crate::object::LeafProbe::new(key)?; - let v = unsafe { d.peek() }?.get(&probe)?; - Some(norm(v)) + let v: *const Object = unsafe { d.peek() }?.get(&probe)?; + item(owned, v) } _ => None, } @@ -1562,6 +2976,90 @@ fn new_tuple(owned: &mut Owned, items: [V; 3], n: u8) -> Option { owned.own(t) } +fn new_slice(owned: &mut Owned, items: [V; 3], n: u8) -> Option { + let bound = |v: V| match v { + V::I(i) => Some(Object::Int(i)), + V::N => Some(Object::None), + _ => None, + }; + let [a, b, c] = items; + let step = if n == 3 { bound(c)? } else { Object::None }; + owned.own(Object::Slice(Rc::new(crate::object::PySlice { + start: bound(a)?, + stop: bound(b)?, + step, + }))) +} + +/// The most items a list or tuple literal evaluates frameless (see +/// [`Op::Seq`]). +pub(crate) const SEQ_MAX: usize = 8; + +/// [`Op::Seq`]: a new list (`list`) or tuple of `items`, held by the +/// evaluation (a list tracked as `BUILD_LIST` tracks one). +fn new_seq(owned: &mut Owned, items: &[V], list: bool) -> Option { + if crate::stdlib::tracemalloc_real::is_tracking() + || crate::stdlib::testinternalcapi_mod::reftrace_print_active() + || (list && crate::gc_trace::auto_collect_due()) + { + return None; + } + // (A plain loop: collecting through `Option` cost 35 instructions an + // item.) + let mut objs = Vec::with_capacity(items.len()); + for &v in items { + objs.push(to_object(v)?); + } + let obj = if list { + let l = Object::new_list(objs); + crate::gc_trace::track(&l); + l + } else { + Object::new_tuple(objs) + }; + owned.own(obj) +} + +/// The most pairs a dict literal evaluates frameless (see [`Op::Map`]). +pub(crate) const MAP_MAX: usize = 8; + +/// [`Op::Map`]: a new dict of the key and value pairs `items` (alternating), +/// each key one a native probe hashes and compares (a string, a number, +/// ...: no `__hash__` or `__eq__` runs), a later duplicate's value +/// replacing the earlier's as a literal's does; `None` for any other key. +fn new_map(owned: &mut Owned, items: &[V]) -> Option { + let V::R(p) = new_container(owned, true)? else { + return None; + }; + // SAFETY: the new dict the evaluation holds; nothing else sees it. + let Object::Dict(cell) = (unsafe { &*p }) else { + return None; + }; + // SAFETY: as above. + let d = unsafe { cell.peek_mut() }?; + for &[k, v] in items.as_chunks::<2>().0 { + let key = to_object(k)?; + let value = to_object(v)?; + let probe = crate::object::LeafProbe::new(&key)?; + match d.probe_entry(&probe) { + crate::dictmap::ProbeEntry::Occupied(e) => { + // (The first key stays, as a literal keeps it.) + let slot = e.into_mut(); + let old = std::mem::replace(slot, value); + crate::drop_hot(old); + crate::drop_hot(key); + } + crate::dictmap::ProbeEntry::Vacant(e) => { + if !probe.miss_is_exact() { + return None; + } + e.insert(crate::object::DictKey(key), value); + } + } + } + Some(V::R(p)) +} + fn new_container(owned: &mut Owned, dict: bool) -> Option { if crate::stdlib::tracemalloc_real::is_tracking() || crate::stdlib::testinternalcapi_mod::reftrace_print_active() @@ -1652,7 +3150,7 @@ impl Interpreter { builtins_id, key_idx, } if builtins_id == crate::specialize::rc_id(&f.builtins) - && !self.globals_missing_any.get() + && !self.globals_missing_gate() && slot.get() == [gid, g_stamp, unsafe { (*bdict).mutation_stamp() }] => unsafe { (*bdict).get_index(key_idx as usize) }, _ => return None, @@ -1685,12 +3183,7 @@ impl Interpreter { let recv = unsafe { &*p }; if EFFECT && pend.n > 0 { // A buffered store to this attribute, the latest. - let hit = (0..pend.n) - .rev() - .map(|k| pend.get(k)) - // SAFETY: stable receivers (see `Store`). - .find(|(r, _, n, _)| *n == name && unsafe { (**r).is_same(recv) }); - if let Some((_, _, _, v)) = hit { + if let Some(v) = pend.latest_to(recv, name) { return Some(norm(v)); } } @@ -1703,14 +3196,23 @@ impl Interpreter { // owned scratch; no Python runs. match unsafe { Self::leaf_cached_instance_field(ext, code, inst, pc, name) } { Some(v) => Some(norm(v)), - // A stale or absent site cache resolves through the - // site's own entries (a property through its getter). - None => match self.plan_getter::(ext, pend, inst, recv, pc, nest) { - Some(v) => owned.own(v), - None => { - owned.own(Self::leaf_attr_resolve_site(code, inst, recv, pc, name)?) + None => { + // A class value the site read for this class + // version (`self.version` of an `ipaddress` + // network). + if let Some(v) = Self::leaf_class_value_via(ext, code, inst, pc, name) { + return owned.own(v); } - }, + // A stale or absent site cache resolves through the + // site's own entries (a property through its getter). + match self.plan_getter::(ext, pend, inst, recv, pc, nest) { + Some(v) => owned.own(v), + None => { + let v = Self::leaf_attr_resolve_site(code, inst, recv, pc, name)?; + owned.own(v) + } + } + } } } Object::Type(cls) => { @@ -1722,6 +3224,18 @@ impl Interpreter { .and_then(|s| crate::class_attr_hit(s, cls)) { Some(v) => owned.own(v), + // An attribute of a class under a Python metaclass the + // site found before (an enum's `_member_map_`): its + // stamp is filled only past the checks below. + None if !Self::plain_metaclass(cls) => { + match crate::meta_entry_hit(code, cls, pc as usize) { + Some(v) => owned.own(v), + None => { + let v = Self::leaf_load_type_attr(code, cls, pc, name)?; + owned.own(v) + } + } + } None => { let v = Self::leaf_load_type_attr(code, cls, pc, name)?; // A scalar is a plain class value (see diff --git a/crates/weavepy-vm/src/leaf_plan/jit.rs b/crates/weavepy-vm/src/leaf_plan/jit.rs index 068ea81da..c7d1c8053 100644 --- a/crates/weavepy-vm/src/leaf_plan/jit.rs +++ b/crates/weavepy-vm/src/leaf_plan/jit.rs @@ -18,8 +18,9 @@ //! natively too once the callee's own plan is compiled). use super::{ - binary, compare, is_same, new_container, new_tuple, norm, plan_store, subscr, truth, unary, - LeafPlan, LeafRet, Op, Owned, Pending, NEST, V, + binary, compare, hash_items, is_same, items_compare, new_container, new_slice, new_tuple, norm, + plan_store, same_plain_class, subscr, truth, unary, LeafPlan, LeafRet, Op, Owned, Pending, + NEST, V, }; use crate::object::{Object, PyFunction}; use crate::sync::Rc; @@ -32,11 +33,17 @@ use weavepy_codegen::{ use weavepy_compiler::{BinOpKind, CodeObject, CompareKind}; /// Evaluations of a plan (per effect mode) before it is compiled. A -/// compile costs millions of instructions and saves tens to hundreds per -/// evaluation, so a plan compiles once interpreting it has cost about -/// what compiling would (the rent-or-buy rule): a short run doesn't pay -/// for code it never amortizes, and a long one loses little. -const WARM_RUNS: u32 = 20_000; +/// compile costs 0.5 to 0.8 million instructions for a five-op getter +/// or a fifteen-op key function (measured under callgrind) and saves +/// 350 to 430 per evaluation, so it pays for itself after some 1,700 +/// runs: a plan compiles once interpreting it has cost about what +/// compiling would (the rent-or-buy rule), so a short run doesn't pay +/// for code it never amortizes, and a long one loses little. (The +/// estimate is the common case's. A plan that inlines callees costs up +/// to 1.7 million, and one whose work is all property reads and calls +/// saves next to nothing, the helpers being the interpreter's own: +/// `fractions.Fraction.__str__` is both.) +const WARM_RUNS: u32 = 2_500; /// How deep callee plans are compiled in line. const INLINE_DEPTH: u8 = 2; @@ -52,7 +59,12 @@ const T_B: u64 = 6; const T_N: u64 = 7; /// A compiled plan: `(ctx, argument words) -> status`, where `0` returned -/// (the result's words in `ctx.out`) and anything else declined. +/// (the result's words in `ctx.out`), [`STOPPED`] ended an iterator step +/// as exhausted, and anything else declined. +/// The status of a frameless iterator step that ended at a bare `raise +/// StopIteration` (see `Op::StopIter`). +const STOPPED: u32 = 2; + type NativeFn = unsafe extern "C" fn(*mut Ctx<'static>, *const u64) -> u32; /// A plan's native code and what it was compiled against. @@ -64,11 +76,13 @@ pub(super) struct Native { /// The in-line callees' frame descriptors, which the code addresses, /// and what keeps their identity guards sound: a function's /// allocation stays reserved (so no other function takes its - /// address), and its code stays alive. + /// address), and its code stays alive. (Not the plan's own code, + /// which owns the plan: a count held here would keep the two alive + /// for good.) // Boxed: the code embeds each descriptor's address. #[allow(clippy::vec_box)] _frames: Vec>, - _keep: Vec<(crate::sync::Weak, Rc)>, + _keep: Vec<(crate::sync::Weak, Option>)>, /// The attribute and global sites' caches, which the code addresses. #[allow(clippy::vec_box)] _fields: Vec>, @@ -120,6 +134,14 @@ const CTX_INTERP: i32 = std::mem::offset_of!(Ctx<'static>, interp) as i32; const I_MISSING: i32 = std::mem::offset_of!(Interpreter, globals_missing_any) as i32; /// Where native code finds the evaluation's own function. const TOP_F_OFFSET: i32 = TOP_OFFSET + std::mem::offset_of!(Frame, f) as i32; +/// Where a function holds its globals and its builtins (each one +/// pointer: native code compares them as words). +const F_GLOBALS: i32 = std::mem::offset_of!(PyFunction, globals) as i32; +const F_BUILTINS: i32 = std::mem::offset_of!(PyFunction, builtins) as i32; +const _: () = assert!( + std::mem::size_of::>>() + == std::mem::size_of::() +); /// A class-attribute stamp's scalar tags (see `class_attr_fill`) and the /// register tags of the values they hold. @@ -242,6 +264,9 @@ pub(super) struct Ctx<'a> { owned: Owned, pend: Pending, nest: u8, + /// Set by a declining subscript whose index miss ends the legacy + /// sequence step the evaluation is (see `miss_ends_step`). + stop: bool, } impl Ctx<'_> { @@ -362,6 +387,7 @@ fn enter( owned: Owned::new(), pend: Pending::new(), nest, + stop: false, }; // SAFETY: the code was compiled from `plan` with this signature; the // context and the argument words outlive the call, and the lifetime @@ -373,11 +399,32 @@ fn enter( ) }; if status != 0 { + // A frameless iterator step's bare `raise StopIteration` (see + // `Op::StopIter`): the stores buffered ahead of it land first, as + // a return's do (one that can't declines with nothing done). + if status == STOPPED { + if ctx.pend.n > 0 + && interp + .plan_finish::(code, ext, plan, &ctx.owned, &mut ctx.pend, V::N) + .is_none() + { + return Some(None); + } + return Some(Some(LeafRet::Owned(Object::Unbound))); + } + if ctx.stop { + return Some(Some(LeafRet::Owned(Object::Unbound))); + } return Some(None); } let v = value(ctx.out[0], ctx.out[1]); // In place: registers point into the scratch, which must not move. - Some(interp.plan_finish::(code, ext, plan, &ctx.owned, &mut ctx.pend, v)) + let r = interp.plan_finish::(code, ext, plan, &ctx.owned, &mut ctx.pend, v); + // (Usually nothing is held or buffered: no drop call then.) + if ctx.owned.n == 0 && ctx.pend.n == 0 { + std::mem::forget(ctx); + } + Some(r) } // ---- helpers (the interpreter's operations, for native code) ---------- @@ -399,6 +446,19 @@ fn stamps(ext: &CodeConstObjects) -> crate::Sites<'_, crate::StampSlot> { ext.stamp_sites() } +/// `Op::StopIter`: `0` when the raise of the value in words `(t, p)` +/// ends the evaluation as an exhausted iterator step (see +/// `stop_ends_step`; the stores buffered ahead of it land in [`run`]); +/// `1` to decline. +unsafe extern "C" fn h_stop_iter(ctx: *mut Ctx<'static>, t: u64, p: u64) -> u32 { + // SAFETY: called by native code with its context. + let c = unsafe { cx(ctx) }; + // SAFETY: the evaluation's own frame is live. + let (code, _, _) = unsafe { c.top.parts() }; + let lands = c.pend.n == 0 || c.interp.leaf_stop.get().2; + u32::from(!(lands && super::stop_ends_step(c.interp, code, c.nest, c.args, value(t, p)))) +} + unsafe extern "C" fn h_global( ctx: *mut Ctx<'static>, fr: *const Frame, @@ -508,6 +568,52 @@ unsafe extern "C" fn h_class( unsafe { h_attr::(ctx, fr, t, p, pc_name) } } +/// `Op::SameClass`: `a.__class__ is b.__class__` (`!=` with `invert`) put +/// as a bool. Two instances whose classes keep `object`'s `__class__` +/// compare their classes; anything else reads both through [`h_class`], +/// as the unfused ops would. `pcs` holds the two reads' sites, `name_inv` +/// the name with the inversion in its top bit. +unsafe extern "C" fn h_same_class( + ctx: *mut Ctx<'static>, + fr: *const Frame, + ta: u64, + pa: u64, + tb: u64, + pb: u64, + pcs: u32, + name_inv: u32, +) -> u32 { + // SAFETY: called by native code with its context. + let c = unsafe { cx(ctx) }; + let invert = name_inv >> 31 != 0; + let name = name_inv & 0xffff; + let fast = if EFFECT && c.pend.n > 0 { + None + } else { + same_plain_class(value(ta, pa), value(tb, pb)) + }; + let same = match fast { + Some(same) => same, + None => { + // SAFETY: forwarded; each read's result is taken before the next. + if unsafe { h_class::(ctx, fr, ta, pa, (pcs & 0xffff) | name << 16) } != 0 { + return 1; + } + let c = unsafe { cx(ctx) }; + let x = value(c.out[0], c.out[1]); + // SAFETY: as above. + if unsafe { h_class::(ctx, fr, tb, pb, (pcs >> 16) | name << 16) } != 0 { + return 1; + } + let c = unsafe { cx(ctx) }; + is_same(x, value(c.out[0], c.out[1])) + } + }; + let c = unsafe { cx(ctx) }; + c.put(V::B(same != invert)); + 0 +} + /// [`h_attr`] through the site's [`FieldCache`]: a split field of a plain /// instance whose class the site has seen answers without the general /// read; a general read that found the instance's own field remembers it. @@ -527,14 +633,21 @@ unsafe extern "C" fn h_field( Some(Object::Instance(inst)) => Some(inst), _ => None, }; - // A buffered store to this very attribute answers through the general - // read; one to anything else leaves the instance's field current. - let pending = EFFECT - && c.pend.n > 0 - && inst.is_some() + // A buffered store to this very attribute answers with its value (as + // the general read would); one to anything else leaves the instance's + // field current. + if EFFECT && c.pend.n > 0 && inst.is_some() { // SAFETY: as above. - && c.pend.stores_to(unsafe { &*(p as *const Object) }, pc_name >> 16); - if let Some(inst) = inst.filter(|_| !pending) { + if let Some(v) = c + .pend + .latest_to(unsafe { &*(p as *const Object) }, pc_name >> 16) + { + let v = norm(v); + c.put(v); + return 0; + } + } + if let Some(inst) = inst { let ver = inst.cls_raw().attr_version.get(); for e in &cache.entries { let (v, idx) = e.get(); @@ -544,6 +657,11 @@ unsafe extern "C" fn h_field( let hit = unsafe { if idx & SLOT_FIELD != 0 { inst.laid_out_slot((idx & !SLOT_FIELD) as usize) + } else if idx & DICT_FIELD != 0 { + let (_, ext, _) = (*fr).parts(); + ext.name_objs + .get((pc_name >> 16) as usize) + .and_then(|n| inst.published_field((idx & !DICT_FIELD) as usize, n)) } else { inst.split_field(idx as usize) } @@ -555,10 +673,26 @@ unsafe extern "C" fn h_field( break; } } + // A class value the site read for this class version (the field + // cache holds the instance's own fields only): the general read's + // answer, without it or the resolution below. + // SAFETY: a live frame. + let (code, ext, _) = unsafe { (*fr).parts() }; + if let Some(v) = + Interpreter::leaf_class_value_via(ext, code, inst, pc_name & 0xffff, pc_name >> 16) + { + return match c.owned.own(v) { + Some(v) => { + c.put(v); + 0 + } + None => 1, + }; + } } // SAFETY: forwarded. let status = unsafe { h_attr::(ctx, fr, t, p, pc_name) }; - if let (0, Some(inst)) = (status, inst.filter(|_| !pending)) { + if let (0, Some(inst)) = (status, inst) { // SAFETY: a live frame. let (code, ext, _) = unsafe { (*fr).parts() }; let ver = inst.cls_raw().attr_version.get(); @@ -572,7 +706,11 @@ unsafe extern "C" fn h_field( // The instance's own field (not a class value or descriptor), // from its split layout. let found = match Interpreter::leaf_resolve_instance_attr_ix(code, inst, pc_name >> 16) { - Some((_, Some(idx))) => inst.dict.published().is_none().then_some((idx, 0)), + // (A published dictionary's position, checked by name as read.) + Some((_, Some(idx))) if inst.dict.published().is_some() => { + (idx & (SLOT_FIELD | DICT_FIELD) == 0).then_some((idx | DICT_FIELD, 0)) + } + Some((_, Some(idx))) => Some((idx, 0)), // A class value or descriptor. Some(_) => None, // A `__slots__` member laid out over its class's names. @@ -595,6 +733,12 @@ unsafe extern "C" fn h_field( /// rather than a split field's. const SLOT_FIELD: u32 = 1 << 31; +/// A [`FieldCache`] position in the instance's published dictionary (see +/// [`crate::types::PyInstance::published_field`]), which the read checks +/// by name. Native code's in-line read never takes one: it reads split +/// values only. +const DICT_FIELD: u32 = 1 << 30; + /// Where `inst` keeps the attribute `code.names[name]` when reading it /// means reading a `__slots__` member its class (at version `ver`) lays /// out (see [`crate::types::TypeObject::fresh_slots`]): the member's @@ -662,11 +806,61 @@ unsafe extern "C" fn h_method( 0 } -/// `0`/`1` for the comparison's result, `2` to decline. -extern "C" fn h_compare(ta: u64, pa: u64, tb: u64, pb: u64, kind: u32) -> u32 { +/// `0`/`1` for [`items_compare`]'s result, `2` to decline. `n_kind` is +/// the item count and, above it, the comparison. +#[allow(clippy::too_many_arguments)] +unsafe extern "C" fn h_items_compare( + ta0: u64, + pa0: u64, + ta1: u64, + pa1: u64, + ta2: u64, + pa2: u64, + tb0: u64, + pb0: u64, + tb1: u64, + pb1: u64, + tb2: u64, + pb2: u64, + n_kind: u32, +) -> u32 { // SAFETY: the translation checked `kind` names a comparison. - let kind: CompareKind = unsafe { std::mem::transmute(kind as u8) }; - match compare(value(ta, pa), value(tb, pb), kind) { + let kind: CompareKind = unsafe { std::mem::transmute((n_kind >> 8) as u8) }; + let s = [value(ta0, pa0), value(ta1, pa1), value(ta2, pa2)]; + let t = [value(tb0, pb0), value(tb1, pb1), value(tb2, pb2)]; + items_compare(s, t, n_kind as u8, kind).map_or(2, u32::from) +} + +/// `0`/`1` for the comparison's result, `2` to decline. `kind_depth` is +/// the comparison and, above it, the inline depth of the frame it's in: +/// two plain instances compare by their method as a nested leaf call. +unsafe extern "C" fn h_compare( + ctx: *mut Ctx<'static>, + ta: u64, + pa: u64, + tb: u64, + pb: u64, + kind_depth: u32, +) -> u32 { + // SAFETY: the translation checked `kind` names a comparison. + let kind: CompareKind = unsafe { std::mem::transmute((kind_depth & 0xff) as u8) }; + let (x, y) = (value(ta, pa), value(tb, pb)); + if let Some(b) = compare(x, y, kind) { + return u32::from(b); + } + let (V::R(p), V::R(q)) = (x, y) else { + return 2; + }; + // SAFETY: called by native code with its context; the operands are + // live registers. + let c = unsafe { cx(ctx) }; + if c.pend.n > 0 { + return 2; + } + let nest = c.nest + (kind_depth >> 8) as u8; + // SAFETY: as above. + let (p, q) = unsafe { (&*p, &*q) }; + match c.interp.leaf_compare_nested(p, q, kind, nest) { Some(b) => u32::from(b), None => 2, } @@ -706,7 +900,107 @@ unsafe extern "C" fn h_binary( ) -> u32 { // SAFETY: called by native code with its context. let c = unsafe { cx(ctx) }; - match binary(value(ta, pa), value(tb, pb), kind as u8) { + let (a, b) = (value(ta, pa), value(tb, pb)); + // (Two strings' sum is a new string, held by the evaluation.) + match binary(a, b, kind as u8).or_else(|| super::str_add(&mut c.owned, a, b, kind as u8)) { + Some(v) => { + c.put(v); + 0 + } + None => 1, + } +} + +/// [`Op::Text`] (see [`super::text`]). +unsafe extern "C" fn h_text(ctx: *mut Ctx<'static>, ts: u64, ps: u64) -> u32 { + // SAFETY: called by native code with its context. + let c = unsafe { cx(ctx) }; + match super::text(&mut c.owned, value(ts, ps)) { + Some(v) => { + c.put(v); + 0 + } + None => 1, + } +} + +/// [`Op::Convert`] (see [`super::convert`]). +unsafe extern "C" fn h_convert(ctx: *mut Ctx<'static>, ts: u64, ps: u64, kind: u32) -> u32 { + // SAFETY: called by native code with its context. + let c = unsafe { cx(ctx) }; + match super::convert(&mut c.owned, value(ts, ps), kind as u8) { + Some(v) => { + c.put(v); + 0 + } + None => 1, + } +} + +/// [`Op::Unpack`]'s check (see [`super::unpack_ok`]): `0` to go on. +unsafe extern "C" fn h_unpack(ts: u64, ps: u64, n: u32) -> u32 { + u32::from(super::unpack_ok(value(ts, ps), n as u8).is_none()) +} + +/// [`Op::Item`] (see [`super::subscr`]). +unsafe extern "C" fn h_item(ctx: *mut Ctx<'static>, ts: u64, ps: u64, idx: u32) -> u32 { + // SAFETY: called by native code with its context. + let c = unsafe { cx(ctx) }; + match subscr(&mut c.owned, value(ts, ps), V::I(i64::from(idx))) { + Some(v) => { + c.put(v); + 0 + } + None => 1, + } +} + +/// [`Op::Seq`] of the `n` items whose tag and payload words `w` holds +/// (see [`super::new_seq`]). +unsafe extern "C" fn h_seq(ctx: *mut Ctx<'static>, w: *const [u64; 2], n: u32, list: u32) -> u32 { + // SAFETY: called by native code with its context and `n` pairs. + let (c, w) = unsafe { (cx(ctx), std::slice::from_raw_parts(w, n as usize)) }; + let mut items = [V::N; super::SEQ_MAX]; + for (item, &[t, p]) in items.iter_mut().zip(w) { + *item = value(t, p); + } + match super::new_seq(&mut c.owned, &items[..w.len()], list != 0) { + Some(v) => { + c.put(v); + 0 + } + None => 1, + } +} + +/// [`Op::Map`] of the `n` pairs whose tag and payload words `w` holds, +/// keys and values alternating (see [`super::new_map`]). +unsafe extern "C" fn h_map(ctx: *mut Ctx<'static>, w: *const [u64; 2], n: u32) -> u32 { + // SAFETY: called by native code with its context and `2 * n` pairs. + let (c, w) = unsafe { (cx(ctx), std::slice::from_raw_parts(w, 2 * n as usize)) }; + let mut items = [V::N; 2 * super::MAP_MAX]; + for (item, &[t, p]) in items.iter_mut().zip(w) { + *item = value(t, p); + } + match super::new_map(&mut c.owned, &items[..w.len()]) { + Some(v) => { + c.put(v); + 0 + } + None => 1, + } +} + +/// [`Op::Join`] of the `n` pieces whose tag and payload pairs `w` holds +/// (see [`super::join`]). +unsafe extern "C" fn h_join(ctx: *mut Ctx<'static>, w: *const [u64; 2], n: u32) -> u32 { + // SAFETY: called by native code with its context and `n` pairs. + let (c, w) = unsafe { (cx(ctx), std::slice::from_raw_parts(w, n as usize)) }; + let mut pieces = [V::N; super::JOIN_MAX]; + for (piece, &[t, p]) in pieces.iter_mut().zip(w) { + *piece = value(t, p); + } + match super::join(&mut c.owned, &pieces[..w.len()]) { Some(v) => { c.put(v); 0 @@ -751,13 +1045,88 @@ unsafe extern "C" fn h_tuple( } } +/// `hash` of a tuple of the first `n` of three operands, building no +/// tuple, when the callee is the builtin `hash` (see [`hash_items`]). +#[allow(clippy::too_many_arguments)] +unsafe extern "C" fn h_hash_items( + ctx: *mut Ctx<'static>, + tf: u64, + pf: u64, + ta: u64, + pa: u64, + tb: u64, + pb: u64, + tc: u64, + pc: u64, + n: u32, +) -> u32 { + // SAFETY: called by native code with its context. + let c = unsafe { cx(ctx) }; + if !c.interp.is_builtin_hash(value(tf, pf)) { + return 1; + } + let items = [value(ta, pa), value(tb, pb), value(tc, pc)]; + match hash_items(items, n as u8) { + Some(h) => { + c.put(V::I(h)); + 0 + } + None => 1, + } +} + +/// A slice of the first `n` of three bounds (see [`new_slice`]). +#[allow(clippy::too_many_arguments)] +unsafe extern "C" fn h_slice( + ctx: *mut Ctx<'static>, + ta: u64, + pa: u64, + tb: u64, + pb: u64, + tc: u64, + pc: u64, + n: u32, +) -> u32 { + // SAFETY: called by native code with its context. + let c = unsafe { cx(ctx) }; + let items = [value(ta, pa), value(tb, pb), value(tc, pc)]; + match new_slice(&mut c.owned, items, n as u8) { + Some(v) => { + c.put(v); + 0 + } + None => 1, + } +} + /// `a[b]` (see [`subscr`]). +/// `Op::Contains`: `0` the answer put, `1` declined. +unsafe extern "C" fn h_contains( + ctx: *mut Ctx<'static>, + ta: u64, + pa: u64, + tb: u64, + pb: u64, + invert: u32, +) -> u32 { + // SAFETY: called by native code with its context. + let c = unsafe { cx(ctx) }; + match super::contains(value(ta, pa), value(tb, pb)) { + Some(found) => { + c.put(V::B(found != (invert != 0))); + 0 + } + None => 1, + } +} + unsafe extern "C" fn h_subscr(ctx: *mut Ctx<'static>, ta: u64, pa: u64, tb: u64, pb: u64) -> u32 { // SAFETY: called by native code with its context. let c = unsafe { cx(ctx) }; // A dict read by a `str` key (`env[name]`), the commonest shape, as - // `subscr` reads it. - if ta == T_R && tb == T_R { + // `subscr` reads it (a dict the evaluation holds itself is `subscr`'s, + // which holds the value too). + if ta == T_R && tb == T_R && !c.owned.holds(pa as *const Object) { // SAFETY: as `norm`; the borrows end before anything could change // the dict (no Python runs during an evaluation). let (a, k) = unsafe { (&*(pa as *const Object), &*(pb as *const Object)) }; @@ -781,7 +1150,23 @@ unsafe extern "C" fn h_subscr(ctx: *mut Ctx<'static>, ta: u64, pa: u64, tb: u64, c.put(v); 0 } - None => 1, + None => { + // SAFETY: the evaluation's own frame is live. + let (code, _, _) = unsafe { c.top.parts() }; + if c.pend.n == 0 + && super::miss_ends_step( + c.interp, + code, + c.nest, + c.args, + value(ta, pa), + value(tb, pb), + ) + { + c.stop = true; + } + 1 + } } } @@ -842,6 +1227,28 @@ unsafe extern "C" fn h_store( } } +/// [`Op::StoreItem`] (only a `last` one reaches here): `0` stored, `1` +/// declined with nothing done (an attribute store waiting in the buffer +/// too, which the store would land ahead of). +unsafe extern "C" fn h_store_item( + ctx: *mut Ctx<'static>, + tc: u64, + pc: u64, + tk: u64, + pk: u64, + tv: u64, + pv: u64, +) -> u32 { + // SAFETY: called by native code with its context. + let c = unsafe { cx(ctx) }; + if c.pend.n > 0 { + return 1; + } + u32::from( + super::store_item(&mut c.owned, value(tc, pc), value(tk, pk), value(tv, pv)).is_none(), + ) +} + /// A leaf call at `pc` of frame `fr` (at in-line `depth`) on the registers /// whose words start at `w`: the callee, its self slot, then `argc` /// arguments. A pure-leaf Python callee is evaluated one level down @@ -869,6 +1276,9 @@ unsafe extern "C" fn h_call( if n > 8 { return 1; } + // (A builtin type's pure constructor half, as the plan's interpreter + // calls it: `list(self.items)`, `str(n)`.) + let mut ctor = None; let (fp, native) = match reg(0) { V::Fn(fp) => (fp, None), V::Bi(b) => (std::ptr::null(), Some((b, None))), @@ -876,10 +1286,78 @@ unsafe extern "C" fn h_call( V::R(p) => match unsafe { &*p } { Object::Function(func) => (Rc::as_ptr(func), None), Object::Builtin(b) => (std::ptr::null(), Some((Rc::as_ptr(b), Some(b)))), + Object::Type(t) if t.flags.is_builtin => { + ctor = Some(t); + (std::ptr::null(), None) + } _ => return 1, }, _ => return 1, }; + // `hash(x)` of a value that hashes natively: its hash, with no call + // (as the plan's interpreter takes it). + if let Some((b, _)) = native { + if n == 1 && c.interp.is_builtin_hash_fn(b) { + if let Some(h) = super::hash_item(reg(first)) { + c.put(V::I(h)); + return 0; + } + } + // `len(x)` of a common container: its length, read in line. + if n == 1 && c.interp.is_builtin_len_fn(b) { + if let Some(k) = super::len_item(reg(first)) { + c.put(V::I(k)); + return 0; + } + } + } + if native.is_some() || ctor.is_some() { + // A read-only builtin, on borrowed copies of the arguments (scalars + // made as objects, which have no drop glue): never dropped, so no + // reference moves. + let mut copies = [const { std::mem::MaybeUninit::::uninit() }; 8]; + for (k, slot) in copies.iter_mut().enumerate().take(n) { + slot.write(match reg(first + k) { + // SAFETY: the register names a live object; the copy is + // never dropped. + V::R(p) => unsafe { std::ptr::read(p) }, + V::I(i) => Object::Int(i), + V::F(x) => Object::Float(x), + V::B(b) => Object::Bool(b), + V::N => Object::None, + V::Fn(_) | V::Bi(_) | V::Null => return 1, + }); + } + // SAFETY: the first `n` copies were written. + let args = unsafe { std::slice::from_raw_parts(copies.as_ptr().cast::(), n) }; + let r = match (native, ctor) { + // (`isinstance(other, C)`, an `__eq__`'s first test: straight to + // the check, past the method slot and kind lookups.) + (Some((b, _)), _) if n == 2 && c.interp.is_builtin_isinstance_fn(b) => { + Interpreter::leaf_isinstance(args) + } + // (`d.get(k, default)`: the dict's native probe, past the + // method slot and kind lookups.) + (Some((b, rc)), _) => c + .interp + .is_dict_get_fn(b) + .then(|| Interpreter::leaf_dict_get_fast(args)) + .flatten() + .or_else(|| c.interp.leaf_pure_builtin(code, pc as usize, b, rc, args)), + (None, Some(t)) => crate::seqiter::builtin_ctor_pure(t, args), + (None, None) => None, + }; + let Some(r) = r else { + return 1; + }; + return match c.owned.own(r) { + Some(v) => { + c.put(v); + 0 + } + None => 1, + }; + } // Scalar arguments are staged as objects (no drop glue); heap ones are // borrowed in place. let mut staged = [const { std::mem::MaybeUninit::::uninit() }; 8]; @@ -898,28 +1376,6 @@ unsafe extern "C" fn h_call( }; ptrs[k] = staged[k].write(o); } - if let Some((b, rc)) = native { - // A read-only builtin, on borrowed copies of the arguments: never - // dropped, so no reference moves. - let mut copies = [const { std::mem::MaybeUninit::::uninit() }; 8]; - for k in 0..n { - // SAFETY: each pointer names a live object; the copy is never - // dropped. - copies[k].write(unsafe { std::ptr::read(ptrs[k]) }); - } - // SAFETY: the first `n` copies were written. - let args = unsafe { std::slice::from_raw_parts(copies.as_ptr().cast::(), n) }; - let Some(r) = c.interp.leaf_pure_builtin(code, pc as usize, b, rc, args) else { - return 1; - }; - return match c.owned.own(r) { - Some(v) => { - c.put(v); - 0 - } - None => 1, - }; - } // SAFETY: the class or the namespace holds the callee, and nothing // here runs code that could release it. let callee = unsafe { &*fp }; @@ -1039,6 +1495,7 @@ fn compile_with( depth: 0, frames: Vec::new(), keep: Vec::new(), + own: std::ptr::from_ref(code), fields: Vec::new(), globals: Vec::new(), methods: Vec::new(), @@ -1132,7 +1589,10 @@ struct Lower<'b> { // Boxed: the code embeds each descriptor's address. #[allow(clippy::vec_box)] frames: Vec>, - keep: Vec<(crate::sync::Weak, Rc)>, + keep: Vec<(crate::sync::Weak, Option>)>, + /// The code the plan being compiled belongs to (never counted in + /// `keep`: see `Native::_keep`). + own: *const CodeObject, #[allow(clippy::vec_box)] fields: Vec>, #[allow(clippy::vec_box)] @@ -1260,6 +1720,21 @@ impl Lower<'_> { let at = self.b.ins().iconst(ptr, cache); let want = self.b.ins().load(types::I64, f, at, FIELD_VER_OFFSET); let idx = self.b.ins().uload32(f, at, FIELD_IDX_OFFSET); + // A site whose entry names a member slot reads it first, past none + // of the split checks; one that has never read a member slot isn't + // compiled to (the helper reads one otherwise). + let slots = l.slots_ok && slot_site; + let slot = if slots { + let slot = self.b.create_block(); + let split = self.b.create_block(); + let bit = self.b.ins().band_imm(idx, i64::from(SLOT_FIELD)); + let is_slot = self.b.ins().icmp_imm(IntCC::NotEqual, bit, 0); + self.b.ins().brif(is_slot, slot, &[], split, &[]); + self.b.switch_to_block(split); + Some(slot) + } else { + None + }; let lazy = self.b.ins().load(ptr, f, inst, l.inst_dict_lazy); let flag = self.b.ins().iconst(ptr, l.cells_unguarded as i64); let shared = self.b.ins().uload8(types::I64, f, flag, 0); @@ -1275,13 +1750,7 @@ impl Lower<'_> { let bad = self.b.ins().bor(bad, busy); let bad = self.b.ins().bor(bad, empty); let bad = self.b.ins().bor(bad, other); - // A slot entry fails the split checks (its position is out of any - // split range), so the slot read waits behind them; it's compiled - // only for a site that has read member slots (the helper reads one - // otherwise). - let slots = l.slots_ok && slot_site; - let slot = if slots { self.b.create_block() } else { miss }; - self.miss_if(bad, slot); + self.miss_if(bad, miss); // A block over the class's names that holds the position. let keys = self.b.ins().load(ptr, f, block, l.split_keys); let ckeys = self.b.ins().load(ptr, f, cls, l.type_shared_keys); @@ -1292,27 +1761,18 @@ impl Lower<'_> { .ins() .icmp(IntCC::UnsignedGreaterThanOrEqual, idx, len); let bad = self.b.ins().bor(foreign, absent); - self.miss_if(bad, slot); + self.miss_if(bad, miss); let off = self.b.ins().ishl_imm(idx, 4); let v = self.b.ins().iadd(block, off); let v = self.b.ins().iadd_imm(v, i64::from(l.split_values)); - let v = if slots { + let v = if let Some(slot) = slot { let read = self.b.create_block(); self.b.append_block_param(read, ptr); self.b.ins().jump(read, &[v.into()]); // A member slot laid out over the entry's layout, and set, with - // the class checked and cells unshared. (Past the entry's kind, - // everything is read again here: values the split path reads - // stay unneeded past it.) + // the class checked and cells unshared. (The instance, its + // class and the entry, loaded before the branch, hold here.) self.b.switch_to_block(slot); - let split_miss = self.b.ins().band_imm(idx, i64::from(SLOT_FIELD)); - let split_miss = self.b.ins().icmp_imm(IntCC::Equal, split_miss, 0); - self.miss_if(split_miss, miss); - let inst = self.b.ins().load(ptr, f, p, 8); - let cls = self.b.ins().load(ptr, f, inst, l.inst_class); - let ver = self.b.ins().load(types::I64, f, cls, l.type_attr_version); - let at = self.b.ins().iconst(ptr, cache); - let want = self.b.ins().load(types::I64, f, at, FIELD_VER_OFFSET); let flag = self.b.ins().iconst(ptr, l.cells_unguarded as i64); let shared = self.b.ins().uload8(types::I64, f, flag, 0); let unset = self.b.ins().icmp_imm(IntCC::Equal, want, 0); @@ -1452,17 +1912,33 @@ impl Lower<'_> { self.b.ins().jump(done, &hit_args); } - /// [`h_global`]'s cache in line: the frame runs its compile-time - /// function, whose globals still have the cached stamp, under the - /// cached value epoch. Jumps to `done` with the value's words, or to - /// `slow`. + /// [`h_global`]'s cache in line: the frame runs a function over its + /// compile-time function's globals and builtins, the globals still + /// have the cached stamp, and the value epoch is the cached one. + /// Jumps to `done` with the value's words, or to `slow`. fn inline_global(&mut self, fl: &FrameLower<'_>, cache: i64, done: Block, slow: Block) { let f = MemFlags::trusted(); let ptr = self.ptr; if fl.depth == 0 { - // The evaluation's own function may be another with this code. + // The evaluation's own function may be another with this code + // (a lambda or a nested function, made anew each time its + // `def` runs): the namespaces are what the read depends on, + // and those functions share them. + // SAFETY: the compile-time function is alive (see + // `FrameLower::func`); each field is one pointer. + let (want_g, want_b) = unsafe { + let at = fl.func.cast::(); + ( + at.add(F_GLOBALS as usize).cast::().read_unaligned(), + at.add(F_BUILTINS as usize).cast::().read_unaligned(), + ) + }; let top = self.b.ins().load(ptr, f, self.ctx, TOP_F_OFFSET); - let other = self.b.ins().icmp_imm(IntCC::NotEqual, top, fl.func as i64); + let g = self.b.ins().load(ptr, f, top, F_GLOBALS); + let bi = self.b.ins().load(ptr, f, top, F_BUILTINS); + let other_g = self.b.ins().icmp_imm(IntCC::NotEqual, g, want_g as i64); + let other_b = self.b.ins().icmp_imm(IntCC::NotEqual, bi, want_b as i64); + let other = self.b.ins().bor(other_g, other_b); self.miss_if(other, slow); } // SAFETY: the frame's function is alive while its code runs (see @@ -1740,7 +2216,7 @@ impl Lower<'_> { self.decline = self.b.create_block(); let fr = self.b.ins().iadd_imm(self.ctx, i64::from(TOP_OFFSET)); let fl = self.frame(plan, code, ext, fr, 0, None, Rc::as_ptr(f)); - self.keep.push((Rc::downgrade(f), f.code())); + self.keep.push((Rc::downgrade(f), None)); let flags = MemFlags::trusted(); for k in 0..usize::from(plan.nargs) { let t = self.b.ins().load(types::I64, flags, argw, (16 * k) as i32); @@ -1791,7 +2267,7 @@ impl Lower<'_> { .iter() .map(|op| { let before = seen; - seen |= matches!(op, Op::StoreAttr { .. }); + seen |= matches!(op, Op::StoreAttr { .. } | Op::StoreItem { .. }); before }) .collect(); @@ -1864,7 +2340,7 @@ impl Lower<'_> { if cplan .ops .iter() - .any(|op| matches!(op, Op::StoreAttr { .. })) + .any(|op| matches!(op, Op::StoreAttr { .. } | Op::StoreItem { .. })) { return None; } @@ -1874,6 +2350,90 @@ impl Lower<'_> { Some((f, ccode, cext, cplan)) } + /// [`Self::inline_target`] for a plain function call: the callee + /// register `at` was last filled by a global load, and that name is + /// bound to a pure-leaf function in the compile-time function's + /// globals now. A global's value reaches the register as a borrowed + /// object, so the call's guard reads it: the last two results are the + /// function value's tag byte and payload word. + #[allow(clippy::type_complexity)] + fn inline_global_target( + &self, + fl: &FrameLower<'_>, + i: usize, + at: u8, + argc: u8, + ) -> Option<( + ( + Rc, + Rc, + &'static CodeConstObjects, + &'static LeafPlan, + ), + u8, + u64, + )> { + if fl.depth >= INLINE_DEPTH || (self.effect && fl.depth == 0 && fl.may_store[i]) { + return None; + } + let writer = fl.plan.ops[..i] + .iter() + .rev() + .find(|op| op.writes().contains(&Some(at)))?; + let Op::Global { pc, .. } = *writer else { + return None; + }; + let name = fl + .code + .names + .get(fl.code.instructions.get(usize::from(pc))?.arg as usize)?; + // SAFETY: the compile-time function is alive (see + // `FrameLower::func`); a read that runs no code, the function + // cloned out of it at once. A value is at least two words: its + // tag byte first, a pointer payload in the second. + let (f, tag, word) = unsafe { + let held = (*(*fl.func).globals.as_ptr()).get(&crate::object::StrKey(name))?; + let Object::Function(f) = held else { + return None; + }; + let at = std::ptr::from_ref(held).cast::(); + ( + f.clone(), + at.read(), + at.add(8).cast::().read_unaligned(), + ) + }; + // (The payload word must be the function's own pointer, or the + // guard below would not name it.) + // SAFETY: an `Rc` is one pointer word. + if word != unsafe { std::mem::transmute_copy::, usize>(&f) } as u64 { + return None; + } + let ccode = f.code(); + if !crate::code_is_pure_leaf(&ccode) + || !Interpreter::leaf_code_ok(&ccode) + || crate::leaf_arity(&ccode) != usize::from(argc) + || ccode.has_varkeywords + { + return None; + } + let cext = crate::code_vm_ext(&ccode)?; + let cplan = cext + .leaf_plan + .get_or_init(|| super::build(&ccode, cext).map(Box::new)) + .as_deref()?; + if cplan + .ops + .iter() + .any(|op| matches!(op, Op::StoreAttr { .. } | Op::StoreItem { .. })) + { + return None; + } + // SAFETY: as in `inline_target`. + let (cext, cplan) = unsafe { (&*std::ptr::from_ref(cext), &*std::ptr::from_ref(cplan)) }; + Some(((f, ccode, cext, cplan), tag, word)) + } + /// Lower one op; whether it falls through to the next. #[allow(clippy::too_many_lines)] fn op(&mut self, fl: &FrameLower<'_>, i: usize, op: &Op) -> Option { @@ -2083,8 +2643,66 @@ impl Lower<'_> { let bit = self.b.ins().fcmp(fcc, xa, xb); self.b.ins().jump(merge, &[bit.into()]); self.b.switch_to_block(slow); - let k = self.u32c(u32::from(kind)); - let r = self.call(h_compare as *const () as usize, &[ta, pa, tb, pb, k]); + let k = self.u32c(u32::from(kind) | u32::from(fl.depth) << 8); + let r = self.call( + h_compare as *const () as usize, + &[self.ctx, ta, pa, tb, pb, k], + ); + let bit = self.bit_or_decline(r); + self.b.ins().jump(merge, &[bit.into()]); + self.b.switch_to_block(merge); + let bit = self.b.block_params(merge)[0]; + self.set_bool(fl, dst, bit); + } + Op::ItemsCompare { + dst, + a0, + a1, + a2, + b0, + b1, + b2, + n, + kind, + } => { + let cc = match kind { + k if k == CompareKind::Lt as u8 => IntCC::SignedLessThan, + k if k == CompareKind::LtE as u8 => IntCC::SignedLessThanOrEqual, + k if k == CompareKind::Eq as u8 => IntCC::Equal, + k if k == CompareKind::NotEq as u8 => IntCC::NotEqual, + k if k == CompareKind::Gt as u8 => IntCC::SignedGreaterThan, + k if k == CompareKind::GtE as u8 => IntCC::SignedGreaterThanOrEqual, + _ => return None, + }; + let (ta0, pa0) = self.get(fl, a0); + let (ta1, pa1) = self.get(fl, a1); + let (ta2, pa2) = self.get(fl, a2); + let (tb0, pb0) = self.get(fl, b0); + let (tb1, pb1) = self.get(fl, b1); + let (tb2, pb2) = self.get(fl, b2); + // Two first items that are unequal ints decide in line; + // anything else takes the helper. + let ia = self.b.ins().icmp_imm(IntCC::Equal, ta0, T_I as i64); + let ib = self.b.ins().icmp_imm(IntCC::Equal, tb0, T_I as i64); + let ne = self.b.ins().icmp(IntCC::NotEqual, pa0, pb0); + let both = self.b.ins().band(ia, ib); + let fast = self.b.ins().band(both, ne); + let first = self.b.create_block(); + let slow = self.b.create_block(); + let merge = self.b.create_block(); + self.b.append_block_param(merge, types::I8); + self.b.ins().brif(fast, first, &[], slow, &[]); + self.b.switch_to_block(first); + let bit = self.b.ins().icmp(cc, pa0, pb0); + self.b.ins().jump(merge, &[bit.into()]); + self.b.switch_to_block(slow); + let k = self.u32c(u32::from(n) | u32::from(kind) << 8); + let r = self.call( + h_items_compare as *const () as usize, + &[ + ta0, pa0, ta1, pa1, ta2, pa2, tb0, pb0, tb1, pb1, tb2, pb2, k, + ], + ); let bit = self.bit_or_decline(r); self.b.ins().jump(merge, &[bit.into()]); self.b.switch_to_block(merge); @@ -2103,6 +2721,28 @@ impl Lower<'_> { let bit = self.b.ins().ireduce(types::I8, r); self.set_bool(fl, dst, bit); } + Op::SameClass { + dst, + a, + b, + invert, + pa, + pb, + name, + } => { + let (ta, va) = self.get(fl, a); + let (tb, vb) = self.get(fl, b); + let pcs = self.u32c(u32::from(pa) | u32::from(pb) << 16); + let ni = self.u32c(u32::from(name) | u32::from(invert) << 31); + let addr = if effect { + h_same_class:: as *const () as usize + } else { + h_same_class:: as *const () as usize + }; + let st = self.call(addr, &[self.ctx, fl.fr, ta, va, tb, vb, pcs, ni]); + self.check(st); + self.set_out(fl, dst, 0); + } Op::Truth { dst, src } => { let bit = self.truth(fl, src); self.set_bool(fl, dst, bit); @@ -2283,6 +2923,22 @@ impl Lower<'_> { self.check(st); self.set_out(fl, dst, 0); } + Op::Contains { + dst, + item, + cont, + invert, + } => { + let (ta, pa) = self.get(fl, item); + let (tb, pb) = self.get(fl, cont); + let inv = self.u32c(u32::from(invert)); + let st = self.call( + h_contains as *const () as usize, + &[self.ctx, ta, pa, tb, pb, inv], + ); + self.check(st); + self.set_out(fl, dst, 0); + } Op::Subscr { dst, a, b } => { let (ta, pa) = self.get(fl, a); let (tb, pb) = self.get(fl, b); @@ -2290,6 +2946,85 @@ impl Lower<'_> { self.check(st); self.set_out(fl, dst, 0); } + Op::Text { dst, src } => { + let (ts, ps) = self.get(fl, src); + let st = self.call(h_text as *const () as usize, &[self.ctx, ts, ps]); + self.check(st); + self.set_out(fl, dst, 0); + } + Op::Convert { dst, src, kind } => { + let (ts, ps) = self.get(fl, src); + let kv = self.u32c(u32::from(kind)); + let st = self.call(h_convert as *const () as usize, &[self.ctx, ts, ps, kv]); + self.check(st); + self.set_out(fl, dst, 0); + } + Op::Unpack { src, n } => { + let (ts, ps) = self.get(fl, src); + let nv = self.u32c(u32::from(n)); + let st = self.call(h_unpack as *const () as usize, &[ts, ps, nv]); + self.check(st); + } + Op::Item { dst, src, idx } => { + let (ts, ps) = self.get(fl, src); + let iv = self.u32c(u32::from(idx)); + let st = self.call(h_item as *const () as usize, &[self.ctx, ts, ps, iv]); + self.check(st); + self.set_out(fl, dst, 0); + } + Op::Seq { at, n, list } => { + let slot = self.b.create_sized_stack_slot(StackSlotData::new( + StackSlotKind::ExplicitSlot, + 16 * u32::from(n), + 3, + )); + for j in 0..n { + let (t, p) = self.get(fl, at + j); + self.b.ins().stack_store(t, slot, 16 * i32::from(j)); + self.b.ins().stack_store(p, slot, 16 * i32::from(j) + 8); + } + let w = self.b.ins().stack_addr(self.ptr, slot, 0); + let nv = self.u32c(u32::from(n)); + let lv = self.u32c(u32::from(list)); + let st = self.call(h_seq as *const () as usize, &[self.ctx, w, nv, lv]); + self.check(st); + self.set_out(fl, at, 0); + } + Op::Map { at, n } => { + let k = 2 * n; + let slot = self.b.create_sized_stack_slot(StackSlotData::new( + StackSlotKind::ExplicitSlot, + 16 * u32::from(k), + 3, + )); + for j in 0..k { + let (t, p) = self.get(fl, at + j); + self.b.ins().stack_store(t, slot, 16 * i32::from(j)); + self.b.ins().stack_store(p, slot, 16 * i32::from(j) + 8); + } + let w = self.b.ins().stack_addr(self.ptr, slot, 0); + let nv = self.u32c(u32::from(n)); + let st = self.call(h_map as *const () as usize, &[self.ctx, w, nv]); + self.check(st); + self.set_out(fl, at, 0); + } + Op::Join { at, n } => { + let slot = self.b.create_sized_stack_slot(StackSlotData::new( + StackSlotKind::ExplicitSlot, + 16 * u32::from(n), + 3, + )); + for k in 0..n { + let (t, p) = self.get(fl, at + k); + self.b.ins().stack_store(t, slot, 16 * i32::from(k)); + self.b.ins().stack_store(p, slot, 16 * i32::from(k) + 8); + } + let w = self.b.ins().stack_addr(self.ptr, slot, 0); + let nv = self.u32c(u32::from(n)); + let st = self.call(h_join as *const () as usize, &[self.ctx, w, nv]); + self.check(st); + self.set_out(fl, at, 0); + } Op::Tuple { dst, a, b, c, n } => { let (ta, pa) = self.get(fl, a); let (tb, pb) = self.get(fl, b); @@ -2302,10 +3037,68 @@ impl Lower<'_> { self.check(st); self.set_out(fl, dst, 0); } + Op::HashItems { at, a, b, c, n } => { + let (tf, pf) = self.get(fl, at); + let (ta, pa) = self.get(fl, a); + let (tb, pb) = self.get(fl, b); + let (tc, pc) = self.get(fl, c); + let nv = self.u32c(u32::from(n)); + let st = self.call( + h_hash_items as *const () as usize, + &[self.ctx, tf, pf, ta, pa, tb, pb, tc, pc, nv], + ); + self.check(st); + self.set_out(fl, at, 0); + } + Op::Slice { dst, a, b, c, n } => { + let (ta, pa) = self.get(fl, a); + let (tb, pb) = self.get(fl, b); + let (tc, pc) = self.get(fl, c); + let nv = self.u32c(u32::from(n)); + let st = self.call( + h_slice as *const () as usize, + &[self.ctx, ta, pa, tb, pb, tc, pc, nv], + ); + self.check(st); + self.set_out(fl, dst, 0); + } Op::Decline => { self.b.ins().jump(self.decline, &[]); return Some(false); } + Op::StopIter { src } => { + // (An in-line callee's raise declines: only the step's own + // frame may end it.) + if fl.ret.is_some() { + self.b.ins().jump(self.decline, &[]); + return Some(false); + } + let (t, p) = self.get(fl, src); + let st = self.call(h_stop_iter as *const () as usize, &[self.ctx, t, p]); + self.check(st); + let two = self.b.ins().iconst(types::I32, i64::from(STOPPED)); + self.b.ins().return_(&[two]); + return Some(false); + } + Op::StoreItem { + cont, + key, + val, + last, + } => { + if !effect || !last { + self.b.ins().jump(self.decline, &[]); + return Some(false); + } + let (tc, pc) = self.get(fl, cont); + let (tk, pk) = self.get(fl, key); + let (tv, pv) = self.get(fl, val); + let st = self.call( + h_store_item as *const () as usize, + &[self.ctx, tc, pc, tk, pk, tv, pv], + ); + self.check(st); + } Op::StoreAttr { recv, val, @@ -2364,23 +3157,55 @@ impl Lower<'_> { /// a guard, falling back to the helper. fn call_op(&mut self, fl: &FrameLower<'_>, i: usize, at: u8, argc: u8, pc: u16) -> Option<()> { let cont = self.b.create_block(); - if let Some((f, ccode, cext, cplan)) = self.inline_target(fl, i, at, argc) { - // The guard: the register holds this function, called with an - // instance receiver, and the function still runs this code. + // A method call's callee takes its receiver; a plain function + // call's self slot is the empty one. + let target = match self.inline_target(fl, i, at, argc) { + Some(t) => Some((t, None)), + None => self + .inline_global_target(fl, i, at, argc) + .map(|(t, tag, word)| (t, Some((tag, word)))), + }; + if let Some(((f, ccode, cext, cplan), held)) = target { + let method = held.is_none(); let (tf, pf) = self.get(fl, at); let (ts, _) = self.get(fl, at + 1); - let is_fn = self.b.ins().icmp_imm(IntCC::Equal, tf, T_FN as i64); - let same = self - .b - .ins() - .icmp_imm(IntCC::Equal, pf, Rc::as_ptr(&f) as i64); - let has_self = self.b.ins().icmp_imm(IntCC::Equal, ts, T_R as i64); - let ok = self.b.ins().band(is_fn, same); - let ok = self.b.ins().band(ok, has_self); let code_check = self.b.create_block(); let inline = self.b.create_block(); let generic = self.b.create_block(); - self.b.ins().brif(ok, code_check, &[], generic, &[]); + match held { + // The guard: the register holds this function, called + // with an instance receiver, and (below) the function + // still runs this code. + None => { + let is_fn = self.b.ins().icmp_imm(IntCC::Equal, tf, T_FN as i64); + let same = self + .b + .ins() + .icmp_imm(IntCC::Equal, pf, Rc::as_ptr(&f) as i64); + let has_self = self.b.ins().icmp_imm(IntCC::Equal, ts, T_R as i64); + let ok = self.b.ins().band(is_fn, same); + let ok = self.b.ins().band(ok, has_self); + self.b.ins().brif(ok, code_check, &[], generic, &[]); + } + // A global's: the register borrows an object that is this + // function (its tag, and its payload the function's + // pointer), and the self slot is the empty one. + Some((tag, word)) => { + let is_obj = self.b.ins().icmp_imm(IntCC::Equal, tf, T_R as i64); + let no_self = self.b.ins().icmp_imm(IntCC::Equal, ts, T_NULL as i64); + let ok = self.b.ins().band(is_obj, no_self); + let probe = self.b.create_block(); + self.b.ins().brif(ok, probe, &[], generic, &[]); + self.b.switch_to_block(probe); + let flags = MemFlags::trusted(); + let now_tag = self.b.ins().uload8(types::I64, flags, pf, 0); + let now_word = self.b.ins().load(types::I64, flags, pf, 8); + let same_tag = self.b.ins().icmp_imm(IntCC::Equal, now_tag, i64::from(tag)); + let same_word = self.b.ins().icmp_imm(IntCC::Equal, now_word, word as i64); + let ok = self.b.ins().band(same_tag, same_word); + self.b.ins().brif(ok, code_check, &[], generic, &[]); + } + } self.b.switch_to_block(code_check); let cell = f.code.as_ptr(); // SAFETY: the cell holds an `Rc` (one pointer word); the guard @@ -2404,15 +3229,21 @@ impl Lower<'_> { self.depth = self.depth.max(depth); let ret = Some((fl.tags[usize::from(at)], fl.pays[usize::from(at)], cont)); let cfl = self.frame(cplan, &ccode, cext, fr, depth, ret, Rc::as_ptr(&f)); - // The receiver and the arguments become the callee's first - // registers. - for k in 0..=usize::from(argc) { - let (t, p) = self.get(fl, at + 1 + k as u8); + // The receiver (a method's) and the arguments become the + // callee's first registers. + let (first, count) = if method { + (1, usize::from(argc) + 1) + } else { + (2, usize::from(argc)) + }; + for k in 0..count { + let (t, p) = self.get(fl, at + first + k as u8); self.set(&cfl, k as u8, t, p); } self.b.ins().jump(cfl.blocks[0], &[]); self.frames.push(frame); - self.keep.push((Rc::downgrade(&f), ccode.clone())); + let held = (!std::ptr::eq(Rc::as_ptr(&ccode), self.own)).then(|| ccode.clone()); + self.keep.push((Rc::downgrade(&f), held)); self.body(&cfl)?; self.b.switch_to_block(generic); } diff --git a/crates/weavepy-vm/src/lib.rs b/crates/weavepy-vm/src/lib.rs index 522b127b3..0f0475dfe 100644 --- a/crates/weavepy-vm/src/lib.rs +++ b/crates/weavepy-vm/src/lib.rs @@ -78,6 +78,7 @@ pub mod rare_events; pub mod rc; pub mod recursion; mod seqiter; +mod setalg; pub mod shared_value; pub mod specialize; pub mod stdlib; @@ -1072,15 +1073,45 @@ pub struct Interpreter { #[allow(clippy::vec_box)] chain_pool: Vec>, /// The builtins the leaf burst may call directly (see [`LeafFns`]), - /// resolved on first use. - leaf_fns: std::cell::OnceCell, - /// The registered leaf builtins (see [`leaf_builtins`]) as last - /// snapshotted, with the registry generation they reflect. - leaf_opaque: ThreadCell<(u64, leaf_builtins::LeafMap)>, + /// resolved on first use. Shared with the interpreter's forks for + /// threads: the table doesn't change once built, and a copy of its + /// maps was a twentieth of a thread's start. + leaf_fns: std::cell::OnceCell>, + /// The registered leaf builtins (see [`leaf_builtins`]) this + /// interpreter has looked up, and the builtins it found unregistered + /// under the registry generation beside them. + leaf_opaque: ThreadCell<(u64, leaf_builtins::LeafMap, LeafMisses)>, /// The last builtin [`Interpreter::leaf_call_kind`] found no leaf, by /// address, and the registry generation it looked under: a call path /// asks for the same builtin several times over. leaf_miss: std::cell::Cell<(usize, u64)>, + /// The `__next__` code and iterator (by address) of the frameless + /// step [`Interpreter::leaf_python_step`] is running: that evaluation + /// alone may end at a bare `raise StopIteration` as exhausted (see + /// `leaf_plan::Op::StopIter`), and whether the stores it buffered + /// ahead of the raise may land (not when the caller then runs the + /// full call to raise the exception, which would repeat them). + pub(crate) leaf_stop: std::cell::Cell<(usize, usize, bool)>, + /// Whether that step also ends at a bare `raise IndexError` (a + /// legacy `__getitem__` sequence's step, see `seqiter_step`). + pub(crate) leaf_stop_index: std::cell::Cell, + /// The class (its address and attribute version) `make_iter` last + /// found to be a legacy sequence: no `__iter__` anywhere, a plain + /// Python `__getitem__` (see `Self::legacy_seq_iter`). + legacy_seq: std::cell::Cell<(usize, u64)>, + /// `collections.abc.Mapping.keys` as last verified (see + /// `Self::abc_keys_fn`): the function, with `Mapping`'s and + /// `KeysView`'s classes and their attribute versions then. + abc_keys: RefCell>, + /// The class (its address and attribute version) last found to take + /// its `keys` from `collections.abc.Mapping` (see + /// `Self::thin_mapping_dict`). + abc_keys_class: std::cell::Cell<(usize, u64)>, + /// The last builtin [`Interpreter::leaf_call_kind`] found a leaf kind + /// for, the registry generation it looked under, and the kind. The weak + /// handle keeps the address from being reused while it is remembered. + leaf_hit: + std::cell::RefCell, u64, LeafKind)>>, /// The core loop's last native iterator `__next__`, keyed by the /// (process-unique) attribute version of the class that resolved it /// (see [`Interpreter::core_leaf_next`]): a whole-body leaf with its @@ -1090,6 +1121,9 @@ pub struct Interpreter { /// How the last class seen in a boolean context answers it (see /// [`Interpreter::leaf_instance_truth`]), by attribute version. core_truth: ThreadCell>, + /// The classes `core_truth` answered for before its current one (see + /// [`Self::core_truth_recall`]). + core_truth_more: ThreadCell<[Option<(u64, NativeTruth)>; 3]>, /// `WP_DBG_SAMPLE`: periodic frame-entry sampling to stderr. dbg_sample: bool, /// The GIL, held while the fields above drop (see the `Drop` impl). @@ -1338,10 +1372,21 @@ impl Default for Interpreter { recs: frame_jit::DirectRecs::new(), chain_pool: Vec::new(), leaf_fns: std::cell::OnceCell::new(), - leaf_opaque: ThreadCell::new((0, leaf_builtins::LeafMap::default())), + leaf_opaque: ThreadCell::new(( + 0, + leaf_builtins::LeafMap::default(), + LeafMisses::default(), + )), leaf_miss: std::cell::Cell::new((0, 0)), + leaf_stop: std::cell::Cell::new((0, 0, false)), + leaf_stop_index: std::cell::Cell::new(false), + legacy_seq: std::cell::Cell::new((0, 0)), + abc_keys: RefCell::new(None), + abc_keys_class: std::cell::Cell::new((0, 0)), + leaf_hit: std::cell::RefCell::new(None), core_next: ThreadCell::new(None), core_truth: ThreadCell::new(None), + core_truth_more: ThreadCell::new([None, None, None]), dbg_sample: crate::hot_gates::env_flags::dbg_sample(), drop_gil: crate::gil::GilScope::idle(), }; @@ -1492,11 +1537,24 @@ impl Interpreter { lazy_top: std::cell::Cell::new(0), recs: frame_jit::DirectRecs::new(), chain_pool: Vec::new(), - leaf_fns: std::cell::OnceCell::new(), - leaf_opaque: ThreadCell::new((0, leaf_builtins::LeafMap::default())), + // (The same builtins, so the same function objects: the + // table itself, when the parent has built it.) + leaf_fns: self.leaf_fns.clone(), + leaf_opaque: ThreadCell::new(( + 0, + leaf_builtins::LeafMap::default(), + LeafMisses::default(), + )), leaf_miss: std::cell::Cell::new((0, 0)), + leaf_stop: std::cell::Cell::new((0, 0, false)), + leaf_stop_index: std::cell::Cell::new(false), + legacy_seq: std::cell::Cell::new((0, 0)), + abc_keys: RefCell::new(None), + abc_keys_class: std::cell::Cell::new((0, 0)), + leaf_hit: std::cell::RefCell::new(None), core_next: ThreadCell::new(None), core_truth: ThreadCell::new(None), + core_truth_more: ThreadCell::new([None, None, None]), dbg_sample: crate::hot_gates::env_flags::dbg_sample(), drop_gil: crate::gil::GilScope::idle(), } @@ -1998,18 +2056,8 @@ impl Interpreter { // to trip an auto-collection), so engage the GIL here just as // `run_module_as` does for the program body. The process is // single-threaded at this point, so the acquire is uncontended. - let engaged_gil = if crate::gil::current_thread_holds_gil() { - false - } else { - crate::gil::push_gil_guard(crate::gil::global_gil().acquire()); - crate::gil::note_gil_acquired(); - true - }; - let site_result = self.run_site_inner(); - if engaged_gil { - drop(crate::gil::pop_gil_guard()); - } - site_result + let _gil = crate::gil::hold_gil(); + self.run_site_inner() } fn run_site_inner(&mut self) -> Result<(), RuntimeError> { @@ -2069,6 +2117,15 @@ impl Interpreter { args: &[Object], kwargs: &[(String, Object)], ) -> Result { + // A native function's callback (`bisect`'s `key`, a hook) from a + // VM frame of this interpreter: already published, its handles + // active, so the call is all that's left. + if crate::vm_singletons::current_interpreter_ptr() == Some(std::ptr::from_mut::(self)) + && crate::vm_singletons::thread_handles_are(&self.frame_stack) + { + let globals = self.builtins.clone(); + return self.call(&callable, args, kwargs, &globals); + } let _interp_guard = crate::vm_singletons::publish_interpreter_ptr(std::ptr::from_mut::(self)); let _handles = self.activate_thread_handles(); @@ -2087,6 +2144,12 @@ impl Interpreter { kwargs: &[(String, Object)], globals: &Rc>, ) -> Result { + // (Published and active already: see `call_object`.) + if crate::vm_singletons::current_interpreter_ptr() == Some(std::ptr::from_mut::(self)) + && crate::vm_singletons::thread_handles_are(&self.frame_stack) + { + return self.call(callable, args, kwargs, globals); + } let _interp_guard = crate::vm_singletons::publish_interpreter_ptr(std::ptr::from_mut::(self)); let _handles = self.activate_thread_handles(); @@ -2264,6 +2327,10 @@ impl Interpreter { UnaryKind::Pos => "__pos__", _ => "__invert__", }; + // (A native dunder's body directly: `-td`, `+dec`.) + if let Some(r) = instance_native_dunder(v, dunder, None) { + return r; + } match instance_method(v, dunder) { Some(method) => self.call(&method, &[], &[], &globals), None => unary_op(&v.native_value().unwrap_or_else(|| v.clone()), op), @@ -2459,6 +2526,16 @@ impl Interpreter { /// state — critical now that worker threads have their own /// forked interpreter with independent frame / exception stacks. pub(crate) fn activate_thread_handles(&self) -> crate::vm_singletons::ThreadHandlesGuard { + // (Re-entered with its own handles on top, the common nested + // call: nothing to push.) + if crate::vm_singletons::thread_handles_top_is( + &self.frame_stack, + &self.exc_info_stack, + &self.excepthook, + &self.unraisable_hook, + ) { + return crate::vm_singletons::ThreadHandlesGuard::unpushed(); + } crate::vm_singletons::activate_thread_handles(crate::vm_singletons::ThreadHandles { frame_stack: self.frame_stack.clone(), exc_info_stack: self.exc_info_stack.clone(), @@ -2525,13 +2602,9 @@ impl Interpreter { // `_CallItem.__dict__` corruption under ProcessPoolExecutor). // Guarded so re-entrant `run_module` calls (REPL lines, the // in-process conformance runner) don't stack redundant guards. - let engaged_gil = if crate::gil::current_thread_holds_gil() { - false - } else { - crate::gil::push_gil_guard(crate::gil::global_gil().acquire()); - crate::gil::note_gil_acquired(); - true - }; + // (Declared first, so released last: the frame, the code and the + // thread handles below are objects, released while it is held.) + let _gil = crate::gil::hold_gil(); let _interp_guard = crate::vm_singletons::publish_interpreter_ptr(std::ptr::from_mut::(self)); let _handles = self.activate_thread_handles(); @@ -2602,9 +2675,6 @@ impl Interpreter { // failure must not change the program's overall exit // status. self.run_pending_finalizers(); - if engaged_gil { - drop(crate::gil::pop_gil_guard()); - } result } @@ -2621,8 +2691,15 @@ impl Interpreter { match dropped.strong_word() { None => return std::mem::forget(dropped), // SAFETY: `dropped` owns a reference, released here unless - // it is the last one. - Some(word) if unsafe { crate::rc::try_release_word(word) } => { + // it is the last one (with a locked update once the bias + // is gone). + Some(word) + if unsafe { + crate::rc::try_release_word(word) + || (!crate::rc::refcounts_biased() + && crate::rc::release_unless_last(word)) + } => + { return std::mem::forget(dropped); } Some(_) => {} @@ -2730,28 +2807,55 @@ impl Interpreter { fn maybe_donate_tuple(&self, dropped: Object) { const PER_LEN_CAP: usize = 8; - let Object::Tuple(t) = dropped else { return }; - if t.is_empty() || t.len() > 16 || ThinArc::strong_count(&t) != 1 { - return; - } - let mut t = t; - if let Some(slots) = ThinArc::get_mut(&mut t) { - // (The last first, as CPython's tuple goes: `f(*args)`'s run - // through a leaf callee's locals this way.) - for s in slots.iter_mut().rev() { - let old = std::mem::replace(s, Object::Unbound); - // Scalars have no drop glue; skip the out-of-line call. - if matches!( - old, - Object::Int(_) | Object::Float(_) | Object::Bool(_) | Object::None - ) { - std::mem::forget(old); - } else { - drop(old); + let scalar = |s: &Object| { + matches!( + s, + Object::Int(_) | Object::Float(_) | Object::Bool(_) | Object::None + ) + }; + let n = match &dropped { + Object::Tuple(t) => { + let n = t.len(); + if n == 0 || n > 16 { + return; } + // A full bucket (a loop that only drops tuples fills it for + // good) takes nothing: a tuple of scalars goes as any other, + // without its slots cleared first. (Other items are released + // last first below, as CPython's tuple releases them.) + if t.iter().all(scalar) + && !self + .tuple_pool + .try_borrow() + .is_ok_and(|pool| pool[n - 1].len() < PER_LEN_CAP) + { + return; + } + n } - let mut pool = self.tuple_pool.borrow_mut(); - let bucket = &mut pool[t.len() - 1]; + _ => return, + }; + let Object::Tuple(mut t) = dropped else { + return; + }; + let Some(slots) = ThinArc::get_mut(&mut t) else { + return; + }; + // (The last first, as CPython's tuple goes: `f(*args)`'s run + // through a leaf callee's locals this way.) + for s in slots.iter_mut().rev() { + if matches!( + s, + Object::Int(_) | Object::Float(_) | Object::Bool(_) | Object::None + ) { + // SAFETY: a scalar has no drop glue, so it's overwritten. + unsafe { std::ptr::write(s, Object::Unbound) }; + } else { + drop(std::mem::replace(s, Object::Unbound)); + } + } + if let Ok(mut pool) = self.tuple_pool.try_borrow_mut() { + let bucket = &mut pool[n - 1]; if bucket.len() < PER_LEN_CAP { bucket.push(t); } @@ -2785,18 +2889,24 @@ impl Interpreter { /// for small bytecode tuples. A miss needs only the final allocation. fn alloc_tuple_array(&self, items: [Object; N]) -> Object { if N > 0 && N <= 16 { - let popped = self.tuple_pool.borrow_mut()[N - 1].pop(); + let popped = match self.tuple_pool.try_borrow_mut() { + Ok(mut pool) => pool[N - 1].pop(), + Err(_) => None, + }; if let Some(mut tuple) = popped { - if let Some(slots) = ThinArc::get_mut(&mut tuple) { - for (slot, value) in slots.iter_mut().zip(items) { - // SAFETY: a pooled tuple's slots were cleared to - // `Unbound` (see `maybe_donate_tuple`), which has - // no drop glue. - debug_assert!(matches!(slot, Object::Unbound)); - unsafe { std::ptr::write(slot, value) }; - } - return Object::Tuple(tuple); + // SAFETY: a parked tuple is its allocation's only owner, with + // `N` slots each `Unbound` (see `maybe_donate_tuple` and + // `park_tuple`), which has no drop glue: the items move in + // over them. + unsafe { + let slots = ThinArc::get_mut_unchecked(&mut tuple); + debug_assert!( + slots.len() == N && slots.iter().all(|s| matches!(s, Object::Unbound)) + ); + std::ptr::copy_nonoverlapping(items.as_ptr(), slots.as_mut_ptr(), N); } + std::mem::forget(items); + return Object::Tuple(tuple); } } Object::new_tuple_array(items) @@ -2926,13 +3036,29 @@ impl Interpreter { // (test_bdb saw a `WeakKeyDictionary.remove` frame in place // of its first 'line' event). Callbacks run untraced, like an // audit hook. - let _untraced = crate::trace::TracingSuppressGuard::enter(); - for (cb, wr) in callbacks { - let globals = self.builtins.clone(); - if let Err(err) = self.call(&cb, std::slice::from_ref(&wr), &[], &globals) { - self.write_unraisable_fmt(&err, "calling weakref callback", &cb); + if !callbacks.is_empty() { + let _untraced = crate::trace::TracingSuppressGuard::enter(); + for (cb, wr) in callbacks { + // A weak table's own removal closure: what its body + // does, with no frame (see + // `weakref_real::removal_twin`). + if crate::stdlib::weakref_real::removal_twin(&cb, &wr) { + continue; + } + let globals = self.builtins.clone(); + if let Err(err) = self.call(&cb, std::slice::from_ref(&wr), &[], &globals) { + self.write_unraisable_fmt(&err, "calling weakref callback", &cb); + } } } + // Nothing queued meanwhile (the usual case): done, by the + // entry's own three reads, with no second drain. + if !crate::vm_singletons::has_pending_finalizers() + && !crate::vm_singletons::has_pending_weakref_callbacks() + && crate::hot_gates::load() & crate::hot_gates::PENDING_FINALIZERS == 0 + { + return finalizers_run; + } } } @@ -3107,6 +3233,11 @@ impl Interpreter { /// alive), so non-daemon threads have finished and atexit output is /// produced before the interpreter tears down. pub fn run_interpreter_shutdown(&mut self) { + // The shutdown runs Python (`threading._shutdown`, exit handlers) + // and releases objects while other threads may still run: under + // the GIL, as the program's body ran (a join inside gives it up + // while it waits, as any blocking call does). + let _gil = crate::gil::hold_gil(); let _interp_guard = crate::vm_singletons::publish_interpreter_ptr(std::ptr::from_mut::(self)); // (1) threading._shutdown() — only when threading was imported, @@ -3274,6 +3405,9 @@ impl Interpreter { /// lets a finalizer that resurrects/creates new finalizable objects /// settle without risking an unbounded loop at exit. pub fn run_shutdown_finalizers(&mut self) { + // (Under the GIL, as `run_interpreter_shutdown`: daemon threads + // may still be running.) + let _gil = crate::gil::hold_gil(); let _interp_guard = crate::vm_singletons::publish_interpreter_ptr(std::ptr::from_mut::(self)); // From here on the interpreter is finalizing: fresh imports @@ -3471,10 +3605,27 @@ impl Interpreter { let Object::Instance(inst) = obj else { return true; }; + // The class's `__del__` a plain Python function (remembered per + // class version): called with the instance, as the bound method + // below calls it. + if let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::DEL_FN), + "__del__", + ) { + let del = Object::Function(f); + let globals = self.builtins.clone(); + if let Err(err) = self.call(&del, std::slice::from_ref(obj), &[], &globals) { + self.write_unraisable_fmt(&err, "calling deallocator", &del); + } + return true; + } let Some(del) = inst.cls().lookup("__del__") else { return true; }; - let bound = Object::BoundMethod(Rc::new(BoundMethod::new(obj.clone(), del.clone()))); + // (Anything else: a descriptor's `__get__` is honoured, and a + // plain callable or a static method is called with no argument.) + let bound = Object::BoundMethod(Rc::new(BoundMethod::dispatch(obj.clone(), del.clone()))); let kwargs: Vec<(String, Object)> = Vec::new(); let outer = Rc::new(RefCell::new(DictData::default())); if let Err(err) = self.call(&bound, &[], &kwargs, &outer) { @@ -5787,7 +5938,8 @@ impl Interpreter { // parked. The pool only ever holds sole-owner shells, so the // `get_mut` is a formality — but a fresh allocation is always a // correct fallback. - if let Some(mut pooled) = self.frame_shell_pool.borrow_mut().pop() { + let pooled = self.frame_shell_pool.borrow_mut().pop(); + if let Some(mut pooled) = pooled.or_else(crate::object::take_spare_shell) { if let Some(m) = Rc::get_mut(&mut pooled) { if is_gen { // A generator's shell outlives this activation inside @@ -7439,6 +7591,16 @@ impl Interpreter { if !self.specialized_binary_op(frame, cache_pc, kind)? { let b = frame.pop()?; let a = frame.pop()?; + // (Compiled code keeps an instance operator's operands on the + // stack, where its method's direct call leaves them, at a site + // known to see instances: see `instance_site`.) + if matches!(a, Object::Instance(_)) || matches!(b, Object::Instance(_)) { + if let Some(ext) = code_vm_ext_existing(&frame.code) { + if !instance_site(ext, cache_pc as usize) { + instance_site_note(ext, frame.code.instructions.len(), cache_pc as usize); + } + } + } let r_res = if inplace { self.dispatch_inplace_op(&a, &b, kind, &frame.globals) } else { @@ -7459,6 +7621,15 @@ impl Interpreter { // ops on mutables return the same object; the registry // keyed by identity just overwrites, which is harmless. self.record_alloc(&r); + // A heap result (`d1 | d2`, `k & s`, `b * 3`): compiled code + // takes the helper that keeps one, not the numbers' (which + // leaves for the core loop on anything else). + if !matches!( + r, + Object::Int(_) | Object::Float(_) | Object::Bool(_) | Object::None + ) { + Self::heap_result_note(frame, cache_pc as usize); + } frame.push(r); // Mirror of the BINARY_SUBSCR retirement: CPython decrefs // both operands as BINARY_OP retires them, so a chained @@ -7475,6 +7646,17 @@ impl Interpreter { Ok(()) } + /// Note that the `BINARY_OP` at `pc` built a heap value (see + /// [`heap_site`]). + #[cold] + fn heap_result_note(frame: &Frame, pc: usize) { + if let Some(ext) = code_vm_ext_existing(&frame.code) { + if !heap_site(ext, pc) { + heap_site_note(ext, frame.code.instructions.len(), pc); + } + } + } + /// Operand retirement for `BINARY_OP` / `COMPARE_OP`: an instance /// always goes through the prompt-reap cascade (it may carry a /// `__del__` or weakref callbacks). A tracked container that was a @@ -7573,6 +7755,16 @@ impl Interpreter { // on their metaclass; everything else (native objects like files // and locks) goes through the generic attribute path, which is // type-level for those objects anyway. + // A native receiver whose methods follow from its kind alone (a + // stream's, a view's): the shared method and the receiver, as a + // method call loads them, with no bound method made for the call. + if crate::builtins::method_memo_tag(owner).is_some() { + if let Some(Object::Builtin(b)) = crate::builtins::lookup_method(owner, name) { + if b.binds_instance { + return Ok((Object::Builtin(b), owner.clone())); + } + } + } let lookup = |vm: &mut Self, name: &str| -> Result, RuntimeError> { match owner { Object::Instance(_) => Ok(instance_method(owner, name)), @@ -7999,9 +8191,20 @@ impl Interpreter { } } } else { - let result = self.inline_finish(&mut done, exit); + let raised = matches!( + &exit, + QuietExit::Outcome { + stepped: Err(RuntimeError::PyException(_)), + .. + } + ); match inl.last_mut() { - None => self.inline_deliver(frame, done, result), + None => { + let hook = Self::attr_hook_receiver(frame, &done, raised); + let result = self.inline_finish(&mut done, exit); + self.attr_hook_context(frame, done.call_pc, &result, hook); + self.inline_deliver(frame, done, result) + } Some(caller) => { let caller = &mut **caller; // SAFETY: as above. @@ -8010,6 +8213,9 @@ impl Interpreter { } else { &mut caller.frame }; + let hook = Self::attr_hook_receiver(caller_frame, &done, raised); + let result = self.inline_finish(&mut done, exit); + self.attr_hook_context(caller_frame, done.call_pc, &result, hook); self.inline_deliver(caller_frame, done, result) } } @@ -8090,6 +8296,7 @@ impl Interpreter { wait_pending: None, outer_lazy: 0, fold: std::ptr::null(), + caught: false, }; let status = native.run_direct(&mut st, pc); // (`frame` again: the helpers reach the frame through `st`.) @@ -8684,7 +8891,8 @@ impl Interpreter { } else { // The storage escaped (a materialized frame shares it): the // slot takes fresh storage. - let fresh = match self.frame_locals_pool.borrow_mut().pop() { + let pooled = self.frame_locals_pool.borrow_mut().pop(); + let fresh = match pooled.or_else(crate::object::take_spare_locals) { Some(rc) => rc, None => Rc::new(RefCell::new(Vec::new())), }; @@ -8735,6 +8943,7 @@ impl Interpreter { act.init_inst = None; act.lru = None; act.new_init = None; + act.back_for = None; if self.inline_pool.len() < INLINE_POOL_CAP { push_fast(&mut self.inline_pool, act); } @@ -9292,13 +9501,41 @@ impl Interpreter { Err(e) => Err(e), }, }; - let result = match (done.op.take(), result) { + let op = done.op.take(); + let stored = matches!(op, Some(MethodOp::Store)); + let result = match (op, result) { (Some(MethodOp::Binary(op, inplace, l, r)), Ok(v)) if v.is_same(&crate::vm_singletons::not_implemented()) => { Err(binop_type_error(op, inplace, &l, &r)) } (Some(MethodOp::Compare(arg)), Ok(v)) => self.compare_finish(frame, arg, v), + (Some(MethodOp::Iter), Ok(v)) => iter_result(v), + (Some(MethodOp::Truth(from_len)), Ok(v)) => truth_result(v, from_len).map(Object::Bool), + (Some(MethodOp::Len), Ok(v)) => coerce_len_result(v).map(Object::Int), + (Some(MethodOp::Format), Ok(v)) => format_result(v), + (Some(MethodOp::Str), Ok(v)) => str_result(v), + (Some(MethodOp::Repr), Ok(v)) => repr_result(v), + (Some(MethodOp::Hash), Ok(v)) => self.normalize_hash_result(v), + (Some(MethodOp::HasAttr), Ok(v)) => { + self.release(v); + Ok(Object::Bool(true)) + } + (Some(MethodOp::HasAttr), Err(e)) if self.is_attribute_error(&e) => { + Ok(Object::Bool(false)) + } + (Some(MethodOp::GetAttrOr(d)), Err(e)) if self.is_attribute_error(&e) => Ok(d), + (Some(MethodOp::Inplace(op, a, b)), Ok(v)) + if v.is_same(&crate::vm_singletons::not_implemented()) => + { + let globals = frame.globals.clone(); + self.inplace_binop_fallback(&a, &b, op, &globals) + } + (Some(MethodOp::Contains(invert)), Ok(v)) => { + let globals = frame.globals.clone(); + self.obj_truthy(&v, &globals) + .map(|b| Object::Bool(b != invert)) + } (_, result) => result, }; // A `functools.lru_cache` miss's function returned: its result is @@ -9309,7 +9546,7 @@ impl Interpreter { } } let call_pc = done.call_pc; - let discard = done.discard; + let discard = done.discard || stored; self.lean_pending_exit(done.caller_pending); // SAFETY: the callable is moved out exactly once; the parked slot // treats the field as stale until `inline_bind` rewrites it. @@ -9434,7 +9671,8 @@ impl Interpreter { } else { crate::object::FrameSlot::new(frame.cells.clone()) }; - if let Some(mut pooled) = self.frame_shell_pool.borrow_mut().pop() { + let pooled = self.frame_shell_pool.borrow_mut().pop(); + if let Some(mut pooled) = pooled.or_else(crate::object::take_spare_shell) { if let Some(m) = Rc::get_mut(&mut pooled) { // SAFETY: see `push_frame_shell`; a lean activation pops // its shell through `pop_frame_shell` like any other. @@ -9713,7 +9951,11 @@ impl Interpreter { }); } if code.has_varkeywords { - v.push(Object::Dict(Rc::new(RefCell::new(DictData::default())))); + let d = Object::Dict(Rc::new(RefCell::new(DictData::default()))); + if !varkw_stays_local(code) { + gc_trace::track_built(&d); + } + v.push(d); } } @@ -9932,10 +10174,14 @@ impl Interpreter { // The interned empty tuple. Object::new_tuple(Vec::new()) } else { - Object::Tuple(crate::tuple_storage::TupleStorage::from_exact_iter( - // SAFETY: the caller's contract. - (direct..nargs).map(|k| unsafe { src.add(k).read() }), - )) + // SAFETY: the caller's contract: the surplus arguments move + // into the tuple. + Object::Tuple(unsafe { + crate::tuple_storage::TupleStorage::from_moved_raw( + src.add(direct), + nargs - direct, + ) + }) } }); if missing > 0 { @@ -9948,7 +10194,11 @@ impl Interpreter { } v.extend(star); if code.has_varkeywords { - v.push(Object::Dict(Rc::new(RefCell::new(DictData::default())))); + let d = Object::Dict(Rc::new(RefCell::new(DictData::default()))); + if !varkw_stays_local(code) { + gc_trace::track_built(&d); + } + v.push(d); } } @@ -10164,8 +10414,12 @@ impl Interpreter { for (j, v) in stack.take_from(len - kwc).enumerate() { let nibble = (perm >> (4 * j)) & 0xF; if nibble == specialize::KW_TO_VARKW { + // (Distinct names, appended without a probe: see + // `core_pure_kw_call`.) if let (Some(d), Some(name)) = (varkw.as_mut(), names.get(j)) { - d.insert(DictKey(name.clone()), v); + let key = DictKey(name.clone()); + let hash = crate::dictmap::Probe::probe_hash(&key); + d.insert_unique_hashed(hash, key, v); } continue; } @@ -10188,13 +10442,22 @@ impl Interpreter { drop(run); } if let Some(d) = varkw { - locals[total + usize::from(code.has_varargs)] = Object::Dict(Rc::new(RefCell::new(d))); + let d = Object::Dict(Rc::new(RefCell::new(d))); + if !varkw_stays_local(code) { + gc_trace::track_built(&d); + } + locals[total + usize::from(code.has_varargs)] = d; } #[allow(clippy::needless_range_loop)] for slot in direct..total { if covered & (1 << slot) == 0 { locals[slot] = if slot < npos { f.defaults[f.defaults.len() - (npos - slot)].clone() + } else if Self::kwonly_aligned(f, code) { + // (The defaults line up with the parameters: no search.) + f.kw_defaults + .get(slot - npos) + .map_or(Object::Unbound, |(_, v)| v.clone()) } else { let name = code.varnames[slot].as_str(); f.kw_defaults @@ -10610,6 +10873,107 @@ impl Interpreter { Some(self.inline_bind(frame, shell, pc, act, code, Object::Function(getter), guard)) } + /// The getter of the `property` that the attribute form of the + /// `LOAD_SUPER_ATTR` `ins` (either form) of `code` reads over its three + /// operands `ops` (the `super` global, the class, the receiver): a + /// property later in an instance receiver's MRO than the class, whose + /// getter is a plain Python function of `self` the lean paths run. + /// `None` for anything else. + pub(crate) fn super_property_getter( + code: &CodeObject, + ins: weavepy_compiler::Instruction, + ops: &[Object], + ) -> Option> { + let [g, Object::Type(cls), Object::Instance(inst)] = ops else { + return None; + }; + if ins.op != OpCode::LoadSuperAttr || ins.arg & 1 != 0 || !is_super_callable(g) { + return None; + } + let name = code.names.get((ins.arg >> 2) as usize)?; + let prop = { + let mro = inst.cls_raw().mro.try_borrow().ok()?; + let start = mro.iter().position(|t| Rc::ptr_eq(t, cls))? + 1; + let key = crate::object::StrKey(name.as_str()); + let mut found = None; + for owner in &mro[start..] { + if owner.c_ext_ptr.get() != 0 { + return None; + } + let d = owner.dict.try_borrow().ok()?; + if let Some(v) = d.get(&key) { + found = Some(v.clone()); + break; + } + } + match found? { + Object::Property(p) => p, + _ => return None, + } + }; + // SAFETY: GIL-serialized raw read of the getter cell; the clone is + // taken before anything else runs. + let Object::Function(f) = (unsafe { &*prop.fget.as_ptr() }) else { + return None; + }; + Self::lean_getter_ok(f).then(|| f.clone()) + } + + /// Whether `f` is a getter the lean paths call: a plain function of + /// one positional parameter, not a generator or coroutine, whose code + /// and cells they run. + pub(crate) fn lean_getter_ok(f: &PyFunction) -> bool { + let code = f.code(); + code.arg_count == 1 + && !code.is_generator + && !code.is_coroutine + && !code.is_async_generator + && !code.has_varargs + && !code.has_varkeywords + && code.kwonly_count == 0 + && Self::lean_code_ok(&code) + && f.lean_cells_ref(&code).is_some() + } + + /// `super().name` (the attribute form of the `LOAD_SUPER_ATTR` at `pc` + /// of `frame`, either form) of an instance where the name is a + /// `property` later in its class's MRO whose getter is a plain Python + /// function of `self`: an inline activation of the getter, as + /// [`Self::try_inline_property`] makes for `obj.name` (a super proxy's + /// read runs the getter alike, with no `__getattr__` fallback). The + /// three operands leave the stack; the getter's result takes their + /// place. + fn try_inline_super_property( + &mut self, + frame: &mut Frame, + shell: &mut QuietShell<'_>, + pc: usize, + ) -> Option> { + let ins = frame.code.instructions.get(pc)?; + let n = frame.stack.len(); + if n < 3 { + return None; + } + let getter = Self::super_property_getter(&frame.code, *ins, &frame.stack[n - 3..])?; + let code = getter.code(); + // Past the recursion limit the nested lean path raises. + let crate::recursion::Enter::Ok(guard) = crate::recursion::enter() else { + return None; + }; + // Committed. + let receiver = frame.stack.pop()?; + let cls_obj = frame.stack.pop(); + let super_obj = frame.stack.pop(); + drop((cls_obj, super_obj)); + let act = self.inline_slot(); + // SAFETY: a parked slot's locals storage is its own, and empty. + let locals = unsafe { act.frame.locals.storage() }; + locals.push(receiver); + fill_unbound(locals, code.varnames.len()); + frame.pc = pc as u32 + 1; + Some(self.inline_bind(frame, shell, pc, act, code, Object::Function(getter), guard)) + } + /// `obj.name = value` (the `STORE_ATTR` at `pc` of `frame`) for a /// `property` whose setter is a plain Python function of `(self, /// value)`, as an inline activation of the setter (CPython calls it @@ -10634,10 +10998,11 @@ impl Interpreter { let hook = if Self::default_setattr(inst.cls_raw()) { None } else { - let Object::Function(hook) = inst.cls_raw().lookup("__setattr__")? else { - return None; - }; - Some(hook) + Some(Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::SETATTR_FN), + "__setattr__", + )?) }; let f = match &hook { Some(hook) => hook.clone(), @@ -10698,6 +11063,319 @@ impl Interpreter { Some(act) } + /// The Python method that decides `inst`'s truth, as + /// [`Self::obj_truthy`] finds it: the class's `__bool__` of `(self)` + /// (`false`), or, the class defining no `__bool__`, its `__len__` + /// (`true`). `None` when neither is a plain Python function of one + /// parameter (a `__bool__` of `None` blocks the protocol). + pub(crate) fn truth_function( + inst: &PyInstance, + ) -> Option<(Rc, bool)> { + use crate::types::{vm_key, AttrKey}; + let (f, from_len) = + match Self::instance_dunder_function(inst, AttrKey::vm(vm_key::BOOL_FN), "__bool__") { + Some(f) => (f, false), + None => { + if inst.cls_raw().lookup("__bool__").is_some() { + return None; + } + let f = Self::instance_dunder_function( + inst, + AttrKey::vm(vm_key::LEN_FN), + "__len__", + )?; + (f, true) + } + }; + // SAFETY: GIL-serialized raw read of the function's code cell. + let fc = unsafe { &*f.code.as_ptr() }; + if fc.arg_count != 1 + || fc.kwonly_count != 0 + || fc.has_varargs + || fc.has_varkeywords + || fc.is_generator + || fc.is_coroutine + || fc.is_async_generator + { + return None; + } + Some((f, from_len)) + } + + /// The Python method of `(self, x)` a class's instances take + /// `CONTAINS_OP` (`key` `vm_key::CONTAINS`, `name` `__contains__`) or + /// `DELETE_SUBSCR` (`DELITEM_FN`, `__delitem__`) through. `None` for + /// anything else. + /// The Python in-place method (`__iadd__`, …) of `a`'s class that + /// `a = b` calls first, for an instance without a native payload + /// (whose in-place result CPython's slot remaps). `None` for anything + /// else. + pub(crate) fn inplace_instance_dunder( + a: &Object, + op: BinOpKind, + ) -> Option> { + let Object::Instance(ai) = a else { + return None; + }; + if ai.native.get().is_some() { + return None; + } + let k = op as usize; + let f = Self::instance_dunder_function( + ai, + crate::types::AttrKey::vm(crate::types::vm_key::IBINOP_FN + k as u32), + op.inplace_dunder(), + )?; + // SAFETY: GIL-serialized raw read of the function's code cell. + let fc = unsafe { &*f.code.as_ptr() }; + if fc.arg_count != 2 + || fc.kwonly_count != 0 + || fc.has_varargs + || fc.has_varkeywords + || fc.is_generator + || fc.is_coroutine + || fc.is_async_generator + { + return None; + } + Some(f) + } + + /// The Python method of `(self)` a unary operator (`kind` an + /// `UnaryKind` other than `not`) calls on `inst`. `None` for anything + /// else. + /// `+v` (`kind` 0) or `-v` (1) of a natively served instance (a + /// `timedelta`, a `Decimal`) whose class resolves the operator method + /// to a native with a pure fast half: the half's result, when it + /// gives one. + pub(crate) fn unary_native_fast(&self, v: &Object, kind: u32) -> Option { + let Object::Instance(inst) = v else { + return None; + }; + let cls = inst.cls_raw(); + let name = match kind { + 0 => "__pos__", + 1 => "__neg__", + _ => return None, + }; + if cls.native_kind.get() == 0 { + // An `int` or `float` subclass's instance that keeps its + // base's method (an `IntEnum` member): the payload's. + let payload = inst.native.get()?; + if !matches!(payload, Object::Int(_) | Object::Long(_) | Object::Float(_)) + || cls.c_ext_ptr.get() != 0 + || !cls.memo_verdict(crate::types::Verdict::NumConvPlain, name, || { + matches!( + cls.lookup_with_owner(name), + Some((Object::Builtin(_), owner)) if owner.flags.is_builtin + ) + }) + { + return None; + } + let op = if kind == 0 { + UnaryKind::Pos + } else { + UnaryKind::Neg + }; + return unary_op(payload, op).ok(); + } + let f = Self::native_num_leaf(inst, kind, name)?; + f(std::slice::from_ref(v))?.ok() + } + + /// The leaf half of a natively served class's numeric method `name` + /// (`which` its place among `vm_key::NATIVE_NUM_LEAF`'s: `__pos__`, + /// `__neg__`, `__abs__`, `__round__`, `__divmod__`), cached on the + /// class under its attribute version. `None` for any other class, or + /// a method without one. + #[inline] + pub(crate) fn native_num_leaf( + inst: &PyInstance, + which: u32, + name: &str, + ) -> Option { + use crate::types::LeafAttrKind as K; + let cls = inst.cls_raw(); + if cls.native_kind.get() == 0 { + return None; + } + let ver = cls.attr_version.get(); + let key = crate::types::AttrKey::vm(crate::types::vm_key::NATIVE_NUM_LEAF + which); + match cls.leaf_attrs.get(key, ver) { + Some(K::LeafFast(f)) => Some(*f), + Some(_) => None, + None => Self::instance_dunder_leaf_slow(cls, key, ver, name), + } + } + + pub(crate) fn unary_dunder_function( + inst: &PyInstance, + kind: u32, + ) -> Option> { + let name = match kind { + 0 => "__pos__", + 1 => "__neg__", + 3 => "__invert__", + _ => return None, + }; + let f = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::UNARY_FN + kind), + name, + )?; + // SAFETY: GIL-serialized raw read of the function's code cell. + let fc = unsafe { &*f.code.as_ptr() }; + if fc.arg_count != 1 + || fc.kwonly_count != 0 + || fc.has_varargs + || fc.has_varkeywords + || fc.is_generator + || fc.is_coroutine + || fc.is_async_generator + { + return None; + } + Some(f) + } + + pub(crate) fn binary_dunder_function( + inst: &PyInstance, + key: u32, + name: &str, + ) -> Option> { + let f = Self::instance_dunder_function(inst, crate::types::AttrKey::vm(key), name)?; + // SAFETY: GIL-serialized raw read of the function's code cell. + let fc = unsafe { &*f.code.as_ptr() }; + if fc.arg_count != 2 + || fc.kwonly_count != 0 + || fc.has_varargs + || fc.has_varkeywords + || fc.is_generator + || fc.is_coroutine + || fc.is_async_generator + { + return None; + } + Some(f) + } + + /// The Python function a `STORE_ATTR` of `co_names[name_idx]` on + /// `inst` calls, and how (see [`StoreCall`]): the class's own + /// `__setattr__` of `(self, name, value)`, as + /// [`Self::try_inline_setter`] finds it, or else the setter of + /// `(self, value)` of the class's `property` of that name, or the + /// `__set__` of `(self, obj, value)` of another data descriptor there. + /// `None` for any other store. + pub(crate) fn store_attr_function( + code: &CodeObject, + inst: &PyInstance, + name_idx: u32, + ) -> Option<(Rc, StoreCall)> { + let (f, how) = if !Self::default_setattr(inst.cls_raw()) { + let f = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::SETATTR_FN), + "__setattr__", + )?; + (f, StoreCall::Hook) + } else { + match Self::leaf_resolve_instance_attr(code, inst, name_idx) { + Some(LeafAttr::Property(prop)) => { + // SAFETY: GIL-serialized raw read of the setter cell; + // the clone is taken before anything else runs. + let Object::Function(f) = (unsafe { &*prop.fset.as_ptr() }) else { + return None; + }; + (f.clone(), StoreCall::Setter) + } + _ => { + if crate::object::exotic_str_keys_possible() { + return None; + } + let name = code.names.get(name_idx as usize)?; + let desc = inst.cls_raw().lookup(name)?; + let Object::Instance(d) = &desc else { + return None; + }; + let f = Self::instance_dunder_function( + d, + crate::types::AttrKey::vm(crate::types::vm_key::SET_FN), + "__set__", + )?; + (f, StoreCall::Descriptor(desc)) + } + } + }; + // SAFETY: GIL-serialized raw read of the function's code cell. + let fc = unsafe { &*f.code.as_ptr() }; + let arity = if matches!(how, StoreCall::Setter) { + 2 + } else { + 3 + }; + if fc.arg_count != arity + || fc.is_generator + || fc.is_coroutine + || fc.is_async_generator + || fc.has_varargs + || fc.has_varkeywords + || fc.kwonly_count != 0 + { + return None; + } + Some((f, how)) + } + + /// `recv. = value` on a `threading.local` whose + /// class keeps the native `__setattr__` hook, where the store runs no + /// Python code (see `local_native::setattr_fast`): `true` once stored + /// (the value cloned in), `false` touching nothing. + pub(crate) fn local_store_fast( + code: &CodeObject, + recv: &Object, + name_idx: u32, + value: &Object, + ) -> bool { + let Object::Instance(inst) = recv else { + return false; + }; + if Self::default_setattr(inst.cls_raw()) { + return false; + } + let Some(b) = Self::instance_native_dunder( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::SETATTR_NATIVE), + "__setattr__", + false, + ) else { + return false; + }; + let Some(name) = code_name_obj(code, name_idx) else { + return false; + }; + Self::native_setattr_hook(&b, recv, name, value) + } + + /// `recv.name = value` through the native `__setattr__` `b`, when it + /// is one compiled code may call in place (a `threading.local`'s, a + /// `decimal.Context`'s) and the store runs no Python code: `true` + /// once stored (the value cloned in), `false` touching nothing. + #[inline] + fn native_setattr_hook( + b: &crate::object::BuiltinFn, + recv: &Object, + name: &Object, + value: &Object, + ) -> bool { + if crate::stdlib::local_native::is_hook(b, true) { + crate::stdlib::local_native::setattr_fast(recv, name, value) + } else { + crate::stdlib::decimal_native::is_setattr_hook(b) + && crate::stdlib::decimal_native::setattr_fast(recv, name, value) + } + } + /// `obj.name = value` (the `STORE_ATTR` at `frame.pc`) for a `property` /// whose setter is a registered leaf builtin (a native class's /// settable field): the setter runs in place and both operands leave @@ -10715,17 +11393,14 @@ impl Interpreter { if !Self::default_setattr(inst.cls_raw()) { // A `threading.local`'s native `__setattr__`, where it runs no // Python code: the entry stored in place. - let Some(Object::Builtin(b)) = inst.cls_raw().lookup("__setattr__") else { - return None; - }; + let b = Self::instance_native_dunder( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::SETATTR_NATIVE), + "__setattr__", + false, + )?; let name = code_name_obj(&frame.code, ins.arg)?; - if !crate::stdlib::local_native::is_hook(&b, true) - || !crate::stdlib::local_native::setattr_fast( - &frame.stack[n - 1], - name, - &frame.stack[n - 2], - ) - { + if !Self::native_setattr_hook(&b, &frame.stack[n - 1], name, &frame.stack[n - 2]) { return None; } let receiver = frame.stack.pop().expect("checked above"); @@ -10804,14 +11479,32 @@ impl Interpreter { || code.has_varargs || code.has_varkeywords || !code_is_effect_leaf(&code) - || code_vm_ext(&code) - .is_none_or(|e| e.pure_leaf.load(std::sync::atomic::Ordering::Relaxed) != 16) || !pure_leaf_warm(&code) { return false; } let args: [*const Object; 2] = [receiver, value]; - self.leaf_init_eval(&code, f, &args).is_some() + // The setter shape (`self._x = value`) through its own evaluator; + // any other effect leaf (a setter that checks its value first) as + // the general evaluation runs it, its stores committed at the + // return and its result (`None`) let go. + let shape = code_vm_ext(&code).map_or(0, |e| { + e.pure_leaf.load(std::sync::atomic::Ordering::Relaxed) + }); + if shape == 16 { + return self.leaf_init_eval(&code, f, &args).is_some(); + } + let depth = crate::recursion::current_depth(); + if depth >= crate::recursion::recursion_limit() { + return false; + } + match self.pure_leaf_call(&code, f, &args, true, depth) { + Some(r) => { + drop(r); + true + } + None => false, + } } /// `receiver.name = value` (the `STORE_ATTR` at `pc` of `code`) for a @@ -10829,12 +11522,16 @@ impl Interpreter { let Object::Instance(inst) = receiver else { return false; }; + if let Some(f) = Self::setter_site_hit(code, pc, inst) { + return self.leaf_setter_eval(&f, receiver, value); + } let Some(ins) = code.instructions.get(pc) else { return false; }; if ins.op != OpCode::StoreAttr || !Self::default_setattr(inst.cls_raw()) { return false; } + let ver = inst.cls_raw().attr_version.get(); let Some(LeafAttr::Property(prop)) = Self::leaf_resolve_instance_attr(code, inst, ins.arg) else { return false; @@ -10844,7 +11541,29 @@ impl Interpreter { match unsafe { &*prop.fset.as_ptr() } { Object::Function(f) => { let f = f.clone(); - self.leaf_setter_eval(&f, receiver, value) + let ran = self.leaf_setter_eval(&f, receiver, value); + // The site remembers the setter under the class's version + // (see `setter_site_hit`), its property in `keys`. + if ran && inst.cls_raw().attr_version.get() == ver { + if let Some(ext) = code_vm_ext(code) { + leaf_site_set( + ext, + code, + pc, + Some(LeafSiteData { + ver, + func: Rc::downgrade(&f), + // SAFETY: GIL-serialized raw read of the + // function's code cell. + code: Rc::as_ptr(unsafe { &*f.code.as_ptr() }), + effect: true, + keys: Rc::as_ptr(&prop) as usize, + limit: 0, + }), + ); + } + } + ran } // A native setter's fast half (asyncio's `Task._log_destroy_pending`), // which runs no Python code, as the core loop's store runs it. @@ -10859,6 +11578,38 @@ impl Interpreter { } } + /// The Python setter of the property that the `STORE_ATTR` at `pc` of + /// `code` last stored through (see [`Self::leaf_setter_at`]), when + /// `inst`'s class is still at the version it was found under and the + /// property still holds that setter: the class's attribute version + /// covers its dictionary, its bases' and its `__setattr__`, so the + /// store needs neither the plain store's attempt nor the lookup. + #[inline] + pub(crate) fn setter_site_hit( + code: &CodeObject, + pc: usize, + inst: &PyInstance, + ) -> Option> { + let ext = code_vm_ext(code)?; + if !ext.leaf_sites.is_allocated() { + return None; + } + let hit = leaf_site_hit(ext, pc, inst.cls_raw().attr_version.get())?; + // A setter site records its property (a method site, its class's + // shared names; never at a `STORE_ATTR`). + if hit.keys == 0 || code.instructions.get(pc)?.op != OpCode::StoreAttr { + return None; + } + // SAFETY: the class holds the property at the version the site + // recorded it under; GIL-serialized raw read of its setter cell (a + // re-initialized property holds another setter). + let prop = unsafe { &*(hit.keys as *const crate::object::PyProperty) }; + match unsafe { &*prop.fset.as_ptr() } { + Object::Function(f) if Rc::as_ptr(f) == hit.fp => Some(f.clone()), + _ => None, + } + } + /// The data descriptor written in Python that reading /// `co_names[name_idx]` of `inst` calls, and its `__get__`: an instance /// on the class's MRO whose own class has `__set__` or `__delete__` @@ -10879,9 +11630,12 @@ impl Interpreter { { return None; } - // (A non-data descriptor would yield to the instance's own - // attribute; those stay on the full path, as do dunders.) - let (descr, get) = Self::leaf_class_data_descr(code, cls, name_idx)?; + // (A non-data descriptor yields to the instance's own attribute: + // only a certain miss of the instance's reads through it.) + let (descr, get, data) = Self::leaf_class_data_descr(code, cls, name_idx)?; + if !data && inst_may_shadow(inst, code, name_idx) { + return None; + } // SAFETY: GIL-serialized raw read of the function's code cell. let gcode: &CodeObject = unsafe { &*get.code.as_ptr() }; if gcode.arg_count != 3 @@ -11010,6 +11764,183 @@ impl Interpreter { Some(self.inline_bind(frame, shell, pc, act, code, Object::Function(hook), guard)) } + /// `iter(v)` for a plain instance (no native payload, of a Python + /// class without `__length_hint__`) whose `__iter__`, and `__len__` if + /// it has one, evaluate as pure leaves, the first answering a native + /// iterator (`return iter(self.items)`): that iterator, `PyObject_ + /// LengthHint`'s `len()` having run with nothing to observe. `None` + /// for anything else, having run nothing observable. + fn leaf_instance_iter(&self, v: &Object) -> Option { + use crate::types::{vm_key, AttrKey}; + let Object::Instance(inst) = v else { + return None; + }; + let cls = inst.cls_raw(); + if cls.flags.is_builtin || inst.native.get().is_some() { + return None; + } + let iter = Self::iter_dunder(v)?; + if cls.lookup("__length_hint__").is_some() { + return None; + } + if cls.lookup("__len__").is_some() { + let len = Self::instance_dunder_function(inst, AttrKey::vm(vm_key::LEN_FN), "__len__")?; + match self.call_pure_leaf_with(&len, Some(v), &[])? { + Object::Int(n) if n >= 0 => {} + _ => return None, + } + } + match self.call_pure_leaf_with(&iter, Some(v), &[])? { + it @ Object::Iter(_) => Some(it), + _ => None, + } + } + + /// `recv.name` (`name` the `name_idx`th name of `code`) by the class's + /// `__getattr__` when the default lookup misses it and that hook is a + /// warm pure leaf of `(self, name)`, evaluated in place; `None` for + /// everything else, having run nothing. + pub(crate) fn leaf_getattr_hook( + &self, + recv: &Object, + name: &str, + code: &CodeObject, + name_idx: u32, + ) -> Option { + let Object::Instance(inst) = recv else { + return None; + }; + let cls = inst.cls_raw(); + if crate::object::exotic_str_keys_possible() + || !Self::default_getattribute(cls) + || !default_lookup_misses(recv, name, true) + { + return None; + } + self.leaf_getattr_hook_run(inst, recv, name, code, name_idx) + } + + /// [`Self::leaf_getattr_hook`] at a site that saw the hook answer for + /// the receiver's class version with the class itself missing the name + /// (see [`Self::getattr_hook_class_misses`]): the version vouches for + /// the class's half of the default lookup, so only the instance's own + /// `__dict__` is probed. + pub(crate) fn leaf_getattr_hook_known( + &self, + recv: &Object, + name: &str, + code: &CodeObject, + name_idx: u32, + ) -> Option { + let Object::Instance(inst) = recv else { + return None; + }; + if crate::object::exotic_str_keys_possible() + || !inst_dict_misses(inst, name) + || inst + .native + .get() + .is_some_and(|p| !payload_class_misses(p, name)) + { + return None; + } + self.leaf_getattr_hook_run(inst, recv, name, code, name_idx) + } + + /// The instance's own half of the default lookup's certain miss, for + /// a site whose memo vouches for the class's (see + /// [`Self::getattr_hook_class_misses`]). + pub(crate) fn getattr_hook_inst_misses(inst: &PyInstance, name: &str) -> bool { + !crate::object::exotic_str_keys_possible() + && inst_dict_misses(inst, name) + && inst + .native + .get() + .is_none_or(|p| payload_class_misses(p, name)) + } + + /// Whether `inst`'s class (at its current version) certainly lacks + /// `name` for the default lookup: a site whose hook answered may then + /// take [`Self::leaf_getattr_hook_known`] for that version. + pub(crate) fn getattr_hook_class_misses(inst: &PyInstance, name: &str) -> bool { + let cls = inst.cls_raw(); + // (A built-in subclass's instance: its payload's class lacks the + // name too, for good.) + inst.native + .get() + .is_none_or(|p| payload_class_misses(p, name)) + && inst.c_body.get() == 0 + && cls.native_kind.get() == 0 + && !cls.flags.is_builtin + && !name.starts_with("__") + && Self::default_getattribute(cls) + && cls.verdict_cached(crate::types::Verdict::AttrMissing, name) == Some(true) + } + + /// [`Self::leaf_getattr_hook`] once the default lookup is known to + /// miss: the class's `__getattr__`, if a warm pure leaf of `(self, + /// name)`, evaluated in place. + #[inline] + fn leaf_getattr_hook_run( + &self, + inst: &Rc, + recv: &Object, + name: &str, + code: &CodeObject, + name_idx: u32, + ) -> Option { + // (The hook found once per class version.) + let hook = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::GETATTR_FN), + "__getattr__", + )?; + let hcode = hook.code(); + if hcode.arg_count != 2 + || !code_is_pure_leaf(&hcode) + || !pure_leaf_warm(&hcode) + || crate::recursion::current_depth() >= crate::recursion::recursion_limit() + { + return None; + } + let name = code_name_str(code, name_idx, name); + let args = [std::ptr::from_ref(recv), std::ptr::from_ref(&name)]; + self.pure_leaf_eval::(&hcode, &hook, &args) + } + + /// `obj.name` at `frame.pc` for an instance the default lookup misses + /// whose class's `__getattr__` is a warm pure leaf of `(self, name)`: + /// its result replaces the receiver, as the inline activation + /// [`Self::try_inline_attr_hook`] would leave it. `false` touches + /// nothing. + fn try_leaf_attr_hook(&mut self, frame: &mut Frame) -> bool { + use crate::types::Dunder; + let pc = frame.pc as usize; + let Some(ins) = frame.code.instructions.get(pc) else { + return false; + }; + if ins.op != OpCode::LoadAttr || crate::object::exotic_str_keys_possible() { + return false; + } + let Some(recv @ Object::Instance(inst)) = frame.stack.last() else { + return false; + }; + let cls = inst.cls_raw(); + let Some(name) = frame.code.names.get(ins.arg as usize) else { + return false; + }; + if !cls.dunder(Dunder::GetAttr).present() { + return false; + } + let Some(r) = self.leaf_getattr_hook(recv, name, &frame.code, ins.arg) else { + return false; + }; + let receiver = std::mem::replace(frame.stack.last_mut().expect("checked above"), r); + frame.pc = pc as u32 + 1; + self.release(receiver); + true + } + /// `BINARY_SUBSCR` at `pc` of `frame` on an instance whose class's /// `__getitem__` is a plain Python function of `(self, key)`, as an /// inline activation (CPython's `BINARY_SUBSCR_GETITEM`): the operands @@ -11018,6 +11949,34 @@ impl Interpreter { /// `__getitem__` (the site's remembered function) is a pure leaf: the /// result replaces the operands, as the full call would leave it. /// `false` touches nothing. + /// The `LOAD_ATTR` at `frame`'s pc of an enum member's `name` or + /// `value` through `enum.property` (see [`Self::enum_property_value`]): + /// the field in place of the receiver, no activation. `false` touches + /// nothing. + fn try_enum_property_read(&mut self, frame: &mut Frame) -> bool { + let pc = frame.pc as usize; + let Some(ins) = frame.code.instructions.get(pc) else { + return false; + }; + if ins.op != OpCode::LoadAttr { + return false; + } + let Some(Object::Instance(inst)) = frame.stack.last() else { + return false; + }; + let Some((descr, _)) = Self::descr_getter(&frame.code, inst, ins.arg) else { + return false; + }; + let Some(v) = Self::enum_property_value(&descr, inst) else { + return false; + }; + let recv = frame.stack.pop().expect("checked above"); + frame.stack.push(v); + frame.pc = pc as u32 + 1; + self.release(recv); + true + } + fn try_leaf_getitem(&mut self, frame: &mut Frame) -> bool { let pc = frame.pc as usize; let n = frame.stack.len(); @@ -11059,6 +12018,61 @@ impl Interpreter { /// class's version (see [`Self::try_inline_getitem`]), else the /// class's own. For a class whose metaclass isn't `type` /// (`Color["RED"]`, which `EnumType` serves), the metaclass's. + /// The plain Python function the class of instance `v` answers + /// `__iter__` with (no native payload, no native or C class): compiled + /// `GET_ITER` calls it directly. + pub(crate) fn iter_dunder(v: &Object) -> Option> { + let Object::Instance(inst) = v else { + return None; + }; + let cls = inst.cls_raw(); + if inst.native.get().is_some() || cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 { + return None; + } + Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::ITER_FN), + "__iter__", + ) + } + + /// The plain Python function the class of instance `v` answers + /// `__aiter__` with (no native payload, no native or C class): a + /// compiled `async for` evaluates a leaf that returns the instance in + /// place. + pub(crate) fn aiter_dunder(v: &Object) -> Option> { + let Object::Instance(inst) = v else { + return None; + }; + let cls = inst.cls_raw(); + if inst.native.get().is_some() || cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 { + return None; + } + Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::AITER_FN), + "__aiter__", + ) + } + + /// The plain Python function the class of instance `v` answers + /// `__anext__` with (no native payload, no native or C class): a + /// compiled `async for` awaits a coroutine function's body directly. + pub(crate) fn anext_dunder(v: &Object) -> Option> { + let Object::Instance(inst) = v else { + return None; + }; + let cls = inst.cls_raw(); + if inst.native.get().is_some() || cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 { + return None; + } + Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::ANEXT_FN), + "__anext__", + ) + } + pub(crate) fn getitem_dunder( code: &CodeObject, pc: usize, @@ -11150,6 +12164,13 @@ impl Interpreter { let crate::recursion::Enter::Ok(guard) = crate::recursion::enter() else { return None; }; + // (The site's method, for the frame JIT to lower in line.) + #[cfg(feature = "jit")] + if let Some(ext) = code_vm_ext_existing(&frame.code) { + if !dunder_known(ext, pc) { + getitem_note(ext, pc, &f, &frame.stack[n - 2]); + } + } // Committed. let key = frame.stack.pop()?; let container = frame.stack.pop()?; @@ -11168,6 +12189,48 @@ impl Interpreter { /// function of `(self, key, value)`, as an inline activation of it /// (CPython calls it from `STORE_SUBSCR` alike): the three operands /// leave the stack as its arguments, and its result is discarded. + /// The Python `__setitem__` of `(self, key, value)` a `STORE_SUBSCR` (the + /// `pc`th instruction of `code`) into `inst` calls, as + /// [`Self::try_inline_setitem`] finds it (the site remembering it by the + /// class's attribute version). `None` for any other store. + pub(crate) fn setitem_function( + code: &CodeObject, + pc: usize, + inst: &PyInstance, + ) -> Option> { + let cls = inst.cls_raw(); + let ver = cls.attr_version.get(); + let slot = code_method_slot(code, pc as u32); + let f = match slot.and_then(|s| s.get_held(ver)) { + Some(f) => f, + None => { + if crate::object::exotic_str_keys_possible() { + return None; + } + let Some(Object::Function(f)) = cls.lookup("__setitem__") else { + return None; + }; + if let Some(s) = slot { + s.set(ver, &f); + } + f + } + }; + // SAFETY: GIL-serialized raw read of the function's code cell. + let fc = unsafe { &*f.code.as_ptr() }; + if fc.arg_count != 3 + || fc.kwonly_count != 0 + || fc.has_varargs + || fc.has_varkeywords + || fc.is_generator + || fc.is_coroutine + || fc.is_async_generator + { + return None; + } + Some(f) + } + fn try_inline_setitem( &mut self, frame: &mut Frame, @@ -11468,16 +12531,26 @@ impl Interpreter { if self.lean_pending.last() == Some(&addr) { self.lean_pending.pop(); } else { - // (Newer entries above it would leave this one behind, its - // activation gone: see `State::outer_lazy`.) - debug_assert!( - !self.lean_pending.contains(&addr), - "pending entry left behind" - ); + self.lean_pending_exit_cold(addr); } } } + /// [`Self::lean_pending_exit`] of an entry not on top: older + /// activations that registered late (a lazily running caller whose + /// native body drives a generator, `sum(f(x) for x in xs)` from + /// compiled code, registers when the generator's callee first needs + /// the spine) sit above it, still running. The entry leaves from + /// where it is; left behind, it would name an activation gone from the + /// native stack, which the next flush would write through. + #[cold] + #[inline(never)] + fn lean_pending_exit_cold(&mut self, addr: usize) { + if let Some(pos) = self.lean_pending.iter().rposition(|a| *a == addr) { + self.lean_pending.remove(pos); + } + } + /// The common construction shape, done directly: a plain Python class /// (no `__new__` of its own, `object.__new__` allocating, no native /// payload, not abstract) whose `__init__` is a plain Python function @@ -11489,30 +12562,91 @@ impl Interpreter { /// instance `tuple.__new__(cls, (a, b, c))` builds, without running /// the generated function. `None` (nothing done) for any other shape. #[inline] - fn instantiate_named_tuple(&mut self, cls: &Rc, args: &[Object]) -> Option { + fn instantiate_named_tuple( + &mut self, + cls: &Rc, + args: &[Object], + kwargs: &[(String, Object)], + ) -> Option { let plan = self.instance_plan(cls); - let (code, nfields) = plan.tuple_new?; - if args.len() != nfields { - return None; + let items = Self::named_tuple_items( + &plan, + args, + &mut kwargs.iter().map(|(k, v)| (k.as_str(), v)), + )?; + let (inst, tracked) = crate::stdlib::collections_native::new_named_tuple(cls, items); + if tracked && gc_trace::maybe_auto_collect() { + self.run_pending_finalizers(); } + Some(inst) + } + + /// The items `cls(*positional, **kw)` gives a named tuple class whose + /// plan has its generated `__new__` (see + /// [`Self::instantiate_named_tuple`]): the positionals, each keyword + /// at its field, and the function's defaults (its `__defaults__` as + /// it stands) for the fields left. `None` for any call that binds + /// otherwise (too many arguments, an unknown or repeated name, a + /// field nothing fills), which the generated function then reports, + /// and while the function's code was replaced or an observer must see + /// it run. + fn named_tuple_items<'k>( + plan: &crate::types::InstancePlan, + positional: &[Object], + kw: &mut dyn Iterator, + ) -> Option> { + let (code, nfields) = plan.tuple_new?; let Some(Object::Function(f)) = &plan.user_new else { return None; }; - // `__new__.__code__ = …` since registration, or a call observer - // that must see the function run. - // SAFETY: GIL-serialized raw read of the function's code cell; only - // the pointer is compared. - if unsafe { Rc::as_ptr(&*f.code.as_ptr()) } as usize != code + // SAFETY: GIL-serialized raw read of the function's code cell. + let code_rc = unsafe { &*f.code.as_ptr() }; + if Rc::as_ptr(code_rc) as usize != code || crate::trace::any_observers_active() + || positional.len() > nfields { return None; } - let (inst, tracked) = - crate::stdlib::collections_native::new_named_tuple(cls, args.to_vec()); - if tracked && gc_trace::maybe_auto_collect() { - self.run_pending_finalizers(); + let mut items: Vec = Vec::with_capacity(nfields); + crate::object::extend_cloned(&mut items, positional); + let mut kw = kw.peekable(); + if items.len() == nfields && kw.peek().is_none() { + return Some(items); + } + // (Unfilled fields hold `Unbound` until the keywords and defaults + // have been placed.) + items.resize(nfields, Object::Unbound); + let names = code_rc.varnames.get(1..=nfields)?; + for (name, value) in kw { + let at = names.iter().position(|n| n.as_str() == name)?; + if !matches!(items[at], Object::Unbound) { + return None; + } + items[at] = value.clone(); } - Some(inst) + if items.iter().any(|v| matches!(v, Object::Unbound)) { + let overridden; + let defaults: &[Object] = if f.defaults_maybe_overridden() { + match f.slot("__defaults__") { + None => &f.defaults, + Some(Object::Tuple(t)) => { + overridden = t; + &overridden + } + Some(Object::None) => &[], + Some(_) => return None, + } + } else { + &f.defaults + }; + let first = nfields.checked_sub(defaults.len())?; + for (i, v) in items.iter_mut().enumerate() { + if matches!(v, Object::Unbound) { + *v = defaults.get(i.checked_sub(first)?)?.clone(); + } + } + } + Some(items) } fn instantiate_plain_lean( @@ -12014,6 +13148,17 @@ impl Interpreter { } } } + // `super().name` of a property: its getter's activation (the + // core loop's arm takes only plain methods and values). + if frame + .code + .instructions + .get(pc) + .is_some_and(|i| i.op == OpCode::LoadSuperAttr && i.arg & 1 == 0) + && self.core_super_property(sw) + { + return None; + } // SAFETY: as above (`core_property` declined untouched). let (frame, last_pc) = unsafe { (&mut *sw.cur, &mut *sw.last) }; match self.leaf_core_helper(frame, last_pc) { @@ -12228,6 +13373,8 @@ impl Interpreter { let done = match ins.op { OpCode::Call => self.leaf_core_call(frame, ins, pc), OpCode::LoadSpecial => Self::leaf_load_special(frame, ins.arg, pc), + OpCode::ImportName => self.leaf_import_name(frame, ins.arg), + OpCode::ImportFrom => Self::leaf_import_from(frame, ins.arg), _ => self.leaf_core_attr(frame, ins, pc), }; match done { @@ -12243,6 +13390,48 @@ impl Interpreter { done } + /// `import m` of a module already imported (see + /// [`Self::cached_import`]): the module in place of the level and + /// from-list. Declines anything else, touching nothing. + fn leaf_import_name(&self, frame: &mut Frame, arg: u32) -> CoreAttr { + let n = frame.stack.len(); + if n < 2 { + return CoreAttr::Decline; + } + let Some(name) = frame.code.names.get(arg as usize).cloned() else { + return CoreAttr::Decline; + }; + let Some(module) = + self.cached_import(frame, &name, &frame.stack[n - 2], &frame.stack[n - 1]) + else { + return CoreAttr::Decline; + }; + // (The level is an int; the from-list a constant.) + frame.stack.truncate(n - 2); + frame.stack.push(module); + CoreAttr::Done + } + + /// `from m import x` of a name in the module's dict: the value above + /// the module. Declines anything else (a submodule, a missing name). + fn leaf_import_from(frame: &mut Frame, arg: u32) -> CoreAttr { + let (Some(Object::Module(m)), Some(name)) = + (frame.stack.last(), frame.code.names.get(arg as usize)) + else { + return CoreAttr::Decline; + }; + let Some(v) = m + .dict + .try_borrow() + .ok() + .and_then(|d| d.get(&crate::object::StrKey(name)).cloned()) + else { + return CoreAttr::Decline; + }; + frame.stack.push(v); + CoreAttr::Done + } + /// `LOAD_SPECIAL` at `pc` of an instance whose class resolves the /// method to a plain function: the function and the instance as its /// self (what the full handler's bound method unpacks to at the call), @@ -12259,6 +13448,20 @@ impl Interpreter { SPECIAL_AEXIT => "__aexit__", _ => return CoreAttr::Decline, }; + // A native file's (`with open(p) as f`) or view's (`with + // f.getbuffer() as v`): its type's native method, bound by the call. + if let Some(f @ (Object::File(_) | Object::MemoryView(_))) = frame.stack.last() { + let Some(Object::Builtin(b)) = builtins::lookup_method(f, name) else { + return CoreAttr::Decline; + }; + if !b.binds_instance || !native_call_ic_safe(b.name) { + return CoreAttr::Decline; + } + let owner = frame.stack.pop().expect("checked above"); + frame.stack.push(Object::Builtin(b)); + frame.stack.push(owner); + return CoreAttr::Done; + } let Some(Object::Instance(inst)) = frame.stack.last() else { return CoreAttr::Decline; }; @@ -12314,8 +13517,32 @@ impl Interpreter { } // SAFETY: `len > 0`. let top = unsafe { base.add(len - 1) }; - let Object::Instance(inst) = (unsafe { &*top }) else { - return None; + let inst = match unsafe { &*top } { + Object::Instance(inst) => inst, + // A native file's or view's: its type's native method, bound + // by the call (as `leaf_load_special` takes it). + recv @ (Object::File(_) | Object::MemoryView(_)) => { + let name = match ins.arg { + SPECIAL_ENTER => "__enter__", + SPECIAL_EXIT => "__exit__", + _ => return None, + }; + let Some(Object::Builtin(b)) = builtins::lookup_method(recv, name) else { + return None; + }; + if !b.binds_instance || !native_call_ic_safe(b.name) { + return None; + } + // SAFETY: `len < cap`; the receiver moves up into the + // self slot. + unsafe { + let recv = top.read(); + top.write(Object::Builtin(b)); + base.add(len).write(recv); + } + return Some(len + 1); + } + _ => return None, }; let cls = inst.cls_raw(); let ver = cls.attr_version.get(); @@ -12433,13 +13660,13 @@ impl Interpreter { } // A native method the site cached for this class version: // straight to its fused call (the Python leaf probes below - // would miss). + // would miss, and so would a second try of this one). if let (Object::Instance(i), Some(ms)) = (other, mslots.get(pc + 1)) { if ms .peek_inst_builtin(i.cls_raw().attr_version.get()) .is_some() { - if let Some(hit) = self.core_native_method( + return self.core_native_method( code, other, pc + 1, @@ -12448,9 +13675,7 @@ impl Interpreter { lbase, nlocals, consts, - ) { - return Some(hit); - } + ); } } let pure_site = !missed @@ -12768,6 +13993,7 @@ impl Interpreter { wait_pending: None, outer_lazy: 0, fold: std::ptr::null(), + caught: false, }); nst.len = len; nst.pc = pc; @@ -13033,6 +14259,10 @@ impl Interpreter { len -= 1; last = pc + 1; pc += 2; + // (The value it replaced may have + // queued a finalizer, which runs + // before the next instruction.) + after_release!(); continue; } clone_hot(other) @@ -13176,7 +14406,7 @@ impl Interpreter { .collect(); len -= n; let obj = Object::new_list(items); - gc_trace::track(&obj); + gc_trace::track_built(&obj); // SAFETY: `len < cap` (the operands' slots were freed). unsafe { base.add(len).write(obj) }; len += 1; @@ -13521,11 +14751,18 @@ impl Interpreter { { int_hot(a << b) } - BinOpKind::FloorDiv | BinOpKind::Mod if b > 0 && a >= 0 => { - Object::Int(if kind == BinOpKind::FloorDiv { - a / b - } else { - a % b + // Floored for any signs (`-x % 3`); a zero + // divisor and `MIN // -1` decline. + BinOpKind::FloorDiv | BinOpKind::Mod + if b != 0 && !(a == i64::MIN && b == -1) => + { + let (q, r) = (a / b, a % b); + let adjust = r != 0 && ((r < 0) != (b < 0)); + Object::Int(match (kind == BinOpKind::FloorDiv, adjust) { + (true, true) => q - 1, + (true, false) => q, + (false, true) => r + b, + (false, false) => r, }) } BinOpKind::Pow if (0..=i64::from(u32::MAX)).contains(&b) => { @@ -13677,6 +14914,40 @@ impl Interpreter { after_release!(); continue; } + // `seq * n` and `n * seq` for a tuple or list, + // out of line (a list's `*=` repeats it in place: + // the full handler's). + (Object::Tuple(_) | Object::List(_), Object::Int(_)) + | (Object::Int(_), Object::Tuple(_) | Object::List(_)) + if kind == BinOpKind::Mult + && (matches!(a, Object::Tuple(_) | Object::Int(_)) + || ins.arg & weavepy_compiler::BINARY_OP_INPLACE_FLAG + == 0) => + { + if !Self::core_droppable(a) || !Self::core_droppable(b) { + break None; + } + let Some(r) = Self::core_seq_repeat(a, b) else { + break None; + }; + // (A heap result: compiled code takes the + // helper that keeps one, not the numbers'.) + if let Some(e) = ext { + heap_site_note(e, ninstrs, pc); + } + // SAFETY: both operand slots are initialized and + // leave the stack; the result takes the first. + unsafe { + drop_hot_at(base.add(len - 1)); + drop_hot_at(base.add(len - 2)); + } + len -= 1; + unsafe { base.add(len - 1).write(r) }; + last = pc; + pc += 1; + after_release!(); + continue; + } // `bytes + bytes`; `ba += b` extends the bytearray // in place (unless a buffer export pins its size) // and leaves it as the result. @@ -13688,10 +14959,7 @@ impl Interpreter { } let r = match (a, b) { (Object::Bytes(x), Object::Bytes(y)) => { - let mut v = Vec::with_capacity(x.len() + y.len()); - v.extend_from_slice(x); - v.extend_from_slice(y); - Object::new_bytes(v) + Object::bytes_concat(x, y) } (Object::ByteArray(x), Object::Bytes(y)) if ins.arg & weavepy_compiler::BINARY_OP_INPLACE_FLAG @@ -13907,9 +15175,7 @@ impl Interpreter { } // Two natively served instances (see // `stdlib::datetime_native`), out of line. - (Object::Instance(i), Object::Instance(_)) - if i.cls_raw().native_kind.get() != 0 => - { + (Object::Instance(i), _) if i.cls_raw().native_kind.get() != 0 => { let r = match Self::core_native_compare(kind, a, b) { Some(Ok(r)) if Self::core_droppable(a) && Self::core_droppable(b) => @@ -14037,7 +15303,11 @@ impl Interpreter { last = pc; pc += 1 + ins.arg as usize; } - OpCode::Nop | OpCode::NotTaken | OpCode::Resume | OpCode::CopyFreeVars => { + OpCode::Nop + | OpCode::NotTaken + | OpCode::Resume + | OpCode::CopyFreeVars + | OpCode::AsyncGenWrap => { last = pc; pc += 1; } @@ -14105,6 +15375,48 @@ impl Interpreter { Object::Generator(_) | Object::Coroutine(_) ) { + // `yield from` a range, tuple or list iterator, + // sent `None`: its next item takes the sent + // value's slot, or the `SEND` exits at its end + // (see `gen_fast::send_iter_step`). + // SAFETY: `len >= 2` (checked first). + if let (true, Object::Iter(it), Object::None) = ( + len >= 2 && ins.arg & GEN_SEND == 0, + unsafe { &*base.add(len - 2) }, + unsafe { &*base.add(len - 1) }, + ) { + // A collecting consumer drains this frame and + // its next instruction is the yield that would + // fold each item: the items go to its sink at + // once, and the step below finds the end. + if let Some((ff, FoldSink::Collect(out))) = self.sum_fold { + // SAFETY: `pc + 1` is checked first; see + // `CoreSwitch`; the sink is the consumer's + // local, alive while the resume runs. + if ff == sw.cur as usize + && pc + 1 < ninstrs + && unsafe { (*instrs.add(pc + 1)).op } == OpCode::YieldValue + && unsafe { (*sw.inl).is_empty() } + { + gen_fast::send_iter_drain(it, unsafe { &mut *out }); + } + } + if let Some(item) = gen_fast::send_iter_step(it) { + let exit = item.is_none(); + // SAFETY: the sent `None`'s slot (no drop + // glue owed). + unsafe { + base.add(len - 1).write(item.unwrap_or(Object::None)) + }; + last = pc; + pc += 1; + if exit { + pc += ins.arg as usize; + } + after_release!(); + continue; + } + } // `await fut` of a native asyncio future: its // iterator's step, the sent value replaced by // what it yields, or by the result as the @@ -14187,7 +15499,48 @@ impl Interpreter { // stays exhausted) and ends the loop. obj @ Object::Instance(inst) => { let Some(step) = self.leaf_next_step(obj, inst) else { - break None; + // A Python `__next__` that evaluates + // frameless, its bare `raise + // StopIteration` included (any other + // end is the full arm's). + match self.leaf_python_step(obj, inst) { + Some(Some(v)) => { + // SAFETY: `len < cap`. + unsafe { base.add(len).write(v) }; + len += 1; + last = pc; + pc += 1; + continue; + } + // The iterator leaves the stack, and + // the loop exits past its + // `END_FOR`/`POP_ITER` pair (a + // finalizer its release queued runs + // before the next instruction). + Some(None) => { + len -= 1; + // SAFETY: the slot is initialized. + unsafe { drop_hot(base.add(len).read()) }; + last = pc; + pc += 1 + ins.arg as usize; + let op_at = |pc: usize| { + // SAFETY: as the generator's exit. + Some(unsafe { (*instrs.add(pc)).op }) + }; + if op_at(pc) == Some(OpCode::EndFor) { + pc += 1; + if matches!( + op_at(pc), + Some(OpCode::PopIter | OpCode::PopTop) + ) { + pc += 1; + } + } + after_release!(); + continue; + } + None => break None, + } }; match step { Ok(v) => { @@ -14357,7 +15710,7 @@ impl Interpreter { // list, as `next_value` does, so a later // append can't resurrect it. if !unique { - *items = Rc::new(RefCell::new(Vec::new())); + *items = crate::object::detached_store(); } retire = true; Object::None @@ -14550,22 +15903,45 @@ impl Interpreter { *current = current.wrapping_add(*step); int_hot(v) } - crate::object::PyIterator::List { items, index, .. } => { + crate::object::PyIterator::List { + items, + index, + owner, + } => { // SAFETY: as above. let v = match unsafe { items.peek() } { Some(xs) => xs.get(*index).map(Self::clone_operand), None => None, }; - let Some(v) = v else { break None }; - *index += 1; - v + match v { + Some(v) => { + *index += 1; + v + } + // The end: the cursor detaches from + // its list as its own end does, and + // the loop retires the iterator (a + // finalizer its release queues runs + // before the next instruction). + None if owner.is_none() => { + *items = crate::object::detached_store(); + retire = true; + Object::None + } + None => break None, + } } crate::object::PyIterator::Tuple { items, index } => { - let Some(v) = items.get(*index).cloned() else { - break None; - }; - *index += 1; - v + match items.get(*index).cloned() { + Some(v) => { + *index += 1; + v + } + None => { + retire = true; + Object::None + } + } } crate::object::PyIterator::Bytes { data, index } => { let Some(&b) = data.get(*index) else { @@ -14596,10 +15972,13 @@ impl Interpreter { _ => break None, }; let i = *count; - *count = next_count; - if !fuse { + if retire { + Object::None + } else if !fuse { + *count = next_count; Object::new_tuple_array([Object::Int(i), x]) } else { + *count = next_count; // `UNPACK_SEQUENCE` leaves the first item on // top. SAFETY: `len + 2 <= cap`. unsafe { base.add(len).write(x) }; @@ -14909,7 +16288,7 @@ impl Interpreter { unsafe { frame.stack.set_len(len) }; frame.pc = pc as u32; *last_pc = last; - if self.core_call_forward(sw, pc) || sw.pending.is_some() { + if self.core_call_forward(sw, pc, snap_gen) || sw.pending.is_some() { break Some(CoreExit::Reload); } // Declined untouched: the leaf arm builds the dict. @@ -14986,10 +16365,17 @@ impl Interpreter { unsafe { std::slice::from_raw_parts(base.add(start), len - start) }; let r = match &ops[0] { // A natively served class's constructor (see - // `stdlib::datetime_native`). - Object::Type(ty) if ty.native_kind.get() != 0 => { + // `stdlib::datetime_native`), or an exact + // `itertools` class's adapter. + Object::Type(ty) + if ty.native_kind.get() != 0 || ty.lazy_ctor.get() != 0 => + { Self::core_native_ctor_kw(ops, argc, true) } + // (A pure constructor's parameters named.) + Object::Type(ty) if ty.pure_new_kw.get().is_some() => { + Self::core_pure_new_kw(ops, argc) + } // A native method of an exact `decimal.Decimal` // (see `stdlib::decimal_native::method_kw`). Object::Builtin(_) @@ -15000,13 +16386,34 @@ impl Interpreter { } // A native method's leaf half that also takes // keywords (`od.popitem(last=False)`). + // (A `functools.partial`'s own `__call__` over + // a pure leaf first: see `partial_leaf_kw`.) + Object::Builtin(b) + if matches!(&ops[1], Object::Instance(_)) + && crate::stdlib::functools_mod::is_partial_call(b) => + { + self.partial_leaf_kw(ops, argc) + .or_else(|| Self::core_native_kw_call(ops, argc)) + } + // (`s.replace(a, b, count=1)`, `n.to_bytes(4, + // byteorder="big")`: keywords naming the next + // parameters in order make the positional call, + // on the operands where they are, ahead of any + // registered keyword half, which binds by name.) + Object::Builtin(b) + if builtin_method_kw_params(&ops[1], b.name).is_some() => + { + self.core_method_kw_positional(ops, argc) + .or_else(|| Self::core_native_kw_call(ops, argc)) + } Object::BoundMethod(_) | Object::Builtin(_) => { Self::core_native_kw_call(ops, argc) } - // `dict(k=v, ...)`: the keywords' own names are - // the keys (see `core_dict_kw`). + // `dict(k=v, ...)`, `dict(d, k=v, ...)`: the + // keywords' own names are the keys (see + // `core_dict_kw`). Object::Type(ty) - if argc == 0 && Rc::ptr_eq(ty, &builtin_types().dict_) => + if argc <= 1 && Rc::ptr_eq(ty, &builtin_types().dict_) => { Self::core_dict_kw(ops) } @@ -15128,7 +16535,15 @@ impl Interpreter { }; if Self::core_all_droppable(ops) { let r = match kind { - Some(LeafKind::Fast(f)) => f(ops), + Some(LeafKind::Fast(f)) => f(ops).or_else(|| { + // `next(it)` of a Python iterator + // class's instance, as `FOR_ITER`. + if b.name == "next" { + self.leaf_next_instance(ops) + } else { + None + } + }), Some(LeafKind::Isinstance) => Self::core_isinstance(ops), Some(LeafKind::Opaque) => Some(match b.call_kw.as_ref() { Some(ckw) => ckw(ops, &[]), @@ -15771,7 +17186,7 @@ impl Interpreter { && if held & 1 == 0 { stamp[2] == 0 } else { - !self.globals_missing_any.get() + !self.globals_missing_gate() && stamp[2] == unsafe { (*bdict).mutation_stamp() } } { // SAFETY: the dicts are as they were when the @@ -15789,7 +17204,7 @@ impl Interpreter { builtins_id, key_idx, } if builtins_id == specialize::rc_id(&frame.builtins) - && !self.globals_missing_any.get() + && !self.globals_missing_gate() && stamp == [gid, g_stamp, unsafe { (*bdict).mutation_stamp() }] => { @@ -16054,7 +17469,7 @@ impl Interpreter { // SAFETY: as above. if matches!( unsafe { &*top }, - Object::Generator(_) | Object::Coroutine(_) + Object::Generator(_) | Object::Coroutine(_) | Object::AsyncGenerator(_) ) { // SAFETY: `len < cap`: `top` and the slot above. if unsafe { core_gen_method(code, ins.arg, top) } { @@ -16264,6 +17679,20 @@ impl Interpreter { pc += 1; continue; } + // A class's own names and links + // (`cls.__qualname__`, `__mro__`). + if let Some(v) = Self::leaf_type_name(code, cls, ins.arg) { + if Rc::strong_count(cls) > 1 { + // SAFETY: the receiver is + // replaced in place. + unsafe { + drop_hot(std::mem::replace(&mut *top, v)) + }; + last = pc; + pc += 1; + continue; + } + } offload!(OFFLOAD_HELPER); } } @@ -16293,6 +17722,22 @@ impl Interpreter { } offload!(OFFLOAD_HELPER); } + // A bound method's receiver, function, or its + // function's names. + Object::BoundMethod(bm) => { + match Self::leaf_bound_method_read(code, bm, ins.arg) { + Some(v) if Self::core_droppable(unsafe { &*top }) => { + // SAFETY: the receiver (droppable) is + // replaced in place. + unsafe { drop_hot(std::mem::replace(&mut *top, v)) }; + last = pc; + pc += 1; + after_release!(); + continue; + } + _ => offload!(OFFLOAD_HELPER), + } + } // A builtin container's method read as a value // (`append = y.append`), a frame's or code // object's field (the helper's plain values). @@ -16440,6 +17885,9 @@ impl Interpreter { len -= 2; last = pc; pc += 1; + // (The value it replaced may have queued a finalizer, + // which runs before the next instruction.) + after_release!(); } // `yield from`'s delegate: a generator (or, in a // coroutine, a coroutine) stays; an instance whose @@ -16705,6 +18153,22 @@ impl Interpreter { | Object::Str(_) ) || !Self::core_droppable(v) { + // A `list` or `tuple` subclass's instance whose + // class inherits its base's `__iter__`: the base's + // iterator over its payload (an `email` token + // list's loop). + if let Some(it) = Self::core_subclass_iter(v) { + // SAFETY: the iterable is replaced in place. + unsafe { drop_hot(std::mem::replace(&mut *top, it)) }; + last = pc; + pc += 1; + continue; + } + // (Compiled code calls an instance's Python + // `__iter__` directly at a site that has seen one.) + if let (Object::Instance(_), Some(e)) = (v, ext) { + instance_site_note(e, ninstrs, pc); + } offload!(OFFLOAD_HELPER); } let Ok(it) = v.make_iter() else { @@ -16719,6 +18183,9 @@ impl Interpreter { // `{1, 2, 3}`'s update from its folded constant // (`core_set_op`, or else the full handler). OpCode::SetUpdate => break None, + // A function-level `import m` / `from m import x` of an + // imported module (the helper's, as compiled code's). + OpCode::ImportName | OpCode::ImportFrom => offload!(OFFLOAD_HELPER), // An opcode the full leaf arms have no arm for is the quiet // loop's straight away. op if !SLOW_LEAF_OPS[op as u8 as usize] => { @@ -16740,6 +18207,29 @@ impl Interpreter { } } + /// `iter(v)` of a `list` or `tuple` subclass's instance inheriting its + /// base's `__iter__`: the base's iterator over the payload, as + /// compiled code's `GET_ITER` makes it. `None` for anything else. + #[inline(never)] + fn core_subclass_iter(v: &Object) -> Option { + let Object::Instance(inst) = v else { + return None; + }; + let native @ (Object::List(_) | Object::Tuple(_)) = inst.native.get()? else { + return None; + }; + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || !cls.dunder(crate::types::Dunder::Iter).builtin_owner() + || !Self::core_droppable(v) + { + return None; + } + let it = native.make_iter().ok()?; + Some(Object::Iter(Rc::new(RefCell::new(it)))) + } + /// [`Self::core_pending_enter`] with its commonest case in line: the /// caller an inline activation other than the burst's entry, with no /// shell yet (the call paths' callers). @@ -16925,35 +18415,10 @@ impl Interpreter { /// call's, and the stored keywords bind by name (see /// [`Self::lean_bind_keywords`]), and the function runs as a frameless /// leaf, its result in place, or as an inline activation switched to - /// here. `false` touches nothing (the native `__call__` takes the call, - /// its errors included). - /// [`Self::core_partial_call`] of a partial over a builtin with a leaf - /// half and no stored keywords: the result, for `ops` the partial - /// instance and the call's positionals, of the builtin's leaf half - /// over the stored positionals and those (four at most). `None` for - /// anything else, a decline or an error. - fn core_partial_builtin(&self, ops: &[Object]) -> Option { - let [Object::Instance(inst), args @ ..] = ops else { - return None; - }; - let mut buf: [Object; 4] = std::array::from_fn(|_| Object::None); - let (b, n) = crate::stdlib::functools_mod::with_partial_call(inst, |func, stored, kw| { - let Object::Builtin(b) = func else { - return None; - }; - let n = stored.len() + args.len(); - if !kw.is_empty() || b.binds_instance || n > buf.len() { - return None; - } - for (slot, v) in buf.iter_mut().zip(stored.iter().chain(args)) { - *slot = v.clone(); - } - Some((b.clone(), n)) - })?; - let kind = self.leaf_call_kind(&b)?; - self.leaf_builtin_call(kind, &b, &buf[..n])?.ok() - } - + /// here. A partial over a builtin with a leaf half and no stored + /// keywords runs that half over the stored positionals and the call's + /// (four at most). `false` touches nothing (the native `__call__` takes + /// the call, its errors included). #[inline(never)] fn core_partial_call(&mut self, sw: &mut CoreSwitch, pc: usize) -> bool { // SAFETY: see `CoreSwitch`: the running activation is synced and @@ -16973,87 +18438,154 @@ impl Interpreter { if !crate::stdlib::functools_mod::is_partial_call(b) { return false; } - // A warm pure leaf evaluates in place, its arguments borrowed. + // The partial's fields, read once: a warm pure leaf evaluates in + // place, its arguments borrowed; a builtin with a leaf half runs + // over the merged arguments (`partial(operator.add, 1)`); any other + // function's arguments bind for the lean call below. + enum Step { + Done(Object), + Builtin(Rc, [Object; 4], usize), + Type(Rc, [Object; 4], usize), + Bound(Rc), + } let depth = crate::recursion::current_depth(); let args = &frame.stack[callee_slot + 2..]; - let r = crate::stdlib::functools_mod::with_partial_call(inst, |func, stored, kw| { - let Object::Function(f) = func else { - return None; - }; - // SAFETY: GIL-serialized raw read of the function's code cell; - // the partial holds the function. - let code = unsafe { &*f.code.as_ptr() }; - if !code_is_pure_leaf(code) - || !pure_leaf_warm(code) - || depth >= crate::recursion::recursion_limit() - { - return None; + // (Taken only for a call that binds a frame's locals.) + let mut bound: Option> = None; + let step = crate::stdlib::functools_mod::with_partial_call(inst, |func, stored, kw| { + match func { + Object::Function(f) => { + // SAFETY: GIL-serialized raw read of the function's + // code cell; the partial holds the function. + let code = unsafe { &*f.code.as_ptr() }; + if code_is_pure_leaf(code) + && pure_leaf_warm(code) + && depth < crate::recursion::recursion_limit() + { + let mut ptrs = [std::ptr::null::(); 8]; + // (No keywords, the usual partial: no walk of the + // empty dict.) + let arity = if kw.is_empty() { + Self::leaf_bind_positional(code, stored, args, &mut ptrs).or_else( + || { + Self::leaf_bind_keywords( + f, + code, + stored, + args, + std::iter::empty(), + &mut ptrs, + ) + }, + ) + } else { + let kws = kw.iter().map(|(k, v)| (&k.0, v)); + Self::leaf_bind_keywords(f, code, stored, args, kws, &mut ptrs) + }; + if let Some(arity) = arity { + if let Some(r) = + self.pure_leaf_call(code, f, &ptrs[..arity], false, depth) + { + return Some(Step::Done(r)); + } + } + } + if code.is_generator + || code.is_coroutine + || code.is_async_generator + || (f.defaults_maybe_overridden() + && (f.slot("__defaults__").is_some() + || f.slot("__kwdefaults__").is_some())) + { + return None; + } + let kws = kw.iter().map(|(k, v)| (&k.0, v)); + let v = bound.insert(self.pooled_scratch()); + Self::lean_bind_keywords(f, code, stored, args, kws, v)?; + Some(Step::Bound(f.clone())) + } + Object::Builtin(b) => { + let n = stored.len() + args.len(); + if !kw.is_empty() || b.binds_instance || n > 4 { + return None; + } + let mut buf: [Object; 4] = std::array::from_fn(|_| Object::None); + for (slot, v) in buf.iter_mut().zip(stored.iter().chain(args)) { + *slot = v.clone(); + } + Some(Step::Builtin(b.clone(), buf, n)) + } + // A builtin type (`partial(int, base=16)`): its keywords in + // the places of the parameters they name, for the native + // constructor, which runs no code. + Object::Type(t) if t.flags.is_builtin => { + let n = stored.len() + args.len(); + let total = n + kw.len(); + if total > 4 { + return None; + } + let mut buf: [Object; 4] = std::array::from_fn(|_| Object::Unbound); + for (slot, v) in buf.iter_mut().zip(stored.iter().chain(args)) { + *slot = v.clone(); + } + if !kw.is_empty() { + let params = crate::builtin_kw_params(t)?; + if total > params.len() { + return None; + } + for (k, v) in kw.iter() { + let Object::Str(name) = &k.0 else { + return None; + }; + let at = params.iter().position(|p| *p == name.as_ref())?; + if at < n || !matches!(buf[at], Object::Unbound) { + return None; + } + buf[at] = v.clone(); + } + if buf[..total].iter().any(|v| matches!(v, Object::Unbound)) { + return None; + } + } + Some(Step::Type(t.clone(), buf, total)) + } + _ => None, } - let mut ptrs = [std::ptr::null::(); 8]; - let kw = kw.iter().map(|(k, v)| (&k.0, v)); - let arity = Self::leaf_bind_keywords(f, code, stored, args, kw, &mut ptrs)?; - self.pure_leaf_call(code, f, &ptrs[..arity], false, depth) }); - if let Some(r) = r { - // The operands leave the stack, the result in their place. - self.release_call_operands(&mut frame.stack, callee_slot); - frame.stack.push(r); - frame.pc = pc as u32 + 1; - // SAFETY: the running activation's last-pc slot. - unsafe { *sw.last = pc }; - // SAFETY: the running thread's own flag (see `quiet_run`). - if unsafe { (*sw.maybe_dead).get() } { - sw.pending = Some(CoreExit::Stop(LeafStop::Marked)); - } - return true; - } - // A builtin with a leaf half over the merged arguments - // (`partial(operator.add, 1)`): its result in place. A decline or - // an error leaves the call to the native `__call__`, which repeats - // it (a leaf runs no code, so nothing is observed twice). - if let Some(r) = self.core_partial_builtin(&frame.stack[callee_slot + 1..]) { - self.release_call_operands(&mut frame.stack, callee_slot); - frame.stack.push(r); - frame.pc = pc as u32 + 1; - // SAFETY: the running activation's last-pc slot. - unsafe { *sw.last = pc }; - // SAFETY: the running thread's own flag (see `quiet_run`). - if unsafe { (*sw.maybe_dead).get() } { - sw.pending = Some(CoreExit::Stop(LeafStop::Marked)); - } - return true; - } - let mut bound: Vec = self.pooled_scratch(); - let f = { - let stack = &frame.stack; - let Object::Instance(inst) = &stack[callee_slot + 1] else { - return false; - }; - let args = &stack[callee_slot + 2..]; - crate::stdlib::functools_mod::with_partial_call(inst, |func, stored, kw| { - let Object::Function(f) = func else { - return None; + let (f, mut bound) = match (step, bound) { + (Some(Step::Bound(f)), Some(bound)) => (f, bound), + (other, scratch) => { + let r = match other { + Some(Step::Done(r)) => Some(r), + // (A decline or an error leaves the call to the native + // `__call__`, which repeats it: a leaf runs no code, so + // nothing is observed twice.) + Some(Step::Builtin(b, buf, n)) => self + .leaf_call_kind(&b) + .and_then(|kind| self.leaf_builtin_call(kind, &b, &buf[..n])) + .and_then(Result::ok), + Some(Step::Type(t, buf, n)) => self.leaf_type_call(&t, &buf[..n]), + _ => None, }; - // SAFETY: GIL-serialized raw read of the function's code - // cell; the partial holds the function. - let code = unsafe { &*f.code.as_ptr() }; - if code.is_generator - || code.is_coroutine - || code.is_async_generator - || (f.defaults_maybe_overridden() - && (f.slot("__defaults__").is_some() || f.slot("__kwdefaults__").is_some())) - { - return None; + if let Some(mut v) = scratch { + v.clear(); + self.recycle_scratch(v); } - let kw = kw.iter().map(|(k, v)| (&k.0, v)); - Self::lean_bind_keywords(f, code, stored, args, kw, &mut bound)?; - Some(f.clone()) - }) - }; - let Some(f) = f else { - bound.clear(); - self.recycle_scratch(bound); - return false; + let Some(r) = r else { + return false; + }; + // The operands leave the stack, the result in their place. + self.release_call_operands(&mut frame.stack, callee_slot); + frame.stack.push(r); + frame.pc = pc as u32 + 1; + // SAFETY: the running activation's last-pc slot. + unsafe { *sw.last = pc }; + // SAFETY: the running thread's own flag (see `quiet_run`). + if unsafe { (*sw.maybe_dead).get() } { + sw.pending = Some(CoreExit::Stop(LeafStop::Marked)); + } + return true; + } }; let code = f.code(); // A frameless leaf evaluates in place. @@ -17149,7 +18681,10 @@ impl Interpreter { match recv { Some(recv) => { if !b.binds_instance { - return None; + // A native classmethod's function bound to its class + // (`chain.from_iterable(xs)`): the full call, with the + // class first, as the dispatch makes it. + return matches!(recv, Object::Type(_)).then_some(true); } // Calling a method body on any receiver is what the full // handler's dispatch does for these names. @@ -17171,9 +18706,22 @@ impl Interpreter { // another native `__init__`) on a plain instance: the // dispatch's only `__init__` case is a dict payload's, // whose `dict.__init__` body reads the payload itself. - if native_init_call(b, recv) || dict_init_call(b, recv) { + if native_init_call(b, recv) || container_init_call(b, recv) { return Some(false); } + // A builtin subclass's instance (`Counter.items`): the + // method the site loaded from its class, called as the full + // handler calls it. + if matches!(recv, Object::Instance(i) if i.native.get().is_some()) { + return Some(true); + } + // A native method of a class written in Python, on its + // plain instance (`deque.extend`): through the dispatch, as + // the full handler calls it (the dispatch takes such a + // receiver's argument as it comes). + if matches!(recv, Object::Instance(_)) && builtin_method_via_call(b.name) { + return Some(true); + } // The names below are dispatched by the interpreter, which // knows them on the builtin kinds' receivers. builtins::method_memo_tag(recv)?; @@ -17303,7 +18851,23 @@ impl Interpreter { None }; let args = std::slice::from_raw_parts(base.add(first), len - first); - let result = if via_call { + // `bytes.join` or `str.join` of a list, a tuple or a native + // iterator (`"".join(reversed(s))`) reads the parts in place: + // no iteration for the dispatch to drive. + let joins_in_place = via_call + && !b.is_null() + && (*b).name == "join" + && (*b).call_kw.is_none() + && matches!( + args, + [ + Object::Bytes(_) | Object::Str(_), + Object::List(_) | Object::Tuple(_) | Object::Iter(_) + ] + ); + let result = if joins_in_place { + ((*b).call)(args) + } else if via_call { let globals = frame.globals.clone(); match &*base.add(start) { callable @ (Object::Builtin(_) | Object::Type(_)) => { @@ -17373,6 +18937,52 @@ impl Interpreter { } } + /// A compiled consumer's inlined drain of the fresh generator `g` (an + /// inlined `list(...)` or `any(...)` loop's first `FOR_ITER`, at `pc` + /// of `sw`'s running activation `frame`, synced with the generator on + /// top) whose body the fast steps don't run (it calls): the + /// generator's lean resume folds the yields `fold` takes, as `sum()`'s + /// does (see [`Self::gen_drain_next`]), with the activation waiting on + /// the pending list, or, `lazy`, running lazily (as + /// [`Self::core_native_body`] runs a builtin's body). `None` once the + /// generator is exhausted, else the first yield the sink declined. + /// + /// # Safety + /// + /// As [`Self::core_native_body`]'s, `lazy` null or the running lazy + /// activation's state. + #[cfg(feature = "jit")] + #[inline(never)] + pub(crate) unsafe fn core_gen_fold( + &mut self, + sw: &mut CoreSwitch, + frame: &mut Frame, + pc: usize, + g: &Rc, + fold: FoldSink, + lazy: *mut frame_jit::State, + ) -> Result, RuntimeError> { + frame.pc = pc as u32 + 1; + // SAFETY: the caller's contract (as `core_native_body`'s). + unsafe { + let pending = if lazy.is_null() { + self.core_pending_enter_fast(sw, frame, pc) + } else { + (*lazy).wait_pc = pc; + None + }; + let result = self.gen_drain_next(g, Some(fold), false); + let pending = if lazy.is_null() { + pending + } else { + (*lazy).wait_pc = usize::MAX; + (*lazy).wait_pending.take() + }; + self.core_pending_exit(sw, pending); + result + } + } + /// A `BINARY_OP` or `COMPARE_OP` at `sw`'s running activation's `pc` /// the core loop's arms declined (a Python dunder, `Vector.__sub__`; a /// `%` of a `dict`): the full handler's own step, run with the activation @@ -17523,6 +19133,9 @@ impl Interpreter { let Some(v) = op.and_then(|op| set_algebra_fast(a, b, op)) else { return false; }; + // (A heap result: compiled code takes the helper that keeps + // one, not the numbers', which would leave after it.) + Self::heap_result_note(frame, pc); let b = frame.stack.pop().expect("checked above"); let a = frame.stack.pop().expect("checked above"); frame.stack.push(v); @@ -17725,6 +19338,175 @@ impl Interpreter { } } + /// A Python class whose construction runs no Python code of its own + /// (`functools.partial`): a native `__new__`, `object`'s `__init__`, + /// and `type`'s call. [`Self::core_builtin_kw_lane`] runs a compiled + /// `CALL_KW` of one as it does a native callee's. + pub(crate) fn native_ctor_kw_callee(&self, callee: &Object, slot: &Object) -> bool { + let (Object::Type(t), Object::Unbound) = (callee, slot) else { + return false; + }; + if t.flags.is_builtin || t.native_kind.get() != 0 || !Self::metaclass_calls_like_type(t) { + return false; + } + let plan = self.instance_plan(t); + plan.abstract_error.is_none() + && plan.init_from_object + && matches!(plan.user_new, Some(Object::Builtin(_))) + } + + /// [`Self::core_builtin_kw_lane`]'s native method or function (not a + /// class) whose `CALL_KW` operands start at `start` (the callee, its + /// self slot, `argc` positionals, `kwc` keyword values and the names + /// tuple): its body runs on them where they are, as + /// [`Self::core_native_body`] runs a positional call's, the keyword + /// values cloned into the pooled pairs. The body runs directly when the + /// interpreter's dispatch would only end up calling it; otherwise + /// through [`Self::call`]. Then the names tuple, the arguments (the + /// keyword values last) and the callee are released, as the drained + /// lane releases them. `false` touches nothing. + /// + /// # Safety + /// + /// `sw`'s running activation is synced and unborrowed elsewhere, and its + /// stack holds the call's operands from `start` to its top. + #[inline(never)] + unsafe fn core_builtin_kw_in_place( + &mut self, + sw: &mut CoreSwitch, + pc: usize, + start: usize, + argc: usize, + kwc: usize, + ) -> bool { + const POOL_CAP: usize = 8; + const KEPT_PAIRS: usize = 8; + // SAFETY: the caller's contract; the stack isn't resized while the + // body runs (nested code runs activations of its own). + unsafe { + let frame = &mut *sw.cur; + let len = frame.stack.len(); + let base = frame.stack.as_mut_ptr(); + let b: *const crate::object::BuiltinFn = + match (&*base.add(start), &*base.add(start + 1)) { + (Object::Builtin(b), _) => Rc::as_ptr(b), + // (A bound method calls its builtin with the receiver first, + // unless the dispatch knows the name: the generator family's + // `.`-names, and a dict subclass's `__getitem__`.) + (Object::BoundMethod(bm), Object::Unbound) => match &bm.function { + Object::Builtin(b) + if !b.name.starts_with('.') && b.name != "__getitem__" => + { + Rc::as_ptr(b) + } + _ => return false, + }, + _ => return false, + }; + let Object::Tuple(names) = &*base.add(len - 1) else { + return false; + }; + // Committed. + let mut kwargs: Vec<(String, Object)> = + self.kw_scratch_pool.borrow_mut().pop().unwrap_or_default(); + kwargs.truncate(kwc); + let values = std::slice::from_raw_parts(base.add(start + 2 + argc), kwc); + for (j, (name, v)) in names.iter().zip(values).enumerate() { + let Object::Str(name) = name else { + unreachable!("checked by the caller") + }; + let name: &str = name; + match kwargs.get_mut(j) { + Some(pair) => { + if pair.0 != name { + pair.0.clear(); + pair.0.push_str(name); + } + pair.1 = v.clone(); + } + None => kwargs.push((name.to_owned(), v.clone())), + } + } + if matches!(&*base.add(start + 1), Object::Unbound) { + if let Object::BoundMethod(bm) = &*base.add(start) { + // (The empty self slot needs no release.) + base.add(start + 1).write(bm.receiver.clone()); + } + } + let first = if matches!(&*base.add(start + 1), Object::Unbound) { + start + 2 + } else { + start + 1 + }; + let args = std::slice::from_raw_parts(base.add(first), start + 2 + argc - first); + frame.pc = pc as u32 + 1; + let pending = self.core_pending_enter_fast(sw, frame, pc); + let b = &*b; + // (The names the dispatch takes before reaching the body, or + // whose arguments it converts first.) + let direct = b.call_kw.as_ref().filter(|_| { + !burst_stats::enabled() + && !builtin_needs_interp(b.name) + && !matches!( + b.name, + "len" + | "hash" + | "isinstance" + | "issubclass" + | "repr" + | "str" + | "__new__" + | "open" + | "fspath" + | "fsdecode" + | "fsencode" + ) + }); + let result = match direct { + Some(call_kw) => call_kw(args, &kwargs), + None => { + let globals = frame.globals.clone(); + match &*base.add(start) { + callable @ Object::Builtin(_) => { + self.call(callable, args, &kwargs, &globals) + } + callable => self.call(&bm_builtin(callable), args, &kwargs, &globals), + } + } + }; + self.core_pending_exit(sw, pending); + for pair in &mut kwargs { + drop(std::mem::replace(&mut pair.1, Object::None)); + } + if kwargs.len() <= KEPT_PAIRS { + let mut pool = self.kw_scratch_pool.borrow_mut(); + if pool.len() < POOL_CAP { + pool.push(kwargs); + } + } + // The operands leave the stack, then are released: the names, + // the arguments in order (the keyword values last), the callee. + frame.stack.set_len(start); + release_operands(self, base.add(len - 1), 1); + release_operands(self, base.add(start + 1), len - 2 - start); + release_operands(self, base.add(start), 1); + match result { + Ok(v) => { + base.add(start).write(v); + frame.stack.set_len(start + 1); + // SAFETY: the running activation's last-pc slot. + *sw.last = pc; + } + Err(e) => sw.pending = Some(CoreExit::Stop(LeafStop::Raised(e))), + } + // SAFETY: the running thread's own flag (see `quiet_run`). + if sw.pending.is_none() && (*sw.maybe_dead).get() { + sw.pending = Some(CoreExit::Stop(LeafStop::Marked)); + } + true + } + } + /// [`Self::core_builtin_lane`] for the `CALL_KW` at `pc` of a native /// callee (see [`Self::kw_lane_callee`]: `sorted(xs, key=f)`, /// `xs.sort(reverse=True)`, `int(s, base=2)`), in `sw`'s synced running @@ -17756,11 +19538,23 @@ impl Interpreter { let Some(callee_at) = n.checked_sub(argc + kwc + 3) else { return false; }; - if !Self::kw_lane_callee(&frame.stack[callee_at], &frame.stack[callee_at + 1]) + let (callee, slot) = (&frame.stack[callee_at], &frame.stack[callee_at + 1]); + if !(Self::kw_lane_callee(callee, slot) || self.native_ctor_kw_callee(callee, slot)) || !names.iter().all(|name| matches!(name, Object::Str(_))) { return false; } + // A native method or function (not a class): its body reads the + // operands where they are. + // SAFETY: the activation is synced and its stack holds the call's + // `n - callee_at` operands. + if unsafe { self.core_builtin_kw_in_place(sw, pc, callee_at, argc, kwc) } { + return true; + } + let frame = unsafe { &mut *sw.cur }; + let Some(Object::Tuple(names)) = frame.stack.last() else { + return false; + }; // Committed: the operands leave the stack. let mut kwargs: Vec<(String, Object)> = self.kw_scratch_pool.borrow_mut().pop().unwrap_or_default(); @@ -18213,6 +20007,33 @@ impl Interpreter { true } + /// [`Self::core_property`] for `super().name` of a property + /// ([`Self::try_inline_super_property`]). `false` touches nothing. + #[inline(never)] + fn core_super_property(&mut self, sw: &mut CoreSwitch) -> bool { + if !self.inline_calls_ok() { + return false; + } + let mut tmp = None; + // SAFETY: see `CoreSwitch` (as in `core_call`). + let act = unsafe { + let depth = (*sw.inl).len(); + let (frame, _, shell) = sw.activation(depth, &mut tmp); + let pc = (*frame).pc as usize; + self.try_inline_super_property(&mut *frame, &mut *shell.cast::>(), pc) + }; + let Some(mut act) = act else { + return false; + }; + let callee: *mut Frame = &raw mut *act.frame; + // SAFETY: as above. + unsafe { push_fast(&mut *sw.inl, act) }; + sw.cur = callee; + sw.scratch = usize::MAX; + sw.last = &raw mut sw.scratch; + true + } + /// [`Self::core_property`] for a `STORE_ATTR` a property's Python setter /// serves ([`Self::try_inline_setter`]). `false` touches nothing. #[inline(never)] @@ -18278,6 +20099,11 @@ impl Interpreter { note(unsafe { &*sw.cur }, pc); return true; } + // `member.name` / `member.value`: the field, no activation. + // SAFETY: as above. + if descr && self.try_enum_property_read(unsafe { &mut *sw.cur }) { + return true; + } let mut tmp = None; // SAFETY: see `CoreSwitch` (as in `core_call`). let act = unsafe { @@ -18312,6 +20138,11 @@ impl Interpreter { /// ([`Self::try_inline_attr_hook`]). `false` touches nothing. #[inline(never)] fn core_attr_hook(&mut self, sw: &mut CoreSwitch) -> bool { + // A pure leaf `__getattr__`: evaluated in place, no activation. + // SAFETY: see `CoreSwitch`: the running activation is synced. + if self.try_leaf_attr_hook(unsafe { &mut *sw.cur }) { + return true; + } if !self.inline_calls_ok() { return false; } @@ -18376,6 +20207,23 @@ impl Interpreter { /// ordinary call with the caller published /// (consuming the argument may run Python code), as the builtin lane /// runs a builtin function. `false` touches nothing. + /// Whether [`Self::core_type_lane`] builds `ty`'s one-argument call + /// itself (`list(x)`, `tuple(x)`, `set(x)`, `frozenset(x)`, `dict(x)`, + /// `str(x)`), rather than through the ordinary protocol. + pub(crate) fn core_type_lane_class(ty: &Rc) -> bool { + let bt = builtin_types(); + [ + &bt.list_, + &bt.tuple_, + &bt.set_, + &bt.frozenset_, + &bt.dict_, + &bt.str_, + ] + .iter() + .any(|t| Rc::ptr_eq(t, ty)) + } + fn core_type_lane(&mut self, sw: &mut CoreSwitch) -> bool { // SAFETY: see `CoreSwitch`: the running activation is synced and // unborrowed here. @@ -18402,18 +20250,7 @@ impl Interpreter { return false; } // (`str(obj)` runs the object's `__str__`.) - if ins.arg != 1 - || ![ - &bt.list_, - &bt.tuple_, - &bt.set_, - &bt.frozenset_, - &bt.dict_, - &bt.str_, - ] - .iter() - .any(|t| Rc::ptr_eq(t, ty)) - { + if ins.arg != 1 || !Self::core_type_lane_class(ty) { // Any other class's call takes the ordinary protocol, on the // operands where they are. // SAFETY: the activation is synced, and the shape was checked; @@ -18531,6 +20368,16 @@ impl Interpreter { matches!(frame.stack[callee_at + 1], Object::Unbound) && self.builtin_lane(b, None).is_some() } + // A `functools.lru_cache` wrapper spread from a tuple without + // keywords (`typing`'s `_tp_cache`: `cached(*args, **kwds)`): + // through `call`, which settles a hit natively. + callee @ Object::Instance(_) + if ins.op == OpCode::CallEx + && crate::stdlib::functools_mod::is_lru_wrapper(callee) => + { + builtin = true; + matches!(frame.stack[callee_at + 1], Object::Unbound) + } _ => false, }; if !ok { @@ -18731,8 +20578,20 @@ impl Interpreter { }; // A file is its own iterator, and its step (a line read) can run a // signal handler: it takes the lane too. + // An instance with a Python `__next__` (an iterator class): the + // call with the activation waiting, its `StopIteration` the end. let source = match frame.stack.last() { Some(it @ (Object::LazyIter(_) | Object::File(_))) => it.clone(), + Some(it @ Object::Instance(inst)) + if Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::NEXT_FN), + "__next__", + ) + .is_some() => + { + it.clone() + } _ => return false, }; if ins.op != OpCode::ForIter { @@ -18757,6 +20616,10 @@ impl Interpreter { let next = match &source { Object::LazyIter(l) => self.lazy_iter_next(l, &globals), Object::File(f) => crate::builtins::file_iter_next(f), + Object::Instance(_) => match self.iter_step(&source, &globals) { + Err(e) if crate::seqiter::is_stop_iteration(&e) => Ok(None), + r => r, + }, _ => unreachable!("matched above"), }; self.core_pending_exit(sw, pending); @@ -18837,7 +20700,13 @@ impl Interpreter { } let ok = match recv { None => !b.binds_instance, - Some(recv) => b.binds_instance && builtins::method_memo_tag(recv).is_some(), + // (A builtin subclass's instance too, `Counter.items`: the + // method its class gave the site, which unwraps the payload.) + Some(recv) => { + b.binds_instance + && (builtins::method_memo_tag(recv).is_some() + || matches!(recv, Object::Instance(i) if i.native.get().is_some())) + } } && self.leaf_call_kind(b).is_some(); // A method body safe to call directly runs as such. let via_call = recv.is_none() || !native_call_ic_safe(b.name); @@ -18972,7 +20841,7 @@ impl Interpreter { } // A plain class's construction, as a `CALL`'s. Some(Object::Type(_)) => { - if self.core_new_ex(sw, pc, snap_gen) { + if self.core_new_ex(sw, pc, snap_gen) || self.core_new_mapping(sw, pc, snap_gen) { return true; } } @@ -19112,6 +20981,53 @@ impl Interpreter { let [callee, Object::Unbound, spread, mapping] = &frame.stack[callee_slot..] else { return None; }; + // `dict(**kw)`: the mapping the call built (no one else holds it) + // is the new dict, its keys all exact strings as keywords are. + if let (Object::Type(t), Object::Tuple(sp), Object::Dict(d)) = (callee, spread, mapping) { + // SAFETY: a read that runs no code. + if Rc::ptr_eq(t, &builtin_types().dict_) + && sp.is_empty() + && Rc::strong_count(d) == 1 + && unsafe { d.peek() } + .is_some_and(|m| m.keys().all(|k| matches!(k.0, Object::Str(_)))) + { + let out = frame.stack.pop()?; + let ops: Vec = frame.stack.drain(callee_slot..).collect(); + frame.pc = pc as u32 + 1; + frame.stack.push(out); + for o in ops { + self.release(o); + } + return Some(Ok(())); + } + } + // `template.format(**kw)` of an exact string: `format_map` over + // the mapping the call built (string keys, as keywords are), which + // reads the same values; any error is the general call's to raise. + if let (Object::BoundMethod(bm), Object::Tuple(sp), Object::Dict(d)) = + (callee, spread, mapping) + { + if sp.is_empty() + && !bm.redispatch_descriptor + && matches!(bm.receiver, Object::Str(_)) + && matches!(&bm.function, Object::Builtin(b) if b.name == ".format") + // SAFETY: a read that runs no code. + && unsafe { d.peek() } + .is_some_and(|m| m.keys().all(|k| matches!(k.0, Object::Str(_)))) + { + let args = [bm.receiver.clone(), mapping.clone()]; + if let Some(Ok(v)) = crate::builtins::str_format_map_leaf(&args) { + drop(args); + let ops: Vec = frame.stack.drain(callee_slot..).collect(); + frame.pc = pc as u32 + 1; + frame.stack.push(v); + for o in ops { + self.release(o); + } + return Some(Ok(())); + } + } + } // A builtin, or a native method bound to its receiver // (`callback(*args, **kwds)` of a saved `log.append`), which takes // the receiver first, as a `CALL` of the method passes it. @@ -19247,7 +21163,7 @@ impl Interpreter { /// `CALL_FUNCTION_EX` three instructions on runs inline. `false` /// touches nothing (the instructions run one by one). #[inline(never)] - fn core_call_forward(&mut self, sw: &mut CoreSwitch, pc: usize) -> bool { + fn core_call_forward(&mut self, sw: &mut CoreSwitch, pc: usize, snap_gen: u64) -> bool { if !self.inline_calls_ok() { return false; } @@ -19264,10 +21180,21 @@ impl Interpreter { Some(Object::Dict(d)) => Object::Dict(d.clone()), _ => return false, }; + // (`[callee, NULL, tuple]` before the mapping goes on.) + let class = frame + .stack + .len() + .checked_sub(3) + .is_some_and(|k| matches!(frame.stack[k], Object::Type(_))) + && std::ptr::eq(sw.cur, &raw const *frame); frame.stack.push(mapping); if self.try_leaf_call_ex(frame, pc + 3) { return true; } + // A plain class's construction, its keywords from the mapping. + if class && self.core_new_mapping(sw, pc + 3, snap_gen) { + return true; + } self.try_inline_call_ex(frame, &mut *shell.cast::>(), pc + 3) }; let Some(mut act) = act else { @@ -19294,16 +21221,63 @@ impl Interpreter { /// over an exact tuple, with no keywords or (a pure leaf's) a plain /// dictionary of them (see [`Self::leaf_bind_keywords`]): evaluated in /// place, its result replacing the operands. `false` touches nothing. + /// `f(*items)` (with `head`, a bound method's receiver, first) of a + /// warm pure or effect leaf whose positional parameters the items fill + /// exactly, as [`Self::try_leaf_call_ex`] takes its commonest shape: + /// the result, or `None` (nothing run that matters) for anything else. + pub(crate) fn leaf_call_spread( + &self, + f: &PyFunction, + head: &[Object], + items: &[Object], + ) -> Option { + // SAFETY: GIL-serialized raw read of the function's code cell; the + // caller holds the function across the call. + let code: &CodeObject = unsafe { &*f.code.as_ptr() }; + let given = head.len() + items.len(); + if given != code.arg_count as usize || code.has_varargs || code.has_varkeywords { + return None; + } + let pure = code_is_pure_leaf(code); + let depth = crate::recursion::current_depth(); + if !(pure || code_is_effect_leaf(code)) + || !pure_leaf_warm(code) + || depth >= crate::recursion::recursion_limit() + { + return None; + } + let arity = leaf_arity(code); + if arity > 8 { + return None; + } + let mut ptrs: [*const Object; 8] = [std::ptr::null(); 8]; + for (p, a) in ptrs.iter_mut().zip(head.iter().chain(items.iter())) { + *p = a; + } + if code.kwonly_count != 0 && leaf_kwonly_defaults(f, code, &mut ptrs, 0).is_none() { + return None; + } + self.pure_leaf_call(code, f, &ptrs[..arity], !pure, depth) + } + fn try_leaf_call_ex(&mut self, frame: &mut Frame, pc: usize) -> bool { let n = frame.stack.len(); let Some(cs) = n.checked_sub(4) else { return false; }; - let [Object::Function(f), Object::Unbound, Object::Tuple(items), mapping] = - &frame.stack[cs..] - else { + let [callee, Object::Unbound, Object::Tuple(items), mapping] = &frame.stack[cs..] else { return false; }; + // A function, or a bound method of one (`obj.m(*args)`, which + // loads the method as an attribute): its receiver first. + let (f, head): (&Rc, &[Object]) = match callee { + Object::Function(f) => (f, &[]), + Object::BoundMethod(bm) if !bm.redispatch_descriptor => match &bm.function { + Object::Function(f) => (f, std::slice::from_ref(&bm.receiver)), + _ => return false, + }, + _ => return false, + }; let kw = match mapping { Object::Unbound => None, // SAFETY: a read that runs no code (nor does a pure leaf). @@ -19332,26 +21306,44 @@ impl Interpreter { } let mut ptrs: [*const Object; 8] = [std::ptr::null(); 8]; let arity = leaf_arity(code); + let given = head.len() + items.len(); if kw.is_none() - && items.len() == code.arg_count as usize + && given == code.arg_count as usize && !code.has_varargs && !code.has_varkeywords && arity <= 8 { // The common exact shape: the items in order, any keyword-only // parameters from their defaults. - for (p, a) in ptrs.iter_mut().zip(items.iter()) { + for (p, a) in ptrs.iter_mut().zip(head.iter().chain(items.iter())) { *p = a; } if code.kwonly_count != 0 && leaf_kwonly_defaults(f, code, &mut ptrs, 0).is_none() { return false; } + } else if let Some(missing) = (kw.is_none() + && code.kwonly_count == 0 + && !code.has_varargs + && !code.has_varkeywords + && arity <= 8) + .then(|| Self::missing_defaults(f, code, given)) + .flatten() + { + // Fewer items: the trailing parameters from the function's + // positional defaults. + for (p, a) in ptrs.iter_mut().zip(head.iter().chain(items.iter())) { + *p = a; + } + let defaults = &f.defaults[f.defaults.len() - missing..]; + for (p, d) in ptrs[given..given + missing].iter_mut().zip(defaults) { + *p = d; + } } else { let kw = kw .into_iter() .flat_map(|d| d.iter()) .map(|(k, v)| (&k.0, v)); - if Self::leaf_bind_keywords(f, code, &[], items, kw, &mut ptrs).is_none() { + if Self::leaf_bind_keywords(f, code, head, items, kw, &mut ptrs).is_none() { return false; } } @@ -19633,8 +21625,8 @@ impl Interpreter { // The interned empty tuple. Object::new_tuple(Vec::new()) } else if direct >= skip { - Object::Tuple(crate::tuple_storage::TupleStorage::from_exact_iter( - rest[direct - skip..].iter().cloned(), + Object::Tuple(crate::tuple_storage::TupleStorage::from_cloned_slice( + &rest[direct - skip..], )) } else { // (Some of `head` is surplus too.) @@ -19642,9 +21634,11 @@ impl Interpreter { }); } if code.has_varkeywords { - out.push(Object::Dict(Rc::new(RefCell::new( - varkw.unwrap_or_default(), - )))); + let d = Object::Dict(Rc::new(RefCell::new(varkw.unwrap_or_default()))); + if !varkw_stays_local(code) { + gc_trace::track_built(&d); + } + out.push(d); } Some(()) } @@ -19655,6 +21649,32 @@ impl Interpreter { /// no reference taken (nothing may change them while `out` is in use). /// The number of parameters bound, or `None` when anything needs the /// generic binder. + /// [`Self::leaf_bind_keywords`] of a call with no keywords that passes + /// exactly the positional parameters (`head` then `rest`) of a code with + /// no `*args`, `**kwargs` or keyword-only ones: the pointers in order, + /// and their count. `None` for any other shape. + #[inline] + fn leaf_bind_positional<'a>( + code: &CodeObject, + head: &'a [Object], + rest: &'a [Object], + out: &mut [*const Object; 8], + ) -> Option { + let n = head.len() + rest.len(); + if code.has_varargs + || code.has_varkeywords + || code.kwonly_count != 0 + || code.arg_count as usize != n + || n > out.len() + { + return None; + } + for (p, v) in out.iter_mut().zip(head.iter().chain(rest)) { + *p = v; + } + Some(n) + } + fn leaf_bind_keywords<'a>( f: &'a PyFunction, code: &CodeObject, @@ -19830,6 +21850,41 @@ impl Interpreter { false } + /// `cls(*args, **kwargs)` (the `CALL_FUNCTION_EX` at `pc` of `sw`'s + /// synced running activation, `[cls, NULL, tuple, dict]` atop its + /// stack) of a plain class whose `__init__` a lean activation can run, + /// with a mapping of `str` keys (`dataclasses.replace`'s + /// `self.__class__(**changes)`): bound and run as + /// [`Self::core_new_kw`] binds and runs a keyword call. `false` touches + /// nothing. + #[inline(never)] + fn core_new_mapping(&mut self, sw: &mut CoreSwitch, pc: usize, snap_gen: u64) -> bool { + if !self.core_new_ok(snap_gen) { + return false; + } + // SAFETY: see `CoreSwitch`. + let frame = unsafe { &mut *sw.cur }; + let Some(callee_slot) = frame.stack.len().checked_sub(4) else { + return false; + }; + let [Object::Type(_), Object::Unbound, Object::Tuple(items), Object::Dict(d)] = + &frame.stack[callee_slot..] + else { + return false; + }; + // SAFETY: a read that runs no code (the binding only clones). + let Some(kw) = (unsafe { d.peek() }) else { + return false; + }; + self.core_new_bind( + sw, + pc, + callee_slot, + items, + &mut kw.iter().map(|(k, v)| (&k.0, v)), + ) + } + /// `cls(..., name=value)` (the `CALL_KW` at `pc` of `sw`'s synced /// running activation) of a plain class whose `__init__` a lean /// activation can run: the arguments bind by name as the generic @@ -19838,12 +21893,7 @@ impl Interpreter { /// touches nothing. #[inline(never)] fn core_new_kw(&mut self, sw: &mut CoreSwitch, pc: usize, snap_gen: u64) -> bool { - if !self.inline_calls_ok() - || crate::stdlib::tracemalloc_real::is_tracking() - || crate::stdlib::testinternalcapi_mod::reftrace_print_active() - || crate::stdlib::testinternalcapi_mod::nomem_alloc_fails() - || self.lean_snapshot() != Some(snap_gen) - { + if !self.core_new_ok(snap_gen) { return false; } // SAFETY: see `CoreSwitch`. @@ -19860,6 +21910,80 @@ impl Interpreter { let Some(callee_slot) = len.checked_sub(kwc + argc + 3) else { return false; }; + let values = &frame.stack[len - 1 - kwc..len - 1]; + // A named tuple: its items placed by field name (see + // `named_tuple_items`). + if let Object::Type(ty) = &frame.stack[callee_slot] { + if !ty.flags.is_builtin + && ty.native_kind.get() == 0 + && matches!(frame.stack[callee_slot + 1], Object::Unbound) + && Self::metaclass_calls_like_type(ty) + { + let ty = ty.clone(); + let plan = self.instance_plan(&ty); + let mut kw = names.iter().zip(values).map(|(k, v)| match k { + Object::Str(k) => (&**k, v), + _ => ("", v), + }); + if let Some(fields) = plan.tuple_new.and_then(|_| { + Self::named_tuple_items( + &plan, + &frame.stack[callee_slot + 2..len - 1 - kwc], + &mut kw, + ) + }) { + drop(plan); + let (inst, tracked) = + crate::stdlib::collections_native::new_named_tuple(&ty, fields); + self.release_call_operands(&mut frame.stack, callee_slot); + frame.stack.push(inst); + frame.pc = pc as u32 + 1; + if tracked && gc_trace::maybe_auto_collect() { + self.run_pending_finalizers(); + } + return true; + } + } + } + let values = &frame.stack[len - 1 - kwc..len - 1]; + self.core_new_bind( + sw, + pc, + callee_slot, + &frame.stack[callee_slot + 2..len - 1 - kwc], + &mut names.iter().zip(values), + ) + } + + /// Whether the interpreter may construct an instance inline: nothing + /// that watches allocations or calls, and the snapshot `snap_gen` still + /// current. + #[inline] + fn core_new_ok(&self, snap_gen: u64) -> bool { + self.inline_calls_ok() + && !crate::stdlib::tracemalloc_real::is_tracking() + && !crate::stdlib::testinternalcapi_mod::reftrace_print_active() + && !crate::stdlib::testinternalcapi_mod::nomem_alloc_fails() + && self.lean_snapshot() == Some(snap_gen) + } + + /// The construction [`Self::core_new_kw`] and [`Self::core_new_mapping`] + /// share: the class at `callee_slot` of `sw`'s synced running + /// activation (an empty self slot above it, every operand from there + /// up the stack's), called by the instruction at `pc` with `positional` + /// and the keywords `kw`. Bound as the generic binder would, the + /// instance made, and its `__init__` made the running activation. + /// `false` touches nothing. + fn core_new_bind<'a>( + &mut self, + sw: &mut CoreSwitch, + pc: usize, + callee_slot: usize, + positional: &'a [Object], + kw: &mut dyn Iterator, + ) -> bool { + // SAFETY: see `CoreSwitch`. + let frame = unsafe { &mut *sw.cur }; let Object::Type(ty) = &frame.stack[callee_slot] else { return false; }; @@ -19901,13 +22025,12 @@ impl Interpreter { // (The instance isn't made until the binding holds: `None` keeps // its parameter's place.) let receiver = Object::None; - let values = &frame.stack[len - 1 - kwc..len - 1]; let bound = Self::lean_bind_keywords( init, code, std::slice::from_ref(&receiver), - &frame.stack[callee_slot + 2..len - 1 - kwc], - names.iter().zip(values), + positional, + kw, locals, ); let guard = match (bound, crate::recursion::enter_with(sw.depth_cell)) { @@ -20028,11 +22151,10 @@ impl Interpreter { // SAFETY: as above. let proven = unsafe { ty.instance_plan.peek() } .and_then(Option::as_ref) - .filter(|(v, plan)| { - *v == ty.attr_version.get() - && plan.store_init.load(std::sync::atomic::Ordering::Relaxed) == 1 - }) - .and_then(|(_, plan)| { + .filter(|(v, _)| *v == ty.attr_version.get()) + .map(|(_, plan)| self.call_plan(plan, ty, argc)) + .filter(|plan| plan.store_init.load(std::sync::atomic::Ordering::Relaxed) == 1) + .and_then(|plan| { let (init, code) = plan.lean_init.as_ref()?; // SAFETY: GIL-serialized raw read of the function's code // cell; only the pointer is compared. @@ -20075,7 +22197,8 @@ impl Interpreter { { // SAFETY: GIL-serialized raw read of the function's code cell; // only the pointer is compared. - if argc == nfields && unsafe { Rc::as_ptr(&*f.code.as_ptr()) } as usize == code { + let same = unsafe { Rc::as_ptr(&*f.code.as_ptr()) } as usize == code; + if argc == nfields && same && !crate::trace::any_observers_active() { let fields: Vec = frame.stack.drain(self_slot + 1..).collect(); let (inst, tracked) = crate::stdlib::collections_native::new_named_tuple(&ty, fields); @@ -20087,13 +22210,84 @@ impl Interpreter { } return true; } + // (Fewer arguments: the rest from the function's defaults.) + if let Some(fields) = (argc < nfields) + .then(|| { + Self::named_tuple_items( + &plan, + &frame.stack[self_slot + 1..], + &mut std::iter::empty(), + ) + }) + .flatten() + { + let (inst, tracked) = + crate::stdlib::collections_native::new_named_tuple(&ty, fields); + // (The operands leave as the generic call releases them.) + self.release_call_operands(&mut frame.stack, callee_slot); + frame.stack.push(inst); + frame.pc = pc as u32 + 1; + if tracked && gc_trace::maybe_auto_collect() { + self.run_pending_finalizers(); + } + return true; + } } + // (`Path(...)`: a call of the class its `__new__` picks.) + if plan.trivial_new.is_some() { + if let Some(m) = self.trivial_new_retarget(&plan, &ty, argc) { + frame.stack[callee_slot] = Object::Type(m); + return self.core_new_n(sw, pc, argc, snap_gen); + } + } + // (A `__new__` that only allocates: as though it were + // `object.__new__`.) + let plan = self.call_plan(&plan, &ty, argc).clone(); // A class with a plain Python `__new__` (`pathlib`'s paths). if let Some(Object::Function(new_f)) = &plan.user_new { let new_f = new_f.clone(); return self.core_new_user(sw, pc, argc, &ty, &plan, &new_f); } let Some((init, code)) = plan.lean_init.as_ref() else { + // `C(x)` for a subclass of an immutable built-in that keeps the + // base's `__new__` and `object.__init__`, of an argument of the + // base's own type: the base's constructor returns the argument + // itself, so it is the payload (`configparser._Line`'s `str`). + if argc == 1 + && plan.user_new.is_none() + && plan.init_from_object + && ty.native_kind.get() == 0 + { + if let crate::types::NativeKind::Value { + base, + mutable: false, + } = &plan.native + { + let fits = base.flags.is_builtin + && matches!( + (base.name.as_str(), &frame.stack[self_slot + 1]), + ("str", Object::Str(_)) + | ("int", Object::Int(_)) + | ("float", Object::Float(_)) + | ("tuple", Object::Tuple(_)) + | ("bytes", Object::Bytes(_)) + | ("frozenset", Object::FrozenSet(_)) + ); + if fits { + let payload = frame.stack.pop().expect("the argument"); + let inst = + Object::Instance(Rc::new(PyInstance::with_native(ty.clone(), payload))); + gc_trace::track(&inst); + frame.stack.truncate(callee_slot); + frame.stack.push(inst); + frame.pc = pc as u32 + 1; + if gc_trace::maybe_auto_collect() { + self.run_pending_finalizers(); + } + return true; + } + } + } // `E(*args)` for an exception class that keeps // `BaseException`'s allocator and `__init__`: the allocation, // and that `__init__`'s `args` (and a `StopIteration`'s @@ -20295,6 +22489,17 @@ impl Interpreter { } return false; }; + // An `__init__` its plan found no store-only shape in (for good, for + // this class version) that isn't a leaf either (a verdict that never + // turns): neither path below takes it, so it costs no argument + // count or shape check (every construction of such a class runs + // its own frame). + if plan.store_init.load(std::sync::atomic::Ordering::Relaxed) == 2 + && code.jit_hint.pure_leaf() == Some(false) + && !code.jit_hint.effect_leaf() + { + return false; + } // (Neither path below seeds an exception's `args`.) if plan.seeds_exception_args || !matches!(plan.native, crate::types::NativeKind::Plain) @@ -20356,9 +22561,14 @@ impl Interpreter { plan: &Rc, new_f: &Rc, ) -> bool { - // (The shapes `instantiate` treats before or around `__new__`.) + // (The shapes `instantiate` treats before or around `__new__`. A + // value type's subclass makes its payload in the `__new__` it + // chains to, `configparser`'s `_Line(str)`.) if plan.abstract_error.is_some() - || !matches!(plan.native, crate::types::NativeKind::Plain) + || !matches!( + plan.native, + crate::types::NativeKind::Plain | crate::types::NativeKind::Value { .. } + ) || plan.seeds_exception_args || ty.is_type_subclass() || ty.native_kind.get() != 0 @@ -20660,20 +22870,127 @@ impl Interpreter { callee_slot: usize, depth_cell: *const std::cell::Cell, ) -> bool { + let args = self_slot + 1; + let Some(inst) = self.store_init_build( + ty, + plan, + init, + code, + prove, + argc, + missing, + depth_cell, + |j, last| { + let slot = &mut frame.stack[args + j - 1]; + if last { + std::mem::replace(slot, Object::Unbound) + } else { + slot.clone() + } + }, + ) else { + return false; + }; + // The class, the self slot and the arguments the stores left. + // SAFETY: the operands leave the stack, each released once. + unsafe { + let base = frame.stack.as_ptr(); + let n = frame.stack.len(); + frame.stack.set_len(callee_slot); + for k in callee_slot..n { + let o = base.add(k).read(); + if !matches!(o, Object::Unbound) { + self.release(o); + } + } + } + frame.stack.push(inst); + true + } + + /// Tier 2's call of the class `ty` with `argc` arguments, `arg(j)` + /// the `j`th (from 1), when its `__init__` only stores them (see + /// [`Self::core_store_init`], whose proved plan it needs): the fresh + /// instance, with no `__init__` frame and no Python code run. `None` + /// touches nothing. + pub(crate) fn store_init_call( + &self, + ty: &Rc, + argc: usize, + depth_cell: *const std::cell::Cell, + arg: impl Fn(usize) -> Object, + ) -> Option { + // (The checks the frame JIT's lane makes, see `ctor_store_init`.) + if ty.flags.is_builtin + || self.lean_snapshot().is_none() + || !self.inline_calls_ok() + || crate::stdlib::tracemalloc_real::is_tracking() + || crate::stdlib::testinternalcapi_mod::reftrace_print_active() + || crate::stdlib::testinternalcapi_mod::nomem_alloc_fails() + || !Self::metaclass_calls_like_type(ty) + { + return None; + } + // SAFETY: a guard-free read of the memoized plan, cloned before + // anything runs. + let plan = match unsafe { ty.instance_plan.peek() }.and_then(Option::as_ref) { + Some((ver, plan)) + if *ver == ty.attr_version.get() + && plan.store_init.load(std::sync::atomic::Ordering::Relaxed) == 1 => + { + plan.clone() + } + _ => return None, + }; + let (init, init_code) = plan.lean_init.as_ref()?; + // SAFETY: GIL-serialized raw read of the function's code cell; only + // the pointer is compared. + if !std::ptr::eq( + unsafe { Rc::as_ptr(&*init.code.as_ptr()) }, + Rc::as_ptr(init_code), + ) { + return None; + } + let missing = Self::missing_defaults(init, init_code, argc + 1)?; + self.store_init_build( + ty, + &plan, + init, + init_code, + false, + argc, + missing, + depth_cell, + |j, _| arg(j), + ) + } + + /// [`Self::core_store_init`]'s instance, its arguments from `arg(j, + /// last)`, the `j`th (from 1), taken on its last use. + #[allow(clippy::too_many_arguments)] + fn store_init_build( + &self, + ty: &Rc, + plan: &crate::types::InstancePlan, + init: &Rc, + code: &Rc, + prove: bool, + argc: usize, + missing: usize, + depth_cell: *const std::cell::Cell, + mut arg: impl FnMut(usize, bool) -> Object, + ) -> Option { let Some(shape) = code_store_init(code) else { // (No store-only shape, for this class version's `__init__`.) if prove { plan.store_init .store(2, std::sync::atomic::Ordering::Relaxed); } - return false; + return None; }; - let Some(slots) = code_vm_ext(code) + let slots = code_vm_ext(code) .filter(|e| e.field_slots.is_allocated()) - .map(|e| e.field_slots.view()) - else { - return false; - }; + .map(|e| e.field_slots.view())?; let ver = ty.attr_version.get(); if argc + 1 + missing != code.arg_count as usize || ty.flags.is_builtin @@ -20685,7 +23002,7 @@ impl Interpreter { // SAFETY: this thread's own depth cell. || unsafe { (*depth_cell).get() } >= crate::recursion::recursion_limit() { - return false; + return None; } // A class that lays its `__slots__` members out: each store's site // must have last stored a distinct member of this class version's @@ -20716,9 +23033,9 @@ impl Interpreter { if let Some(proving) = proving { proving.store(2, std::sync::atomic::Ordering::Relaxed); } - return false; + return None; } - _ => return false, + _ => return None, } } // (The positions hold for this class version: its plan's.) @@ -20733,9 +23050,23 @@ impl Interpreter { Some((v, idx)) if v == ver && idx == k as u32 => {} Some((v, _)) if v == ver => { proving.store(2, std::sync::atomic::Ordering::Relaxed); - return false; + return None; + } + _ => { + // A store through a data descriptor of this class + // version (a property's setter) never records a + // position. + let at = code.instructions[pc as usize].arg as usize; + if code + .names + .get(at) + .and_then(|name| ty.lookup(name)) + .is_some_and(|a| self.is_data_descriptor(&a)) + { + proving.store(2, std::sync::atomic::Ordering::Relaxed); + } + return None; } - _ => return false, } } } @@ -20745,13 +23076,13 @@ impl Interpreter { .iter() .any(|&(_, src)| matches!(src, StoreSrc::Const(c) if c as usize >= consts.len())) { - return false; + return None; } let keys = match laid_out { Some(_) => None, None => match ty.shared_keys.get() { Some(keys) if keys.len() >= shape.stores.len() => Some(keys), - _ => return false, + _ => return None, }, }; // A fresh container is made as `BUILD_LIST`/`BUILD_MAP` would make @@ -20762,7 +23093,7 @@ impl Interpreter { || crate::stdlib::testinternalcapi_mod::reftrace_print_active() || gc_trace::auto_collect_due()) { - return false; + return None; } // Committed. let (inst, _) = self.alloc_plain_instance_obj(ty); @@ -20777,7 +23108,6 @@ impl Interpreter { } // The parameters: the instance, the arguments (moved out of the // stack on their last use), then the defaults. - let args = self_slot + 1; let mut left = [0u8; 8]; left[..shape.uses.len()].copy_from_slice(&shape.uses); let defaults = &init.defaults[init.defaults.len() - missing..]; @@ -20791,12 +23121,7 @@ impl Interpreter { let j = j as usize; left[j] -= 1; if j <= argc { - let slot = &mut frame.stack[args + j - 1]; - if left[j] == 0 { - std::mem::replace(slot, Object::Unbound) - } else { - slot.clone() - } + arg(j, left[j] == 0) } else { defaults[j - argc - 1].clone() } @@ -20897,24 +23222,10 @@ impl Interpreter { } } } - // The class, the self slot and the arguments the stores left. - // SAFETY: the operands leave the stack, each released once. - unsafe { - let base = frame.stack.as_ptr(); - let n = frame.stack.len(); - frame.stack.set_len(callee_slot); - for k in callee_slot..n { - let o = base.add(k).read(); - if !matches!(o, Object::Unbound) { - self.release(o); - } - } - } - frame.stack.push(inst); if let Some(proving) = proving { proving.store(1, std::sync::atomic::Ordering::Relaxed); } - true + Some(inst) } fn core_leaf_init( @@ -20968,6 +23279,7 @@ impl Interpreter { Some(done) => { // Every return is `return None` (checked above). drop(done); + code.jit_hint.note_leaf_hit(); frame.stack.truncate(callee_slot); frame.stack.push(inst); true @@ -20975,8 +23287,10 @@ impl Interpreter { None => { // A declined `__init__` may have stored into the instance // before it stopped; nothing else ever saw it, so it goes - // (the framed call starts over on a fresh one). + // (the framed call starts over on a fresh one). One that + // keeps declining stops being tried. drop(inst); + code.jit_hint.note_leaf_miss(); false } } @@ -20986,18 +23300,118 @@ impl Interpreter { /// string over a slice of ints): the full handler's slicing, or /// `None` for it to run (and raise) itself. #[inline(never)] - fn core_slice(c: &Object, sl: &crate::object::PySlice) -> Option { + pub(crate) fn core_slice(c: &Object, sl: &crate::object::PySlice) -> Option { match c { Object::List(items) => { let items = items.try_borrow().ok()?; - Some(Object::new_list(slice_seq(&items, sl).ok()?)) + // (A contiguous slice copies its run straight out: the + // words copied in bulk and the counts taken after, not a + // per-element clone.) + let run = if matches!(sl.step, Object::None | Object::Int(1)) { + let (lo, hi) = Self::slice_bounds(sl, items.len())?; + crate::object::cloned_vec(&items[lo..hi.max(lo)]) + } else { + slice_seq(&items, sl).ok()? + }; + let out = Object::new_list(run); + // (Deferred without scanning: a cycle through it is still + // the collector's to find.) + gc_trace::track_built(&out); + Some(out) + } + Object::Tuple(items) => { + // A contiguous slice clones its range straight into the new + // tuple (the whole tuple is itself, as CPython's). + if matches!(sl.step, Object::None | Object::Int(1)) { + let (lo, hi) = Self::slice_bounds(sl, items.len())?; + let hi = hi.max(lo); + if lo == 0 && hi == items.len() { + return Some(c.clone()); + } + if lo == hi { + return Some(Object::new_tuple(Vec::new())); + } + return Some(Object::Tuple( + crate::tuple_storage::TupleStorage::from_cloned_slice(&items[lo..hi]), + )); + } + Some(Object::new_tuple(slice_seq(&items[..], sl).ok()?)) } - Object::Tuple(items) => Some(Object::new_tuple(slice_seq(&items[..], sl).ok()?)), Object::Str(st) => str_subscript_slice(st, sl).ok(), + // A range of machine ints sliced by machine ints: another + // range, by arithmetic. + Object::Range(r) => range_slice_small(r, sl), + Object::Bytes(b) => { + // (A contiguous slice copies its range once.) + if matches!(sl.step, Object::None | Object::Int(1)) { + let (lo, hi) = Self::slice_bounds(sl, b.len())?; + return Some(Object::Bytes(SharedSlice::from(&b[lo..hi.max(lo)]))); + } + Some(Object::new_bytes(slice_seq(&b[..], sl).ok()?)) + } + // A live view's sub-view, when another owner holds the view (its + // release here then frees nothing) and tracking the sub-view + // starts no collection. + Object::MemoryView(mv) + if Rc::strong_count(mv) > 1 + && !mv.released.get() + && !mv.restricted.get() + && !mv.zero_dim.get() + && !crate::stdlib::tracemalloc_real::is_tracking() + && !gc_trace::auto_collect_due() => + { + mv_slice_subview(mv, sl).ok() + } + // A contiguous slice of a `bytearray`: a new one over the range. + Object::ByteArray(b) if matches!(sl.step, Object::None | Object::Int(1)) => { + let b = b.try_borrow().ok()?; + let (lo, hi) = Self::slice_bounds(sl, b.len())?; + Some(Object::new_bytearray(&b[lo..hi.max(lo)])) + } + // A `str`, `list` or `tuple` subclass's instance whose class + // keeps its base's own `__getitem__` (`email`'s header tokens and + // token lists): the base's slice, exact, as CPython's is. + Object::Instance(inst) => { + let native = inst.native.get()?; + let bt = builtin_types(); + let base = match native { + Object::Str(_) => &bt.str_, + Object::List(_) => &bt.list_, + Object::Tuple(_) => &bt.tuple_, + _ => return None, + }; + let own = base + .dict + .try_borrow() + .ok()? + .get(&crate::object::StrKey("__getitem__")) + .cloned()?; + match inst.cls_raw().lookup("__getitem__") { + Some(g) if g.is_same(&own) => Self::core_slice(native, sl), + _ => None, + } + } _ => None, } } + /// A unit-step slice's clamped `[lo, hi)` over `n` items, its bounds + /// plain ints or omitted (`None` otherwise). + #[inline] + pub(crate) fn slice_bounds(sl: &crate::object::PySlice, n: usize) -> Option<(usize, usize)> { + let n = n as i64; + let at = |v: &Object, dflt: i64| -> Option { + let i = match v { + Object::None => dflt, + Object::Int(i) if *i < 0 => (*i + n).max(0), + Object::Int(i) => (*i).min(n), + _ => return None, + }; + Some(i as usize) + }; + Some((at(&sl.start, 0)?, at(&sl.stop, n)?)) + } + /// The core loop's `BINARY_OP` over strings: `str + str`, a small /// `str * int`, and `str % args` over scalar and string arguments /// (the leaf arms' string cases). `None` for the full handler, which @@ -21029,6 +23443,29 @@ impl Interpreter { { Object::from_str(percent_format(t, args).ok()?) } + // A tuple subclass's instance (a namedtuple's `repr_fmt % + // self`) is the argument pack its tuple is (CPython's + // `PyTuple_Check`), here when its items are what + // `percent_leaf_args` takes. Another owner holds it, so its + // release frees nothing. + (Object::Str(t), Object::Instance(inst)) + if kind == BinOpKind::Mod && Rc::strong_count(inst) > 1 => + { + let args = inst + .native + .get() + .filter(|n| matches!(n, Object::Tuple(_)))?; + if !percent_leaf_args(args) || percent_args_need_bridge(args) { + return None; + } + Object::from_str(percent_format(t, args).ok()?) + } + // A template of bare `%s` conversions over `str`, `int` or + // `float` subclass instances that render as their payloads + // (`"%s" % SomeStrEnum.A`): each instance is its `str()`. + (Object::Str(t), args) if kind == BinOpKind::Mod && percent_payload_args(args) => { + Object::from_str(percent_format_payloads(t, args)?) + } // (A dict another owner holds: its release frees nothing.) (Object::Str(t), Object::Dict(d)) if kind == BinOpKind::Mod && Rc::strong_count(d) > 1 => @@ -21053,8 +23490,8 @@ impl Interpreter { if x.is_empty() { return Some(b.clone()); } - Some(Object::new_tuple( - x.iter().chain(y.iter()).cloned().collect(), + Some(Object::Tuple( + crate::tuple_storage::TupleStorage::from_cloned_pair(x, y), )) } (Object::List(x), Object::List(y)) => { @@ -21063,10 +23500,62 @@ impl Interpreter { } let (x, y) = (x.try_borrow().ok()?, y.try_borrow().ok()?); let mut items = Vec::with_capacity(x.len() + y.len()); - items.extend(x.iter().cloned()); - items.extend(y.iter().cloned()); + crate::object::extend_cloned(&mut items, &x); + crate::object::extend_cloned(&mut items, &y); let obj = Object::new_list(items); - gc_trace::track(&obj); + gc_trace::track_built(&obj); + Some(obj) + } + _ => None, + } + } + + /// The largest result [`Self::core_seq_repeat`] builds; a longer one + /// is the full handler's (its size checks and `MemoryError`). + const CORE_REPEAT_MAX: usize = 4096; + + /// `seq * n` or `n * seq` for an exact tuple or list and an int (the + /// full handler's repetition: `t * 1` is `t` itself), when the result + /// is short, or `None` for it: a list is tracked like `BUILD_LIST`'s, + /// so one whose allocation would start a collection is left to the + /// full handler. (A list's `*=` repeats it in place: not this.) + #[inline(never)] + fn core_seq_repeat(a: &Object, b: &Object) -> Option { + let (seq, n) = match (a, b) { + (Object::Tuple(_) | Object::List(_), Object::Int(n)) => (a, *n), + (Object::Int(n), Object::Tuple(_) | Object::List(_)) => (b, *n), + _ => return None, + }; + let times = usize::try_from(n).unwrap_or(0); + match seq { + Object::Tuple(x) => { + if n == 1 { + return Some(seq.clone()); + } + let total = x.len().checked_mul(times)?; + if total > Self::CORE_REPEAT_MAX { + return None; + } + if total == 0 { + return Some(Object::new_tuple(Vec::new())); + } + Some(Object::Tuple( + crate::tuple_storage::TupleStorage::from_repeated_slice(x, times), + )) + } + Object::List(x) => { + if crate::stdlib::tracemalloc_real::is_tracking() || gc_trace::auto_collect_due() { + return None; + } + let x = x.try_borrow().ok()?; + if x.len().checked_mul(times)? > Self::CORE_REPEAT_MAX { + return None; + } + let mut out = Vec::new(); + repeat_objects(&x, times, &mut out); + drop(x); + let obj = Object::new_list(out); + gc_trace::track_built(&obj); Some(obj) } _ => None, @@ -21177,7 +23666,25 @@ impl Interpreter { len: usize, cap: usize, ) -> Option { - match ins.op { + // SAFETY: the caller's contract. + unsafe { self.exc_op(ins.op, base, len, cap) } + } + + /// [`Self::core_exc_op`] by opcode (compiled code's helper names the + /// instruction itself: see `frame_jit::h_exc_op`). + /// + /// # Safety + /// + /// As [`Self::core_exc_op`]'s. + #[inline(always)] + pub(crate) unsafe fn exc_op( + &mut self, + op: OpCode, + base: *mut Object, + len: usize, + cap: usize, + ) -> Option { + match op { OpCode::PushExcInfo => { // SAFETY: `len > 0` is checked first. if len == 0 @@ -21728,6 +24235,9 @@ impl Interpreter { /// compares natively (see [`Self::dict_get_hot`]): `None` declines. #[inline(always)] pub(crate) fn contains_hot(c: &Object, item: &Object) -> Option { + if let Object::Instance(i) = item { + return Self::contains_instance_hot(c, i); + } let found = match c { // SAFETY: a read between two instructions (the probe runs no // code). @@ -21740,6 +24250,26 @@ impl Interpreter { Some(found.1.is_ok()) } + /// [`Self::contains_hot`] for an instance hashed by identity (`obj in + /// seen`): `None` declines (another hash, or a stored key of another + /// kind with its hash). + #[inline(always)] + fn contains_instance_hot(c: &Object, i: &Rc) -> Option { + if i.native.get().is_some() || !i.class_dunder(crate::types::Dunder::Hash).object_owner() { + return None; + } + let found = match c { + // SAFETY: a read between two instructions (the probe runs no + // code). + Object::Set(s) => unsafe { s.peek() }?.find_instance_native(i)?, + // SAFETY: as above. + Object::Dict(d) => unsafe { d.peek() }?.find_instance_native(i)?, + Object::FrozenSet(s) => s.find_instance_native(i)?, + _ => return None, + }; + Some(found.is_ok()) + } + /// The core loop's commonest subscripts, ahead of /// [`Self::core_container_op`]: `BINARY_SUBSCR` (`store` false) or /// `STORE_SUBSCR` on the top of the `len`-deep stack at `base`, through @@ -21892,15 +24422,25 @@ impl Interpreter { // SAFETY: `len >= 2`. let (c, k) = unsafe { (&*base.add(len - 2), &*base.add(len - 1)) }; // (An instance goes to the caller's native subscript, which - // grades its own release.) - if !matches!( + // grades its own release, except for a slice: a `str`, + // `list` or `tuple` subclass's keeping its base's + // `__getitem__` is the base's slice here.) + if !(matches!( c, Object::List(_) | Object::Tuple(_) | Object::Dict(_) | Object::Str(_) + | Object::Bytes(_) + | Object::ByteArray(_) | Object::MappingProxy(_) - ) || !Self::core_droppable(c) + ) || matches!( + (c, k), + ( + Object::Instance(_) | Object::MemoryView(_) | Object::Range(_), + Object::Slice(_) + ) | (Object::MemoryView(_) | Object::Range(_), Object::Int(_)) + )) || !Self::core_droppable(c) { return None; } @@ -21932,6 +24472,56 @@ impl Interpreter { } clone_hot(&t[i as usize]) } + (Object::Bytes(b), Object::Int(i)) => { + let n = b.len() as i64; + let i = if *i < 0 { *i + n } else { *i }; + if i < 0 || i >= n { + return None; + } + Object::Int(i64::from(b[i as usize])) + } + (Object::ByteArray(b), Object::Int(i)) => { + // SAFETY: a read between two instructions. + let b = unsafe { b.peek() }?; + let n = b.len() as i64; + let i = if *i < 0 { *i + n } else { *i }; + if i < 0 || i >= n { + return None; + } + Object::Int(i64::from(b[i as usize])) + } + // A machine-width range's item that is a machine int + // (anything else, an index out of range included, is + // the full subscript's). + (Object::Range(r), Object::Int(i)) if r.big.is_none() => { + let (start, stop, step) = (r.start, r.stop, r.step); + let span = if step > 0 { + stop.checked_sub(start)? + } else { + start.checked_sub(stop)? + }; + let n = if span > 0 { + (span - 1) / step.abs() + 1 + } else { + 0 + }; + let at = i128::from(*i) + if *i < 0 { n } else { 0 }; + if at < 0 || at >= n { + return None; + } + let v = at.checked_mul(step)?.checked_add(start)?; + Object::Int(i64::try_from(v).ok()?) + } + // A live view another owner holds, or whose release + // runs nothing (over bytes, a `bytearray`, or views + // of them): the byte of a plain view, the element of + // a 1-D view of a simple format (`cast("I")`). + (Object::MemoryView(mv), Object::Int(i)) + if !mv.released.get() + && (Rc::strong_count(mv) > 1 || mv_frees_quietly(mv, 0)) => + { + mv_leaf_item(mv, *i)? + } // (A tuple key's probe takes only ints and strings, // which compare and drop without running code.) (Object::Dict(d), Object::Str(_) | Object::Int(_) | Object::Tuple(_)) => { @@ -21967,10 +24557,19 @@ impl Interpreter { // `seq[a:b:c]` with plain int (or omitted) bounds: the // full handler's own slicing, out of line (a bad step // declines, and the full handler raises). - (Object::List(_) | Object::Tuple(_) | Object::Str(_), Object::Slice(sl)) - if [&sl.start, &sl.stop, &sl.step] - .iter() - .all(|v| matches!(v, Object::None | Object::Int(_))) => + ( + Object::List(_) + | Object::Tuple(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::ByteArray(_) + | Object::MemoryView(_) + | Object::Range(_) + | Object::Instance(_), + Object::Slice(sl), + ) if [&sl.start, &sl.stop, &sl.step] + .iter() + .all(|v| matches!(v, Object::None | Object::Int(_))) => { Self::core_slice(c, sl)? } @@ -22002,8 +24601,17 @@ impl Interpreter { &*base.add(len - 1), ) }; - if !matches!(c, Object::List(_) | Object::Tuple(_) | Object::Str(_)) - || !Self::core_droppable(c) + if !matches!( + c, + Object::List(_) + | Object::Tuple(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::ByteArray(_) + | Object::MemoryView(_) + | Object::Range(_) + | Object::Instance(_) + ) || !Self::core_droppable(c) || !matches!(a, Object::None | Object::Int(_)) || !matches!(b, Object::None | Object::Int(_)) { @@ -22049,6 +24657,47 @@ impl Interpreter { // stack into the list. std::mem::replace(&mut xs[i as usize], unsafe { base.add(len - 3).read() }) } + // `buf[i] = n` of a `bytearray` by an int index, the value + // a byte (`re`'s charset map). + (Object::ByteArray(b), Object::Int(i)) => { + // SAFETY: `len >= 3`. + let byte = match unsafe { &*base.add(len - 3) } { + Object::Int(v) if (0..=255).contains(v) => *v as u8, + Object::Bool(t) => u8::from(*t), + _ => return None, + }; + let mut bs = b.try_borrow_mut().ok()?; + let n = bs.len() as i64; + let i = if *i < 0 { *i + n } else { *i }; + if i < 0 || i >= n { + return None; + } + bs[i as usize] = byte; + // SAFETY: the value slot (a scalar) leaves the stack. + unsafe { base.add(len - 3).read() } + } + // `view[i] = n` through a live, writable, plain view of + // bytes another owner holds (its release here frees + // nothing), the value a byte. + (Object::MemoryView(mv), Object::Int(i)) + if Rc::strong_count(mv) > 1 && !mv.released.get() && !mv.readonly.get() => + { + // SAFETY: `len >= 3`. + let byte = match unsafe { &*base.add(len - 3) } { + Object::Int(v) if (0..=255).contains(v) => *v as u8, + _ => return None, + }; + let (start, n) = mv_plain_bytes(mv)?; + let i = if *i < 0 { *i + n as i64 } else { *i }; + if i < 0 || i >= n as i64 { + return None; + } + mv.buffer + .with_write(|all| all.get_mut(start + i as usize).map(|at| *at = byte)) + .flatten()?; + // SAFETY: the value slot (a scalar) leaves the stack. + unsafe { base.add(len - 3).read() } + } // Any key the leaf probe hashes and compares natively // (a `str`, an `int`, a tuple of them, or an object // keyed by identity). @@ -22112,6 +24761,8 @@ impl Interpreter { return None; } let removed_ok = |v: &Object| scalar(v) || Self::core_droppable(v); + // (A slice's run, released with the other removals.) + let mut run_items: Vec = Vec::new(); let (removed, key) = match (c, k) { (Object::List(xs), Object::Int(i)) => { // SAFETY: a store between two instructions (the @@ -22124,6 +24775,68 @@ impl Interpreter { } (xs.remove(i as usize), Object::None) } + // `del buf[i]` of a bytearray no buffer view holds (an + // export makes the full path raise `BufferError`): the + // byte in range removed, nothing to release. + (Object::ByteArray(b), Object::Int(i)) + if !crate::object::bytearray_is_exported(b) => + { + // SAFETY: as for a list above. + let data = unsafe { b.peek_mut() }?; + let n = data.len() as i64; + let i = if *i < 0 { *i + n } else { *i }; + if i < 0 || i >= n { + return None; + } + data.remove(i as usize); + (Object::None, Object::None) + } + // `del buf[a:b]` of a bytearray no buffer view holds, of + // a unit step, by plain bounds (a consumed prefix, + // `del buf[:n]`): the run removed, nothing to release. + (Object::ByteArray(b), Object::Slice(sl)) + if matches!(sl.step, Object::None | Object::Int(1)) + && matches!(sl.start, Object::None | Object::Int(_)) + && matches!(sl.stop, Object::None | Object::Int(_)) + && !crate::object::bytearray_is_exported(b) => + { + // SAFETY: as for a list above. + let data = unsafe { b.peek_mut() }?; + let n = data.len() as i64; + let bound = |o: &Object, default: i64| match o { + Object::Int(i) => { + if *i < 0 { i.saturating_add(n) } else { *i }.clamp(0, n) + } + _ => default, + }; + let (lo, hi) = (bound(&sl.start, 0), bound(&sl.stop, n)); + data.drain((lo as usize)..(hi.max(lo) as usize)); + (Object::None, Object::None) + } + // `del xs[a:b]` of a unit step, by plain bounds, whose + // items release without running code. + (Object::List(xs), Object::Slice(sl)) + if matches!(sl.step, Object::None | Object::Int(1)) + && matches!(sl.start, Object::None | Object::Int(_)) + && matches!(sl.stop, Object::None | Object::Int(_)) => + { + // SAFETY: as above. + let xs = unsafe { xs.peek_mut() }?; + let n = xs.len() as i64; + let bound = |o: &Object, default: i64| match o { + Object::Int(i) => { + if *i < 0 { i.saturating_add(n) } else { *i }.clamp(0, n) + } + _ => default, + }; + let (lo, hi) = (bound(&sl.start, 0), bound(&sl.stop, n)); + let run = (lo as usize)..(hi.max(lo) as usize); + if !xs[run.clone()].iter().all(removed_ok) { + return None; + } + run_items = xs.drain(run).collect(); + (Object::None, Object::None) + } (Object::Dict(cell), Object::Str(_) | Object::Int(_)) => { if crate::capi_watchers::dicts_active() { return None; @@ -22131,11 +24844,7 @@ impl Interpreter { let probe = crate::object::LeafProbe::new(k)?; // SAFETY: as above (the probe runs no code). let d = unsafe { cell.peek_mut() }?; - let at = d.get_index_of(&probe)?; - if !d.get_index(at).is_some_and(|(_, v)| removed_ok(v)) { - return None; - } - let (key, v) = d.shift_remove_index(at)?; + let (key, v) = d.lazy_remove_entry_if(&probe, removed_ok)?; crate::object::dict_watch_bump(cell); crate::object::dict_mutation_event(cell); (v, key.0) @@ -22150,6 +24859,10 @@ impl Interpreter { } drop_hot(removed); drop_hot(key); + // (Last first, as `list_ass_slice` releases them.) + for v in run_items.into_iter().rev() { + drop_hot(v); + } Some(len - 2) } OpCode::UnpackSequence => { @@ -22231,8 +24944,13 @@ impl Interpreter { return None; } let items: Vec = match value { - Object::Tuple(t) => t.to_vec(), + Object::Tuple(t) => crate::object::cloned_vec(t), Object::List(l) if !Rc::ptr_eq(l, dst) => l.try_borrow().ok()?.clone(), + // `xs[a:b] = filter(None, ys)` (`urljoin`'s), drained + // whole when that runs no code. + Object::LazyIter(l) if dst.try_borrow_mut().is_ok() => { + crate::seqiter::filter_collect(l)? + } _ => return None, }; let mut d = dst.try_borrow_mut().ok()?; @@ -22305,7 +25023,9 @@ impl Interpreter { _ => unreachable!("checked above"), }; let mid_end = items.len() - after; - let mid = Object::new_list(items[before..mid_end].to_vec()); + let mid = + Object::new_list(crate::object::cloned_vec(&items[before..mid_end])); + gc_trace::track_built(&mid); let mut k = len - 1; for x in items[mid_end..].iter().rev() { base.add(k).write(clone_hot(x)); @@ -22433,14 +25153,24 @@ impl Interpreter { return None; }; let str_keys = |d: &DictData| d.keys().all(|k| matches!(k.0, Object::Str(_))); - if !str_keys(&s) - || !str_keys(&t) - || (ins.arg & 1 != 0 && s.keys().any(|k| t.contains_key(k))) - { - return None; - } - for (k, v) in s.iter() { - t.insert(k.clone(), v.clone()); + // (A keyword splat's keys must be strings: the full + // handler raises for any other.) + if t.is_empty() && (ins.arg & 1 == 0 || str_keys(&s)) { + // (`{**d}`, `f(**kw)`: the source's table copied whole, + // its keys hashed already and none repeated, so nothing + // compares them.) + let map: &mut crate::object::DictMap = &mut t; + map.clone_from(&s); + } else { + if !str_keys(&s) + || !str_keys(&t) + || (ins.arg & 1 != 0 && s.keys().any(|k| t.contains_key(k))) + { + return None; + } + for (k, v) in s.iter() { + t.insert(k.clone(), v.clone()); + } } drop((t, s)); // SAFETY: the source leaves the stack. @@ -22484,12 +25214,12 @@ impl Interpreter { Object::Tuple(t) => { // SAFETY: a store between two instructions; growing // the list runs no code. - unsafe { lst.peek_mut() }?.extend(t.iter().cloned()); + crate::object::extend_cloned(unsafe { lst.peek_mut() }?, t); } Object::List(l) if !Rc::ptr_eq(l, lst) => { // SAFETY: as above; two distinct lists. - let items = unsafe { l.peek() }?.clone(); - unsafe { lst.peek_mut() }?.extend(items); + let items = unsafe { l.peek() }?; + crate::object::extend_cloned(unsafe { lst.peek_mut() }?, items); } _ => return None, } @@ -22514,6 +25244,33 @@ impl Interpreter { if !Self::core_droppable(src) { return None; } + // `{*xs, ...}` over an exact list's or tuple's items that + // hash natively (numbers, strings, tuples of them): each + // one inserted as `SET_ADD` inserts it, a duplicate left + // out. (An item past the check that the probe can't settle + // stops the update part-way, which the full handler then + // finishes: inserting an item again changes nothing.) + let unpacked: Option<&[Object]> = match src { + Object::Tuple(t) => Some(t), + // SAFETY: a read between two instructions. + Object::List(l) => Some(unsafe { l.peek() }?), + _ => None, + }; + if let Some(items) = unpacked { + if !items.iter().all(|x| crate::seqiter::plain_hashable(x, 0)) { + return None; + } + // SAFETY: a store between two instructions (the probes + // and the inserts run no code). + let t = unsafe { target.peek_mut() }?; + for x in items { + let probe = crate::object::LeafProbe::new(x)?; + t.insert_probe_if(&probe, |p| p.miss_is_exact(), || DictKey(x.clone()))?; + } + // SAFETY: the source leaves the stack (droppable). + drop(unsafe { base.add(len - 1).read() }); + return Some(len - 1); + } let items = match src { Object::FrozenSet(s) => (**s).clone(), // SAFETY: a read between two instructions. @@ -22547,6 +25304,16 @@ impl Interpreter { /// size or key change the checked step reports, an exhaustion that /// could release anything (a shared iterator, the dict's last /// reference, a subclass keepalive), or a reverse iterator. + /// The next key, value or item of a dict or dict-view iterator, for a + /// leaf `next()`; `None`, having changed nothing, where + /// [`Self::core_dict_next`] declines or the iterator ends. + pub(crate) fn core_dict_next_item(it: &mut crate::object::PyIterator) -> Option { + match Self::core_dict_next(it, false, false) { + DictStep::Item(v, _) => Some(v), + DictStep::Exhausted | DictStep::Decline => None, + } + } + #[inline(never)] fn core_dict_next(it: &mut crate::object::PyIterator, fuse: bool, unique: bool) -> DictStep { use crate::object::DictViewKind; @@ -22576,7 +25343,12 @@ impl Interpreter { return DictStep::Decline; } let Some((k, v)) = data.get_index(*index) else { - if !unique || owner.is_some() || Rc::strong_count(d) == 1 { + // (A dict subclass's instance the iterator keeps alive: its + // release when the iterator goes must not be its last.) + let owner_dies = owner + .as_ref() + .is_some_and(|o| !matches!(o, Object::Instance(i) if Rc::strong_count(i) > 1)); + if !unique || owner_dies || Rc::strong_count(d) == 1 { return DictStep::Decline; } // CPython clears `di_dict` on the first StopIteration. @@ -22891,7 +25663,16 @@ impl Interpreter { }; // SAFETY: a read between two instructions; the value is cloned // before anything else runs. - let v = (unsafe { inst.laid_out_slot(idx) }).map(Self::clone_operand)?; + let v = match unsafe { inst.laid_out_slot_any(idx) }? { + // Unset: the descriptor's default, where it has one (a + // never-raised exception's `__traceback__` is `None`); a + // `__slots__` member's `AttributeError` is the full path's. + Object::Unbound => match cls.lookup(code.names.get(name_idx as usize)?) { + Some(Object::SlotDescriptor(sd)) => sd.default.clone()?, + _ => return None, + }, + v => Self::clone_operand(v), + }; // The site's inline cache takes the slot shape too, as the full // handler's specialization would: the frameless evaluators read // the member through it. @@ -23228,6 +26009,10 @@ impl Interpreter { if n.starts_with("__") || !Self::meta_store_transparent(cls, n) { return false; } + // (The object the name already holds, stored again, changes + // nothing a lookup resolves: the class keeps its version.) + let mut same = false; + let mut inert = false; let old = { let Ok(mut d) = cls.dict.try_borrow_mut() else { return false; @@ -23237,7 +26022,11 @@ impl Interpreter { Some(slot) if !Self::core_droppable(slot) => return false, // SAFETY: the value moves into the dictionary; its slot is // forgotten below. - Some(slot) => Some(std::mem::replace(slot, unsafe { std::ptr::read(value) })), + Some(slot) => { + same = slot.is_same(value); + inert = inert_class_values(slot, value); + Some(std::mem::replace(slot, unsafe { std::ptr::read(value) })) + } None => { // SAFETY: as above. d.insert(DictKey(name.clone()), unsafe { std::ptr::read(value) }); @@ -23245,7 +26034,13 @@ impl Interpreter { } } }; - cls.bump_attr_version(); + // (An entry's value replaced in place moves no name on the MRO.) + match &old { + _ if same => {} + Some(_) if inert => cls.bump_attr_version_inert(), + Some(_) => cls.bump_attr_version_values(), + None => cls.bump_attr_version(), + } // SAFETY: the class leaves by a plain decrement (checked droppable); // the value's slot moved out above. unsafe { drop_hot(recv.read()) }; @@ -23300,7 +26095,7 @@ impl Interpreter { && frame.class_namespace_obj().is_none() && frame.builtins_obj().is_none() && !frame.code.is_class_body - && !self.globals_missing_any.get() + && !self.globals_missing_gate() } /// A plain namespace in front of the module scope, for the core loop's @@ -23312,7 +26107,7 @@ impl Interpreter { frame.class_namespace().is_some() && frame.class_namespace_obj().is_none() && frame.builtins_obj().is_none() - && !self.globals_missing_any.get() + && !self.globals_missing_gate() } /// The probe for `co_names[name_idx]` in a namespace frame (see @@ -23609,6 +26404,26 @@ impl Interpreter { BinOpKind::BitAnd => a & b, BinOpKind::BitOr => a | b, BinOpKind::BitXor => a ^ b, + // (Floored, as Python's: the remainder takes the + // divisor's sign. A zero divisor raises through + // the full path.) + BinOpKind::Mod if b != 0 => { + let r = a.checked_rem(b)?; + if r != 0 && (r ^ b) < 0 { + r + b + } else { + r + } + } + BinOpKind::FloorDiv if b != 0 => { + let q = a.checked_div(b)?; + if (a ^ b) < 0 && q * b != a { + q - 1 + } else { + q + } + } + BinOpKind::RShift if (0..64).contains(&b) => a >> b, _ => return None, }; ops[n - 2].write(Object::Int(r)); @@ -23825,7 +26640,10 @@ impl Interpreter { let code_rc: &Rc = unsafe { &*f.code.as_ptr() }; let pure = code_is_pure_leaf(code_rc); let effect = !pure && code_is_effect_leaf(code_rc); - if !(pure || effect) || !pure_leaf_warm(code_rc) { + // (No warm-up gate: the evaluation's own bookkeeping sends the call + // that makes the callee due to the framed path, see + // `Self::leaf_call_entry`.) + if !(pure || effect) { return None; } let (missing, slot_self) = code_call_slot(code, call_pc)?.hit(fp, Rc::as_ptr(code_rc))?; @@ -24122,7 +26940,10 @@ impl Interpreter { note_predicate_stage(code_rc, 0); let pure = code_is_pure_leaf(code_rc); let effect = !pure && code_is_effect_leaf(code_rc); - if !(pure || effect) || !pure_leaf_warm(code_rc) { + // (No warm-up gate: the evaluation's own bookkeeping sends the call + // that makes the callee due to the framed path, see + // `Self::leaf_call_entry`.) + if !(pure || effect) { return None; } #[cfg(test)] @@ -24132,12 +26953,22 @@ impl Interpreter { let missing = match hit { Some((missing, slot_self)) if slot_self == has_self => missing, Some(_) => return None, - // A positional call caches no shape for keyword-only - // parameters (the defaults bind them below): its count of - // positional defaults, directly. + // A callee with keyword-only parameters (the defaults bind + // them below): its count of positional defaults, cached as the + // site's shape, which the framed call binds and compiled code + // lowers in line from. None if code_rc.kwonly_count != 0 => { let given = ops.len() - 2 + usize::from(has_self); - u32::try_from(Self::missing_defaults(f, code_rc, given)?).ok()? + let missing = u32::try_from(Self::missing_defaults(f, code_rc, given)?).ok()?; + if let Some(slot) = code_call_slot(code, pc) { + slot.set(CallShape { + func: Rc::downgrade(f), + code: Rc::downgrade(code_rc), + missing, + has_self, + }); + } + missing } None => return None, }; @@ -24250,6 +27081,16 @@ impl Interpreter { // bookkeeping sends the call that makes the callee due to the // framed path, see `Self::leaf_call_entry`.) if !(pure || effect) { + // A forwarding wrapper the site cached (see + // `frame_jit::site_forward_fits`): its target's evaluation. + if missing == 0 && code_rc.has_varargs && Self::core_all_droppable(ops) { + let first = if matches!(ops.get(1)?, Object::Unbound) { + 2 + } else { + 1 + }; + return self.forward_pure_call(f, &ops[first..], true); + } return None; } if missing > 0 @@ -24366,7 +27207,10 @@ impl Interpreter { // `PyFunction::code`); only compared and borrowed below, while the // caller's stack keeps the function alive. let code_rc: &Rc = unsafe { &*f.code.as_ptr() }; - if !code_is_pure_leaf(code_rc) || !pure_leaf_warm(code_rc) || !Self::leaf_code_ok(code_rc) { + // (No warm-up gate: the evaluation's own bookkeeping sends the call + // that makes the callee due to the framed path, see + // `Self::leaf_call_entry`.) + if !code_is_pure_leaf(code_rc) || !Self::leaf_code_ok(code_rc) { return None; } let (_, covered) = Self::kw_names_bind_cached(code, pc, f, func_id, perm, names, eff_argc)?; @@ -24392,7 +27236,19 @@ impl Interpreter { args[k] = o; } let kw_vals = &ops[first + eff_argc..ops.len() - 1]; - let mut varkw: Option = None; + // A `**kwargs` dictionary that can't outlive the evaluation is the + // spare one tier 2's keyword calls keep (see `recycle_kw_dict`). + let stays = code_rc.has_varkeywords && varkw_stays_local(code_rc); + let mut varkw = code_rc.has_varkeywords.then(|| { + if stays { + spare_kw_dict(kw_vals.len()) + } else { + Rc::new(RefCell::new(DictData::with_capacity_and_hasher( + kw_vals.len(), + crate::fasthash::FxBuildHasher, + ))) + } + }); // The caller releases the operands in call order. Keywords given out // of their parameters' order, when one dies with the call, take the // activation, whose locals go in the parameters' order. @@ -24409,16 +27265,15 @@ impl Interpreter { for (j, o) in kw_vals.iter().enumerate() { let slot = ((perm >> (4 * j)) & 0xF) as usize; if slot == specialize::KW_TO_VARKW as usize { - // Collected into a fresh dictionary, in call order (the - // bind check proved the callee has one). - varkw - .get_or_insert_with(|| { - DictData::with_capacity_and_hasher( - kw_vals.len(), - crate::fasthash::FxBuildHasher, - ) - }) - .insert(DictKey(names.get(j)?.clone()), o.clone()); + // Collected into the dictionary, in call order (the bind + // check proved the callee has one). A call's keyword names + // are distinct (the compiler rejects a repeat), so each is + // appended without a probe (into a dictionary only the call + // holds yet). + let d = varkw.as_mut().and_then(Rc::get_mut)?.get_mut(); + let key = DictKey(names.get(j)?.clone()); + let hash = crate::dictmap::Probe::probe_hash(&key); + d.insert_unique_hashed(hash, key, o.clone()); continue; } if slot >= total { @@ -24432,12 +27287,18 @@ impl Interpreter { } } leaf_kwonly_defaults(f, code_rc, &mut args, covered)?; - let dict; - if code_rc.has_varkeywords { - dict = Object::Dict(Rc::new(RefCell::new(varkw.unwrap_or_default()))); - args[total] = &raw const dict; + let dict = varkw.map(Object::Dict); + if let Some(d) = &dict { + if !stays { + gc_trace::track_built(d); + } + args[total] = d; } - self.pure_leaf_eval::(code_rc, f, &args[..arity]) + let result = self.pure_leaf_eval::(code_rc, f, &args[..arity]); + if let (true, Some(Object::Dict(d))) = (stays, dict) { + recycle_kw_dict(d); + } + result } /// A tier-2 keyword call (the `CALL_KW` at `pc` of `caller`) of the warm @@ -24480,7 +27341,10 @@ impl Interpreter { // SAFETY: GIL-serialized raw read of the function's code cell; the // caller keeps the function alive across the evaluation. let code_rc: &Rc = unsafe { &*f.code.as_ptr() }; - if !code_is_pure_leaf(code_rc) || !pure_leaf_warm(code_rc) || !Self::leaf_code_ok(code_rc) { + // (No warm-up gate: the evaluation's own bookkeeping sends the call + // that makes the callee due to the framed path, see + // `Self::leaf_call_entry`.) + if !code_is_pure_leaf(code_rc) || !Self::leaf_code_ok(code_rc) { return None; } let (_, covered) = @@ -24505,18 +27369,17 @@ impl Interpreter { // The `**kwargs` dictionary is built where it lives: no move of a // filled table into its cell. It reuses the last call's when that // one didn't escape (see `recycle_kw_dict`). - let varkw = code_rc - .has_varkeywords - .then(|| Object::Dict(spare_kw_dict(kwc))); + let mut spare = code_rc.has_varkeywords.then(|| spare_kw_dict(kwc)); for (j, o) in vals[eff_argc..].iter().enumerate() { let slot = ((perm >> (4 * j)) & 0xF) as usize; if slot == specialize::KW_TO_VARKW as usize { - // The bind check proved the callee collects it. - let Some(Object::Dict(d)) = &varkw else { - return None; - }; - d.borrow_mut() - .insert(DictKey(names.get(j)?.clone()), o.clone()); + // The bind check proved the callee collects it. (Distinct + // names, appended without a probe into a dictionary only + // the call holds yet: see `core_pure_kw_call`.) + let d = spare.as_mut().and_then(Rc::get_mut)?.get_mut(); + let key = DictKey(names.get(j)?.clone()); + let hash = crate::dictmap::Probe::probe_hash(&key); + d.insert_unique_hashed(hash, key, o.clone()); continue; } if slot >= total { @@ -24530,6 +27393,7 @@ impl Interpreter { } } leaf_kwonly_defaults(f, code_rc, &mut args, covered)?; + let varkw = spare.map(Object::Dict); if let Some(d) = &varkw { args[total] = d; } @@ -24565,7 +27429,6 @@ impl Interpreter { if arity > 8 || locals.len() < arity || !code_is_pure_leaf(code_rc) - || !pure_leaf_warm(code_rc) || !Self::leaf_code_ok(code_rc) || crate::recursion::current_depth() >= crate::recursion::recursion_limit() { @@ -24578,6 +27441,41 @@ impl Interpreter { self.pure_leaf_eval::(code_rc, f, &args[..arity]) } + /// [`Self::leaf_cached_instance_field`] for a class the site's cache + /// isn't for: the instance's own value at the position the site's + /// polymorphic entries give for the class's version (see [`AttrPoly`]), + /// where the name still sits. An entry is recorded only by a full + /// lookup that found the name in an instance's dict with no data + /// descriptor of the class ahead of it, which holds for as long as the + /// class reads that version; an instance value wins over anything else + /// the class has. (A getter read for two classes in turn otherwise + /// takes the general resolution for every read of the second.) + /// + /// # Safety + /// + /// As [`Self::leaf_cached_instance_field`]'s. + #[inline(never)] + unsafe fn leaf_poly_field<'a>( + ext: &CodeConstObjects, + code: &CodeObject, + inst: &'a PyInstance, + cache_pc: u32, + name_idx: u32, + ) -> Option<&'a Object> { + let ver = inst.cls_raw().attr_version.get(); + let ix = ext.attr_poly_slot(cache_pc as usize)?.index(ver)?; + if ix & SLOT_FIELD != 0 { + // A `__slots__` member's place in the class's layout (see + // `leaf_attr_resolve_site`), while the instance is laid out + // over it and holds a value there. + // SAFETY: the caller keeps this rooted read callback-free. + return unsafe { inst.laid_out_slot((ix & !SLOT_FIELD) as usize) }; + } + // SAFETY: as above. + let (key, value) = unsafe { inst.attr_peek_index(ix as usize) }?; + slot_name_matches_in(&ext.name_objs, code, name_idx, key).then_some(value) + } + /// Borrow a guarded instance-dictionary or slot cache hit. `names` is /// the code's interned name objects (see [`slot_name_matches_in`]). /// @@ -24607,14 +27505,22 @@ impl Interpreter { return Some(v); } let names: &[Object] = &ext.name_objs; + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 { + return None; + } let (key_idx, cached, is_slot) = match code.caches.get(cache_pc) { IC::LoadAttrInstance { key_idx, ver } => (key_idx, ver, false), IC::LoadAttrSlot { key_idx, ver } => (key_idx, ver, true), - _ => return None, + // (A site the interpreter never specialized has no entries.) + IC::Empty => return None, + // A site whose cache gave way to a second class (a cooldown). + // SAFETY: forwarded contract. + _ => return unsafe { Self::leaf_poly_field(ext, code, inst, cache_pc, name_idx) }, }; - let cls = inst.cls_raw(); - if cls.native_kind.get() != 0 || cls.attr_version.get() != cached { - return None; + if cls.attr_version.get() != cached { + // SAFETY: forwarded contract. + return unsafe { Self::leaf_poly_field(ext, code, inst, cache_pc, name_idx) }; } if !is_slot { // SAFETY: the caller keeps this rooted read callback-free. @@ -24845,16 +27751,21 @@ impl Interpreter { nest: u8, ) -> Option { let ext = code_vm_ext(code)?; - if ext.pure_leaf.load(std::sync::atomic::Ordering::Relaxed) >= 3 { - return self - .leaf_eval::(code, f, args, nest) - .map(leaf_plan::LeafRet::Owned); + let r = if ext.pure_leaf.load(std::sync::atomic::Ordering::Relaxed) >= 3 { + self.leaf_eval::(code, f, args, nest) + .map(leaf_plan::LeafRet::Owned) + } else { + let plan = ext + .leaf_plan + .get_or_init(|| leaf_plan::build(code, ext).map(Box::new)) + .as_deref()?; + self.leaf_run_ret::(code, ext, plan, f, args, nest) + }; + #[cfg(feature = "jit")] + if r.is_some() { + note_leaf_warm(ext); } - let plan = ext - .leaf_plan - .get_or_init(|| leaf_plan::build(code, ext).map(Box::new)) - .as_deref()?; - self.leaf_run_ret::(code, ext, plan, f, args, nest) + r } /// [`Self::leaf_eval`] of a callee certified as one of the tiny @@ -26514,6 +29425,11 @@ impl Interpreter { let shell = self.push_lean_shell(&done.frame, done.frame.pc); done.act.shell = Some(shell); } + let mut tmp = None; + // SAFETY: the caller is the innermost remaining activation. + let (cframe, clast, _) = unsafe { sw.activation(depth - 1, &mut tmp) }; + // SAFETY: as above. + let hook = Self::attr_hook_receiver(unsafe { &*cframe }, &done, true); let result = self.inline_finish( &mut done, QuietExit::Outcome { @@ -26522,9 +29438,8 @@ impl Interpreter { }, ); done.clean = false; - let mut tmp = None; - // SAFETY: the caller is the innermost remaining activation. - let (cframe, clast, _) = unsafe { sw.activation(depth - 1, &mut tmp) }; + // SAFETY: as above. + self.attr_hook_context(unsafe { &*cframe }, done.call_pc, &result, hook); // SAFETY: as above. let entry = unsafe { self.inline_deliver(&mut *cframe, done, result) }; sw.cur = cframe; @@ -27153,12 +30068,16 @@ impl Interpreter { /// `__dict__` is the default member. Valid while the class's attribute /// version holds. pub(crate) fn managed_dict_attr(cls: &TypeObject) -> bool { + // (The two lookups by name memoized: the interpreter asks at every + // `x.__dict__` read, 280 instructions a read otherwise.) cls.has_managed_dict() && Self::default_getattribute(cls) - && cls.lookup("__getattr__").is_none() - && cls - .lookup("__dict__") - .is_some_and(|m| crate::builtins::class_of(&m).name == "member_descriptor") + && cls.memo_verdict(crate::types::Verdict::ManagedDict, "", || { + cls.lookup("__getattr__").is_none() + && cls + .lookup("__dict__") + .is_some_and(|m| crate::builtins::class_of(&m).name == "member_descriptor") + }) } /// `f.name` or `f.name = v` (`ins`, a `LOAD_ATTR` without the method @@ -27385,17 +30304,39 @@ impl Interpreter { let (Object::Type(cls), Object::Unbound) = (ops.first()?, ops.get(1)?) else { return None; }; + // `SomeEnum(value)` of a member's value: the member. + if !kw && argc == 1 && !cls.flags.is_builtin && !Self::plain_metaclass(cls) { + if let Some(m) = Self::enum_value_member(cls, ops.get(2)?) { + return Some(m); + } + } + // A class with a native constructor of its own (`defaultdict()`). + if !kw && !cls.flags.is_builtin { + if let Some(pure) = cls.pure_new.get() { + if let Some(v) = pure(cls, ops.get(2..2 + argc)?) { + return Some(v); + } + } + } if cls.native_kind.get() == 0 { // The exact `itertools` classes: their native adapters, when // building one runs no code. (A builtin type's call is // `core_builtin_ctor`'s, which every caller tries as well.) - if kw || cls.flags.is_builtin || cls.lazy_ctor.get() == 0 { + if cls.flags.is_builtin || cls.lazy_ctor.get() == 0 { return None; } let args = ops.get(2..2 + argc)?; if !Self::core_all_droppable(ops) { return None; } + // (`product(xs, repeat=2)`: the keyword values, then the names.) + if kw { + let Object::Tuple(names) = ops.last()? else { + return None; + }; + let values = ops.get(2 + argc..2 + argc + names.len())?; + return crate::stdlib::itertools_mod::native_new_pure_kw(cls, args, names, values); + } return crate::stdlib::itertools_mod::native_new_pure(cls, args); } let args = ops.get(2..2 + argc)?; @@ -27413,6 +30354,124 @@ impl Interpreter { crate::stdlib::datetime_native::construct_names(cls, args, names, values)?.ok() } + /// `cls(*args, **kwargs)` (the core loop's `CALL_KW` operands) of a + /// class with a pure constructor whose keywords name its next + /// positional parameters, in order (`deque(xs, maxlen=5)`, see + /// [`TypeObject::pure_new_kw`]): that constructor's call with the + /// keyword values in their places (they follow the positional + /// arguments on the stack). `None` for anything else. + #[inline(never)] + pub(crate) fn core_pure_new_kw(ops: &[Object], argc: usize) -> Option { + let (Object::Type(cls), Object::Unbound, Object::Tuple(names)) = + (ops.first()?, ops.get(1)?, ops.last()?) + else { + return None; + }; + let pure = cls.pure_new.get()?; + let params = *cls.pure_new_kw.get()?; + let all = ops.get(2..ops.len() - 1)?; + if all.len() != argc + names.len() + || all.len() > params.len() + || !names + .iter() + .zip(¶ms[argc..]) + .all(|(n, p)| matches!(n, Object::Str(s) if s.as_ref() == *p)) + { + return None; + } + pure(cls, all) + } + + /// `cls(value)` of an enum class whose metaclass's `__call__` and + /// whose `__new__` are `enum`'s own (`EnumType.__call__`, + /// `Enum.__new__`), with members: `value` itself when it is a member + /// of exactly `cls`, else the member `_value2member_map_` holds for a + /// value that hashes and compares natively, as `Enum.__new__` finds + /// it. `None` for anything else (a miss, an unhashable value, a + /// `_missing_` hook's case), which the Python call decides. + fn enum_value_member(cls: &Rc, value: &Object) -> Option { + type Maps = ( + crate::sync::Weak>, + crate::sync::Weak>, + ); + thread_local! { + /// The last enum class answered for, under its and its + /// metaclass's versions, with its member maps. + static MEMO: RefCell> = const { RefCell::new(None) }; + } + // SAFETY: GIL-serialized raw read, as in `plain_metaclass`. + let meta = unsafe { (*cls.metaclass.as_ptr()).as_ref() }?; + if meta.c_ext_ptr.get() != 0 || crate::object::exotic_str_keys_possible() { + return None; + } + let key = ( + Rc::as_ptr(cls) as usize, + cls.attr_version.get(), + meta.attr_version.get(), + ); + let lookup = |members: &Rc>, v2m: &Rc>| { + if members.try_borrow().ok()?.is_empty() { + return None; + } + if let Object::Instance(i) = value { + if std::ptr::eq(i.cls_raw(), Rc::as_ptr(cls)) { + return Some(value.clone()); + } + } + let probe = crate::object::LeafProbe::new(value)?; + let m = v2m.try_borrow().ok()?; + m.get(&probe).cloned() + }; + let hit = MEMO.with(|m| { + let m = m.try_borrow().ok()?; + let (p, v, mv, (members, v2m)) = m.as_ref()?; + ((*p, *v, *mv) == key && key.1 != 0) + .then(|| Some((members.upgrade()?, v2m.upgrade()?))) + .flatten() + }); + if let Some((members, v2m)) = hit { + return lookup(&members, &v2m); + } + let is_enum_fn = |f: &Rc, qualname: &str| { + // SAFETY: GIL-serialized raw read of the function's code cell. + let code: &CodeObject = unsafe { &*f.code.as_ptr() }; + code.qualname == qualname + && f.globals.try_borrow().is_ok_and(|g| { + matches!( + g.get(&crate::object::StrKey("__name__")), + Some(Object::Str(n)) if &**n == "enum" + ) + }) + }; + match meta.lookup("__call__") { + Some(Object::Function(f)) if is_enum_fn(&f, "EnumType.__call__") => {} + _ => return None, + } + match cls.lookup("__new__") { + Some(Object::Function(f)) if is_enum_fn(&f, "Enum.__new__") => {} + _ => return None, + } + let Some(Object::Dict(members)) = cls.lookup("_member_map_") else { + return None; + }; + let Some(Object::Dict(v2m)) = cls.lookup("_value2member_map_") else { + return None; + }; + // (The maps are the class's attributes: a new one moves its + // version.) + MEMO.with(|m| { + if let Ok(mut m) = m.try_borrow_mut() { + *m = Some(( + key.0, + key.1, + key.2, + (Rc::downgrade(&members), Rc::downgrade(&v2m)), + )); + } + }); + lookup(&members, &v2m) + } + /// A keyword call of a natively served method (see /// [`crate::stdlib::decimal_native::method_kw`]): `ops` is the core /// loop's `CALL_KW` operands. The result, or `None` (nothing touched) @@ -27430,14 +30489,111 @@ impl Interpreter { /// handler builds it from their strings. `ops` is the core loop's /// `CALL_KW` operands; `None` (nothing touched) for the full handler. #[inline(never)] + /// `d.update(k=v, ...)` of an exact dict, keywords only: each keyword's + /// own name object stored as [`builtins::dict_insert_exact`] stores a + /// key (whose probe runs no code), the result `None`. `None` for the + /// full call, which a store declined partway repeats in full: storing + /// the same keywords again leaves the same dict. + pub(crate) fn core_dict_update_kw(ops: &[Object], argc: usize) -> Option { + let d = match (ops.first()?, ops.get(1)?) { + (Object::BoundMethod(bm), Object::Unbound) if !bm.redispatch_descriptor => { + match (&bm.function, &bm.receiver) { + (Object::Builtin(b), Object::Dict(d)) + if b.binds_instance && b.name == "update" => + { + d + } + _ => return None, + } + } + (Object::Builtin(b), Object::Dict(d)) if b.binds_instance && b.name == "update" => d, + _ => return None, + }; + let Object::Tuple(names) = ops.last()? else { + return None; + }; + if argc != 0 || ops.len() != names.len() + 3 || crate::trace::any_observers_active() { + return None; + } + for (name, v) in names.iter().zip(&ops[2..2 + names.len()]) { + if !matches!(name, Object::Str(_)) { + return None; + } + match builtins::dict_insert_exact(d, name.clone(), v.clone()) { + Ok(old) => drop(old), + Err(_) => return None, + } + } + Some(Object::None) + } + + /// `types.SimpleNamespace(k=v, ...)` (the exact class, keywords only): + /// a namespace over [`Self::core_dict_kw`]'s dictionary, as its + /// constructor builds it. + pub(crate) fn core_namespace_kw(ops: &[Object]) -> Option { + let Object::Dict(d) = Self::core_dict_kw(ops)? else { + return None; + }; + let ns = Object::SimpleNamespace(d); + gc_trace::track(&ns); + Some(ns) + } + fn core_dict_kw(ops: &[Object]) -> Option { let (Object::Unbound, Some(Object::Tuple(names))) = (ops.get(1)?, ops.last()) else { return None; }; - if ops.len() != names.len() + 3 { + match ops.len().checked_sub(names.len() + 3)? { + 0 => Self::dict_of_keywords(names, &ops[2..2 + names.len()]), + 1 => Self::dict_copy_with_keywords(&ops[2], names, &ops[3..3 + names.len()]), + _ => None, + } + } + + /// `dict(d, k=v, ...)` of an exact dict `d`: its table copied once, as + /// CPython's merge copies an exact dict's, and each keyword's name put + /// in as its key, the probe settled natively. `None` for another first + /// argument, a name that isn't a `str`, a probe that would compare by + /// `__eq__`, or while an allocation observer or a due collection wants + /// the full handler. + fn dict_copy_with_keywords( + src: &Object, + names: &[Object], + values: &[Object], + ) -> Option { + let Object::Dict(src) = src else { + return None; + }; + if names.len() != values.len() + || crate::stdlib::tracemalloc_real::is_tracking() + || crate::stdlib::testinternalcapi_mod::reftrace_print_active() + || gc_trace::auto_collect_due() + { return None; } - Self::dict_of_keywords(names, &ops[2..2 + names.len()]) + let mut d = src.try_borrow().ok()?.clone(); + for (name, v) in names.iter().zip(values) { + if !matches!(name, Object::Str(_)) { + return None; + } + let probe = crate::object::LeafProbe::new(name)?; + match d.probe_entry(&probe) { + crate::dictmap::ProbeEntry::Occupied(e) => { + // (The value it replaces is the source's too: only a + // count goes.) + drop(std::mem::replace(e.into_mut(), v.clone())); + } + crate::dictmap::ProbeEntry::Vacant(e) => { + if !probe.miss_is_exact() { + return None; + } + e.insert(DictKey(name.clone()), v.clone()); + } + } + } + let obj = Object::Dict(Rc::new(RefCell::new(d))); + gc_trace::track_built(&obj); + Some(obj) } /// The dictionary `dict(**{n: v ...})` makes of a call's keyword @@ -27454,14 +30610,98 @@ impl Interpreter { return None; } let mut d = DictData::with_capacity_and_hasher(names.len(), crate::fasthash::FxBuildHasher); - for (name, v) in names.iter().zip(values) { - d.insert(DictKey(name.clone()), v.clone()); + // Names whose hashes differ pairwise differ too: each goes in + // without the probe for an equal key (a call's keyword names are + // distinct, but a hand-built code object's might not be). + let mut hashes = [0i64; 8]; + let distinct = names.len() <= hashes.len() + && names.iter().enumerate().all(|(k, n)| { + let Object::Str(s) = n else { + return false; + }; + let h = SharedStr::hash_cached(s); + hashes[k] = h; + !hashes[..k].contains(&h) + }); + for (k, (name, v)) in names.iter().zip(values).enumerate() { + if distinct { + d.insert_unique_hashed(hashes[k], DictKey(name.clone()), v.clone()); + } else { + d.insert(DictKey(name.clone()), v.clone()); + } } let obj = Object::Dict(Rc::new(RefCell::new(d))); - gc_trace::track(&obj); + // (Born full: deferred like a built dict, promoted by a collection + // once it can anchor a cycle.) + gc_trace::track_built(&obj); Some(obj) } + /// [`Self::core_native_kw_call`]'s binding of a call with `argc` + /// positionals and the keywords `names` to a registered builtin's + /// parameters `params`: each bound parameter's operand index (the + /// positionals from 2, then the keyword values), [`KW_UNBOUND`] for an + /// optional parameter the call leaves out, and how many parameters the + /// half takes. `None` for a call the half doesn't serve. + fn kw_bind_plan( + params: leaf_builtins::KwNames, + names: &[Object], + argc: usize, + ) -> Option<([u8; KW_MAX], usize)> { + // (A parameter named `*name` is keyword-only: no positional binds + // it, and the half takes `Unbound` where the call leaves it out. One + // named `?name` is optional the same way but may come positionally, + // and one named `/name` is positional-only: no keyword binds it.) + let keyword_only = |p: &str| p.starts_with('*'); + let optional = |p: &str| p.starts_with('*') || p.starts_with('?'); + if params.len() > KW_MAX || params.iter().take(argc).any(|p| keyword_only(p)) { + return None; + } + let mut bound: [Option; KW_MAX] = [None; KW_MAX]; + for (i, slot) in bound.iter_mut().enumerate().take(argc) { + *slot = Some(2 + i as u8); + } + for (j, name) in names.iter().enumerate() { + let Object::Str(name) = name else { + return None; + }; + let name: &str = name; + let i = params.iter().position(|p| { + let bare = match p.as_bytes().first() { + Some(b'/') => return false, + Some(b'*' | b'?') => &p[1..], + _ => p, + }; + bare == name + })?; + if i >= KW_MAX || bound[i].is_some() { + return None; + } + bound[i] = Some((2 + argc + j) as u8); + } + let mut map = [KW_UNBOUND; KW_MAX]; + let n = if params.iter().any(|p| optional(p)) { + for (i, p) in params.iter().enumerate() { + match bound[i] { + Some(at) => map[i] = at, + None if optional(p) => {} + None => return None, + } + } + params.len() + } else { + let n = bound.iter().take_while(|a| a.is_some()).count(); + if bound[n..].iter().any(Option::is_some) { + return None; + } + for (m, a) in map.iter_mut().zip(&bound[..n]) { + *m = a.expect("bound"); + } + n + }; + Some((map, n)) + } + /// A keyword call of a native method registered with /// [`leaf_builtins::register_fast_kw`]: `ops` is the core loop's /// `CALL_KW` operands (the callee, the self slot, the positionals, the @@ -27476,43 +30716,57 @@ impl Interpreter { let Object::Builtin(b) = &bm.function else { return None; }; - (b, &bm.receiver) + (b, Some(&bm.receiver)) } (Object::Builtin(b), recv) if !matches!(recv, Object::Unbound) && b.binds_instance => { - (b, recv) + (b, Some(recv)) } + // A builtin function (`sorted(xs, reverse=True)`). + (Object::Builtin(b), Object::Unbound) if !b.binds_instance => (b, None), _ => return None, }; let Object::Tuple(names) = ops.last()? else { return None; }; let kwc = names.len(); - if ops.len() != argc + kwc + 3 || argc + kwc > 4 || crate::trace::any_observers_active() { + if ops.len() != argc + kwc + 3 + || argc + kwc > KW_MAX + || crate::trace::any_observers_active() + { return None; } - let (params, fast) = leaf_builtins::fast_kw(b)?; - let mut bound: [Option<&Object>; 4] = [None; 4]; - for (i, a) in ops[2..2 + argc].iter().enumerate() { - bound[i] = Some(a); + // The site's binding: each bound parameter's operand (an index into + // `ops`, `UNBOUND` for an optional one the call left out). + let (map, n, fast) = kw_bind_memo(b, ops.last()?, argc, || { + let (params, fast) = leaf_builtins::fast_kw(b)?; + let (map, n) = Self::kw_bind_plan(params, names, argc)?; + Some((map, n, fast)) + })?; + if !Self::core_all_droppable(ops) { + return None; } - for (name, value) in names.iter().zip(&ops[2 + argc..2 + argc + kwc]) { - let Object::Str(name) = name else { - return None; + // Bitwise views of the receiver and the bound arguments, never + // dropped: the leaf half reads them (and clones what it keeps), and + // nothing it runs can reach the operands they alias. + let mut args = [const { std::mem::MaybeUninit::::uninit() }; KW_MAX + 1]; + let first = usize::from(recv.is_some()); + if let Some(recv) = recv { + // SAFETY: a borrowed copy of the live receiver. + args[0].write(unsafe { std::ptr::read(recv) }); + } + let unbound = Object::Unbound; + for (slot, &at) in args[first..].iter_mut().zip(&map[..n]) { + let a = if at == KW_UNBOUND { + &unbound + } else { + ops.get(at as usize)? }; - let i = params.iter().position(|p| *p == name.as_ref())?; - if i >= 4 || bound[i].is_some() { - return None; - } - bound[i] = Some(value); + // SAFETY: a borrowed copy of a live operand (or of `Unbound`). + slot.write(unsafe { std::ptr::read(a) }); } - let n = bound.iter().take_while(|a| a.is_some()).count(); - if bound[n..].iter().any(Option::is_some) || !Self::core_all_droppable(ops) { - return None; - } - let mut args = Vec::with_capacity(n + 1); - args.push(recv.clone()); - args.extend(bound[..n].iter().map(|a| (*a).expect("prefix").clone())); - fast(&args)?.ok() + // SAFETY: the first `n + first` entries were written. + let args = unsafe { std::slice::from_raw_parts(args.as_ptr().cast::(), n + first) }; + fast(args)?.ok() } /// A call of a `functools.lru_cache` wrapper settled natively (see @@ -27844,14 +31098,36 @@ impl Interpreter { return Some(v); } } + // A property the site cached for this class at its version: + // the `LOAD_ATTR` arm's offload evaluates or calls its getter, + // so the full resolution below would only decline (it cost an + // interpreted read ~780 instructions first). + if let Some(ms) = ext.method_slot(attr_pc) { + // SAFETY: a read between two instructions; nothing outlives it. + if unsafe { ms.getter_peek(inst.cls_raw().attr_version.get()) }.is_some() { + return None; + } + } + } + if let Object::BoundMethod(bm) = local { + return Self::leaf_bound_method_read(code, bm, name_idx); } // (Decoded once for the arms below.) let cache = code.caches.get(attr_pc as u32); if let (IC::LoadAttrInstance { key_idx, ver }, Object::Instance(inst)) = (cache, local) { let cls = inst.cls_raw(); - if cls.native_kind.get() != 0 || cls.attr_version.get() != ver { + if cls.native_kind.get() != 0 { return None; } + let now = cls.attr_version.get(); + if now != ver { + // Another class's instance: the site's polymorphic entry + // for it (an instance field's place, recorded by the full + // resolution at this class version), read as the site's + // own class's is below. + return code_attr_poly(code, attr_pc as u32) + .and_then(|poly| poly.hit(code, inst, now, name_idx)); + } let names: &[Object] = ext.map_or(&[], |t| &t.name_objs); // SAFETY: a read between two instructions (see `peek`). let (k, v) = unsafe { inst.attr_peek_index(key_idx as usize) }?; @@ -27871,7 +31147,22 @@ impl Interpreter { }; } match local { - Object::Instance(i) if i.cls_raw().native_kind.get() == 0 => {} + Object::Instance(i) if i.cls_raw().native_kind.get() == 0 => { + // A polymorphic site (its cache cooling down after a + // deopt): the entry for this class first, as above. (A + // property's or a method's site cools down too, with no + // entries: its table answers on one compare.) + if !matches!(cache, IC::LoadAttrSlot { .. }) { + let poly = ext.and_then(|ext| { + warm_site(ext, code, &ext.attr_poly, attr_pc, AttrPoly::empty) + }); + if let Some(v) = poly.and_then(|poly| { + poly.hit(code, i, i.cls_raw().attr_version.get(), name_idx) + }) { + return Some(v); + } + } + } Object::Module(_) => {} _ => return None, } @@ -28342,7 +31633,7 @@ impl Interpreter { value: &Object, ) -> bool { let cls = inst.cls_raw(); - Self::plain_store_class(code, inst, name_idx) + (Self::plain_store_class(code, inst, name_idx) && Self::core_store_new_attr( code, inst, @@ -28351,7 +31642,45 @@ impl Interpreter { name_idx, cls.attr_version.get(), value, - ) + )) + // (A `__slots__` member, which the plain store declines.) + || Self::leaf_slot_store(code, inst, attr_pc, name_idx, value) + } + + /// `inst.name = value` into a `__slots__` member of a class the + /// site's cache doesn't serve (a setter shared by several slotted + /// classes): the member's store, in place, when the class stores + /// `name` there by the default `__setattr__`. As `core_store_attr`: + /// on `true` the value moved, `false` touched nothing. + fn leaf_slot_store( + code: &CodeObject, + inst: &Rc, + attr_pc: usize, + name_idx: u32, + value: &Object, + ) -> bool { + let Some(Object::Str(name)) = code_name_obj(code, name_idx) else { + return false; + }; + let Some(i) = Self::slot_store_position(inst, name) else { + return false; + }; + // SAFETY: a store between two instructions (see `peek_mut`). + let Some(slot) = (unsafe { inst.laid_out_slot_mut(i, value.is_gc_atomic()) }) else { + return false; + }; + if !Self::core_droppable(slot) { + return false; + } + // SAFETY: the value moves out of the caller's stack slot, as in + // `core_store_attr`. + drop(std::mem::replace(slot, unsafe { std::ptr::read(value) })); + // (The site's shortcut to the member, for the class: a setter that + // only ever runs frameless fills no cache otherwise.) + if let Some(ext) = code_vm_ext(code) { + slot_field_note_with(code, ext, attr_pc, inst, i as u32, name_idx, false); + } + true } /// Whether [`Self::leaf_attr_store`] would perform this store right @@ -28365,6 +31694,51 @@ impl Interpreter { Self::core_store_attr_ready(code, inst, attr_pc, name_idx) || (Self::plain_store_class(code, inst, name_idx) && Self::store_new_attr_ready(code, inst, name_idx)) + || Self::leaf_slot_store_ready(code, inst, name_idx) + } + + /// Where `inst.name = …` stores in `inst`'s laid-out slots when its + /// class stores `name` in a `__slots__` member by the default + /// `__setattr__` (see [`Self::leaf_slot_store`]): the member's + /// position in the class's slot layout. + fn slot_store_position(inst: &PyInstance, name: &str) -> Option { + let cls = inst.cls_raw(); + // (The layout first: most stores that reach here are a property's + // or a class without slots, which a scan of a few names settles.) + let layout = cls.slot_layout.get().and_then(Option::as_ref)?; + let i = layout + .iter() + .position(|k| matches!(&k.0, Object::Str(s) if &**s == name))?; + if crate::object::exotic_str_keys_possible() + || inst.c_body.get() != 0 + || cls.native_kind.get() != 0 + || crate::capi_watchers::dicts_active() + || !cls.memo_verdict(crate::types::Verdict::SlotStore, name, || { + !cls.flags.is_builtin + && cls.setattr_is_default() + && matches!( + cls.lookup(name), + Some(Object::SlotDescriptor(s)) + if s.name == name && s.default.is_none() && !s.readonly + ) + }) + { + return None; + } + Some(i) + } + + /// Whether [`Self::leaf_slot_store`] would store right now, touching + /// nothing. + fn leaf_slot_store_ready(code: &CodeObject, inst: &PyInstance, name_idx: u32) -> bool { + let Some(Object::Str(name)) = code_name_obj(code, name_idx) else { + return false; + }; + let Some(i) = Self::slot_store_position(inst, name) else { + return false; + }; + // SAFETY: an unused view with nothing running. + unsafe { inst.laid_out_slot_any(i) }.is_some_and(Self::core_droppable) } /// The constructor shape of [`Self::core_store_attr`]: a @@ -28941,6 +32315,15 @@ impl Interpreter { Err(_) => break, } } + // (`"%s" % SomeStrEnum.A`: see `percent_format_payloads`.) + (Object::Str(a), args) + if kind == BinOpKind::Mod && percent_payload_args(args) => + { + match percent_format_payloads(a, args) { + Some(s) => Object::from_str(s), + None => break, + } + } (Object::Str(a), args @ Object::Dict(d)) if kind == BinOpKind::Mod && Rc::strong_count(d) > 1 => { @@ -29018,9 +32401,7 @@ impl Interpreter { a.partial_cmp(b) } (Object::Str(a), Object::Str(b)) => Some(a.as_bytes().cmp(b.as_bytes())), - (Object::Instance(i), Object::Instance(_)) - if i.cls_raw().native_kind.get() != 0 => - { + (Object::Instance(i), _) if i.cls_raw().native_kind.get() != 0 => { // Natively served operands (see // `stdlib::datetime_native`): the result is // already the answer. @@ -29089,7 +32470,11 @@ impl Interpreter { last = pc; pc += 1 + ins.arg as usize; } - OpCode::Nop | OpCode::NotTaken | OpCode::Resume | OpCode::CopyFreeVars => { + OpCode::Nop + | OpCode::NotTaken + | OpCode::Resume + | OpCode::CopyFreeVars + | OpCode::AsyncGenWrap => { last = pc; pc += 1; } @@ -29401,7 +32786,7 @@ impl Interpreter { break; }; let items: Vec = match &stack[n - 4] { - Object::Tuple(t) => t.to_vec(), + Object::Tuple(t) => crate::object::cloned_vec(t), Object::List(l) => match l.try_borrow() { Ok(l) => l.clone(), Err(_) => break, @@ -29513,7 +32898,7 @@ impl Interpreter { break; }; let items: Vec = match src { - Object::Tuple(t) => t.to_vec(), + Object::Tuple(t) => crate::object::cloned_vec(t), Object::List(l) if !Rc::ptr_eq(l, dst) => match l.try_borrow() { Ok(l) => l.clone(), Err(_) => break, @@ -29631,7 +33016,9 @@ impl Interpreter { for x in items[mid_end..].iter().rev() { stack.push(x.clone()); } - stack.push(Object::new_list(items[before..mid_end].to_vec())); + let mid = Object::new_list(crate::object::cloned_vec(&items[before..mid_end])); + gc_trace::track_built(&mid); + stack.push(mid); for x in items[..before].iter().rev() { stack.push(x.clone()); } @@ -29677,7 +33064,7 @@ impl Interpreter { } let items = stack.split_off(stack.len() - n); let obj = Object::new_list(items); - gc_trace::track(&obj); + gc_trace::track_built(&obj); stack.push(obj); last = pc; pc += 1; @@ -29692,7 +33079,7 @@ impl Interpreter { break; } let obj = Object::Set(Rc::new(RefCell::new(crate::object::SetData::default()))); - gc_trace::track(&obj); + gc_trace::track_built(&obj); stack.push(obj); last = pc; pc += 1; @@ -29729,7 +33116,7 @@ impl Interpreter { } stack.truncate(split); let obj = Object::Dict(Rc::new(RefCell::new(d))); - gc_trace::track(&obj); + gc_trace::track_built(&obj); stack.push(obj); last = pc; pc += 1; @@ -29764,14 +33151,25 @@ impl Interpreter { break; }; let str_keys = |d: &DictData| d.keys().all(|k| matches!(k.0, Object::Str(_))); - if !str_keys(&s) - || !str_keys(&t) - || (ins.arg & 1 != 0 && s.keys().any(|k| t.contains_key(k))) - { + if crate::capi_watchers::dicts_active() { break; } - for (k, v) in s.iter() { - t.insert(k.clone(), v.clone()); + if t.is_empty() && (ins.arg & 1 == 0 || str_keys(&s)) { + // (`{**d}`, `f(**kw)` into an empty dict: the source's + // table copied whole, its keys hashed already and + // none repeated, so nothing compares them.) + let map: &mut crate::object::DictMap = &mut t; + map.clone_from(&s); + } else { + if !str_keys(&s) + || !str_keys(&t) + || (ins.arg & 1 != 0 && s.keys().any(|k| t.contains_key(k))) + { + break; + } + for (k, v) in s.iter() { + t.insert(k.clone(), v.clone()); + } } drop((t, s)); drop(stack.pop().expect("length checked above")); @@ -29964,6 +33362,47 @@ impl Interpreter { let v = std::mem::replace(value_slot, Object::Unbound); std::mem::replace(slot, v) } + // `xs[a:b] = ys` with constant bounds (the compiler + // folds them into one slice constant): the splice + // `STORE_SLICE`'s arm makes, for a step-less slice + // of int or omitted bounds and an exact list or + // tuple value, which stays in its slot. + (Object::List(dst), Object::Slice(sl)) + if matches!(sl.step, Object::None) => + { + let bound = |o: &Object| match o { + Object::None => Some(None), + Object::Int(i) => Some(Some(*i)), + _ => None, + }; + let (Some(start), Some(stop)) = (bound(&sl.start), bound(&sl.stop)) + else { + break; + }; + let items: Vec = match &*value_slot { + Object::Tuple(t) => crate::object::cloned_vec(t), + Object::List(l) => match l.try_borrow() { + Ok(l) => l.clone(), + Err(_) => break, + }, + _ => break, + }; + let Ok(mut d) = dst.try_borrow_mut() else { + break; + }; + let len = d.len() as i64; + let clamp = |i: Option, dflt: i64| { + let i = i.unwrap_or(dflt); + let i = if i < 0 { i + len } else { i }; + i.clamp(0, len) as usize + }; + let a = clamp(start, 0); + let b = clamp(stop, len).max(a); + let removed: Vec = d.splice(a..b, items).collect(); + drop(d); + drop(removed); + Object::Unbound + } (Object::Dict(cell), key) => { if crate::capi_watchers::dicts_active() { break; @@ -30590,6 +34029,9 @@ impl Interpreter { return Some(found); } let member = Self::leaf_contains_eq; + // (Asked by two arms below: answered once.) + let hash_native = std::cell::OnceCell::new(); + let hash_native = || *hash_native.get_or_init(|| Self::leaf_hash_native(item)); match container { Object::List(l) => { // SAFETY: a read between two instructions (the member test @@ -30610,6 +34052,21 @@ impl Interpreter { } Some(false) } + // `n in range(...)` for a machine int: the arithmetic test + // CPython's `range_contains_long` makes, with no iteration. + Object::Range(r) => match item { + Object::Int(v) if r.big.is_none() => { + let (v, start, stop, step) = (i128::from(*v), r.start, r.stop, r.step); + Some(if step > 0 { + start <= v && v < stop && (v - start) % step == 0 + } else if step < 0 { + stop < v && v <= start && (start - v) % -step == 0 + } else { + false + }) + } + _ => None, + }, // `sub in s`: a substring search runs no Python — the // needle must be a `str`, and a non-`str` needle's TypeError // belongs to the full handler. @@ -30618,28 +34075,42 @@ impl Interpreter { _ => None, }, // A key whose Python `__hash__` evaluates as a pure leaf, found - // only as itself (any other key with its hash declines). + // as itself or, for a stored key of the same hash, by a + // `__eq__` that evaluates as a pure leaf too (stored key first, + // as CPython compares; see `object::leaf_instance_probe`). Any + // other comparison declines. Object::Dict(_) | Object::Set(_) | Object::FrozenSet(_) - if matches!(item, Object::Instance(_)) && !Self::leaf_hash_native(item) => + if matches!(item, Object::Instance(_)) && !hash_native() => { // SAFETY: the running thread's interpreter, under the GIL; - // the evaluation runs no Python and takes no frame. + // the evaluations run no Python and take no frame. let interp = unsafe { &*crate::vm_singletons::current_interpreter_ptr()? }; - let probe = - crate::object::LeafProbe::with_hash(item, interp.leaf_instance_hash(item)?); + let hash = interp.leaf_instance_hash(item)?; + let probe = crate::object::LeafProbe::with_hash(item, hash); + let declined = std::cell::Cell::new(false); + let eq = interp.leaf_eq_match(item, &declined); + // SAFETY: (each) a read between two instructions; the probe + // and the pure comparisons run no code. let found = match container { - // SAFETY: as below (the probe runs no code). - Object::Dict(d) => unsafe { d.peek() }?.get_index_of(&probe).is_some(), - // SAFETY: as below. - Object::Set(st) => unsafe { st.peek() }?.get_index_of(&probe).is_some(), - Object::FrozenSet(fs) => fs.get_index_of(&probe).is_some(), + Object::Dict(d) => { + let m = unsafe { d.peek() }?; + m.get_index_of(&probe).is_some() + || (!probe.miss_is_exact() && m.find_by_hash(hash, eq).is_some()) + } + Object::Set(st) => { + let m = unsafe { st.peek() }?; + m.get_index_of(&probe).is_some() + || (!probe.miss_is_exact() && m.find_by_hash(hash, eq).is_some()) + } + Object::FrozenSet(fs) => { + fs.get_index_of(&probe).is_some() + || (!probe.miss_is_exact() && fs.find_by_hash(hash, eq).is_some()) + } _ => return None, }; - (found || probe.miss_is_exact()).then_some(found) + (!declined.get()).then_some(found) } - Object::Dict(_) | Object::Set(_) | Object::FrozenSet(_) - if Self::leaf_hash_native(item) => - { + Object::Dict(_) | Object::Set(_) | Object::FrozenSet(_) if hash_native() => { // A `str`, `int`, or identity-hashed key settles natively // (see `LeafProbe`). if let Some(probe) = crate::object::LeafProbe::new(item) { @@ -30672,6 +34143,85 @@ impl Interpreter { // A class's `__dict__` view (`'__dict__' in type.__dict__`, as // `inspect` asks) tests the class dict it wraps. Object::MappingProxy(d) => Self::leaf_contains(&Object::Dict(d.clone()), item), + // `x in SomeEnum`: `EnumType.__contains__`'s answer. + Object::Type(t) if !t.metaclass_is_type() => Self::enum_contains(t, item), + // (A dict subclass's view keeps its instance alive, which the + // full handler releases.) + Object::DictView(view) if view.owner.is_none() => match view.kind { + crate::object::DictViewKind::Keys => { + Self::leaf_contains(&Object::Dict(view.dict.clone()), item) + } + // `(k, v) in d.items()`: CPython's `dictitems_contains`, the + // key probed and its value compared with `v`; anything but + // a pair is absent (a tuple subclass's instance declines). + crate::object::DictViewKind::Items => { + let pair = match item { + Object::Tuple(t) if t.len() == 2 => t, + Object::Tuple(_) => return Some(false), + Object::Instance(_) => return None, + _ => return Some(false), + }; + let probe = crate::object::LeafProbe::new(&pair[0])?; + // SAFETY: a read between two instructions (the probe + // runs no code); the value is cloned before comparing. + let found = unsafe { view.dict.peek() }?.get(&probe).cloned(); + match found { + Some(v) => member(&v, &pair[1]), + None => probe.miss_is_exact().then_some(false), + } + } + crate::object::DictViewKind::Values => { + // SAFETY: as above (the member test runs no code). + let d = unsafe { view.dict.peek() }?; + for x in d.values() { + if member(x, item)? { + return Some(true); + } + } + Some(false) + } + }, + // An instance whose class's Python `__contains__` evaluates as a + // pure leaf with a scalar answer (anything else is the full + // path's, which runs it again: nothing observed the first). + Object::Instance(inst) => { + // A builtin subclass's own `__contains__`: its payload's. + if let Some(native) = Self::native_payload_for( + inst, + crate::types::vm_key::NATIVE_CONTAINS, + "__contains__", + ) { + return Self::leaf_contains(native, item); + } + // (A Python `__contains__`, found through the class's + // cache, first: a `ChainMap`'s is native, and its check + // looks the name up uncached.) + let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::CONTAINS), + "__contains__", + ) else { + // A deque of plain items, a `ChainMap` over exact + // dicts, or a number in an `array` (their native + // `__contains__`). + return crate::stdlib::collections_native::deque_contains_fast(inst, item) + .or_else(|| { + crate::stdlib::collections_native::chainmap_contains_fast(inst, item) + }) + .or_else(|| { + crate::stdlib::struct_mod::array_contains_leaf(inst, container, item) + }); + }; + // SAFETY: the running thread's interpreter, under the GIL; + // a pure leaf runs no other Python and takes no frame. + let interp = unsafe { &*crate::vm_singletons::current_interpreter_ptr()? }; + match interp.call_pure_leaf_with(&f, Some(container), std::slice::from_ref(item))? { + Object::Bool(b) => Some(b), + Object::Int(i) => Some(i != 0), + Object::None => Some(false), + _ => None, + } + } _ => None, } } @@ -30687,14 +34237,16 @@ impl Interpreter { } // A `str`, machine `int` or plain class in a set or dict, the // commonest tests (`cls in _atomic_types`), probed in line. + // (And an instance hashed by identity, `obj in seen`.) if let ( Object::Set(_) | Object::FrozenSet(_) | Object::Dict(_), - Object::Str(_) | Object::Int(_) | Object::Type(_), + Object::Str(_) | Object::Int(_) | Object::Type(_) | Object::Instance(_), ) = (container, item) { let probe = match item { Object::Type(t) => crate::object::type_hash_is_identity(t) .then(|| crate::object::LeafProbe::identity_type(item)), + Object::Instance(_) => crate::object::LeafProbe::identity_instance(item), _ => crate::object::LeafProbe::new(item), }; if let Some(probe) = probe { @@ -30743,6 +34295,12 @@ impl Interpreter { (inst.native.get().is_none() && inst.class_dunder(crate::types::Dunder::Hash).object_owner()) || crate::object::int_like_value(inst).is_some() + // (A named tuple of plain items hashes as its tuple.) + || (crate::object::tuple_like_value(inst).is_some() + && inst + .native + .get() + .is_some_and(|t| crate::seqiter::plain_hashable(t, 0))) } _ => false, } @@ -30778,7 +34336,7 @@ impl Interpreter { /// [`Self::leaf_member_eq`] for a membership test (`in`), which settles /// a few more pairs itself rather than through a native comparison. - fn leaf_contains_eq(x: &Object, item: &Object) -> Option { + pub(crate) fn leaf_contains_eq(x: &Object, item: &Object) -> Option { if let Some(eq) = Self::leaf_member_eq(x, item) { return Some(eq); } @@ -30842,7 +34400,7 @@ impl Interpreter { /// registered native leaf builtin (found through the class's leaf /// attribute cache): the length, or `None` for the full path (which /// raises whatever a missing or misbehaving `__len__` must). - fn leaf_instance_len(&self, v: &Object) -> Option { + pub(crate) fn leaf_instance_len(&self, v: &Object) -> Option { use crate::types::LeafAttrKind as K; let Object::Instance(inst) = v else { return None; @@ -30862,16 +34420,16 @@ impl Interpreter { Some(K::Method(w)) => { let f = w.upgrade()?; let code = f.code(); - if !code_is_pure_leaf(&code) - || !pure_leaf_warm(&code) - || crate::recursion::current_depth() >= crate::recursion::recursion_limit() - { + let depth = crate::recursion::current_depth(); + if !code_is_pure_leaf(&code) || depth >= crate::recursion::recursion_limit() { return None; } - return match self.pure_leaf_eval::( + return match self.pure_leaf_call( &code, &f, &[std::ptr::from_ref(v)], + false, + depth, )? { Object::Int(n) if n >= 0 => Some(Object::Int(n)), _ => None, @@ -30913,6 +34471,106 @@ impl Interpreter { } } + /// `container[key] = value` for an instance whose class's Python + /// `__setitem__` is the delegating shape (see + /// [`setitem_delegate_shape`]) over an exact dict attribute: the dict's + /// store, in place, as the method would make it. `false` touched + /// nothing (a key that hashes or compares in Python, a target other + /// than a dict, or a tracer that would see the method run). + pub(crate) fn setitem_delegate(container: &Object, key: &Object, value: &Object) -> bool { + let Object::Instance(inst) = container else { + return false; + }; + let cls = inst.cls_raw(); + if inst.native.get().is_some() + || cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || crate::trace::any_observers_active() + { + return false; + } + let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::SETITEM), + "__setitem__", + ) else { + return false; + }; + // SAFETY: GIL-serialized raw read of the function's code cell. + let code: &CodeObject = unsafe { &*f.code.as_ptr() }; + let Some((name, index)) = setitem_delegate_shape(code) else { + return false; + }; + let Some(attr) = + code_name_obj(code, name).and_then(|name| Self::leaf_getattr_value(container, name)) + else { + return false; + }; + // (`self.maps[0]`: an exact list's or tuple's item in range.) + let target = match (index, attr) { + (None, t) => t, + (Some(i), Object::List(l)) => { + match l.try_borrow().ok().and_then(|v| v.get(i as usize).cloned()) { + Some(t) => t, + None => return false, + } + } + (Some(i), Object::Tuple(t)) => match t.get(i as usize) { + Some(t) => t.clone(), + None => return false, + }, + _ => return false, + }; + if !matches!(target, Object::Dict(_)) { + return false; + } + matches!( + crate::builtins::dict_setitem_leaf(&[target, key.clone(), value.clone()]), + Some(Ok(_)) + ) + } + + /// [`Self::leaf_instance_len`] for a class (`len(SomeEnum)`) whose + /// metaclass's `__len__` is a Python function that evaluates as a pure + /// leaf: its answer in place, found through the metaclass's length + /// cache. `None` for anything else, or an answer `len()` would reject + /// (the full path then runs it, which nothing observed). + fn leaf_class_len(&self, cls: &Rc, v: &Object) -> Option { + use crate::types::LeafAttrKind as K; + if crate::object::exotic_str_keys_possible() { + return None; + } + let meta = cls.metaclass_or_type(); + let key = crate::types::AttrKey::vm(crate::types::vm_key::LEN); + let ver = meta.attr_version.get(); + let f = match meta.leaf_attrs.get(key, ver) { + Some(K::Method(w)) => w.upgrade()?, + Some(_) => return None, + None => { + let kind = match meta.lookup("__len__") { + Some(Object::Function(f)) => K::Method(Rc::downgrade(&f)), + _ => K::Other, + }; + let found = matches!(kind, K::Method(_)); + meta.leaf_attrs.set(key, ver, kind); + return if found { + self.leaf_class_len(cls, v) + } else { + None + }; + } + }; + let code = f.code(); + let depth = crate::recursion::current_depth(); + if !code_is_pure_leaf(&code) || depth >= crate::recursion::recursion_limit() { + return None; + } + match self.pure_leaf_call(&code, &f, &[std::ptr::from_ref(v)], false, depth)? { + Object::Int(n) if n >= 0 => Some(Object::Int(n)), + _ => None, + } + } + /// [`Self::leaf_instance_len`] for a class whose `__len__` is a builtin /// registered with a leaf fast half (see `leaf_builtins::register_fast`; /// the length cache marks it with a `Value`): the half's answer, or @@ -30926,24 +34584,22 @@ impl Interpreter { ) -> Option { use crate::types::LeafAttrKind as K; let key = crate::types::AttrKey::vm(crate::types::vm_key::LEN_FAST); + // (The half itself, cached under the class version, as + // `instance_setitem_leaf` caches `__setitem__`'s.) let fast = match cls.leaf_attrs.get(key, ver) { - Some(K::BuiltinMethod(b)) => match self.leaf_call_kind(b)? { - LeafKind::Fast(f) => f, - _ => return None, - }, + Some(K::LeafFast(f)) => *f, Some(_) => return None, None => { - let kind = match cls.lookup("__len__") { - Some(Object::Builtin(b)) if b.binds_instance => K::BuiltinMethod(b), - _ => K::Other, - }; - let found = matches!(kind, K::BuiltinMethod(_)); - cls.leaf_attrs.set(key, ver, kind); - return if found { - self.leaf_instance_len_fast(cls, ver, v) - } else { - None + let fast = match cls.lookup("__len__") { + Some(Object::Builtin(b)) if b.binds_instance => match self.leaf_call_kind(&b) { + Some(LeafKind::Fast(f)) => Some(f), + _ => None, + }, + _ => None, }; + cls.leaf_attrs + .set(key, ver, fast.map_or(K::Other, K::LeafFast)); + fast? } }; match fast(std::slice::from_ref(v))?.ok()? { @@ -30967,6 +34623,20 @@ impl Interpreter { // SAFETY: the caller's contract. let inst = match (unsafe { &*callee }, unsafe { &*callee.add(1) }) { (Object::Instance(inst), Object::Unbound) => inst, + // A class whose metaclass's `__call__` is a builtin type (a + // `TypedDict`'s `__call__ = dict`): a type binds no receiver, + // so calling the class is calling that type. + (Object::Type(t), Object::Unbound) if !t.metaclass_is_type() => { + let meta = t.metaclass_or_type(); + if let Some(Object::Type(call)) = meta.lookup("__call__") { + if call.flags.is_builtin && Rc::strong_count(t) > 1 { + // SAFETY: the class leaves by a plain decrement + // (something else holds it). + unsafe { drop(callee.replace(Object::Type(call))) }; + } + } + return; + } (Object::BoundMethod(_), Object::Unbound) => { // SAFETY: the caller's contract. unsafe { Self::core_bound_callee(callee) }; @@ -31112,6 +34782,30 @@ impl Interpreter { } } + /// Whether `type(inst).__call__` is `functools.partial`'s native call + /// (see [`Self::instance_call_native`]). + pub(crate) fn instance_calls_partial(inst: &PyInstance) -> bool { + Self::instance_call_native(inst) + .is_some_and(|b| crate::stdlib::functools_mod::is_partial_call(&b)) + } + + /// Whether `type(inst).__call__` is the native call `f` that takes the + /// instance first (see [`Self::instance_call_native`]), by its cached + /// entry alone: `false` until a call has filled it. + #[inline] + pub(crate) fn instance_calls_native( + inst: &PyInstance, + f: *const crate::object::BuiltinFn, + ) -> bool { + use crate::types::LeafAttrKind as K; + let cls = inst.cls_raw(); + let key = crate::types::AttrKey::vm(crate::types::vm_key::CALL_NATIVE); + matches!( + cls.leaf_attrs.get(key, cls.attr_version.get()), + Some(K::BuiltinMethod(b)) if std::ptr::eq(Rc::as_ptr(b), f) + ) + } + /// `type(inst).__call__` when it is a plain Python function, cached /// on the class under its attribute version. #[inline(never)] @@ -31141,7 +34835,150 @@ impl Interpreter { /// `type(inst).` when it is a plain Python function, cached on /// the class under its attribute version at `key` (one of the VM's /// own, see `types::vm_key`; one per dunder). - fn instance_dunder_function( + /// The native `__next__` of `inst`'s class that runs no Python code + /// (as [`instance_native_dunder`] admits one), remembered per class + /// version. `None` for a Python `__next__`, or none. + fn instance_native_next(inst: &PyInstance) -> Option> { + use crate::types::{vm_key, AttrKey, LeafAttrKind as K}; + let cls = inst.cls_raw(); + let key = AttrKey::vm(vm_key::NEXT_NATIVE); + let ver = cls.attr_version.get(); + match cls.leaf_attrs.get(key, ver) { + Some(K::BuiltinMethod(b)) => return Some(b.clone()), + Some(_) => return None, + None => {} + } + if crate::object::exotic_str_keys_possible() { + return None; + } + let found = match cls.lookup("__next__") { + Some(Object::Builtin(b)) if b.binds_instance && !builtin_needs_interp(b.name) => { + Some(b) + } + _ => None, + }; + cls.leaf_attrs.set( + key, + ver, + match &found { + Some(b) => K::BuiltinMethod(b.clone()), + None => K::Other, + }, + ); + found + } + + /// The native `__str__` of `inst`'s class that binds the instance and + /// needs no interpreter handle (`BaseException.__str__`), remembered + /// per class version. `None` for a Python `__str__`, or none. + fn instance_native_str(inst: &PyInstance) -> Option> { + Self::instance_native_special(inst, crate::types::vm_key::STR_NATIVE, "__str__") + } + + /// `str(inst)` (and `format(inst, '')`) of an exception whose class + /// keeps `BaseException.__str__` and `object.__format__`, computed in + /// place when it runs no code of the argument's. `None` for anything + /// else. + pub(crate) fn exc_str_leaf(inst: &Rc) -> Option { + let cls = inst.cls_raw(); + if !cls.flags.is_exception || inst.native.get().is_some() { + return None; + } + // (The class's part of the answer, once per class version.) + if !cls.memo_verdict(crate::types::Verdict::ExcBaseStr, "", || { + Self::exc_base_str_class(inst) + }) { + return None; + } + crate::builtin_types::exc_str_text(inst, true)?.ok() + } + + /// Whether `inst`'s exception class takes `str()` from + /// `BaseException.__str__` and `format()` from `object.__format__` + /// (see [`Self::exc_str_leaf`]). + fn exc_base_str_class(inst: &Rc) -> bool { + Self::class_lacks( + inst.cls_raw(), + crate::types::AttrKey::vm(crate::types::vm_key::FORMAT_LACKS), + "__format__", + ) && Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::STR_FN), + "__str__", + ) + .is_none() + && Self::instance_native_str(inst) + .is_some_and(|b| crate::builtin_types::is_base_exception_str(&b)) + } + + /// [`Self::instance_native_str`] of `__repr__` (an exception's, + /// `object`'s). + fn instance_native_repr(inst: &PyInstance) -> Option> { + Self::instance_native_special(inst, crate::types::vm_key::REPR_NATIVE, "__repr__") + } + + /// The native special method `name` of `inst`'s class that binds the + /// instance and needs no interpreter handle, remembered per class + /// version at the VM key `id`. `None` for a Python one, or none. + fn instance_native_special( + inst: &PyInstance, + id: u32, + name: &str, + ) -> Option> { + use crate::types::{AttrKey, LeafAttrKind as K}; + let cls = inst.cls_raw(); + let key = AttrKey::vm(id); + let ver = cls.attr_version.get(); + match cls.leaf_attrs.get(key, ver) { + Some(K::BuiltinMethod(b)) => return Some(b.clone()), + Some(_) => return None, + None => {} + } + if crate::object::exotic_str_keys_possible() { + return None; + } + let found = match cls.lookup(name) { + Some(Object::Builtin(b)) + if b.binds_instance && b.call_kw.is_none() && !builtin_needs_interp(b.name) => + { + Some(b) + } + _ => None, + }; + cls.leaf_attrs.set( + key, + ver, + match &found { + Some(b) => K::BuiltinMethod(b.clone()), + None => K::Other, + }, + ); + found + } + + /// `obj.__index__()` for the plain instance `inst` (`obj`) whose class's + /// `__index__` is a Python function that evaluates as a warm pure leaf + /// to a machine int: that int; `None`, nothing observable done, for + /// anything else. + pub(crate) fn instance_index_leaf(inst: &PyInstance, obj: &Object) -> Option { + if inst.native.get().is_some() { + return None; + } + let f = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::INDEX_FN), + "__index__", + )?; + // SAFETY: the running thread's interpreter, under the GIL; a pure + // leaf runs no other Python and takes no frame. + let interp = unsafe { &*crate::vm_singletons::current_interpreter_ptr()? }; + match interp.call_pure_leaf_with(&f, Some(obj), &[])? { + Object::Int(i) => Some(i), + _ => None, + } + } + + pub(crate) fn instance_dunder_function( inst: &PyInstance, key: crate::types::AttrKey, name: &str, @@ -31170,6 +35007,72 @@ impl Interpreter { } } + /// The Python function `str(inst)` calls: the class's `__str__`, or, + /// for a plain instance (no native payload) whose class keeps + /// `object.__str__`, its `__repr__`, which `object.__str__` calls (the + /// result then checked as `__str__`'s, as [`Self::do_str_call`] + /// checks it). `None` for anything else. + pub(crate) fn instance_str_function( + inst: &PyInstance, + ) -> Option> { + if let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::STR_FN), + "__str__", + ) { + return Some(f); + } + if inst.native.get().is_some() + || !Self::class_lacks( + inst.cls_raw(), + crate::types::AttrKey::vm(crate::types::vm_key::STR_ABSENT), + "__str__", + ) + { + return None; + } + Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::REPR_FN), + "__repr__", + ) + } + + /// [`Self::instance_str_function`] for an instance whose class keeps + /// `object.__format__`, which formats with an empty spec as `str(obj)`. + /// `None` for anything else. + pub(crate) fn instance_format_str_function( + inst: &PyInstance, + ) -> Option> { + if !Self::class_lacks( + inst.cls_raw(), + crate::types::AttrKey::vm(crate::types::vm_key::FORMAT_LACKS), + "__format__", + ) { + return None; + } + Self::instance_str_function(inst) + } + + /// `repr(obj)` for an instance whose class's `__repr__` is a Python + /// function (found once per class version), called with the instance + /// directly: no bound method, and no walk of the MRO. `None` for any + /// other object. + pub(crate) fn instance_python_repr( + &mut self, + obj: &Object, + ) -> Option> { + let Object::Instance(inst) = obj else { + return None; + }; + let f = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::REPR_FN), + "__repr__", + )?; + Some(self.call_dunder_function(f, std::slice::from_ref(obj))) + } + /// Whether `cls` resolves `name` to nothing on its MRO, cached on the /// class under its attribute version at `key` (as /// [`Self::instance_dunder_function`]). @@ -31191,6 +35094,98 @@ impl Interpreter { } } + /// The number `o` stands for under a built-in operator whose forward + /// and reflected methods are `fwd` and `refl` (and in-place one + /// `inplace`): an exact number itself, or the payload of a plain + /// instance of an `int` or `float` subclass (`IntEnum`'s) whose class + /// takes both methods from its built-in base unchanged and defines no + /// in-place one, so CPython's `binary_op1` (or `do_richcompare`) runs + /// the base's own slot, which reads only the payload and answers an + /// exact `int`, `float` or `bool`. The class's answer is cached under + /// its attribute version at `key` (one of [`vm_key::NUM_BINOP`]'s or + /// [`vm_key::NUM_CMP`]'s). `None` for anything else. + /// + /// [`vm_key::NUM_BINOP`]: crate::types::vm_key::NUM_BINOP + /// [`vm_key::NUM_CMP`]: crate::types::vm_key::NUM_CMP + pub(crate) fn kept_number_payload( + o: &Object, + key: u32, + fwd: &str, + refl: &str, + inplace: Option<&str>, + ) -> Option { + use crate::types::LeafAttrKind as K; + let inst = match o { + Object::Int(_) | Object::Bool(_) | Object::Long(_) | Object::Float(_) => { + return Some(o.clone()); + } + Object::Instance(i) => i, + _ => return None, + }; + let v = inst.native.get()?; + if !matches!(v, Object::Int(_) | Object::Long(_) | Object::Float(_)) { + return None; + } + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 { + return None; + } + let key = crate::types::AttrKey::vm(key); + let ver = cls.attr_version.get(); + let kept = match cls.leaf_attrs.get(key, ver) { + Some(K::InstanceOnly) => true, + Some(_) => false, + None => { + if crate::object::exotic_str_keys_possible() { + return None; + } + let base = |name: &str| { + matches!( + cls.lookup_with_owner(name), + Some((Object::Builtin(_), owner)) if owner.flags.is_builtin + ) + }; + let kept = + base(fwd) && base(refl) && inplace.is_none_or(|n| cls.lookup(n).is_none()); + cls.leaf_attrs + .set(key, ver, if kept { K::InstanceOnly } else { K::Other }); + kept + } + }; + kept.then(|| v.clone()) + } + + /// [`Self::kept_number_payload`] for `BINARY_OP` of `op`. + pub(crate) fn binop_number_payload(o: &Object, op: BinOpKind) -> Option { + let (fwd, refl) = binop_dunders(op); + Self::kept_number_payload( + o, + crate::types::vm_key::NUM_BINOP + op as u32, + fwd, + refl, + Some(op.inplace_dunder()), + ) + } + + /// [`Self::kept_number_payload`] for `COMPARE_OP` of `op`. + pub(crate) fn compare_number_payload(o: &Object, op: CompareKind) -> Option { + let name = |op: CompareKind| match op { + CompareKind::Lt => "__lt__", + CompareKind::LtE => "__le__", + CompareKind::Eq => "__eq__", + CompareKind::NotEq => "__ne__", + CompareKind::Gt => "__gt__", + CompareKind::GtE => "__ge__", + }; + Self::kept_number_payload( + o, + crate::types::vm_key::NUM_CMP + op as u32, + name(op), + name(cmp_swapped(op)), + None, + ) + } + /// CPython 3.14's `LOAD_COMMON_CONSTANT` value `arg`, from the /// interpreter-wide `common_consts` table (keep in sync with /// `opcode._common_constants`). @@ -31210,6 +35205,36 @@ impl Interpreter { }) } + /// `a b` (or `a = b`) of a plain number `a` (an `int`, + /// `float` or `bool`, whose own operator answers `NotImplemented` for an + /// instance) and a plain instance `b` whose class's reflected method is + /// a Python function: that method, which CPython calls as + /// `method(b, a)`. `None` for anything else (`**`, a builtin subclass's + /// instance, a native class). + pub(crate) fn binop_reflected_dunder( + a: &Object, + b: &Object, + op: BinOpKind, + ) -> Option> { + if op == BinOpKind::Pow || !matches!(a, Object::Int(_) | Object::Float(_) | Object::Bool(_)) + { + return None; + } + let Object::Instance(bi) = b else { + return None; + }; + let cls = bi.cls_raw(); + if bi.native.get().is_some() || cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 { + return None; + } + let (_, rdunder) = binop_dunders(op); + Self::instance_dunder_function( + bi, + crate::types::AttrKey::vm(crate::types::vm_key::RBINOP_FN + op as u32), + rdunder, + ) + } + /// The plain Python method a `BINARY_OP` of `op` (augmented when /// `inplace`) over `a` and `b` runs alone, as `dispatch_binary_op`'s /// same-class shape finds it: two plain instances of one class that @@ -31250,9 +35275,16 @@ impl Interpreter { // (Two instances of one class never try its reflected method: the // forward one's result stands, `NotImplemented` its `TypeError`, as // CPython's `SLOT1BINFULL` has it.) + // (A builtin subclass's own Python method, `IntFlag.__or__`, runs + // as any class's: only a Python function is ever taken here.) + // (Over a scalar, not a built-in subclass's instance either: past + // its method's `NotImplemented`, the scalar's own slot answers for + // the payload, `Evil(int) + 1`.) if !same - || ai.native.get().is_some() - || (mixed && (cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0)) + || (mixed + && (cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || ai.native.get().is_some())) || (inplace && !Self::class_lacks( cls, @@ -31312,9 +35344,142 @@ impl Interpreter { } } + /// The leaf half (see `leaf_builtins::register_fast`) of `inst`'s + /// `__setitem__` when the class resolves it to a built-in base's own + /// (an `OrderedDict`'s), cached on the class under its attribute + /// version. A store it settles runs no Python code. + #[inline] + pub(crate) fn instance_setitem_leaf(inst: &PyInstance) -> Option { + use crate::types::LeafAttrKind as K; + let cls = inst.cls_raw(); + let ver = cls.attr_version.get(); + let key = crate::types::AttrKey::vm(crate::types::vm_key::SETITEM_LEAF); + match cls.leaf_attrs.get(key, ver) { + Some(K::LeafFast(f)) => Some(*f), + Some(_) => None, + None => Self::instance_dunder_leaf_slow(cls, key, ver, "__setitem__"), + } + } + + /// The leaf half of `inst`'s `__getitem__` when its plain Python class + /// (no native payload or kind) resolves it to a native method with one + /// (the `array` class's), cached on the class as + /// [`Self::instance_setitem_leaf`] caches `__setitem__`'s. + #[cfg(feature = "jit")] + #[inline] + pub(crate) fn instance_getitem_leaf(inst: &PyInstance) -> Option { + Self::plain_instance_leaf(inst, crate::types::vm_key::GETITEM_LEAF, "__getitem__") + } + + /// The leaf half of `inst`'s `__getitem__` when the instance carries + /// a native payload (a `dict` subclass's) and its class resolves the + /// method to a native one a Python class holds (a `decimal` signal + /// mapping's), which reads the payload itself. Cached on the class as + /// [`Self::instance_setitem_leaf`] caches `__setitem__`'s. + #[cfg(feature = "jit")] + pub(crate) fn payload_getitem_leaf(inst: &PyInstance) -> Option { + use crate::types::LeafAttrKind as K; + let cls = inst.cls_raw(); + if inst.native.get().is_none() || cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 { + return None; + } + let ver = cls.attr_version.get(); + let key = crate::types::AttrKey::vm(crate::types::vm_key::GETITEM_OWN_LEAF); + match cls.leaf_attrs.get(key, ver) { + Some(K::LeafFast(f)) => Some(*f), + Some(_) => None, + None => { + if crate::object::exotic_str_keys_possible() { + return None; + } + let fast = match cls.lookup_with_owner("__getitem__") { + Some((Object::Builtin(b), owner)) + if b.binds_instance && !owner.flags.is_builtin => + { + match leaf_builtins::lookup(&b) { + Some((_, leaf_builtins::Entry::Fast(f))) => Some(f), + _ => None, + } + } + _ => None, + }; + cls.leaf_attrs + .set(key, ver, fast.map_or(K::Other, K::LeafFast)); + fast + } + } + } + + /// Likewise the leaf half of `inst`'s native `__add__` (an `array`'s). + #[cfg(feature = "jit")] + #[inline] + pub(crate) fn instance_add_leaf(inst: &PyInstance) -> Option { + Self::plain_instance_leaf(inst, crate::types::vm_key::ADD_LEAF, "__add__") + } + + #[cfg(feature = "jit")] + #[inline] + fn plain_instance_leaf(inst: &PyInstance, key: u32, name: &str) -> Option { + use crate::types::LeafAttrKind as K; + let cls = inst.cls_raw(); + if inst.native.get().is_some() || cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 { + return None; + } + let ver = cls.attr_version.get(); + let key = crate::types::AttrKey::vm(key); + match cls.leaf_attrs.get(key, ver) { + Some(K::LeafFast(f)) => Some(*f), + Some(_) => None, + None => Self::instance_dunder_leaf_slow(cls, key, ver, name), + } + } + + #[inline(never)] + fn instance_dunder_leaf_slow( + cls: &crate::types::TypeObject, + key: crate::types::AttrKey, + ver: u64, + name: &str, + ) -> Option { + use crate::types::LeafAttrKind as K; + if crate::object::exotic_str_keys_possible() { + return None; + } + let fast = match cls.lookup(name) { + Some(Object::Builtin(b)) if b.binds_instance => match leaf_builtins::lookup(&b) { + Some((_, leaf_builtins::Entry::Fast(f))) => Some(f), + _ => None, + }, + _ => None, + }; + cls.leaf_attrs + .set(key, ver, fast.map_or(K::Other, K::LeafFast)); + fast + } + + /// `inst`'s native payload (a `Counter`'s dict, a list subclass's list) + /// when the class resolves the special method `name` to a built-in + /// base's own, cached under `key`: the payload answers for it. + #[inline] + pub(crate) fn native_payload_for<'a>( + inst: &'a PyInstance, + key: u32, + name: &str, + ) -> Option<&'a Object> { + use crate::types::LeafAttrKind as K; + let native = inst.native.get()?; + let cls = inst.cls_raw(); + let key = crate::types::AttrKey::vm(key); + match cls.leaf_attrs.get(key, cls.attr_version.get()) { + Some(K::BuiltinMethod(_)) => Some(native), + Some(_) => None, + None => Self::instance_native_dunder(inst, key, name, true).map(|_| native), + } + } + /// Whether `inst`'s `__getitem__` is a built-in base's own over its /// native payload (a `defaultdict`'s): the native subscript serves it. - fn native_payload_getitem(inst: &PyInstance) -> bool { + pub(crate) fn native_payload_getitem(inst: &PyInstance) -> bool { inst.native.get().is_some() && Self::instance_native_dunder( inst, @@ -31328,13 +35493,23 @@ impl Interpreter { /// Call a class's dunder `f` (see [`Self::instance_dunder_function`]) /// with `args` (the instance first): a warm pure or effect leaf /// evaluates in place, anything else runs as an ordinary call. - fn call_dunder_function( + pub(crate) fn call_dunder_function( &mut self, f: Rc, args: &[Object], ) -> Result { let code = f.code(); - if code.arg_count as usize == args.len() && args.len() <= 8 && pure_leaf_warm(&code) { + let nargs = code.arg_count as usize; + // (Trailing parameters left out take the function's defaults, + // `__round__(self, ndigits=None)` called as `round(x)`, as + // `call_pure_leaf_with` binds them.) + let missing = nargs.saturating_sub(args.len()); + let defaults_ok = missing == 0 + || (code.kwonly_count == 0 + && !code.has_varkeywords + && f.defaults.len() >= missing + && !f.defaults_maybe_overridden()); + if args.len() <= nargs && nargs <= 8 && defaults_ok && pure_leaf_warm(&code) { let pure = code_is_pure_leaf(&code); let depth = crate::recursion::current_depth(); if (pure || code_is_effect_leaf(&code)) && depth < crate::recursion::recursion_limit() { @@ -31342,7 +35517,14 @@ impl Interpreter { for (k, a) in args.iter().enumerate() { ptrs[k] = a; } - if let Some(r) = self.pure_leaf_call(&code, &f, &ptrs[..args.len()], !pure, depth) { + let defs = &f.defaults; + for (p, d) in ptrs[args.len()..nargs] + .iter_mut() + .zip(&defs[defs.len() - missing..]) + { + *p = d; + } + if let Some(r) = self.pure_leaf_call(&code, &f, &ptrs[..nargs], !pure, depth) { return Ok(r); } } @@ -31360,13 +35542,62 @@ impl Interpreter { let Object::Instance(inst) = v else { return None; }; - if inst.native.get().is_some() || crate::object::exotic_str_keys_possible() { + if crate::object::exotic_str_keys_possible() { return None; } - let Some(Object::Function(f)) = inst.cls_raw().lookup("__hash__") else { - return None; - }; + // A value subclass's instance (an `IntEnum` or `StrEnum` member, a + // `str` subclass's): the hash remembered for it, or its payload's + // when its class keeps the base's `__hash__` and hashing the + // payload runs no code (a number, a string). Anything else of the + // kind is the full hash's. + if let Some(payload) = inst.native.get() { + if !matches!( + payload, + Object::Int(_) + | Object::Long(_) + | Object::Float(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::Tuple(_) + ) || inst.cls_raw().c_ext_ptr.get() != 0 + { + return None; + } + if let Some(h) = inst.hash_cache.get() { + return Some(h); + } + // (A class made unhashable, `__hash__ = None` or an `__eq__` + // without one, raises on the full path.) + if matches!(payload, Object::Tuple(_)) + || inst.class_dunder(crate::types::Dunder::Hash).is_none() + || crate::object::instance_has_custom_dunder(v, crate::types::Dunder::Hash) + { + return None; + } + let h = crate::object::py_hash_value(payload)?; + inst.hash_cache.store(h); + return Some(h); + } + // A natively served date or time value keeping its `__hash__`. + if inst.cls_raw().native_kind.get() != 0 { + if let Some(h) = crate::stdlib::datetime_native::leaf_hash(v) { + return Some(h); + } + } + // (The function memoized for the class's version, as the full + // hash reads it.) + let f = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::HASH), + "__hash__", + )?; let code = f.code(); + // An enum member keeping `Enum.__hash__`: its name's hash. + if code.qualname == "Enum.__hash__" { + if let Some(h) = Self::enum_hash(inst) { + return Some(h); + } + } if !code_is_pure_leaf(&code) || !pure_leaf_warm(&code) || crate::recursion::current_depth() >= crate::recursion::recursion_limit() @@ -31394,6 +35625,30 @@ impl Interpreter { } } + /// A `find_by_hash` test of the stored keys of `item`'s hash (an + /// instance's, a [`crate::object::LeafProbe::with_hash`] probe's + /// inexact miss): the same object, or equal by a `__eq__` that + /// evaluates as a pure leaf ([`Self::leaf_instance_eq`], the stored + /// key first, as CPython compares). Any other comparison sets + /// `declined` (and matches nothing after it), for the full path. (A + /// pure `__eq__` reads, and never writes, what the table holds.) + pub(crate) fn leaf_eq_match<'a>( + &'a self, + item: &'a Object, + declined: &'a std::cell::Cell, + ) -> impl FnMut(&DictKey) -> bool + 'a { + move |k: &DictKey| { + if declined.get() { + return false; + } + k.0.is_same(item) + || self.leaf_instance_eq(&k.0, item).unwrap_or_else(|| { + declined.set(true); + false + }) + } + } + /// `stored == key` for two instances of one class whose Python /// `__eq__` evaluates as a pure leaf (a dataclass's field comparisons), /// as a dict probe takes it: `Some` only for a `bool` answer. `None` @@ -31403,20 +35658,37 @@ impl Interpreter { let (Object::Instance(a), Object::Instance(b)) = (stored, key) else { return None; }; - if a.native.get().is_some() - || b.native.get().is_some() - || crate::object::exotic_str_keys_possible() - || crate::gil::free_threading_enabled() - { + if crate::object::exotic_str_keys_possible() || crate::gil::free_threading_enabled() { return None; } + // Two value subclass instances that compare as their payloads do + // (enum members of an `int` or `str` mix-in, named tuples of + // plain values): the payloads' equality. + if a.native.get().is_some() || b.native.get().is_some() { + if let Some((x, y, _)) = Self::seq_cmp_payloads(stored, key, CompareKind::Eq) { + return plain_compare(x, y, CompareKind::Eq); + } + let (x, y) = Self::num_cmp_payloads(stored, key, CompareKind::Eq)?; + return plain_compare(&x, &y, CompareKind::Eq); + } let cls = a.cls_raw(); if !std::ptr::eq(cls, b.cls_raw()) { return None; } - let Some(Object::Function(f)) = cls.lookup("__eq__") else { - return None; - }; + // Two natively served values (dates, times, `Decimal`s): their + // native comparison. + if cls.native_kind.get() != 0 { + return match Self::core_native_compare(CompareKind::Eq, stored, key)? { + Ok(Object::Bool(b)) => Some(b), + _ => None, + }; + } + // (Memoized for the class's version.) + let f = Self::instance_dunder_function( + a, + crate::types::AttrKey::vm(crate::types::vm_key::EQ_FN), + "__eq__", + )?; let code = f.code(); if !code_is_pure_leaf(&code) || !pure_leaf_warm(&code) @@ -31450,6 +35722,11 @@ impl Interpreter { if crate::object::exotic_str_keys_possible() { return None; } + // (A loop that tests instances of a few classes in turn finds each + // one's answer again instead of working it out every time.) + if !matches!(&*self.core_truth.borrow(), Some((v, _)) if *v == ver) { + self.core_truth_recall(ver); + } // The cache (and the class) keep the builtin alive through the // call, whose body runs no Python. let lookup = @@ -31460,6 +35737,8 @@ impl Interpreter { NativeTruth::Len(b) => Ok((Rc::as_ptr(b), true, 0)), NativeTruth::PyLen => Ok((std::ptr::null(), true, PY_LEN_TRUTH)), NativeTruth::PyBool(_) => Ok((std::ptr::null(), false, PY_BOOL_TRUTH)), + NativeTruth::Payload => Ok((std::ptr::null(), false, PAYLOAD_TRUTH)), + NativeTruth::FastBool(_) => Ok((std::ptr::null(), false, FAST_BOOL_TRUTH)), NativeTruth::Decline => Err(false), } }; @@ -31481,6 +35760,21 @@ impl Interpreter { Err(true) => return Some(true), Err(false) => return None, }; + if op == PAYLOAD_TRUTH { + return payload_truth(v); + } + // A native `__bool__`'s fast half (what it declines is the full + // path's). + if op == FAST_BOOL_TRUTH { + let f = match &*self.core_truth.borrow() { + Some((_, NativeTruth::FastBool(f))) => *f, + _ => return None, + }; + return match f(std::slice::from_ref(v))? { + Ok(Object::Bool(b)) => Some(b), + _ => None, + }; + } // A Python `__len__` evaluated in place, or the full path's. if op == PY_LEN_TRUTH { return match self.leaf_instance_len(v)? { @@ -31526,6 +35820,39 @@ impl Interpreter { } } + /// The cached truth verdict for `inst`'s class (see + /// [`Self::leaf_instance_truth`], which just filled it) as a plan a + /// compiled site keeps for the class's version, when it is a native + /// method's. + pub(crate) fn native_truth_plan( + &self, + inst: &crate::types::PyInstance, + ) -> Option<(u64, NativeTruthPlan)> { + let ver = inst.cls_raw().attr_version.get(); + let plan = match &*self.core_truth.borrow() { + Some((v, t)) if *v == ver && ver != 0 => match t { + NativeTruth::Bool(b, op) => NativeTruthPlan { + f: Rc::as_ptr(b), + is_len: false, + op: *op, + }, + NativeTruth::Len(b) => NativeTruthPlan { + f: Rc::as_ptr(b), + is_len: true, + op: 0, + }, + NativeTruth::Payload => NativeTruthPlan { + f: std::ptr::null(), + is_len: false, + op: PAYLOAD_TRUTH, + }, + _ => return None, + }, + _ => return None, + }; + Some((ver, plan)) + } + /// The attribute version of `inst`'s class, when its instances are /// always true in a boolean context (the cached verdict for that /// version, see [`Self::leaf_instance_truth`]): a compiled `TO_BOOL` @@ -31541,6 +35868,26 @@ impl Interpreter { } } + /// Bring the answer remembered for the class version `ver` back into + /// `core_truth`, if one of the last few classes asked about was this + /// one; else make room there for the answer about to be worked out + /// (the current one is kept beside the others). + #[cold] + #[inline(never)] + fn core_truth_recall(&self, ver: u64) { + let mut more = self.core_truth_more.borrow_mut(); + let mut main = self.core_truth.borrow_mut(); + if let Some(k) = more + .iter() + .position(|e| matches!(e, Some((v, _)) if *v == ver)) + { + std::mem::swap(&mut *main, &mut more[k]); + } else if let Some((v, _)) = &*main { + let k = *v as usize % more.len(); + more[k] = main.take(); + } + } + /// How instances of `cls` answer a boolean context natively (keyed by /// the class's attribute version in `core_truth`). #[cold] @@ -31551,6 +35898,38 @@ impl Interpreter { if v.is_same(&crate::vm_singletons::not_implemented()) || !Self::default_getattribute(cls) { return NativeTruth::Decline; } + // A builtin value or container subclass that keeps its base's + // `__bool__` and `__len__`. + if let Object::Instance(inst) = v { + let payload = inst.native.get().is_some_and(|p| { + matches!( + p, + Object::Str(_) + | Object::Bytes(_) + | Object::Tuple(_) + | Object::FrozenSet(_) + | Object::Int(_) + | Object::Float(_) + | Object::List(_) + | Object::Dict(_) + | Object::Set(_) + | Object::ByteArray(_) + ) + }); + let builtin = |name: &str| match cls.lookup_with_owner(name) { + None => true, + Some((Object::Builtin(_), owner)) => owner.flags.is_builtin, + Some(_) => false, + }; + if payload + && cls.native_kind.get() == 0 + && cls.c_ext_ptr.get() == 0 + && builtin("__bool__") + && builtin("__len__") + { + return NativeTruth::Payload; + } + } for (name, is_len) in [("__bool__", false), ("__len__", true)] { match cls.lookup(name) { None => continue, @@ -31564,6 +35943,12 @@ impl Interpreter { NativeTruth::Bool(b, op) }; } + Some(Object::Builtin(b)) if b.binds_instance && !is_len => { + return match self.leaf_call_kind(&b) { + Some(LeafKind::Fast(f)) => NativeTruth::FastBool(f), + _ => NativeTruth::Decline, + }; + } Some(Object::Function(_)) if is_len => return NativeTruth::PyLen, Some(Object::Function(f)) => return NativeTruth::PyBool(f), Some(_) => return NativeTruth::Decline, @@ -31714,16 +36099,26 @@ impl Interpreter { if !Self::default_getattribute(cls) || crate::object::exotic_str_keys_possible() { return None; } - match cls.lookup(name)? { - Object::Builtin(b) - if b.binds_instance - && b.call_kw.is_none() - && self.leaf_call_kind(&b) == Some(LeafKind::Opaque) => - { - Some(b) - } + // (`len()`'s and `next()`'s, the per-call ones, from the class's + // cache under its version.) + let key = match name { + "__len__" => Some(crate::types::vm_key::LEAF_LEN), + "__next__" => Some(crate::types::vm_key::LEAF_NEXT), _ => None, - } + }; + let b = match key { + Some(k) => { + Self::instance_native_dunder(inst, crate::types::AttrKey::vm(k), name, false)? + } + None => match cls.lookup(name)? { + Object::Builtin(b) => b, + _ => return None, + }, + }; + (b.binds_instance + && b.call_kw.is_none() + && self.leaf_call_kind(&b) == Some(LeafKind::Opaque)) + .then_some(b) } /// One `__next__` step of an instance iterator with a registered leaf @@ -31832,6 +36227,8 @@ impl Interpreter { self.leaf_fns.get_or_init(|| { let mut calls = std::collections::HashMap::default(); let mut len_ptr = 0usize; + let mut hash_ptr = 0usize; + let mut isinstance_ptr = 0usize; let mut next_ptr = 0usize; { let b = self.builtins.borrow(); @@ -31843,6 +36240,8 @@ impl Interpreter { ("isinstance", LeafKind::Isinstance), ("getattr", LeafKind::GetAttr), ("hasattr", LeafKind::Fast(Interpreter::leaf_hasattr)), + ("setattr", LeafKind::Fast(Interpreter::leaf_setattr)), + ("format", LeafKind::Fast(leaf_format)), ("issubclass", LeafKind::Fast(leaf_issubclass)), // Bodies that run no Python code for any arguments. ("id", LeafKind::Opaque), @@ -31860,12 +36259,24 @@ impl Interpreter { ("divmod", LeafKind::Fast(crate::seqiter::divmod_fast)), ("vars", LeafKind::Fast(crate::seqiter::vars_fast)), ("pow", LeafKind::Fast(crate::seqiter::pow_fast)), + ("round", LeafKind::Fast(crate::seqiter::round_fast)), + ("repr", LeafKind::Fast(crate::seqiter::repr_fast)), + ("next", LeafKind::Fast(crate::seqiter::next_fast)), + ("hex", LeafKind::Fast(crate::builtins::hex_fast)), + ("oct", LeafKind::Fast(crate::builtins::oct_fast)), + ("bin", LeafKind::Fast(crate::builtins::bin_fast)), ] { if let Some(Object::Builtin(f)) = b.get(&crate::object::StrKey(name)) { calls.insert(Rc::as_ptr(f) as usize, kind); if name == "len" { len_ptr = Rc::as_ptr(f) as usize; } + if name == "hash" { + hash_ptr = Rc::as_ptr(f) as usize; + } + if name == "isinstance" { + isinstance_ptr = Rc::as_ptr(f) as usize; + } } } } @@ -31873,7 +36284,7 @@ impl Interpreter { calls.insert(Rc::as_ptr(&f) as usize, LeafKind::ObjectNew); } let mut methods = Vec::new(); - let table: [(LeafRecv, Object, &[(&'static str, LeafKind)]); 6] = [ + let table: [(LeafRecv, Object, &[(&'static str, LeafKind)]); 8] = [ ( LeafRecv::List, Object::new_list(Vec::new()), @@ -31886,6 +36297,8 @@ impl Interpreter { ("reverse", LeafKind::ListReverse), ("copy", LeafKind::ListCopy), ("remove", LeafKind::ListRemove), + ("sort", LeafKind::Fast(crate::seqiter::list_sort_fast)), + ("clear", LeafKind::Fast(crate::builtins::list_clear_leaf)), ], ), ( @@ -31894,6 +36307,10 @@ impl Interpreter { &[ ("__len__", LeafKind::Len), ("get", LeafKind::DictGet), + ( + "__getitem__", + LeafKind::Fast(crate::builtins::dict_getitem_leaf), + ), ( "setdefault", LeafKind::Fast(crate::builtins::dict_setdefault_leaf), @@ -31901,6 +36318,13 @@ impl Interpreter { ("keys", LeafKind::DictKeys), ("values", LeafKind::DictValues), ("items", LeafKind::DictItems), + ("pop", LeafKind::Fast(crate::builtins::dict_pop_leaf)), + ( + "popitem", + LeafKind::Fast(crate::builtins::dict_popitem_leaf), + ), + // (A table copy: no key is hashed or compared.) + ("copy", LeafKind::Opaque), ], ), ( @@ -31912,6 +36336,7 @@ impl Interpreter { ("discard", LeafKind::SetDiscard), ("remove", LeafKind::SetRemove), ("pop", LeafKind::SetPop), + ("copy", LeafKind::Opaque), ], ), ( @@ -31967,6 +36392,10 @@ impl Interpreter { ("istitle", LeafKind::Opaque), ("isupper", LeafKind::Opaque), ("encode", LeafKind::Fast(crate::builtins::str_encode_leaf)), + ( + "format_map", + LeafKind::Fast(crate::builtins::str_format_map_leaf), + ), ], ), ( @@ -31981,18 +36410,332 @@ impl Interpreter { "bit_length", LeafKind::Fast(crate::builtins::int_bit_length_leaf), ), + // (A machine int's popcount, or a big one's.) + ("bit_count", LeafKind::Opaque), + // (Each reads the int and runs no code: `statistics`' + // `_exact_ratio` calls the first.) + ("as_integer_ratio", LeafKind::Opaque), + ("conjugate", LeafKind::Opaque), + ("is_integer", LeafKind::Opaque), + ], + ), + // (Each reads the float's bits and runs no code.) + ( + LeafRecv::Float, + Object::Float(0.0), + &[ + ("is_integer", LeafKind::Opaque), + ("as_integer_ratio", LeafKind::Opaque), + ("hex", LeafKind::Opaque), + ("conjugate", LeafKind::Opaque), ], ), ( LeafRecv::Bytes, Object::new_bytes(Vec::new()), - &[("decode", LeafKind::Fast(crate::builtins::bytes_decode_leaf))], + &[ + ("decode", LeafKind::Fast(crate::builtins::bytes_decode_leaf)), + ("find", LeafKind::Fast(crate::builtins::bytes_find_leaf)), + ("hex", LeafKind::Fast(crate::builtins::bytes_hex_leaf)), + // (Pure bodies over plain operands.) + ("upper", LeafKind::Fast(crate::builtins::bytes_upper_fast)), + ("lower", LeafKind::Fast(crate::builtins::bytes_lower_fast)), + ("strip", LeafKind::Fast(crate::builtins::bytes_strip_fast)), + ("lstrip", LeafKind::Fast(crate::builtins::bytes_lstrip_fast)), + ("rstrip", LeafKind::Fast(crate::builtins::bytes_rstrip_fast)), + ("count", LeafKind::Fast(crate::builtins::bytes_count_fast)), + ("rfind", LeafKind::Fast(crate::builtins::bytes_rfind_fast)), + ("index", LeafKind::Fast(crate::builtins::bytes_index_fast)), + ("rindex", LeafKind::Fast(crate::builtins::bytes_rindex_fast)), + ( + "partition", + LeafKind::Fast(crate::builtins::bytes_partition_fast), + ), + ( + "rpartition", + LeafKind::Fast(crate::builtins::bytes_rpartition_fast), + ), + ( + "removeprefix", + LeafKind::Fast(crate::builtins::bytes_removeprefix_fast), + ), + ( + "removesuffix", + LeafKind::Fast(crate::builtins::bytes_removesuffix_fast), + ), + ("center", LeafKind::Fast(crate::builtins::bytes_center_fast)), + ("ljust", LeafKind::Fast(crate::builtins::bytes_ljust_fast)), + ("rjust", LeafKind::Fast(crate::builtins::bytes_rjust_fast)), + ("zfill", LeafKind::Fast(crate::builtins::bytes_zfill_fast)), + ( + "capitalize", + LeafKind::Fast(crate::builtins::bytes_capitalize_fast), + ), + ("title", LeafKind::Fast(crate::builtins::bytes_title_fast)), + ( + "swapcase", + LeafKind::Fast(crate::builtins::bytes_swapcase_fast), + ), + ( + "isalnum", + LeafKind::Fast(crate::builtins::bytes_isalnum_fast), + ), + ( + "isalpha", + LeafKind::Fast(crate::builtins::bytes_isalpha_fast), + ), + ( + "isdigit", + LeafKind::Fast(crate::builtins::bytes_isdigit_fast), + ), + ( + "isspace", + LeafKind::Fast(crate::builtins::bytes_isspace_fast), + ), + ( + "islower", + LeafKind::Fast(crate::builtins::bytes_islower_fast), + ), + ( + "isupper", + LeafKind::Fast(crate::builtins::bytes_isupper_fast), + ), + ("split", LeafKind::Fast(crate::builtins::bytes_split_fast)), + ("rsplit", LeafKind::Fast(crate::builtins::bytes_rsplit_fast)), + ( + "replace", + LeafKind::Fast(crate::builtins::bytes_replace_fast), + ), + ( + "splitlines", + LeafKind::Fast(crate::builtins::bytes_splitlines_fast), + ), + ( + "expandtabs", + LeafKind::Fast(crate::builtins::bytes_expandtabs_fast), + ), + ], + ), + // A buffer built a byte or a chunk at a time, and read back. + ( + LeafRecv::ByteArray, + Object::new_bytearray(Vec::new()), + &[ + ( + "append", + LeafKind::Fast(crate::builtins::bytearray_append_leaf), + ), + ( + "extend", + LeafKind::Fast(crate::builtins::bytearray_extend_leaf), + ), + ("pop", LeafKind::Fast(crate::builtins::bytearray_pop_leaf)), + ("decode", LeafKind::Fast(crate::builtins::bytes_decode_leaf)), + ("upper", LeafKind::Fast(crate::builtins::bytes_upper_fast)), + ("lower", LeafKind::Fast(crate::builtins::bytes_lower_fast)), + ("strip", LeafKind::Fast(crate::builtins::bytes_strip_fast)), + ("lstrip", LeafKind::Fast(crate::builtins::bytes_lstrip_fast)), + ("rstrip", LeafKind::Fast(crate::builtins::bytes_rstrip_fast)), + ("count", LeafKind::Fast(crate::builtins::bytes_count_fast)), + ("rfind", LeafKind::Fast(crate::builtins::bytes_rfind_fast)), + ("index", LeafKind::Fast(crate::builtins::bytes_index_fast)), + ("rindex", LeafKind::Fast(crate::builtins::bytes_rindex_fast)), + ( + "partition", + LeafKind::Fast(crate::builtins::bytes_partition_fast), + ), + ( + "rpartition", + LeafKind::Fast(crate::builtins::bytes_rpartition_fast), + ), + ( + "removeprefix", + LeafKind::Fast(crate::builtins::bytes_removeprefix_fast), + ), + ( + "removesuffix", + LeafKind::Fast(crate::builtins::bytes_removesuffix_fast), + ), + ("center", LeafKind::Fast(crate::builtins::bytes_center_fast)), + ("ljust", LeafKind::Fast(crate::builtins::bytes_ljust_fast)), + ("rjust", LeafKind::Fast(crate::builtins::bytes_rjust_fast)), + ("zfill", LeafKind::Fast(crate::builtins::bytes_zfill_fast)), + ( + "capitalize", + LeafKind::Fast(crate::builtins::bytes_capitalize_fast), + ), + ("title", LeafKind::Fast(crate::builtins::bytes_title_fast)), + ( + "swapcase", + LeafKind::Fast(crate::builtins::bytes_swapcase_fast), + ), + ( + "isalnum", + LeafKind::Fast(crate::builtins::bytes_isalnum_fast), + ), + ( + "isalpha", + LeafKind::Fast(crate::builtins::bytes_isalpha_fast), + ), + ( + "isdigit", + LeafKind::Fast(crate::builtins::bytes_isdigit_fast), + ), + ( + "isspace", + LeafKind::Fast(crate::builtins::bytes_isspace_fast), + ), + ( + "islower", + LeafKind::Fast(crate::builtins::bytes_islower_fast), + ), + ( + "isupper", + LeafKind::Fast(crate::builtins::bytes_isupper_fast), + ), + ("split", LeafKind::Fast(crate::builtins::bytes_split_fast)), + ("rsplit", LeafKind::Fast(crate::builtins::bytes_rsplit_fast)), + ( + "replace", + LeafKind::Fast(crate::builtins::bytes_replace_fast), + ), + ( + "splitlines", + LeafKind::Fast(crate::builtins::bytes_splitlines_fast), + ), + ( + "expandtabs", + LeafKind::Fast(crate::builtins::bytes_expandtabs_fast), + ), + ], ), ]; + // `bytes.translate(table, delete=...)` (`shlex.quote`'s), whose + // keyword binds by name: registered once per process. + static KW_LEAVES: std::sync::Once = std::sync::Once::new(); + KW_LEAVES.call_once(|| { + if let Some(Object::Builtin(b)) = crate::builtins::lookup_method( + &Object::new_bytes(Vec::::new()), + "translate", + ) { + leaf_builtins::register_fast_kw( + &b, + &["table", "delete"], + crate::builtins::bytes_translate_fast, + ); + } + // `s.encode(encoding="utf-8")`, `s.split(maxsplit=1)`. + let probe = Object::from_static(""); + if let Some(Object::Builtin(b)) = crate::builtins::lookup_method(&probe, "encode") { + leaf_builtins::register_fast_kw( + &b, + &["encoding", "errors"], + crate::builtins::str_encode_leaf, + ); + } + if let Some(Object::Builtin(b)) = crate::builtins::lookup_method(&probe, "split") { + leaf_builtins::register_fast_kw( + &b, + &["?sep", "?maxsplit"], + crate::builtins::str_split_kw_fast, + ); + } + if let Some(Object::Builtin(b)) = crate::builtins::lookup_method(&probe, "rsplit") { + leaf_builtins::register_fast_kw( + &b, + &["?sep", "?maxsplit"], + crate::builtins::str_rsplit_kw_fast, + ); + } + if let Some(Object::Builtin(b)) = + crate::builtins::lookup_method(&probe, "splitlines") + { + leaf_builtins::register_fast_kw( + &b, + &["?keepends"], + crate::builtins::str_splitlines_kw_fast, + ); + } + // `n.to_bytes(2, byteorder="big")`. + if let Some(Object::Builtin(b)) = + crate::builtins::lookup_method(&Object::Int(0), "to_bytes") + { + leaf_builtins::register_fast_kw( + &b, + &["?length", "?byteorder", "*signed"], + crate::builtins::int_to_bytes_kw_fast, + ); + } + // `b.decode(errors="replace")` of bytes and bytearrays. + for probe in [ + Object::new_bytes(Vec::::new()), + Object::new_bytearray(Vec::new()), + ] { + if let Some(Object::Builtin(b)) = + crate::builtins::lookup_method(&probe, "decode") + { + leaf_builtins::register_fast_kw( + &b, + &["?encoding", "?errors"], + crate::builtins::bytes_decode_kw_fast, + ); + } + } + // `xs.sort(reverse=True)`, `xs.sort(key=None)`: keyword-only. + if let Some(Object::Builtin(b)) = + crate::builtins::lookup_method(&Object::new_list(Vec::new()), "sort") + { + leaf_builtins::register_fast_kw( + &b, + &["*key", "*reverse"], + crate::seqiter::list_sort_kw_fast, + ); + } + }); + // `sorted(xs, reverse=True)`, `max(xs, default=0)` and + // `round(x, ndigits=2)`, this interpreter's builtins. + { + let builtins = self.builtins.borrow(); + let kw_halves: [(&str, leaf_builtins::KwNames, leaf_builtins::Fast); 4] = [ + ( + "sorted", + &["/iterable", "*key", "*reverse"], + crate::seqiter::sorted_kw_fast, + ), + ( + "max", + &["/iterable", "*key", "*default"], + crate::seqiter::max_kw_fast, + ), + ( + "min", + &["/iterable", "*key", "*default"], + crate::seqiter::min_kw_fast, + ), + ("round", &["number", "ndigits"], crate::seqiter::round_fast), + ]; + for (name, params, fast) in kw_halves { + if let Some(Object::Builtin(b)) = builtins.get(&crate::object::StrKey(name)) { + leaf_builtins::register_fast_kw(b, params, fast); + } + } + } for (recv, probe, names) in table { + // The type's own entry for each name, a receiver-checking + // shim over the method (what `str.upper` reads as), takes + // the method's kind too: every kind declines a receiver of + // another kind, which the shim then checks or unwraps. + let cls = crate::builtins::class_of(&probe); for (name, kind) in names.iter().copied() { if let Some(Object::Builtin(f)) = crate::builtins::lookup_method(&probe, name) { calls.insert(Rc::as_ptr(&f) as usize, kind); + if let Some(Object::Builtin(shim)) = + cls.dict.borrow().get(&crate::object::StrKey(name)) + { + if !Rc::ptr_eq(shim, &f) && !matches!(kind, LeafKind::Len) { + calls.insert(Rc::as_ptr(shim) as usize, kind); + } + } methods.push((recv, name, f)); } } @@ -32010,6 +36753,12 @@ impl Interpreter { Rc::as_ptr(&f) as usize, LeafKind::Fast(crate::builtins::int_from_bytes_leaf), ); + // `int.from_bytes(data, byteorder="big")`. + leaf_builtins::register_fast_kw( + &f, + &["bytes", "?byteorder", "*signed"], + crate::builtins::int_from_bytes_kw_fast, + ); } } // And `dict.fromkeys` over a list or tuple of plain keys. @@ -32045,18 +36794,92 @@ impl Interpreter { calls.insert(Rc::as_ptr(f) as usize, LeafKind::Fast(fast)); } } - LeafFns { + let mut method_names: std::collections::HashMap< + &'static str, + Vec<(LeafRecv, Rc)>, + crate::fasthash::FxBuildHasher, + > = std::collections::HashMap::default(); + for (recv, name, f) in &methods { + method_names + .entry(name) + .or_default() + .push((*recv, f.clone())); + } + let dict_get_ptr = methods + .iter() + .find(|(recv, name, _)| matches!(recv, LeafRecv::Dict) && *name == "get") + .map_or(0, |(_, _, f)| Rc::as_ptr(f) as usize); + Rc::new(LeafFns { calls, len_ptr, + hash_ptr, + isinstance_ptr, + dict_get_ptr, next_ptr, methods, + method_names, range_ty: bt.range_.clone(), list_ty: bt.list_.clone(), str_ty: bt.str_.clone(), - } + }) }) } + /// Whether `b` is the builtin `hash`. + #[inline] + pub(crate) fn is_builtin_hash_fn(&self, b: *const crate::object::BuiltinFn) -> bool { + b as usize == self.leaf_fns().hash_ptr + } + + /// Whether `b` is the builtin `len`. + #[inline] + pub(crate) fn is_builtin_len_fn(&self, b: *const crate::object::BuiltinFn) -> bool { + b as usize == self.leaf_fns().len_ptr + } + + /// Whether `b` is the builtin `isinstance`. + #[inline] + pub(crate) fn is_builtin_isinstance_fn(&self, b: *const crate::object::BuiltinFn) -> bool { + b as usize == self.leaf_fns().isinstance_ptr + } + + /// Whether `b` is `dict.get`. + #[inline] + pub(crate) fn is_dict_get_fn(&self, b: *const crate::object::BuiltinFn) -> bool { + b as usize == self.leaf_fns().dict_get_ptr + } + + /// `d.get(key[, default])` of an exact dict (`args` with the receiver + /// first) by the native probe alone, as `LeafKind::DictGet`'s first + /// step answers it: `None` for its full path. + #[inline] + pub(crate) fn leaf_dict_get_fast(args: &[Object]) -> Option { + let ([Object::Dict(d), key] | [Object::Dict(d), key, _]) = args else { + return None; + }; + let probe = crate::object::LeafProbe::new(key)?; + let m = d.try_borrow().ok()?; + match m.get(&probe) { + Some(v) => Some(v.clone()), + None if probe.miss_is_exact() => Some(args.get(2).cloned().unwrap_or(Object::None)), + None => None, + } + } + + /// `isinstance(obj, spec)` as the core loop's leaf arm answers it (an + /// exact class, an MRO, an ABC's cached verdict): `None` for the full + /// check. + #[inline] + pub(crate) fn leaf_isinstance(args: &[Object]) -> Option { + Self::core_isinstance(args)?.ok() + } + + /// Whether a leaf plan register holds the builtin `hash`. + #[inline] + pub(crate) fn is_builtin_hash_obj(&self, o: &Object) -> bool { + matches!(o, Object::Builtin(b) if Rc::as_ptr(b) as usize == self.leaf_fns().hash_ptr) + } + /// `range(...)` / `list(...)` with a leaf argument shape, built /// directly. A list is tracked like `BUILD_LIST`'s; when that /// allocation would trigger a collection (which may queue @@ -32068,13 +36891,107 @@ impl Interpreter { // `__new__`, no class-defined `__init__` to run), as the full // call builds it. if ty.flags.is_builtin && ty.flags.is_exception { - if exc_family_flags(ty) & EXC_FAM_GROUP != 0 || lookup_exception_init(ty).is_some() { + // (`OSError`'s own `__init__` sets what the built instance + // already holds.) + if exc_family_flags(ty) & EXC_FAM_GROUP != 0 + || lookup_exception_init(ty) + .is_some_and(|init| !crate::builtin_types::is_os_error_init(&init)) + { return None; } return Some(self.build_exception_instance(ty.clone(), args)); } + // `float(x)` and `int(x)` of a plain instance whose class's + // `__float__` or `__int__` is a Python function that evaluates as a + // pure leaf, answering an exact `float` or `int` (anything else, + // `__index__` among it, is the full call's), as `str(x)` below. + if let [recv @ Object::Instance(inst)] = args { + let bt = builtin_types(); + // `bool(x)`: the instance's truth, as the truth test reads it + // in place (`__bool__` or `__len__` as a pure leaf, or none). + // (An argument the call holds the last reference to dies with + // it: the full call runs its finalizer promptly.) + if Rc::ptr_eq(ty, &bt.bool_) { + if Rc::strong_count(inst) <= 1 { + return None; + } + return self.leaf_instance_truth(recv).map(Object::Bool); + } + let is_float = Rc::ptr_eq(ty, &bt.float_); + let is_int = Rc::ptr_eq(ty, &bt.int_); + // A natively served value (a `Decimal`): its native method's + // pure half. An `int` or `float` subclass's instance that keeps + // its base's method (an `IntEnum` member): its payload's + // conversion, which that method comes to. (As above for an + // argument the call alone holds.) + if (is_float || is_int) && Rc::strong_count(inst) > 1 { + let name = if is_float { "__float__" } else { "__int__" }; + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 { + let Some(Object::Builtin(b)) = cls.lookup(name) else { + return None; + }; + let Some(LeafKind::Fast(f)) = self.leaf_call_kind(&b) else { + return None; + }; + return match f(std::slice::from_ref(recv))?.ok()? { + v @ Object::Float(_) if is_float => Some(v), + v @ (Object::Int(_) | Object::Long(_)) if !is_float => Some(v), + _ => None, + }; + } + if let Some(p @ (Object::Int(_) | Object::Long(_) | Object::Float(_))) = + inst.native.get() + { + if cls.c_ext_ptr.get() != 0 + || !cls.memo_verdict(crate::types::Verdict::NumConvPlain, name, || { + matches!( + cls.lookup_with_owner(name), + Some((Object::Builtin(_), owner)) if owner.flags.is_builtin + ) + }) + { + return None; + } + return match (p, is_float) { + (Object::Int(_) | Object::Long(_), false) => Some(p.clone()), + (Object::Float(_), true) => Some(p.clone()), + // (Exact while the `int` fits a `float`'s mantissa.) + (Object::Int(i), true) if i.unsigned_abs() < 1 << 53 => { + Some(Object::Float(*i as f64)) + } + (Object::Float(x), false) if x.is_finite() && x.abs() < 9.0e15 => { + Some(Object::Int(x.trunc() as i64)) + } + _ => None, + }; + } + } + if (is_float || is_int) && inst.native.get().is_none() { + let (key, name) = if is_float { + (crate::types::vm_key::FLOAT_FN, "__float__") + } else { + (crate::types::vm_key::INT_FN, "__int__") + }; + let f = Self::instance_dunder_function(inst, crate::types::AttrKey::vm(key), name)?; + return match self.call_pure_leaf_with(&f, Some(recv), &[])? { + v @ Object::Float(_) if is_float => Some(v), + v @ (Object::Int(_) | Object::Long(_)) if !is_float => Some(v), + _ => None, + }; + } + } let fns = self.leaf_fns(); if Rc::ptr_eq(ty, &fns.str_ty) { + // (`str(e)` of an exception that keeps `BaseException.__str__`, + // ahead of the lookups a plain instance's `__str__` takes.) + if let [Object::Instance(inst)] = args { + if inst.cls_raw().flags.is_exception { + if let Some(v) = Self::exc_str_leaf(inst) { + return Some(v); + } + } + } // `str(x)` of a native scalar is its text: no `__str__` // lookup, no instance, no constructor protocol. return match args { @@ -32082,6 +36999,25 @@ impl Interpreter { [Object::Int(n)] => Some(Object::from_str(itoa::Buffer::new().format(*n))), [Object::Bool(b)] => Some(Object::from_static(if *b { "True" } else { "False" })), [Object::None] => Some(Object::from_static("None")), + // An exact `decimal.Decimal` (see `stdlib::decimal_native`). + [Object::Instance(inst)] + if crate::stdlib::decimal_native::is_decimal_instance(inst) => + { + crate::stdlib::decimal_native::leaf_str(inst) + } + // A plain instance whose class's `__str__` is a Python + // function that evaluates as a pure leaf, answering a `str`. + [recv @ Object::Instance(inst)] if inst.native.get().is_none() => { + let Some(f) = Self::instance_str_function(inst) else { + // An exception's `BaseException.__str__`, when it + // runs no code of the argument's. + return Self::exc_str_leaf(inst); + }; + match self.call_pure_leaf_with(&f, Some(recv), &[])? { + s @ Object::Str(_) => Some(s), + _ => None, + } + } _ => crate::seqiter::builtin_ctor_pure(ty, args), }; } @@ -32142,14 +37078,14 @@ impl Interpreter { } v } - [Object::List(l)] => l.try_borrow().ok()?.clone(), - [Object::Tuple(t)] => t.to_vec(), + [Object::List(l)] => crate::object::cloned_vec(&l.try_borrow().ok()?), + [Object::Tuple(t)] => crate::object::cloned_vec(t), // An exact dict's keys, in order (`list(dict.fromkeys(xs))`). [Object::Dict(d)] => d.try_borrow().ok()?.keys().map(|k| k.0.clone()).collect(), _ => return None, }; let obj = Object::new_list(items); - gc_trace::track(&obj); + gc_trace::track_built(&obj); return Some(obj); } if ty.flags.is_builtin { @@ -32166,7 +37102,7 @@ impl Interpreter { /// The leaf method table entry for `name` on a builtin receiver. #[inline] - fn leaf_builtin_method( + pub(crate) fn leaf_builtin_method( &self, recv: &Object, name: &str, @@ -32177,14 +37113,17 @@ impl Interpreter { Object::Set(_) => LeafRecv::Set, Object::Str(_) => LeafRecv::Str, Object::Int(_) => LeafRecv::Int, + Object::Float(_) => LeafRecv::Float, Object::Bytes(_) => LeafRecv::Bytes, + Object::ByteArray(_) => LeafRecv::ByteArray, _ => return None, }; self.leaf_fns() - .methods + .method_names + .get(name)? .iter() - .find(|(r, n, _)| *r == kind && *n == name) - .map(|(_, _, f)| f.clone()) + .find(|(r, _)| *r == kind) + .map(|(_, f)| f.clone()) } /// `inst`'s class's `__next__` when it is a registered leaf builtin @@ -32238,6 +37177,487 @@ impl Interpreter { /// direct operation when it applies, else the builtin. `None` when the /// class's `__next__` is not a registered leaf. #[inline] + /// `next(it)` of a plain iterator class's instance whose `__next__` is + /// a warm pure or effect leaf of `(self)` (`self.i += 1; return x`), + /// for a caller that catches the end as `FOR_ITER` does: its value, the + /// stores committed, or `Some(None)` when it ended at a bare `raise + /// StopIteration` (the exception never built, as nothing could see + /// it). `None` for anything else, having done nothing. + pub(crate) fn leaf_python_step( + &self, + it: &Object, + inst: &PyInstance, + ) -> Option> { + self.leaf_python_step_with(it, inst, true) + } + + /// [`Self::leaf_python_step`]; without `ends_land`, an exhausting + /// step with stores buffered ahead of its raise declines instead + /// (for a caller that then runs the full call, which makes them). + pub(crate) fn leaf_python_step_with( + &self, + it: &Object, + inst: &PyInstance, + ends_land: bool, + ) -> Option> { + use crate::types::{vm_key, AttrKey}; + // The legacy sequence protocol's iterator (`iter(seq)` of a class + // with only `__getitem__`): its sequence's `__getitem__`, frameless. + if let Some(rev) = seqiter_kind(inst) { + return self.seqiter_step(inst, rev); + } + let f = Self::instance_dunder_function(inst, AttrKey::vm(vm_key::NEXT_FN), "__next__")?; + let code = f.code(); + if code.arg_count != 1 || !pure_leaf_warm(&code) { + return None; + } + let pure = code_is_pure_leaf(&code); + if !(pure || code_is_effect_leaf(&code)) { + return None; + } + let depth = crate::recursion::current_depth(); + if depth >= crate::recursion::recursion_limit() { + return None; + } + // (A tracer or monitor would see the raise: the step then declines + // at it, and the full call raises.) + let stop = if crate::trace::any_observers_active() { + (0, 0, false) + } else { + ( + Rc::as_ptr(&code) as usize, + std::ptr::from_ref(it) as usize, + ends_land, + ) + }; + let saved = ( + self.leaf_stop.replace(stop), + self.leaf_stop_index.replace(false), + ); + let r = self.pure_leaf_call(&code, &f, &[std::ptr::from_ref(it)], !pure, depth); + self.leaf_stop.set(saved.0); + self.leaf_stop_index.set(saved.1); + match r { + Some(Object::Unbound) => Some(None), + r => r.map(Some), + } + } + + /// One step of `_seqtools._SeqIter` (or, `rev`, `_ReversedIter`) + /// `inst`, as its `__next__` takes it, when its sequence is an instance + /// whose class's `__getitem__` is a warm pure leaf: the item at the + /// iterator's index (the index moved on), or the end at the body's bare + /// `raise IndexError` or `raise StopIteration`, or at a plain + /// sequence's own index miss (the sequence then dropped, as CPython's + /// `seqiterobject` clears it). `None`, nothing done, for anything else. + fn seqiter_step(&self, inst: &PyInstance, rev: bool) -> Option> { + // SAFETY: views no code runs under: the evaluations below are + // pure, and the dropped sequence (whose release may run a + // finalizer) leaves after their last use. + let [seq_slot, index_slot] = unsafe { seqiter_fields(inst, rev) }?; + let Object::Int(index) = *index_slot else { + return None; + }; + if index == i64::MAX || index == i64::MIN { + return None; + } + let r = if rev && index < 0 { + if !matches!(&*seq_slot, Object::Instance(_)) { + return None; + } + Object::Unbound + } else { + self.leaf_item(seq_slot, index, true)? + .unwrap_or(Object::Unbound) + }; + if matches!(r, Object::Unbound) { + let old = std::mem::replace(seq_slot, Object::None); + drop(old); + return Some(None); + } + *index_slot = Object::Int(if rev { index - 1 } else { index + 1 }); + Some(Some(r)) + } + + /// `seq[index]` (`index` not negative) of an instance whose class's + /// `__getitem__` is a warm pure leaf, evaluated frameless: the item, + /// or `Some(None)` where a plain sequence's own index miss ends the + /// evaluation (the read's `IndexError`, raised by `return + /// self.items[i]`). `None`, nothing done, for anything else. With + /// `ends` (a legacy sequence's iterator asking), the body's bare + /// `raise IndexError` or `raise StopIteration` answers `Some(None)` + /// too. + pub(crate) fn leaf_item(&self, seq: &Object, index: i64, ends: bool) -> Option> { + use crate::types::{vm_key, AttrKey}; + let Object::Instance(sinst) = seq else { + return None; + }; + if sinst.native.get().is_some() { + return None; + } + let f = + Self::instance_dunder_function(sinst, AttrKey::vm(vm_key::GETITEM_FN), "__getitem__")?; + let code = f.code(); + if code.arg_count != 2 || !pure_leaf_warm(&code) || !code_is_pure_leaf(&code) { + return None; + } + let depth = crate::recursion::current_depth(); + if depth >= crate::recursion::recursion_limit() || crate::trace::any_observers_active() { + return None; + } + let at = Object::Int(index); + match Self::delegate_item(&code, seq, sinst, &at) { + Some(Delegated::Item(v)) => return Some(Some(v)), + Some(Delegated::IndexMiss(_)) => return Some(None), + // (A `KeyError` is the call's to raise.) + Some(Delegated::KeyMiss) => return None, + None => {} + } + let args = [std::ptr::from_ref(seq), std::ptr::from_ref(&at)]; + if !ends { + return self + .pure_leaf_call(&code, &f, &args, false, depth) + .map(Some); + } + let stop = (Rc::as_ptr(&code) as usize, args[0] as usize, true); + let saved = ( + self.leaf_stop.replace(stop), + self.leaf_stop_index.replace(true), + ); + let r = self.pure_leaf_call(&code, &f, &args, false, depth); + self.leaf_stop.set(saved.0); + self.leaf_stop_index.set(saved.1); + r.map(|v| (!matches!(v, Object::Unbound)).then_some(v)) + } + + /// `cont[key]` by [`Self::delegate_item`] for a caller with the class's + /// `__getitem__` in hand (compiled code's `BINARY_SUBSCR`, `dict(m)`'s + /// reads): of an instance whose class's `__getitem__` is `f`, + /// a warm pure leaf: the item, or `None` (nothing done) for anything + /// the call itself must answer. + pub(crate) fn delegate_subscr( + f: &crate::object::PyFunction, + cont: &Object, + key: &Object, + ) -> Option { + let Object::Instance(inst) = cont else { + return None; + }; + let code = f.code(); + if code.instructions.len() != 6 + || code.arg_count != 2 + || inst.native.get().is_some() + || !pure_leaf_warm(&code) + || !code_is_pure_leaf(&code) + || crate::trace::any_observers_active() + { + return None; + } + match Self::delegate_item(&code, cont, inst, key) { + Some(Delegated::Item(v)) => Some(v), + _ => None, + } + } + + /// [`Self::delegate_subscr`] with the read's miss told apart from a + /// read the call must make: compiled code raises a miss its own + /// handler takes unseen (see [`Self::caught_unseen`]). + #[cfg(feature = "jit")] + pub(crate) fn delegate_probe( + f: &crate::object::PyFunction, + cont: &Object, + key: &Object, + ) -> Option { + let Object::Instance(inst) = cont else { + return None; + }; + let code = f.code(); + if code.instructions.len() != 6 + || code.arg_count != 2 + || inst.native.get().is_some() + || !pure_leaf_warm(&code) + || !code_is_pure_leaf(&code) + || crate::trace::any_observers_active() + { + return None; + } + Self::delegate_item(&code, cont, inst, key) + } + + /// Whether an exception of the builtin class `class`, raised at `pc` + /// of `frame`'s code, is caught at once by a handler that never looks + /// at it: `except :` with no `as`, whose name is a builtin class + /// `class` derives from (as the frame reads the name), and whose + /// instructions up to its `POP_EXCEPT` only drop the exception and + /// load locals or constants (`Mapping.get`'s `except KeyError: return + /// default`). Nothing can then see the exception or its traceback, so + /// a raise with no frame behind it is the same raise. + #[cfg(feature = "jit")] + pub(crate) fn caught_unseen(&self, frame: &Frame, pc: usize, class: &Rc) -> bool { + let code = &frame.code; + let Some(entry) = find_handler(&code.exception_table, pc as u32) else { + return false; + }; + let h = entry.handler as usize; + let ins = &code.instructions; + let Some(head) = ins.get(h..h + 6) else { + return false; + }; + if entry.push_lasti + || head[0].op != OpCode::PushExcInfo + || head[1].op != OpCode::LoadGlobal + || head[2].op != OpCode::CheckExcMatch + || head[3].op != OpCode::PopJumpIfFalse + || head[4].op != OpCode::NotTaken + || head[5].op != OpCode::PopTop + { + return false; + } + // (Up to the `POP_EXCEPT`: nothing that could run code.) + let quiet = ins[h + 6..] + .iter() + .take(6) + .position(|i| i.op == OpCode::PopExcept) + .is_some_and(|n| { + ins[h + 6..h + 6 + n].iter().all(|i| { + matches!( + i.op, + OpCode::LoadFast + | OpCode::LoadFastBorrow + | OpCode::LoadConst + | OpCode::LoadSmallInt + | OpCode::Swap + | OpCode::Nop + ) + }) + }); + if !quiet { + return false; + } + let Some(name) = code.names.get(head[1].arg as usize) else { + return false; + }; + let key = crate::object::StrKey(name.as_str()); + if self.globals_missing_owner(&frame.globals).is_some() { + return false; + } + let Ok(globals) = frame.globals.try_borrow() else { + return false; + }; + if globals.get(&key).is_some() { + return false; + } + let Ok(builtins) = frame.builtins.try_borrow() else { + return false; + }; + matches!(builtins.get(&key), Some(Object::Type(t)) + if t.flags.is_builtin && (Rc::ptr_eq(t, class) || class.is_subclass_of(t))) + } + + /// The field a `__getitem__` that only delegates reads (`code`, as + /// [`Self::delegate_item`] matches it), as its own attribute site + /// reads it off `seq`: `None` for any other body. + fn delegate_field(code: &CodeObject, seq: &Object, inst: &Rc) -> Option { + let [resume, this, attr, at, sub, ret] = code.instructions.as_slice() else { + return None; + }; + let local = |i: &weavepy_compiler::Instruction, n: u32| { + matches!(i.op, OpCode::LoadFast | OpCode::LoadFastBorrow) && i.arg == n + }; + if resume.op != OpCode::Resume + || !local(this, 0) + || attr.op != OpCode::LoadAttr + || !local(at, 1) + || sub.op != OpCode::BinarySubscr + || ret.op != OpCode::ReturnValue + { + return None; + } + let ext = code_vm_ext(code)?; + // SAFETY: `seq` roots the receiver, and the value is cloned out + // before anything runs. + match unsafe { Self::leaf_cached_instance_field(ext, code, inst, 2, attr.arg) } { + Some(v) => Some(v.clone()), + None => Self::leaf_attr_resolve_site(code, inst, seq, 2, attr.arg), + } + } + + /// `seq[key]` where `code`, the pure-leaf `__getitem__(self, key)` of + /// `seq`'s class, is `return self.[key]` and the field (read as + /// the body's own attribute site reads it) holds a plain container + /// that answers with no code run: a list's or tuple's item at an + /// `int` (`Some(None)` past either end, the read's `IndexError`), or a + /// dict's at a natively hashed key it holds. `None` for any other + /// body, field or key. + #[inline] + fn delegate_item( + code: &CodeObject, + seq: &Object, + inst: &Rc, + key: &Object, + ) -> Option { + let [resume, this, attr, at, sub, ret] = code.instructions.as_slice() else { + return None; + }; + let local = |i: &weavepy_compiler::Instruction, n: u32| { + matches!(i.op, OpCode::LoadFast | OpCode::LoadFastBorrow) && i.arg == n + }; + if resume.op != OpCode::Resume + || !local(this, 0) + || attr.op != OpCode::LoadAttr + || !local(at, 1) + || sub.op != OpCode::BinarySubscr + || ret.op != OpCode::ReturnValue + { + return None; + } + let ext = code_vm_ext(code)?; + let held; + // SAFETY: `seq` roots the receiver, and nothing runs before the + // item is retained. + let field = match unsafe { Self::leaf_cached_instance_field(ext, code, inst, 2, attr.arg) } + { + Some(v) => v, + None => { + held = Self::leaf_attr_resolve_site(code, inst, seq, 2, attr.arg)?; + &held + } + }; + let at = |i: i64, n: usize| { + let n = n as i64; + let i = if i < 0 { i + n } else { i }; + (0..n).contains(&i).then_some(i as usize) + }; + let found = match (field, key) { + (Object::List(l), Object::Int(i)) => { + // SAFETY: a view that ends here. + let xs = unsafe { l.peek() }?; + match at(*i, xs.len()) { + Some(i) => Delegated::Item(clone_hot(&xs[i])), + None => Delegated::IndexMiss("list index out of range"), + } + } + (Object::Tuple(t), Object::Int(i)) => match at(*i, t.len()) { + Some(i) => Delegated::Item(clone_hot(&t[i])), + None => Delegated::IndexMiss("tuple index out of range"), + }, + (Object::Dict(d), Object::Str(_) | Object::Int(_)) => { + let probe = crate::object::LeafProbe::new(key)?; + // SAFETY: a view that ends here (the probe runs no code). + match unsafe { d.peek() }?.get(&probe) { + Some(v) => Delegated::Item(clone_hot(v)), + None => Delegated::KeyMiss, + } + } + _ => return None, + }; + // (An answer here, the read's own miss included, is the leaf's: + // it ends a run of the misses that would withdraw the verdict, + // see `note_leaf_miss`.) + code.jit_hint.note_leaf_hit(); + Some(found) + } + + /// One step of a legacy sequence's iterator `inst` (see + /// [`Self::seqiter_step`], tried first), with no frame for the + /// helper's own `__next__` (CPython's is C): the sequence's + /// `__getitem__` at the iterator's index, an `IndexError` or a + /// `StopIteration` from it the end. `None`, nothing done, for a state + /// its `__next__` takes itself. + pub(crate) fn seqiter_next( + &mut self, + inst: &PyInstance, + rev: bool, + ) -> Option, RuntimeError>> { + if let Some(r) = self.seqiter_step(inst, rev) { + return Some(Ok(r)); + } + // (An observer follows the helper's own `__next__`, as before.) + if crate::trace::any_observers_active() { + return None; + } + let (seq, index) = { + let slots = inst.slots.try_borrow().ok()?; + let seq = slots.get_hinted(0, "_seq")?.clone(); + let Object::Int(i) = *slots.get_hinted(1, "_index")? else { + return None; + }; + (seq, i) + }; + // (The dropped sequence leaves once the borrow has ended: its + // release may run a finalizer.) + let clear = |inst: &PyInstance| { + let old = inst.slots.try_borrow_mut().ok().and_then(|mut s| { + Some(std::mem::replace( + s.get_hinted_mut(0, "_seq")?, + Object::None, + )) + }); + drop(old); + }; + if matches!(seq, Object::None) { + return Some(Ok(None)); + } + if rev && index < 0 { + clear(inst); + return Some(Ok(None)); + } + match self.subscr_get_public(&seq, &Object::Int(index)) { + Ok(v) => { + // (`self._index += 1` reads the index again: the call may + // have stepped the iterator; the reversed one stores the + // index it read before it.) + if let Ok(mut slots) = inst.slots.try_borrow_mut() { + if let Some(at) = slots.get_hinted_mut(1, "_index") { + if rev { + *at = Object::Int(index.saturating_sub(1)); + } else if let Object::Int(now) = *at { + *at = Object::Int(now.saturating_add(1)); + } + } + } + Some(Ok(Some(v))) + } + Err(e) if ends_sequence(&e) => { + clear(inst); + Some(Ok(None)) + } + Err(e) => Some(Err(e)), + } + } + + /// `next(it)` or `next(it, default)` (the builtin's leaf operands) of + /// an instance whose class's `__next__` is a registered native leaf or + /// a warm frameless Python leaf, stepped as `FOR_ITER` steps it (see + /// [`Self::leaf_next_step`], [`Self::leaf_python_step`]). `None` for + /// anything else, having done nothing. + pub(crate) fn leaf_next_instance( + &self, + args: &[Object], + ) -> Option> { + let (it, default) = match args { + [it] => (it, None), + [it, d] => (it, Some(d)), + _ => return None, + }; + let Object::Instance(inst) = it else { + return None; + }; + match self.leaf_next_step(it, inst) { + Some(Err(e)) if default.is_some() && crate::seqiter::is_stop_iteration(&e) => { + return default.cloned().map(Ok); + } + Some(r) => return Some(r), + None => {} + } + match self.leaf_python_step_with(it, inst, default.is_some())? { + Some(v) => Some(Ok(v)), + // (Without a default, the full call raises the exception + // `__next__` raises, traceback and all.) + None => default.cloned().map(Ok), + } + } + fn leaf_next_step( &self, it: &Object, @@ -32284,7 +37704,8 @@ impl Interpreter { } /// Which leaf builtin `b` is, if any (pointer identity). - fn leaf_call_kind(&self, b: &Rc) -> Option { + #[inline] + pub(crate) fn leaf_call_kind(&self, b: &Rc) -> Option { let p = Rc::as_ptr(b) as usize; let gen = leaf_builtins::generation(); // (A builtin freed and another made at its address meanwhile only @@ -32292,29 +37713,78 @@ impl Interpreter { if self.leaf_miss.get() == (p, gen) { return None; } - if let Some(k) = self.leaf_fns().calls.get(&p) { - return Some(*k); + if let Ok(hit) = self.leaf_hit.try_borrow() { + if let Some((w, g, k)) = &*hit { + if std::ptr::eq(w.as_ptr(), Rc::as_ptr(b)) && *g == gen && w.strong_count() > 0 { + return Some(*k); + } + } + } + self.leaf_call_kind_lookup(b, p, gen) + } + + /// [`Self::leaf_call_kind`] past its last answers: the tables' (out of + /// line, so the answers' check stays small in its callers). + #[inline(never)] + fn leaf_call_kind_lookup( + &self, + b: &Rc, + p: usize, + gen: u64, + ) -> Option { + if let Some(&k) = self.leaf_fns().calls.get(&p) { + // (The table never changes: the last builtin asked for is + // answered without its lookup next time, as `map(abs, xs)` + // asks once an item.) + if let Ok(mut hit) = self.leaf_hit.try_borrow_mut() { + *hit = Some((Rc::downgrade(b), gen, k)); + } + return Some(k); } + let kind = |e: &leaf_builtins::Entry| match e { + leaf_builtins::Entry::Fast(f) => LeafKind::Fast(*f), + leaf_builtins::Entry::Opaque => LeafKind::Opaque, + leaf_builtins::Entry::Scalar => LeafKind::Scalar, + }; let found = { let mut opaque = self.leaf_opaque.borrow_mut(); + // (A registration may replace a builtin's entry: what this + // interpreter looked up before it is looked up again.) if opaque.0 != gen { - opaque.1 = leaf_builtins::snapshot(); + opaque.1.clear(); + opaque.2.clear(); opaque.0 = gen; } // The registered builtin must still be *this* allocation: a // recycled address (a torn-down interpreter's module surface) // fails the upgrade or the identity check. - opaque.1.get(&p).and_then(|(w, fast)| { + let cached = opaque.1.get(&p).and_then(|(w, e)| { let live = w.upgrade()?; - Rc::ptr_eq(&live, b).then(|| match fast { - leaf_builtins::Entry::Fast(f) => LeafKind::Fast(*f), - leaf_builtins::Entry::Opaque => LeafKind::Opaque, - leaf_builtins::Entry::Scalar => LeafKind::Scalar, - }) - }) + Rc::ptr_eq(&live, b).then(|| kind(e)) + }); + if cached.is_some() { + cached + } else { + if opaque.2.contains(&p) { + None + } else if let Some(reg) = leaf_builtins::lookup(b) { + let k = kind(®.1); + opaque.1.insert(p, reg); + Some(k) + } else { + opaque.1.remove(&p); + opaque.2.insert(p); + None + } + } }; - if found.is_none() { - self.leaf_miss.set((p, gen)); + match found { + None => self.leaf_miss.set((p, gen)), + Some(k) => { + if let Ok(mut hit) = self.leaf_hit.try_borrow_mut() { + *hit = Some((Rc::downgrade(b), gen, k)); + } + } } found } @@ -32413,7 +37883,21 @@ impl Interpreter { Some(k) => k, None => self.leaf_pure_builtin_kind(slot, b, rc)?, }; - if !kind.is_pure_read() { + // (An opaque `str` method, `s.zfill(5)` or `s.count("a")`, or a + // `bytes`, `int` or `float` method's opaque or fast half, reads its + // immutable receiver and runs no code: its result is its only + // effect.) + // SAFETY: the plan's holder keeps the builtin alive. + let str_method = unsafe { (*b).binds_instance } + && matches!( + (kind, args.first()), + (LeafKind::Opaque, Some(Object::Str(_))) + | ( + LeafKind::Opaque | LeafKind::Fast(_), + Some(Object::Bytes(_) | Object::Int(_) | Object::Float(_)) + ) + ); + if !kind.is_pure_read() && !str_method { return None; } // SAFETY: the plan's holder (a namespace, or the leaf method @@ -32459,9 +37943,134 @@ impl Interpreter { /// callers (`operator.attrgetter`): `None` for what the full path must /// decide. pub(crate) fn leaf_getattr_value(obj: &Object, name: &Object) -> Option { + // A plain instance's attribute at the place an earlier read + // remembered for its class's version (the class supplies nothing + // for the name; see `InstGetattrEntry::place`): the value there, + // ahead of the general read's checks, which that read made. + if let (Object::Instance(inst), Object::Str(n)) = (obj, name) { + let cls = inst.cls_raw(); + if inst.native.get().is_none() + && cls.native_kind.get() == 0 + && !crate::object::exotic_str_keys_possible() + { + if let Some((InstGetattrClass::Nothing | InstGetattrClass::Shadowed, place)) = + instance_getattr_entry(cls, n) + { + if place != 0 && place != PLACE_NONE { + // SAFETY: a read that runs no code, cloned out. + if let Some(v) = unsafe { inst.split_field(place as usize - 1) } { + return Some(v.clone()); + } + } + } + } + } Self::leaf_getattr_parts(obj, name, None, false) } + /// Where `inst` keeps `name` among its laid-out slots, when its class + /// resolves the name to a `__slots__` member without a default (as + /// [`Self::leaf_getattr_value`] noted for the class's version): a + /// native caller reading the name off many instances of the class + /// then reads that position, checking the key there. + pub(crate) fn slot_member_position(inst: &PyInstance, name: &str) -> Option { + let cls = inst.cls_raw(); + if crate::object::exotic_str_keys_possible() + || name.starts_with("__") + || cls.native_kind.get() != 0 + || inst.native.get().is_some() + || !matches!( + instance_getattr_memo(cls, name), + Some(InstGetattrClass::Slot) + ) + { + return None; + } + // SAFETY: a read that runs no code. + let slots = unsafe { inst.slots.peek() }?; + (0..) + .map_while(|i| slots.get_index(i).map(|e| (i, e))) + .find(|(_, (k, _))| matches!(&k.0, Object::Str(n) if { let n: &str = n; n == name })) + .map(|(i, _)| i) + } + + /// The Python function `obj.` binds on a plain instance (no + /// native payload, the default `__getattribute__`, no instance entry + /// shadowing the class's function), for native callers that call the + /// method with the instance first (`operator.methodcaller`): `None` + /// for anything else, which the full attribute read decides. + pub(crate) fn plain_instance_method( + obj: &Object, + name: &str, + ) -> Option> { + let Object::Instance(inst) = obj else { + return None; + }; + if crate::object::exotic_str_keys_possible() || name.starts_with("__") { + return None; + } + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 + || inst.native.get().is_some() + || inst.c_body.get() != 0 + || !Self::default_getattribute(cls) + { + return None; + } + let Some(Object::Function(f)) = cls.lookup(name) else { + return None; + }; + if inst.attr_get_str(name).is_some() { + return None; + } + Some(f) + } + + /// [`Self::plain_instance_method`] for a name held as a string object + /// (a `methodcaller`'s): the class's function is remembered on the + /// class, under the interned name and the class's version, so a + /// caller that asks for every item of a sequence looks it up once. + pub(crate) fn plain_instance_method_named( + obj: &Object, + name: &SharedStr, + ) -> Option> { + use crate::types::LeafAttrKind as K; + let Object::Instance(inst) = obj else { + return None; + }; + if crate::object::exotic_str_keys_possible() || name.starts_with("__") { + return None; + } + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 + || inst.native.get().is_some() + || inst.c_body.get() != 0 + || !Self::default_getattribute(cls) + { + return None; + } + let interned = crate::stdlib::sys::intern_shared_memo(name); + let key = crate::types::AttrKey::name(&interned); + let ver = cls.attr_version.get(); + let f = match cls.leaf_attrs.get(key, ver) { + Some(K::Method(w)) => w.upgrade()?, + held => { + let Some(Object::Function(f)) = cls.lookup(name) else { + return None; + }; + // (An entry another reader left stays as it is.) + if held.is_none() { + cls.leaf_attrs.set(key, ver, K::Method(Rc::downgrade(&f))); + } + f + } + }; + if inst.attr_get_str(name).is_some() { + return None; + } + Some(f) + } + /// `getattr(obj, name[, default])` on a plain instance whose lookup /// runs no code: an instance attribute, a plain class value, or a /// method to bind, and for a missing attribute with no `__getattr__`, @@ -32474,6 +38083,35 @@ impl Interpreter { Self::leaf_getattr_parts(args.first()?, args.get(1)?, args.get(2), false).map(Ok) } + /// `getattr(obj, name[, default])` of a property whose getter is a + /// Python function that evaluates as a pure leaf, on a plain instance + /// (a property is a data descriptor, so no instance entry shadows + /// it): the getter's result. `None` for the full call. + fn leaf_getattr_property(&self, args: &[Object]) -> Option> { + let (recv @ Object::Instance(inst), Object::Str(name)) = (args.first()?, args.get(1)?) + else { + return None; + }; + if args.len() > 3 || crate::object::exotic_str_keys_possible() { + return None; + } + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 + || inst.native.get().is_some() + || inst.c_body.get() != 0 + || !Self::default_getattribute(cls) + { + return None; + } + let Some(Object::Property(p)) = cls.lookup(name) else { + return None; + }; + let Object::Function(fget) = p.fget() else { + return None; + }; + self.call_pure_leaf_with(&fget, Some(recv), &[]).map(Ok) + } + /// [`Self::leaf_getattr`] on its parts, `default` the third argument's /// value if any. With `probe` (`hasattr`), the value found matters /// only as present: a method found to bind is answered with `True` @@ -32495,16 +38133,73 @@ impl Interpreter { let inst = match recv { Object::Instance(inst) => inst, // A function's stored attribute (`__doc__` once read, - // `__wrapped__`). - Object::Function(f) => return function_stored_attr(f, name_obj), - Object::Type(cls) => return Self::leaf_type_getattr(cls, name, default), + // `__wrapped__`), or with a default one the full read found + // missing (`inspect`'s `getattr(func, "__signature__", None)`). + Object::Function(f) => { + if let Some(v) = function_stored_attr(f, name_obj) { + return Some(v); + } + let d = default?; + let c = function_miss_class(recv, name)?; + return (c.verdict_cached(crate::types::Verdict::ValueAttrMissing, name) + == Some(true)) + .then(|| d.clone()); + } + Object::Type(cls) => return Self::leaf_type_getattr_memo(cls, name_obj, default), // A plain module's global (`hasattr(os, 'getpid')`): its // dictionary's value (`ModuleType`'s descriptors are dunders; // a missing name may reach a module `__getattr__`). - Object::Module(m) - if !name.starts_with("__") && !crate::object::module_classes_possible() => + // + // A missing one with a default, the module defining no + // `__getattr__`, is the default (`getattr(os, "name", None)`). + // + // A dunder its dictionary holds is the entry too, as the + // interpreter's read finds it first (`getattr(m, "__spec__", + // None)` in `importlib._bootstrap._find_and_load`); a missing + // one may be synthesized (`__spec__`) or computed. + Object::Module(m) if !crate::object::module_classes_possible() => { + let dict = m.dict.borrow(); + if let Some(v) = dict.get(&crate::object::StrKey(name)) { + return Some(v.clone()); + } + if name.starts_with("__") { + return None; + } + let d = default?; + return (!dict.contains_key(&crate::object::StrKey("__getattr__"))) + .then(|| d.clone()); + } + // A generator's (or coroutine's) public name it doesn't have + // (`hasattr(gen, "keys")`, as a mapping update probes its + // argument): its public attributes are its methods and its + // `gi_`/`cr_`/`ag_` fields. + Object::Generator(_) | Object::Coroutine(_) | Object::AsyncGenerator(_) + if !name.starts_with('_') + && !name.starts_with("gi_") + && !name.starts_with("cr_") + && !name.starts_with("ag_") + && !matches!( + name, + "send" | "throw" | "close" | "asend" | "athrow" | "aclose" + ) => { - return m.dict.borrow().get(&crate::object::StrKey(name)).cloned(); + return default.cloned(); + } + // A namespace's attribute (`ns.x` by name), and with a default + // a public name it doesn't hold (`hasattr(ns, "x")`): missing, + // unless it is an alias, which reads through its origin (the + // type's own methods are all dunders). + Object::SimpleNamespace(d) => { + let dict = d.try_borrow().ok()?; + if let Some(v) = dict.get(&crate::object::StrKey(name)) { + return Some(v.clone()); + } + let default = default?; + if name.starts_with('_') || dict.contains_key(&crate::object::StrKey("__origin__")) + { + return None; + } + return Some(default.clone()); } // A built-in kind's method (`hasattr(stream, "write")`): its // lookup runs no code, and a found method means the attribute @@ -32516,6 +38211,39 @@ impl Interpreter { { return Some(Object::Bool(true)); } + // A string's or container's method (`getattr(s, "upper")`), + // bound as the attribute load binds it (every other attribute + // of theirs is a dunder). + Object::Str(_) + | Object::List(_) + | Object::Dict(_) + | Object::Set(_) + | Object::FrozenSet(_) + | Object::Tuple(_) + | Object::Bytes(_) + | Object::ByteArray(_) + if !name.starts_with('_') && !probe => + { + return match builtins::lookup_method(recv, name) { + Some(m @ Object::Builtin(_)) if matches!(&m, Object::Builtin(b) if b.binds_instance) => { + Some(Object::BoundMethod(Rc::new(BoundMethod::new( + recv.clone(), + m, + )))) + } + Some(_) => None, + // (A miss the full path found, remembered per class + // version, is the default, as for any other built-in + // value below.) + None => { + let d = default?; + let c = builtin_value_class(recv)?; + (c.verdict_cached(crate::types::Verdict::ValueAttrMissing, name) + == Some(true)) + .then(|| d.clone()) + } + }; + } // A built-in value's class the full path found has no such // attribute (`enum`'s `hasattr(1, "__get__")`). _ => { @@ -32532,6 +38260,9 @@ impl Interpreter { if let Some(d) = default.filter(|_| attr_certainly_missing(recv, name)) { return Some(d.clone()); } + if let Some(v) = Self::leaf_plain_class_dunder(inst, name) { + return Some(v); + } return Self::leaf_builtin_dunder_attr(inst, recv, name); } let cls = inst.cls_raw(); @@ -32548,15 +38279,127 @@ impl Interpreter { } return None; } - if cls.native_kind.get() != 0 - || inst.native.get().is_some() - || !Self::default_getattribute(cls) - { + if cls.native_kind.get() != 0 { + return None; + } + // A built-in subclass's instance (`hasattr(token, "encode")` over + // `str` and `list` subclasses): its own value, a plain class value + // it doesn't shadow, a method that is there to find (the class's, + // or one of its payload's kind), or the default for a name that + // certainly misses. + if let Some(payload) = inst.native.get() { + if !Self::default_getattribute(cls) { + return None; + } + return match cls.lookup(name) { + None => { + if let Some(v) = inst.attr_get_hashed(name, SharedStr::hash_cached(name_obj)) { + return Some(v); + } + if probe + && !name.starts_with('_') + && builtins::method_memo_tag(payload).is_some() + && builtins::lookup_method(payload, name).is_some() + { + return Some(Object::Bool(true)); + } + default + .filter(|_| attr_certainly_missing(recv, name)) + .cloned() + } + Some( + v @ (Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Str(_) + | Object::Bytes(_) + | Object::Tuple(_)), + ) => Some( + inst.attr_get_hashed(name, SharedStr::hash_cached(name_obj)) + .unwrap_or(v), + ), + Some(Object::Function(_) | Object::Builtin(_)) if probe => Some(Object::Bool(true)), + Some(_) => None, + }; + } + // The class's part, remembered for its version (see + // `instance_getattr_memo`): nothing on the class, or a slot. + let entry = instance_getattr_entry(cls, name); + let memo = entry.map(|(kind, _)| kind); + // A name the class supplies nothing for, at the place an earlier + // read found it among the class's shared names: this instance's + // value there, with no search for the name. + if let Some((InstGetattrClass::Nothing | InstGetattrClass::Shadowed, place)) = entry { + if place != 0 && place != PLACE_NONE { + // SAFETY: a read that runs no code, the value cloned out. + if let Some(v) = unsafe { inst.split_field(place as usize - 1) } { + return Some(v.clone()); + } + } + } + if memo.is_none() && !Self::default_getattribute(cls) { return None; } // Only class values without `__get__` (or a function, which binds) // leave the instance dictionary in charge. - let on_class = cls.lookup(name); + let on_class = match memo { + Some(InstGetattrClass::Nothing) => None, + Some(InstGetattrClass::Slot) => Some(Object::Unbound), + // A plain class value: the instance's own first (its place + // remembered, as below), the class's only without one. + Some(InstGetattrClass::Shadowed) => { + if let Some(v) = inst.attr_get_hashed(name, SharedStr::hash_cached(name_obj)) { + if let Some((_, 0)) = entry { + note_instance_getattr_place(cls, name, inst); + } + return Some(v); + } + cls.lookup(name) + } + None => { + let on_class = cls.lookup(name); + match &on_class { + None => note_instance_getattr(cls, name, InstGetattrClass::Nothing), + Some(Object::SlotDescriptor(s)) if s.name == name && s.default.is_none() => { + note_instance_getattr(cls, name, InstGetattrClass::Slot) + } + Some( + Object::Function(_) + | Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Str(_) + | Object::Bytes(_) + | Object::Tuple(_), + ) => note_instance_getattr(cls, name, InstGetattrClass::Shadowed), + _ => {} + } + on_class + } + }; + // A `__slots__` member (a data descriptor, ahead of any instance + // dictionary): its stored value, as `obj.name` reads it; unset, the + // default when no `__getattr__` could supply one (the full path + // raises the `AttributeError` otherwise). (`Unbound`: the memo's + // slot.) + if let Some(Object::SlotDescriptor(_) | Object::Unbound) = &on_class { + if let Some(Object::SlotDescriptor(s)) = &on_class { + if s.name != name || s.default.is_some() { + return None; + } + } + if let Some(v) = inst + .slot_get(name) + .filter(|v| !matches!(v, Object::Unbound)) + { + return Some(v); + } + return default + .filter(|_| !cls.dunder(crate::types::Dunder::GetAttr).present()) + .cloned(); + } if !matches!( on_class, None | Some( @@ -32572,7 +38415,10 @@ impl Interpreter { ) { return None; } - if let Some(v) = inst.attr_get_str(name) { + if let Some(v) = inst.attr_get_hashed(name, SharedStr::hash_cached(name_obj)) { + if let Some((InstGetattrClass::Nothing, 0)) = entry { + note_instance_getattr_place(cls, name, inst); + } return Some(v); } Some(match on_class { @@ -32599,22 +38445,166 @@ impl Interpreter { name: &str, default: Option<&Object>, ) -> Option { + match Self::leaf_type_getattr_how(cls, name, default.is_some()) { + TypeGetattr::Found(v, _) => Some(v), + TypeGetattr::Missing => default.cloned(), + TypeGetattr::Decline => None, + } + } + + /// [`Self::leaf_type_getattr`] behind a memo of its answers for a + /// class under plain `type`, by the class's attribute version and the + /// name object: a name nothing supplies (the default answers) or the + /// value found. `inspect`, `typing` and `dataclasses` ask the same few + /// questions of the same classes for every object they handle + /// (`getattr(cls, "__wrapped__", None)`), and each answer cost four + /// lookups along the MRO and three name classifications, about 1,000 + /// instructions. The memo owns only values whose lifetime nothing + /// observes (scalars, builtin functions); any other is borrowed from + /// the Python class whose dictionary holds it, which it does while the + /// version stands, so an object a class stops holding dies when it + /// does. + fn leaf_type_getattr_memo( + cls: &Rc, + name: &SharedStr, + default: Option<&Object>, + ) -> Option { + const SLOTS: usize = 128; + thread_local! { + // (Released under the GIL at its thread's exit: it holds + // names and values.) + static MEMO: crate::gil::ReleaseUnderGil< + RefCell, TypeGetattrKept)>>, + > = const { crate::gil::ReleaseUnderGil::new(RefCell::new(Vec::new())) }; + } + let ver = cls.attr_version.get(); + // (A metaclass's attributes move with its own version, and a + // watched type's lookups are events.) + if ver == 0 || !Self::plain_metaclass(cls) || crate::capi_watchers::types_active() { + return Self::leaf_type_getattr(cls, name, default); + } + let word = SharedStr::addr(name) >> 4; + let slot = ((ver as usize) ^ word).wrapping_mul(0x9E37_79B9_7F4A_7C15_u64 as usize) + >> (usize::BITS - SLOTS.trailing_zeros()); + let hit = MEMO.with(|m| { + let m = m.try_borrow().ok()?; + let (v, n, kept) = m.get(slot)?; + if *v != ver || !n.as_ref().is_some_and(|n| SharedStr::ptr_eq(n, name)) { + return None; + } + Some(match kept { + TypeGetattrKept::Missing => None, + TypeGetattrKept::Owned(v) => Some(v.clone()), + TypeGetattrKept::Borrowed(words) => { + // SAFETY: the value's own words, which a class on the + // MRO holds while the version stands; the view is never + // dropped. + let view = std::mem::ManuallyDrop::new(unsafe { + std::ptr::from_ref(words).cast::().read() + }); + Some(Object::clone(&view)) + } + }) + }); + match hit { + Some(Some(v)) => return Some(v), + // (Missing with no default: the full path raises.) + Some(None) => return default.cloned(), + None => {} + } + let how = Self::leaf_type_getattr_how(cls, name, default.is_some()); + let keep = match &how { + TypeGetattr::Missing => Some(TypeGetattrKept::Missing), + TypeGetattr::Found( + v @ (Object::None + | Object::Bool(_) + | Object::Int(_) + | Object::Float(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::Builtin(_)), + _, + ) => Some(TypeGetattrKept::Owned(v.clone())), + TypeGetattr::Found( + v @ (Object::Tuple(_) + | Object::List(_) + | Object::Dict(_) + | Object::Type(_) + | Object::Function(_) + | Object::Property(_)), + true, + ) => { + const _: () = assert!(std::mem::size_of::() == 16); + // SAFETY: a plain read of the value's two words. + Some(TypeGetattrKept::Borrowed(unsafe { + std::ptr::from_ref(v).cast::<[u64; 2]>().read() + })) + } + _ => None, + }; + if let Some(kept) = keep { + MEMO.with(|m| { + if let Ok(mut m) = m.try_borrow_mut() { + if m.is_empty() { + m.resize_with(SLOTS, || (0, None, TypeGetattrKept::Missing)); + } + // (The name is held: its address names it while the + // entry stands.) + m[slot] = (ver, Some(name.clone()), kept); + } + }); + } + match how { + TypeGetattr::Found(v, _) => Some(v), + TypeGetattr::Missing => default.cloned(), + TypeGetattr::Decline => None, + } + } + + /// How [`Self::leaf_type_getattr`] answers: the value found, a name + /// nothing supplies (asked only `with_default`: without one the full + /// path raises), or neither. + fn leaf_type_getattr_how(cls: &Rc, name: &str, with_default: bool) -> TypeGetattr { + use TypeGetattr::{Decline, Found, Missing}; // (A VM-native builtin class with a C mirror keeps its own dict // authoritative, as in `leaf_load_type_attr`.) if cls.native_kind.get() != 0 || (cls.c_ext_ptr.get() != 0 && !cls.flags.is_builtin) || crate::capi_watchers::types_active() - || (name.starts_with("__") - && !Self::type_dunder_transparent(name) - && !matches!(name, "__format__" | "__new_member__")) { - return None; + return Decline; + } + // A class's name under plain `type`, as `load_attr_type` reads it: + // its own dictionary's string, else the type's own (never the + // MRO's or the metaclass's). + if (name == "__name__" || name == "__qualname__") && Self::plain_metaclass(cls) { + if let Some(v @ Object::Str(_)) = cls.dict.borrow().get(&crate::object::StrKey(name)) { + return Found(v.clone(), false); + } + if name == "__qualname__" { + if let Some(q) = cls.qualname.borrow().as_ref() { + return Found(Object::interned_str(q), false); + } + } + return Found(Object::interned_str(&cls.name), false); + } + if name.starts_with("__") { + // (Classified once: both questions ask the same list.) + let class = Self::type_dunder_class(name); + if class != Some(true) + && !matches!(name, "__format__" | "__new_member__") + && !(class != Some(false) && Self::type_dunder_unclaimed_rest(cls, name)) + { + return Decline; + } } if !Self::plain_metaclass(cls) { // SAFETY: GIL-serialized raw read, as in `plain_metaclass`. - let meta = unsafe { (*cls.metaclass.as_ptr()).as_ref() }?; + let Some(meta) = (unsafe { (*cls.metaclass.as_ptr()).as_ref() }) else { + return Decline; + }; if meta.c_ext_ptr.get() != 0 || !Self::default_getattribute(meta) { - return None; + return Decline; } // (What `leaf_load_meta_class_attr` lets the class answer.) if !matches!( @@ -32629,21 +38619,27 @@ impl Interpreter { | Object::Builtin(_) ) ) { - return None; + return Decline; } } - match cls.lookup(name) { + // (With the class whose dictionary supplies the value: a Python + // class's holds it for as long as the version stands.) + let found = cls + .lookup_with_owner(name) + .map(|(v, owner)| (v, !owner.flags.is_builtin)); + match found { // (A builtin class's miss the full path remembered, as `hasattr` // of `coroutine` finds `_asyncio_future_blocking` missing.) - None => default - .filter(|_| { - type_attr_certainly_missing(cls, name) - || (type_miss_memo_ok(cls, name) - && cls.verdict_cached(crate::types::Verdict::TypeAttrMissing, name) - == Some(true)) - }) - .cloned(), - Some( + None if with_default + && (type_attr_certainly_missing(cls, name) + || (type_miss_memo_ok(cls, name) + && cls.verdict_cached(crate::types::Verdict::TypeAttrMissing, name) + == Some(true))) => + { + Missing + } + None => Decline, + Some(( v @ (Object::None | Object::Bool(_) | Object::Int(_) @@ -32657,21 +38653,54 @@ impl Interpreter { | Object::Function(_) | Object::Builtin(_) | Object::Property(_)), - ) => Some(v), + held, + )) => Found(v, held), // A plain instance stored on the class, unless its class makes - // it a descriptor. - Some(Object::Instance(i)) if i.cls_raw().lookup("__get__").is_none() => { - Some(Object::Instance(i)) - } - // A static method reads as its function, never bound. - Some(Object::StaticMethod(w)) => match w.func() { - f @ Object::Function(_) => Some(f), - _ => None, + // it a descriptor (which its own class's version decides). + Some((Object::Instance(i), _)) if i.cls_raw().lookup("__get__").is_none() => { + Found(Object::Instance(i), false) + } + // A static method reads as its function, never bound (the + // wrapper holds it). + Some((Object::StaticMethod(w), held)) => match w.func() { + f @ Object::Function(_) => Found(f, held), + _ => Decline, }, - Some(_) => None, + Some(_) => Decline, } } + /// A dunder a plain instance reads from a plain value on its class + /// (`getattr(obj, "__dataclass_fields__")`, `obj.__match_args__`): the + /// instance dictionary's entry, else the class's value, which no + /// descriptor protocol touches. `None` for anything else. + fn leaf_plain_class_dunder(inst: &PyInstance, name: &str) -> Option { + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 + || inst.native.get().is_some() + || inst.c_body.get() != 0 + || !Self::default_getattribute(cls) + || cls.is_super_proxy_type() + { + return None; + } + let v = cls.lookup(name)?; + if !matches!( + v, + Object::Dict(_) + | Object::Tuple(_) + | Object::Str(_) + | Object::Int(_) + | Object::Bool(_) + | Object::None + | Object::Float(_) + | Object::FrozenSet(_) + ) { + return None; + } + Some(inst.attr_get_str(name).unwrap_or(v)) + } + /// A dunder a plain instance gets from a builtin method on its class /// (`obj.__reduce_ex__`, which `copy` fetches): what /// `load_attr_instance_default` resolves for it (an instance-dict @@ -32713,6 +38742,99 @@ impl Interpreter { /// `getattr(obj, name, default)`: `True` for a value it finds, `False` /// for a name it proves missing. `None` for anything the full call /// must decide. + /// `setattr(obj, name, value)` of a plain instance whose class sets + /// attributes by default and has no descriptor for the name: the + /// instance-dictionary store `generic_setattr_instance_with_name` makes + /// (the name interned, as there), with nothing to run. `None` for + /// everything else, and for an overwrite whose old value's release + /// could run code (the full path reaps it promptly). + fn leaf_setattr(args: &[Object]) -> Option> { + let [Object::Instance(inst), Object::Str(name), value] = args else { + return None; + }; + let cls = inst.cls_raw(); + if crate::object::exotic_str_keys_possible() + || inst.c_body.get() != 0 + || crate::capi_watchers::dicts_active() + || cls.native_kind.get() != 0 + // (An escaping bound method starts tracking: the full path's.) + || matches!(value, Object::BoundMethod(_)) + { + return None; + } + if !Self::default_setattr(cls) { + // A class's native `__setattr__` that compiled code calls in + // place (a `decimal.Context`'s), where it runs no Python + // code. + let b = Self::instance_native_dunder( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::SETATTR_NATIVE), + "__setattr__", + false, + )?; + return Self::native_setattr_hook(&b, &args[0], &args[1], value) + .then(|| Ok(Object::None)); + } + if !Self::plain_store_verdict(cls, name) { + // A `__slots__` member the class stores by the default + // `__setattr__` (`copy`'s `setattr(y, key, value)` over a + // slotted instance's state): written in place, under the + // rule below for the value it replaces. + let i = Self::slot_store_position(inst, name)?; + // SAFETY: a store between two instructions (see `peek_mut`). + let slot = unsafe { inst.laid_out_slot_mut(i, value.is_gc_atomic()) }?; + let shared = slot.strong_word().is_none_or(|w| { + // SAFETY: a counted variant's word, live while the slot + // holds it. + unsafe { &*w }.load(std::sync::atomic::Ordering::Relaxed) > 1 + }); + if !Self::core_droppable(slot) || !shared { + return None; + } + drop(std::mem::replace(slot, value.clone())); + return Some(Ok(Object::None)); + } + if let Some(i) = inst.attr_position_hashed(name, SharedStr::hash_cached(name)) { + // SAFETY: the view ends before the store below. + let (_, old) = unsafe { inst.attr_peek_index(i as usize) }?; + // (A last reference's release may queue a finalizer, which the + // full path runs at once.) + let shared = old.strong_word().is_none_or(|w| { + // SAFETY: a counted variant's word, live while `old` is. + unsafe { &*w }.load(std::sync::atomic::Ordering::Relaxed) > 1 + }); + if !Self::core_droppable(old) || !shared { + return None; + } + // (Already there: replaced at its position, with no key to + // intern or hash again.) + return match inst.attr_replace_index(i as usize, value.clone()) { + Ok(old) => { + drop(old); + Some(Ok(Object::None)) + } + Err(_) => None, + }; + } + let key = crate::stdlib::sys::intern_shared_memo(name); + let old = match inst.split_store(&key, value.clone()) { + Ok(old) => old, + Err(value) => { + let dict = inst.dict_cell(); + let mut d = dict.try_borrow_mut().ok()?; + let d = &mut *d; + let d = if value.is_gc_atomic() { + d.map_mut_atomic_store() + } else { + &mut **d + }; + d.insert(DictKey(Object::Str(key)), value) + } + }; + drop(old); + Some(Ok(Object::None)) + } + fn leaf_hasattr(args: &[Object]) -> Option> { let [obj, name] = args else { return None; @@ -32725,7 +38847,7 @@ impl Interpreter { /// Call a leaf builtin if `args` (receiver first for methods) has an /// admitted shape; `None` sends the call down the full path. - fn leaf_builtin_call( + pub(crate) fn leaf_builtin_call( &self, kind: LeafKind, b: &crate::object::BuiltinFn, @@ -32733,24 +38855,43 @@ impl Interpreter { ) -> Option> { use LeafKind as K; use Object as O; + // A method kind called unbound with no receiver (`list.pop()`) takes + // the full path, which raises the TypeError. + if args.is_empty() + && !matches!( + kind, + K::Fast(_) | K::ObjectNew | K::Opaque | K::Scalar | K::Isinstance | K::GetAttr + ) + { + return None; + } // Pure leaves as method arguments: hashing, comparison, and // conversion never reach user code. let leaf_key = |o: &Object| matches!(o, O::Str(_) | O::Int(_) | O::Bool(_) | O::None); let leaf_str = |o: &Object| matches!(o, O::Str(_)); let leaf_int = |o: &Object| matches!(o, O::Int(_) | O::Bool(_)); let admitted = match kind { - K::Len if matches!(args, [O::Instance(_)]) => { - return self.leaf_instance_len(&args[0]).map(Ok); - } K::Len => { + // (The common containers' lengths read in line.) + let n = match args { + [O::Instance(_)] => return self.leaf_instance_len(&args[0]).map(Ok), + // `len(SomeEnum)`: the metaclass's `__len__`. + [O::Type(t)] if !t.metaclass_is_type() => { + return self.leaf_class_len(t, &args[0]).map(Ok); + } + [O::List(l)] => Some(l.try_borrow().ok()?.len()), + [O::Tuple(t)] => Some(t.len()), + [O::Str(s)] => Some(crate::object::str_char_len(s)), + [O::Dict(d)] => Some(d.try_borrow().ok()?.len()), + _ => None, + }; + if let Some(n) = n { + return i64::try_from(n).ok().map(|n| Ok(O::Int(n))); + } args.len() == 1 && matches!( args[0], - O::List(_) - | O::Tuple(_) - | O::Dict(_) - | O::Str(_) - | O::Bytes(_) + O::Bytes(_) | O::ByteArray(_) | O::Set(_) | O::FrozenSet(_) @@ -32758,7 +38899,9 @@ impl Interpreter { ) } K::Isinstance => return Self::core_isinstance(args), - K::GetAttr => return Self::leaf_getattr(args), + K::GetAttr => { + return Self::leaf_getattr(args).or_else(|| self.leaf_getattr_property(args)); + } // `list.append` and `list.pop` in line (as `list_append` and // `list_pop` do them). K::ListAppend => { @@ -32867,6 +39010,16 @@ impl Interpreter { // dropping an element, or calling Python. K::SetPop => args.len() == 1 && matches!(args[0], O::Set(_)), K::SetRemove => { + // (An absent key raises through the body below.) + if Self::leaf_set_take(args) == Some(true) { + #[cfg(test)] + LEAF_SET_REMOVALS.with(|counts| { + let mut values = counts.get(); + values[1] += 1; + counts.set(values); + }); + return Some(Ok(O::None)); + } if !(args.len() == 2 && matches!(args[0], O::Set(_)) && Self::leaf_hash_native(&args[1])) @@ -32910,6 +39063,9 @@ impl Interpreter { return Some(Ok(O::None)); } K::SetDiscard => { + if Self::leaf_set_take(args).is_some() { + return Some(Ok(O::None)); + } if !(args.len() == 2 && matches!(args[0], O::Set(_)) && Self::leaf_hash_native(&args[1])) @@ -32931,10 +39087,14 @@ impl Interpreter { !deferred } K::StrStartswith | K::StrEndswith => { - (args.len() == 2 && leaf_str(&args[0]) && leaf_str(&args[1])) + // (The affix a `str` or a tuple of them, `s.startswith(("a", + // "b"))`.) + let affix = + |o: &Object| leaf_str(o) || matches!(o, O::Tuple(t) if t.iter().all(leaf_str)); + (args.len() == 2 && leaf_str(&args[0]) && affix(&args[1])) || (args.len() == 3 && leaf_str(&args[0]) - && leaf_str(&args[1]) + && affix(&args[1]) && leaf_int(&args[2])) } K::StrLower | K::StrUpper | K::StrIsdigit | K::StrIsalpha | K::StrIsspace => { @@ -32980,11 +39140,13 @@ impl Interpreter { && leaf_str(&args[2]) } K::StrJoin => { + // (A `str` subclass's item is read as its payload.) + let item = |x: &Object| leaf_str(x) || crate::builtins::join_item_str(x).is_some(); args.len() == 2 && leaf_str(&args[0]) && match &args[1] { - O::List(l) => l.try_borrow().is_ok_and(|l| l.iter().all(leaf_str)), - O::Tuple(t) => t.iter().all(leaf_str), + O::List(l) => l.try_borrow().is_ok_and(|l| l.iter().all(item)), + O::Tuple(t) => t.iter().all(item), _ => false, } } @@ -33045,6 +39207,34 @@ impl Interpreter { }) } + /// `s.discard(x)` or `s.remove(x)` of an exact set, for a key one + /// native probe settles (a `str`, a machine `int` or a finite `float` + /// met only by stored keys of its own kind, see + /// `Table::find_object_native`): `Some(true)` the key was there and is + /// removed, `Some(false)` it is exactly absent, `None` undecided with + /// nothing touched (another kind of key, a stored key that needs + /// Python to compare, a set that is borrowed or has operations + /// queued). The removed key is of the probe's own builtin kind, so its + /// release runs nothing. + #[inline] + fn leaf_set_take(args: &[Object]) -> Option { + let [Object::Set(st), item] = args else { + return None; + }; + if crate::builtins::set_ops_pending() { + return None; + } + let mut m = st.try_borrow_mut().ok()?; + let (_, found) = m.find_object_hashing(item)?; + let Ok(at) = found else { + return Some(false); + }; + let key = m.swap_remove_index(at); + drop(m); + drop(key); + Some(true) + } + /// The leaf half of `specialized_load_attr`: the value a warm /// instance-dict, slot, or module cache would hand back for the /// receiver at TOS, or `None` for anything the full handler must see. @@ -33129,13 +39319,57 @@ impl Interpreter { // site's own polymorphic entries first, then the class's cache // (which refills them on an instance-dict hit). (_, Object::Instance(inst)) => { + if inst.cls_raw().flags.is_exception { + if let Some(v) = Self::leaf_exc_slot_read(code, inst, name_idx) { + return Some(v); + } + } Self::leaf_attr_resolve_site(code, inst, receiver, cache_pc, name_idx) } (_, Object::Function(f)) => Self::leaf_function_read(code, f, name_idx), + (_, Object::BoundMethod(bm)) => Self::leaf_bound_method_read(code, bm, name_idx), _ => None, } } + /// `m.name` of a bound method as the full path reads it (see + /// `load_attr_inner`): its receiver, its function, or a Python + /// function's name, qualified name or docstring, which the method + /// forwards, read in place. `None` for anything else. + pub(crate) fn leaf_bound_method_read( + code: &CodeObject, + bm: &BoundMethod, + name_idx: u32, + ) -> Option { + match code.names.get(name_idx as usize)?.as_str() { + "__self__" => Some(Self::clone_operand(&bm.receiver)), + "__func__" => Some(Self::clone_operand(&bm.function)), + "__name__" | "__qualname__" | "__doc__" => match &bm.function { + Object::Function(f) => Self::leaf_function_read(code, f, name_idx), + _ => None, + }, + _ => None, + } + } + + /// `e.name` for an exception whose class resolves the name to a slot + /// descriptor (`args`, `__traceback__`, `__cause__`, ...), a data + /// descriptor no instance entry shadows: the slot's value, or the + /// descriptor's default when it's unset (a never-raised exception's + /// `__traceback__` is `None`). `None` for anything else, an unset + /// slot with no default included. + fn leaf_exc_slot_read(code: &CodeObject, inst: &PyInstance, name_idx: u32) -> Option { + let cls = inst.cls_raw(); + if !Self::default_getattribute(cls) || crate::object::exotic_str_keys_possible() { + return None; + } + let name = code.names.get(name_idx as usize)?; + let Some(Object::SlotDescriptor(sd)) = cls.lookup(name) else { + return None; + }; + inst.slot_get(name).or_else(|| sd.default.clone()) + } + /// `f.name` for a Python function, as `load_attr_inner` resolves it /// when the value is stored: a getset slot (`__name__`, `__doc__`, /// ...) from the function's slots, any other name from its @@ -33156,11 +39390,41 @@ impl Interpreter { let read = |d: &DictData| d.get_full(&probe).map(|(_, _, v)| Self::clone_operand(v)); if crate::object::is_function_slot(name) { let slots = f.slots().try_borrow().ok()?; - read(&slots) - } else { + if let Some(v) = read(&slots) { + return Some(v); + } + drop(slots); + // What the full read makes of an unset slot (`inspect`'s + // signature reads them). + return match name { + "__defaults__" if f.defaults.is_empty() => Some(Object::None), + "__defaults__" => Some(Object::tuple_from_slice(&f.defaults)), + "__kwdefaults__" if f.kw_defaults.is_empty() => Some(Object::None), + "__kwdefaults__" => { + let mut d = DictData::default(); + for (k, v) in &f.kw_defaults { + d.insert(DictKey(Object::from_str(k)), v.clone()); + } + Some(Object::Dict(Rc::new(RefCell::new(d)))) + } + _ => None, + }; + } + { let attrs = f.attrs.try_borrow().ok()?; - let dict = attrs.as_ref()?.try_borrow().ok()?; - read(&dict) + if let Some(dict) = attrs.as_ref() { + if let Some(v) = read(&*dict.try_borrow().ok()?) { + return Some(v); + } + } + } + // The function type's own fields, under no dict entry (the full + // read's order). + match name { + "__code__" => Some(Object::Code(f.code())), + "__globals__" => Some(Object::Dict(f.globals.clone())), + "__builtins__" => Some(Object::Dict(f.builtins.clone())), + _ => None, } } @@ -33297,6 +39561,29 @@ impl Interpreter { && fcode.wire.as_ref().is_none_or(|w| w.exec_error.is_none()) } + /// The class value the `LOAD_ATTR` at `cache_pc` read through an + /// instance of `inst`'s class at its current version (see + /// [`class_attr_fill_via`]), when `inst` doesn't shadow it: + /// `self.version` of an `ipaddress` network, a class constant no + /// field cache holds. A version equal to the stamp's proves the name + /// still resolves to that class value (no data descriptor, default + /// attribute access). + #[inline] + pub(crate) fn leaf_class_value_via( + ext: &CodeConstObjects, + code: &CodeObject, + inst: &PyInstance, + cache_pc: u32, + name_idx: u32, + ) -> Option { + let slot = ext.stamp_slot(cache_pc as usize)?; + let cls = inst.cls_raw(); + let v = class_attr_hit_via(slot, cls, CLASS_ATTR_VIA_INSTANCE).or_else(|| { + class_entry_hit(slot, cls, CLASS_ATTR_VIA_INSTANCE, code, cache_pc as usize) + })?; + (!inst_may_shadow(inst, code, name_idx)).then_some(v) + } + /// The cache-free half of [`Self::leaf_load_attr_recv`]: the site's /// own polymorphic entries, then the class cache. A site that has /// never been specialized — every attribute site of a body only ever @@ -33311,6 +39598,49 @@ impl Interpreter { name_idx: u32, ) -> Option { use weavepy_compiler::InlineCache as IC; + // `inst.__class__` where `object`'s descriptor answers (a + // dataclass's `__eq__` reads it of both operands): the class. + if code + .names + .get(name_idx as usize) + .is_some_and(|n| n.as_str() == "__class__") + && inst.c_body.get() == 0 + && inst.cls_raw().class_read_is_plain() + { + return Some(Object::Type(inst.cls())); + } + // A `__slots__` member (a data descriptor no instance dictionary + // shadows) whose site the interpreter never specialized (a body + // the frame JIT runs): its stored value; unset, the full path's + // `AttributeError`. + if let Some(name) = code.names.get(name_idx as usize) { + // (A class key's `__eq__` could run during the lookup.) + if inst.native.get().is_none() + && !crate::object::exotic_str_keys_possible() + && slot_member_class(inst.cls_raw(), name) + { + // A site past its first class remembers the member's place + // for this one (see `leaf_poly_field`: the class finds the + // member first for as long as it reads this version, and a + // layout's positions never change). No other reader of the + // entries takes a position with the flag for a dict's. + let cls = inst.cls_raw(); + let ver = cls.attr_version.get(); + if ver != 0 + && cls.native_kind.get() == 0 + && !matches!(code.caches.get(cache_pc), IC::Empty) + { + if let (Some(p), Some((i, _))) = + (code_attr_poly(code, cache_pc), inst.laid_out_position(name)) + { + p.record(ver, i | SLOT_FIELD); + } + } + return inst + .slot_get(name) + .filter(|v| !matches!(v, Object::Unbound)); + } + } // A scalar class attribute read through an instance that doesn't // shadow it (the stamp was filled below, at this class version), // or a named tuple field. @@ -33458,11 +39788,7 @@ impl Interpreter { // `inst.__class__`, as `load_attr_instance` answers it: `object`'s // descriptor, which the instance dict can't shadow, when nothing // on the MRO overrides it. - if name == "__class__" - && inst.c_body.get() == 0 - && !cls.flags.is_builtin - && cls.class_attr_is_plain() - { + if name == "__class__" && inst.c_body.get() == 0 && cls.class_read_is_plain() { return Some((LeafAttr::Value(Object::Type(inst.cls())), None)); } // A native method the class itself supplies under a dunder name @@ -33482,12 +39808,17 @@ impl Interpreter { return None; } } - let on_class = match Self::leaf_class_attr(code, cls, name_idx)? { - LeafAttr::InstanceOnly => None, + let on_class = match Self::leaf_class_attr(code, cls, name_idx) { + Some(LeafAttr::InstanceOnly) => None, // A data descriptor: the instance dict never shadows it. - prop @ LeafAttr::Property(_) => return Some((prop, None)), - field @ LeafAttr::TupleField(_) => return Some((field, None)), - other => Some(other), + Some(prop @ LeafAttr::Property(_)) => return Some((prop, None)), + Some(field @ LeafAttr::TupleField(_)) => return Some((field, None)), + Some(other) => Some(other), + // A Python non-data descriptor (a `functools.cached_property` + // whose value the instance now holds): the instance's own + // entry, a miss the full path's (the descriptor's `__get__`). + None if Self::leaf_class_non_data_descr(code, cls, name_idx) => None, + None => return None, }; match inst.dict.published() { Some(dict) => { @@ -33506,9 +39837,12 @@ impl Interpreter { } None => { let split = inst.dict.split_cell().try_borrow().ok()?; - let ix = match code_name_obj(code, name_idx) { - Some(Object::Str(n)) => split.position(n), - _ => split.position_str(name.as_str()), + // By the name's cached hash: a method name no instance of + // the class ever set (the usual miss here) answers from the + // names' filter, where a scan compared every name. + let ix = match code_name_key(code, name_idx) { + Some(k) => split.position_hashed(k.s, k.hash), + None => split.position_str(name.as_str()), }; if let Some(ix) = ix { return Some(( @@ -33547,7 +39881,7 @@ impl Interpreter { K::ValueModule(w) => Some(LeafAttr::Value(Object::Module(w.upgrade()?))), K::Property(w) => Some(LeafAttr::Property(w.upgrade()?)), K::TupleField(ix) => Some(LeafAttr::TupleField(*ix)), - K::DataDescr { .. } | K::Other => None, + K::DataDescr { .. } | K::LeafFast(_) | K::Other => None, }; } if crate::object::exotic_str_keys_possible() { @@ -33577,6 +39911,9 @@ impl Interpreter { // class and an instance, never bound. Some(Object::StaticMethod(w)) => match w.func() { Object::Function(f) => K::StaticFn(Rc::downgrade(&f)), + // A native function (`str.maketrans`): the same + // object through a class or an instance, unbound. + Object::Builtin(b) => K::Value(Object::Builtin(b)), _ => K::Other, }, Some(Object::ClassMethod(w)) => match w.func() { @@ -33594,6 +39931,12 @@ impl Interpreter { // A non-binding native function: the same object through a // class or an instance. Some(Object::Builtin(b)) => K::Value(Object::Builtin(b)), + // A struct sequence's field reads its instance dict. + Some(Object::Property(p)) + if crate::stdlib::os::struct_seq_field_descr(name, &p) => + { + K::InstanceOnly + } Some(Object::Property(p)) => K::Property(Rc::downgrade(&p)), Some( v @ (Object::None @@ -33643,7 +39986,7 @@ impl Interpreter { K::ValueModule(w) => w.upgrade().map(|m| LeafAttr::Value(Object::Module(m))), K::Property(w) => w.upgrade().map(LeafAttr::Property), K::TupleField(ix) => Some(LeafAttr::TupleField(*ix)), - K::DataDescr { .. } | K::Other => None, + K::DataDescr { .. } | K::LeafFast(_) | K::Other => None, }; cls.leaf_attrs.set(name_key, ver, kind); out @@ -33655,19 +39998,25 @@ impl Interpreter { fn data_descr_kind(descr: &Rc) -> crate::types::LeafAttrKind { use crate::types::{Dunder, LeafAttrKind as K}; let dcls = descr.cls_raw(); - if !(dcls.dunder(Dunder::Set).present() || dcls.dunder(Dunder::Delete).present()) { - return K::Other; - } + let data = dcls.dunder(Dunder::Set).present() || dcls.dunder(Dunder::Delete).present(); match dcls.lookup("__get__") { Some(Object::Function(get)) => K::DataDescr { descr: Rc::downgrade(descr), get: Rc::downgrade(&get), dver: dcls.attr_version.get(), + data, }, _ => K::Other, } } + /// Whether `cls` resolves `co_names[name_idx]` to a Python non-data + /// descriptor (see [`crate::types::LeafAttrKind::DataDescr`]), which + /// the instance's own entry shadows. + fn leaf_class_non_data_descr(code: &CodeObject, cls: &TypeObject, name_idx: u32) -> bool { + Self::leaf_class_data_descr(code, cls, name_idx).is_some_and(|(_, _, data)| !data) + } + /// The Python data descriptor `cls` resolves `co_names[name_idx]` to /// (see [`crate::types::LeafAttrKind::DataDescr`]), and its `__get__`, /// from the class's leaf attribute cache. @@ -33675,7 +40024,7 @@ impl Interpreter { code: &CodeObject, cls: &TypeObject, name_idx: u32, - ) -> Option<(Rc, Rc)> { + ) -> Option<(Rc, Rc, bool)> { use crate::types::LeafAttrKind as K; let Some(Object::Str(name_obj)) = code_name_obj(code, name_idx) else { return None; @@ -33686,14 +40035,20 @@ impl Interpreter { // (Fills the entry.) Self::leaf_class_attr(code, cls, name_idx); } - let K::DataDescr { descr, get, dver } = cls.leaf_attrs.get(name_key, ver)? else { + let K::DataDescr { + descr, + get, + dver, + data, + } = cls.leaf_attrs.get(name_key, ver)? + else { return None; }; let descr = descr.upgrade()?; if descr.cls_raw().attr_version.get() != *dver { return None; } - Some((descr, get.upgrade()?)) + Some((descr, get.upgrade()?, *data)) } /// `cls.name` for a class with a plain metaclass, when the name is a @@ -33722,6 +40077,18 @@ impl Interpreter { return Some(Self::clone_operand(v)); } } + // A class method (native or Python) this site last bound (see + // below), under a metaclass version no real one has. + if let Some(Object::ClassMethod(cm)) = + slot.and_then(|s| s.class_value(ver, NATIVE_CLASSMETHOD_META)) + { + if Self::plain_metaclass(cls) && (cls.c_ext_ptr.get() == 0 || cls.flags.is_builtin) { + return Some(Object::BoundMethod(Rc::new(BoundMethod::py_method( + Object::Type(cls.clone()), + cm.func(), + )))); + } + } // A plain `type` metaclass has nothing that could intercept a // non-dunder class attribute (the class cache never answers for // dunders). @@ -33813,32 +40180,38 @@ impl Interpreter { } } } - // A builtin class's native class method (`int.from_bytes`), bound - // to the class as `classmethod.__get__` binds it. + // A native class method in the class's own dict (`int.from_bytes`, + // `itertools.chain.from_iterable`), bound to the class as + // `classmethod.__get__` binds it. // (Most names are none: the class remembers which, sparing the // probe's hashing.) let name = code.names.get(name_idx as usize)?; - if cls.flags.is_builtin - && !cls.memo_verdict(crate::types::Verdict::NoNativeClassMethod, name, || { - cls.dict.try_borrow().is_ok_and(|d| { - !matches!( - d.get(&crate::object::StrKey(name)), - Some(Object::ClassMethod(_)) - ) - }) + if !cls.memo_verdict(crate::types::Verdict::NoNativeClassMethod, name, || { + cls.dict.try_borrow().is_ok_and(|d| { + !matches!( + d.get(&crate::object::StrKey(name)), + Some(Object::ClassMethod(cm)) if matches!(cm.func(), Object::Builtin(_)) + ) }) - { + }) { // (Through the type cache: the class's own entry is the one // its MRO walk finds first.) - if let Some((Object::ClassMethod(cm), owner)) = cls.lookup_with_owner(name) { - if Rc::ptr_eq(&owner, cls) { + if let Some((entry, owner)) = cls.lookup_with_owner(name) { + if let (Object::ClassMethod(cm), true) = (&entry, Rc::ptr_eq(&owner, cls)) { let f = cm.func(); - return matches!(f, Object::Builtin(_)).then(|| { - Object::BoundMethod(Rc::new(BoundMethod::py_method( + // (A Python function's is the class attribute lane's, + // below.) + if matches!(f, Object::Builtin(_)) { + // (The site remembers the entry, which the class's + // dict holds while its version stands.) + if let Some(s) = slot { + s.set_class_value(ver, NATIVE_CLASSMETHOD_META, &entry); + } + return Some(Object::BoundMethod(Rc::new(BoundMethod::py_method( Object::Type(cls.clone()), f, - ))) - }); + )))); + } } } } @@ -33868,11 +40241,22 @@ impl Interpreter { Some(v) } LeafAttr::Value(v) => Some(v), - // A class method, bound to the class. - LeafAttr::ClassMethod(f) => Some(Object::BoundMethod(Rc::new(BoundMethod::py_method( - Object::Type(cls.clone()), - Object::Function(f), - )))), + // A class method, bound to the class. The site remembers the + // class's entry, as it does a native one's above (an + // interpreted `cls.helper()` resolved it in full each call). + LeafAttr::ClassMethod(f) => { + if let (Some(s), Some(entry)) = (slot, cls.lookup(name)) { + if matches!(&entry, Object::ClassMethod(cm) + if matches!(cm.func(), Object::Function(g) if Rc::ptr_eq(&g, &f))) + { + s.set_class_value(ver, NATIVE_CLASSMETHOD_META, &entry); + } + } + Some(Object::BoundMethod(Rc::new(BoundMethod::py_method( + Object::Type(cls.clone()), + Object::Function(f), + )))) + } // A native method or a property read off the class is the // descriptor itself (`descriptor_get` with no instance). The // site remembers a native one as it does a non-binding native @@ -33959,15 +40343,7 @@ impl Interpreter { "__class__" => return Some(Object::Type(cls.metaclass_or_type())), // (`type_mro_get`: a class still being made has none, which the // full path answers.) - "__mro__" => { - let mro = cls.mro.try_borrow().ok()?; - if mro.is_empty() { - return None; - } - return Some(Object::new_tuple( - mro.iter().map(|b| Object::Type(b.clone())).collect(), - )); - } + "__mro__" => return cls.links_tuple(false), // (A class made with a tuple subclass of bases keeps that object; // its dict says so.) "__bases__" => { @@ -33977,10 +40353,8 @@ impl Interpreter { { return None; } - let bases = cls.bases.try_borrow().ok()?; - return Some(Object::new_tuple( - bases.iter().map(|b| Object::Type(b.clone())).collect(), - )); + drop(d); + return cls.links_tuple(true); } // The class's own entry, when it's a string. "__module__" => { @@ -34004,12 +40378,7 @@ impl Interpreter { { return Some(v.clone()); } - if name == "__qualname__" { - if let Some(q) = cls.qualname.borrow().as_ref() { - return Some(Object::interned_str(q)); - } - } - Some(Object::interned_str(&cls.name)) + Some(cls.interned_names(name == "__qualname__")) } /// [`Self::type_method_pair`] for the attribute protocol's own dunders @@ -34122,52 +40491,136 @@ impl Interpreter { /// reads to the class's MRO (`dict.__setitem__`, `type(self).__setitem__ /// is ...` in `OrderedDict.update`). fn type_dunder_transparent(name: &str) -> bool { - matches!( - name, - "__init__" - | "__enter__" - | "__exit__" - | "__aenter__" - | "__aexit__" - | "__getitem__" - | "__setitem__" - | "__delitem__" - | "__contains__" - | "__len__" - | "__iter__" - | "__next__" - | "__reversed__" - | "__bool__" - | "__missing__" - | "__lt__" - | "__le__" - | "__gt__" - | "__ge__" - | "__add__" - | "__sub__" - | "__mul__" - | "__truediv__" - | "__floordiv__" - | "__mod__" - | "__format__" - | "__getattr__" - | "__get__" - | "__set__" - | "__delete__" - | "__copy__" - | "__deepcopy__" - | "__setattr__" - | "__delattr__" - | "__getattribute__" - | "__repr__" - | "__str__" - | "__eq__" - | "__ne__" - | "__hash__" - | "__reduce__" - | "__reduce_ex__" - | "__init_subclass__" - ) + Self::type_dunder_class(name) == Some(true) + } + + /// Which of the two dunder lists `name` is on: `Some(true)` the + /// transparent ones (see [`Self::type_dunder_transparent`]), + /// `Some(false)` the ones `type` claims (see + /// [`Self::type_dunder_unclaimed_rest`]), `None` neither. One hashed probe: + /// `getattr(cls, "__name__")` asks for every call, and matching the + /// name against the lists in turn cost it some forty comparisons. + fn type_dunder_class(name: &str) -> Option { + const TRANSPARENT: &[&str] = &[ + "__init__", + "__enter__", + "__exit__", + "__aenter__", + "__aexit__", + "__getitem__", + "__setitem__", + "__delitem__", + "__contains__", + "__len__", + "__iter__", + "__next__", + "__reversed__", + "__bool__", + "__missing__", + "__lt__", + "__le__", + "__gt__", + "__ge__", + "__add__", + "__sub__", + "__mul__", + "__truediv__", + "__floordiv__", + "__mod__", + "__format__", + "__getattr__", + "__get__", + "__set__", + "__delete__", + "__copy__", + "__deepcopy__", + "__setattr__", + "__delattr__", + "__getattribute__", + "__repr__", + "__str__", + "__eq__", + "__ne__", + "__hash__", + "__reduce__", + "__reduce_ex__", + "__init_subclass__", + ]; + const CLAIMED: &[&str] = &[ + "__abstractmethods__", + "__annotations__", + "__base__", + "__bases__", + "__basicsize__", + "__class__", + "__dict__", + "__dir__", + "__doc__", + "__flags__", + "__itemsize__", + "__module__", + "__mro__", + "__name__", + "__qualname__", + "__subclasses__", + "__text_signature__", + "__type_params__", + "__weakref__", + ]; + static KNOWN: std::sync::OnceLock> = + std::sync::OnceLock::new(); + KNOWN + .get_or_init(|| { + TRANSPARENT + .iter() + .map(|n| (*n, true)) + .chain(CLAIMED.iter().map(|n| (*n, false))) + .collect() + }) + .get(name) + .copied() + } + + /// Whether a class attribute read of dunder `name` (one that isn't on + /// [`Self::type_dunder_transparent`]'s list) still resolves in the + /// class's own MRO: the class's metaclass is `type`, which defines no + /// attribute of that name, and `load_attr_type` doesn't serve it from + /// outside the dicts (`__dataclass_fields__`, `__slots__`, + /// `__match_args__`). Only the checks past the lists: the caller + /// classified the name ([`Self::type_dunder_class`]) as not claimed. + fn type_dunder_unclaimed_rest(cls: &TypeObject, name: &str) -> bool { + !name.starts_with("__weavepy") && Self::plain_metaclass(cls) && Self::type_lacks(name) + } + + /// Whether `type` (with `object` behind it) defines no attribute + /// `name`, remembered by name for `type`'s current attribute version: + /// every `getattr(cls, "__wrapped__")` asks, and the answer is the + /// same until `type` itself changes. + fn type_lacks(name: &str) -> bool { + thread_local! { + static LACKS: RefCell<(u64, crate::fasthash::FxHashMap, bool>)> = + RefCell::new((0, crate::fasthash::FxHashMap::default())); + } + let ty = &builtin_types().type_; + let ver = ty.attr_version.get(); + if ver == 0 { + return ty.lookup(name).is_none(); + } + LACKS.with(|c| { + let Ok(mut memo) = c.try_borrow_mut() else { + return ty.lookup(name).is_none(); + }; + if memo.0 != ver || memo.1.len() >= 256 { + memo.0 = ver; + memo.1.clear(); + } + if let Some(&lacks) = memo.1.get(name) { + return lacks; + } + let lacks = ty.lookup(name).is_none(); + memo.1.insert(name.into(), lacks); + lacks + }) } /// Whether `cls`'s metaclass is `type` itself. @@ -34908,6 +41361,19 @@ impl Interpreter { let r = match crate::builtins::dict_lookup(&d, &i)? { Some(found) => found, None if cls.dunder(crate::types::Dunder::Missing).present() => { + // (Compiled code calls a plain Python + // `__missing__` itself once its site has run + // one: see `h_subscr_dunder`.) + #[cfg(feature = "jit")] + if let Some(ext) = code_vm_ext(&frame.code) { + let pc = (frame.pc as usize).wrapping_sub(1); + if frame.code.instructions.get(pc).map(|i| i.op) + == Some(OpCode::BinarySubscr) + && !instance_site(ext, pc) + { + instance_site_note(ext, frame.code.instructions.len(), pc); + } + } match instance_method(&v, "__missing__") { Some(miss) => self.call( &miss, @@ -35855,19 +42321,35 @@ impl Interpreter { // pure-Python numeric types (fractions.Fraction, // decimal.Decimal, user classes) participate. UnaryKind::Neg | UnaryKind::Pos | UnaryKind::Invert => { + // (Compiled code calls an instance's operator + // method itself at a site known to see one.) + if let Some(ext) = code_vm_ext_existing(&frame.code) { + let pc = cache_pc as usize; + if !instance_site(ext, pc) { + instance_site_note(ext, frame.code.instructions.len(), pc); + } + } let dunder = match kind { UnaryKind::Neg => "__neg__", UnaryKind::Pos => "__pos__", _ => "__invert__", }; - match instance_method(&v, dunder) { - Some(method) => self.call(&method, &[], &[], &g)?, - // No user override: a built-in numeric subclass - // (`class C(complex)`, `class C(int)`, …) applies - // the base type's unary op to its native payload, - // matching CPython's inherited slot. - None => { - unary_op(&v.native_value().unwrap_or_else(|| v.clone()), kind)? + // (A native dunder's body directly: `-td`, + // `+dec`.) + if let Some(r) = instance_native_dunder(&v, dunder, None) { + r? + } else { + match instance_method(&v, dunder) { + Some(method) => self.call(&method, &[], &[], &g)?, + // No user override: a built-in numeric + // subclass (`class C(complex)`, + // `class C(int)`, …) applies the base + // type's unary op to its native payload, + // matching CPython's inherited slot. + None => unary_op( + &v.native_value().unwrap_or_else(|| v.clone()), + kind, + )?, } } } @@ -36449,7 +42931,7 @@ impl Interpreter { } let mut pos_args: Vec = match &args_obj { Object::Tuple(items) => items.iter().cloned().collect(), - Object::List(items) => items.borrow().clone(), + Object::List(items) => crate::object::cloned_vec(&items.borrow()), other => { // A single `f(*x)` splat pushes `x` raw; CPython's // `do_call` converts via `PySequence_Tuple` and @@ -36801,12 +43283,31 @@ impl Interpreter { } Err(e) => return Err(e), }, - Object::Instance(_) => { + Object::Instance(inst) => 'inst: { + // A legacy sequence's iterator steps with no frame + // of its own (and no `StopIteration` at its end). + if let Some(rev) = seqiter_kind(inst) { + if let Some(r) = self.seqiter_next(inst, rev) { + break 'inst r?; + } + } // Call __next__; treat StopIteration as exhaustion. - let next = match instance_native_dunder(&it_obj, "__next__", None) { - Some(r) => Some(r), - None => instance_method(&it_obj, "__next__") - .map(|m| self.call(&m, &[], &[], &frame.globals)), + // (A Python `__next__`, cached on the class, is + // called with the instance, without a bound method.) + let py_next = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::NEXT_FN), + "__next__", + ); + let next = match py_next { + Some(f) => { + Some(self.call_python(&f, std::slice::from_ref(&it_obj), &[])) + } + None => match instance_native_dunder(&it_obj, "__next__", None) { + Some(r) => Some(r), + None => instance_method(&it_obj, "__next__") + .map(|m| self.call(&m, &[], &[], &frame.globals)), + }, }; match next { Some(r) => match r { @@ -37230,7 +43731,7 @@ impl Interpreter { let v = frame.pop()?; let items: Vec = match v { Object::Tuple(items) => items.iter().cloned().collect(), - Object::List(items) => items.borrow().clone(), + Object::List(items) => crate::object::cloned_vec(&items.borrow()), Object::Str(s) => s.chars().map(|c| Object::from_str(c.to_string())).collect(), Object::Bytes(b) => b.iter().map(|x| Object::Int(i64::from(*x))).collect(), Object::ByteArray(b) => b @@ -37277,7 +43778,7 @@ impl Interpreter { // Pushed top-down so the next STOREs pop in source order. // Stack layout after: [..., tail_last, ..., tail_first, middle_list, head_last, ..., head_first] let mid_end = items.len() - after; - let middle: Vec = items[before..mid_end].to_vec(); + let middle: Vec = crate::object::cloned_vec(&items[before..mid_end]); // Tail: push reversed so STORE_FAST pops in source order. for x in items[mid_end..].iter().rev() { frame.push(x.clone()); @@ -37325,6 +43826,18 @@ impl Interpreter { let is_kw_merge = ins.arg & 1 != 0; let depth = (ins.arg >> 1) as usize + 1; let other = frame.pop()?; + // A mapping that only wraps one dict reads as that dict; so + // does a dict subclass's instance that keeps dict's + // `__iter__`, whose table CPython's `dict_merge` reads + // whatever its own `keys` and `__getitem__`. + let other = if let Some(d) = Self::plain_dict_payload(&other) { + Object::Dict(d.clone()) + } else { + match self.thin_mapping_dict(&other, true) { + Some(d) => Object::Dict(d), + None => other, + } + }; // For the call-site splat, CPython prefixes the duplicate // keyword TypeError with `PyObject_FunctionStr(func)` — // e.g. `__build_class__() got multiple values for keyword @@ -37358,6 +43871,22 @@ impl Interpreter { } }; match other { + // A display's `**d` merged as `dict.update` merges, in one + // pass while the keys settle natively (the source's table + // copied whole into an empty dict); a call's `**kw` into + // an empty dict when its keys are all strings (nothing + // can repeat). A partial merge leaves the rest to the loop + // below, which stores those keys again harmlessly. + Object::Dict(src) + if !Rc::ptr_eq(&target, &src) + && !crate::capi_watchers::dicts_active() + && (!is_kw_merge + || (target.borrow().is_empty() + && src + .borrow() + .keys() + .all(|k| matches!(k.0, Object::Str(_))))) + && Self::dict_merge_plain(&target, &src) => {} Object::Dict(src) => { let mut t = target.borrow_mut(); for (k, v) in src.borrow().iter() { @@ -37395,8 +43924,11 @@ impl Interpreter { )) } })?; - let keys = self.call(&key_method, &[], &[], &globals)?; - let keys = self.collect_iterable(&keys, &globals)?; + // (The keys are listed through an iterator, as + // CPython's `PyMapping_Keys` lists them: nothing asks + // the view or the mapping its length.) + let keys_of = self.call(&key_method, &[], &[], &globals)?; + let keys = self.listed_keys(&keys_of, &globals)?; // Resolve each value through the *full* subscript protocol // (`subscr_via_protocol` honours a user-defined // `__getitem__`, which the raw `binary_subscr` skips) so @@ -37407,14 +43939,41 @@ impl Interpreter { // hold its `borrow_mut` across the call. let mut pairs = Vec::with_capacity(keys.len()); for k in keys { - let value = - self.subscr_via_protocol(&other, &k, &globals) - .map_err(|_| { - type_error(format!( - "cannot access key in {} for ** spread", - other.type_name() - )) - })?; + let value = match self.mapping_value(&other, &k, &globals) { + Ok(v) => v, + // CPython's `DICT_MERGE` reads a `KeyError` + // of one argument as a repeated keyword (its + // merge raises one for a duplicate); any + // other error, and every error under a dict + // display's `**`, passes as it is. + Err(RuntimeError::PyException(exc)) if is_kw_merge => { + let repeated = match &exc.instance { + Object::Instance(i) + if i.cls_raw() + .is_subclass_of(&builtin_types().key_error) => + { + match i.exc_args_get() { + Some(Object::Tuple(args)) if args.len() == 1 => { + Some(args[0].clone()) + } + _ => None, + } + } + _ => None, + }; + match repeated { + Some(key) => { + let shown = self.str_object(&key)?; + return Err(type_error(format!( + "{}got multiple values for keyword argument '{shown}'", + kw_error_prefix(), + ))); + } + None => return Err(RuntimeError::PyException(exc)), + } + } + Err(e) => return Err(e), + }; pairs.push((k, value)); } let mut t = target.borrow_mut(); @@ -37788,8 +44347,8 @@ impl Interpreter { let excs = frame.pop()?; let orig = frame.pop()?; let items: Vec = match &excs { - Object::List(l) => l.borrow().clone(), - Object::Tuple(t) => t.to_vec(), + Object::List(l) => crate::object::cloned_vec(&l.borrow()), + Object::Tuple(t) => crate::object::cloned_vec(t), other => { return Err(RuntimeError::Internal(format!( "PREP_RERAISE_STAR expects a list, got {}", @@ -38068,24 +44627,36 @@ impl Interpreter { // `!a` conversion alone; FORMAT_SIMPLE/FORMAT_WITH_SPEC // then formats the (now-string) result. let value = frame.pop()?; - let globals = frame.globals.clone(); - let converted = match ins.arg & 0x03 { - 1 => match &value { - Object::WStr(cps) => crate::builtins::bridge_encode_cps(cps), - _ => self.stringify(&value, &globals)?, - }, - 2 => self.repr_of(&value, &globals)?, - 3 => ascii_repr(&value), - other => { - return Err(RuntimeError::Internal(format!( - "unknown CONVERT_VALUE conversion {other}" - ))) + // `!r` of an instance with a Python `__repr__` returning an + // exact `str`: that string, as it stands. + let direct = (ins.arg & 0x03 == 2) + .then(|| self.instance_python_repr(&value)) + .flatten(); + if let Some(r) = direct { + match r? { + s @ Object::Str(_) => frame.push(s), + r => frame.push(Object::from_str(Self::require_str_result(r, "__repr__")?)), } - }; - if matches!(value, Object::WStr(_)) { - frame.push(crate::builtins::bridge_to_object(&converted)); } else { - frame.push(Object::from_str(converted)); + let globals = frame.globals.clone(); + let converted = match ins.arg & 0x03 { + 1 => match &value { + Object::WStr(cps) => crate::builtins::bridge_encode_cps(cps), + _ => self.stringify(&value, &globals)?, + }, + 2 => self.repr_of(&value, &globals)?, + 3 => ascii_repr(&value), + other => { + return Err(RuntimeError::Internal(format!( + "unknown CONVERT_VALUE conversion {other}" + ))) + } + }; + if matches!(value, Object::WStr(_)) { + frame.push(crate::builtins::bridge_to_object(&converted)); + } else { + frame.push(Object::from_str(converted)); + } } } OpCode::FormatValue => { @@ -38094,15 +44665,30 @@ impl Interpreter { let has_spec = (arg & 0x04) != 0; let spec = if has_spec { Some(frame.pop()?) } else { None }; let value = frame.pop()?; - let globals = frame.globals.clone(); - let formatted = self.format_value(&value, conversion, spec.as_ref(), &globals)?; - // A surrogate-bearing value formats into bridged PUA code - // points; map them back so the f-string fragment is a faithful - // `WStr`. Non-`WStr` values never produce bridge-window output. - if matches!(value, Object::WStr(_)) { - frame.push(crate::builtins::bridge_to_object(&formatted)); + // `f"{x}"` of a plain instance with a Python `__str__` and no + // `__format__`: `object.__format__(x, '')` is `str(x)`, and a + // `str` result is the fragment as it stands. + if let Some(r) = (arg == 0) + .then(|| self.format_plain_instance(&value)) + .flatten() + { + frame.push(match r? { + s @ (Object::Str(_) | Object::WStr(_)) => s, + r => Object::from_str(Self::require_str_result(r, "__str__")?), + }); } else { - frame.push(Object::from_str(formatted)); + let globals = frame.globals.clone(); + let formatted = + self.format_value(&value, conversion, spec.as_ref(), &globals)?; + // A surrogate-bearing value formats into bridged PUA code + // points; map them back so the f-string fragment is a + // faithful `WStr`. Non-`WStr` values never produce + // bridge-window output. + if matches!(value, Object::WStr(_)) { + frame.push(crate::builtins::bridge_to_object(&formatted)); + } else { + frame.push(Object::from_str(formatted)); + } } } // PEP 750 t-strings (`-X lang=next`, RFC 0076 WS15). Builds @@ -38357,6 +44943,17 @@ impl Interpreter { // handler below expects. The first drive uses the op's // fixed payload; the popped `value` is forwarded so a // re-drive (after an inner-await passthrough) resumes it. + Object::AsyncGenAwait(a) if !crate::trace::any_observers_active() => { + match self.step_agen_await_raw(a, value) { + Ok(AgenAwaitStep::Passed(v)) => Ok(v), + Ok(AgenAwaitStep::Done(v)) => { + frame.push(v.unwrap_or(Object::None)); + frame.pc += ins.arg; + return Ok(StepOutcome::Continue); + } + Err(e) => Err(e), + } + } Object::AsyncGenAwait(a) => self.step_agen_await(a, value), // A file is its own iterator (`yield from f` delegates to // it directly), advanced like any plain iterator. @@ -38453,6 +45050,12 @@ impl Interpreter { frame.stack.last().cloned().ok_or_else(|| { RuntimeError::Internal("GET_ANEXT empty stack".to_owned()) })?; + if let Object::AsyncGenerator(g) = &aiter { + if let Some(r) = self.anext_in_place(frame, g, &aiter) { + r?; + return Ok(StepOutcome::Continue); + } + } let globals = frame.globals.clone(); let aw = self.get_anext(&aiter, &globals, true)?; frame.push(aw); @@ -38644,6 +45247,224 @@ impl Interpreter { } } + /// What the `LOAD_GLOBAL` at `pc` of `frame`'s code (whose tables are + /// `ext`) would load, when the site's stamp or its inline cache + /// answers: nothing is looked up by name and nothing runs. + #[inline] + fn global_peek( + &self, + frame: &Frame, + ext: &CodeConstObjects, + pc: usize, + arg: u32, + ) -> Option { + use weavepy_compiler::InlineCache as IC; + let Some(slot) = ext.stamp_slot(pc) else { + return self.leaf_global(&frame.code, &frame.globals, &frame.builtins, pc, arg); + }; + // SAFETY (raw dict reads): as in `leaf_global`. + let (gdict, bdict) = (frame.globals.as_ptr(), frame.builtins.as_ptr()); + let gid = specialize::rc_id(&frame.globals); + let g_stamp = unsafe { (*gdict).mutation_stamp() }; + let stamp = slot.get(); + let held = slot.value(); + if held != 0 + && stamp[0] == gid + && stamp[1] == g_stamp + && if held & 1 == 0 { + stamp[2] == 0 + } else { + !self.globals_missing_gate() && stamp[2] == unsafe { (*bdict).mutation_stamp() } + } + { + // SAFETY: the dicts are as they were when the value was read + // (see `StampSlot::value`). + return Some(unsafe { &*((held & !1) as *const Object) }.clone()); + } + // The inline cache's entry under the stamp, recorded (as the core + // loop's arm records it); anything else re-proves the stamp. + let (hit, builtin) = match frame.code.caches.get(pc as u32) { + IC::LoadGlobalModule { + globals_id, + key_idx, + } if globals_id == gid && stamp == [gid, g_stamp, 0] => { + (unsafe { (*gdict).get_index(key_idx as usize) }, false) + } + IC::LoadGlobalBuiltin { + builtins_id, + key_idx, + } if builtins_id == specialize::rc_id(&frame.builtins) + && !self.globals_missing_gate() + && stamp == [gid, g_stamp, unsafe { (*bdict).mutation_stamp() }] => + { + (unsafe { (*bdict).get_index(key_idx as usize) }, true) + } + _ => return self.leaf_global(&frame.code, &frame.globals, &frame.builtins, pc, arg), + }; + let (_, v) = hit?; + slot.set_value(v, builtin); + Some(v.clone()) + } + + /// An exception of class `cls`, raised by the instruction at + /// `raise_pc` of `frame` with `len` slots left on its stack, caught by + /// a clause that can't observe it (see [`blind_handler`]) when nothing + /// else can either (no trace or monitoring callback): the stack cut + /// to the handler's depth and the clause's body run, with no + /// exception pushed, matched or popped. Returns the stack's depth + /// past the clause's `POP_EXCEPT` and that instruction's pc; `None` + /// touched nothing (no such clause, a class it doesn't catch, a name + /// the site's cache can't answer, an unbound local the body reads, or + /// a local it overwrites whose value would die there: its finalizer + /// would see the exception being handled). + /// + /// The caller owns the exception, if one was built, and releases it + /// afterwards, as the clause's `POP_EXCEPT` would have. + /// + /// # Safety + /// + /// `locals` and `stack` are the running activation's (`frame`'s), the + /// stack's first `len` slots initialized and `cap` allocated. + #[allow(clippy::too_many_arguments)] + pub(crate) unsafe fn blind_catch( + &self, + frame: &mut Frame, + locals: *mut Object, + stack: *mut Object, + len: usize, + cap: usize, + raise_pc: u32, + cls: &crate::types::TypeObject, + ) -> Option<(usize, u32)> { + if crate::trace::any_observers_active() || !Self::core_drops_plain() { + return None; + } + let code: &CodeObject = &frame.code; + let ext = code_vm_ext(code)?; + let idx = code + .exception_table + .iter() + .position(|h| raise_pc >= h.start && raise_pc < h.end)?; + let blind = (*blind_handlers(code, ext).get(idx)?)?; + let depth = code.exception_table[idx].depth as usize; + if len < depth { + return None; + } + if blind.nnames != 0 { + if frame + .rare + .as_ref() + .is_some_and(|r| r.builtins_obj.is_some()) + { + return None; + } + // Every name is looked up and checked, as `CHECK_EXC_MATCH` + // checks a tuple's every item. + let base = &builtin_types().base_exception; + let mut matched = false; + for pc in blind.names..blind.names + blind.nnames { + let ins = code.instructions[pc as usize]; + let named = match ins.op { + OpCode::LoadGlobal => self.global_peek(frame, ext, pc as usize, ins.arg)?, + // SAFETY: a read between two instructions. + OpCode::LoadDeref => { + unsafe { frame.cells.get(ins.arg as usize)?.peek() }?.clone() + } + // SAFETY: one of the activation's fast locals. + _ => unsafe { &*locals.add(ins.arg as usize) }.clone(), + }; + let Object::Type(t) = named else { + return None; + }; + if std::ptr::eq(cls, Rc::as_ptr(&t)) { + matched = true; + continue; + } + if !t.flags.is_exception && !t.is_subclass_of(base) { + return None; + } + matched = matched || cls.is_subclass_of(&t); + } + if !matched { + return None; + } + } + let body = &code.instructions[blind.body as usize..blind.end as usize]; + let consts: &[Object] = &ext.objects; + // SAFETY: `locals` are the activation's (`frame`'s), which the + // body's instructions name. + let peak = if blind.arith { + unsafe { blind_check_arith(frame, locals, consts, body, depth)? } + } else { + unsafe { blind_check_moves(frame, locals, consts, body, depth)? } + }; + if peak > cap { + return None; + } + // The raise's unwind to the handler's depth, then the body over + // the slot the previous exception would have taken. + // SAFETY: slots below `len` are initialized; the body's pushes + // stay under `cap`, and its pops take what it pushed (the + // analysis simulated them). + unsafe { + for i in (depth..len).rev() { + drop(stack.add(i).read()); + } + if let Some(e) = frame.exc.as_mut() { + e.pending_lasti = None; + e.cleanup_lasti = None; + } + stack.add(depth).write(Object::None); + let mut n = depth + 1; + for ins in body { + match ins.op { + OpCode::LoadFast | OpCode::LoadFastBorrow => { + stack.add(n).write((*locals.add(ins.arg as usize)).clone()); + n += 1; + } + OpCode::LoadConst => { + stack.add(n).write(consts[ins.arg as usize].clone()); + n += 1; + } + OpCode::LoadDeref => { + let v = frame.cells[ins.arg as usize].peek().cloned(); + stack.add(n).write(v.unwrap_or(Object::None)); + n += 1; + } + OpCode::LoadSmallInt => { + stack.add(n).write(Object::Int(i64::from(ins.arg))); + n += 1; + } + OpCode::BinaryOp => { + // (Two numbers, checked above: nothing to release.) + n -= 1; + let (a, b) = (stack.add(n - 1).read(), stack.add(n).read()); + let r = blind_arith(ins.arg, BlindVal::of(&a), BlindVal::of(&b)) + .map_or(Object::None, BlindVal::object); + stack.add(n - 1).write(r); + } + OpCode::StoreFast => { + n -= 1; + let v = stack.add(n).read(); + drop(std::mem::replace(&mut *locals.add(ins.arg as usize), v)); + } + OpCode::PopTop => { + n -= 1; + drop(stack.add(n).read()); + } + OpCode::Swap => { + std::ptr::swap(stack.add(n - 1), stack.add(n - ins.arg as usize)); + } + _ => {} + } + } + // The clause's `POP_EXCEPT`. + n -= 1; + drop(stack.add(n).read()); + Some((n, blind.end)) + } + } + /// The quiet loop's exception path: `err`, raised by the instruction /// before `frame.pc` in the running activation, goes to this frame's /// handler without leaving the loop, exactly as the general loop's @@ -38658,6 +45479,58 @@ impl Interpreter { frame: &mut Frame, shell: &mut QuietShell<'_>, err: RuntimeError, + ) -> Result<(), RuntimeError> { + // A clause that can't observe the exception, when nothing else + // holds it (see `blind_catch`): its body runs here and the + // exception goes as the clause's `POP_EXCEPT` would release it. + if let RuntimeError::PyException(exc) = &err { + if let Object::Instance(inst) = &exc.instance { + if Rc::strong_count(inst) == 1 { + let cls: *const crate::types::TypeObject = inst.cls_raw(); + let raise_pc = frame.pc.wrapping_sub(1); + // SAFETY: the frame's own locals and stack, with no + // borrow of either live; the class outlives its + // instance, which `err` holds. + let caught = unsafe { + let locals = frame.locals.storage().as_mut_ptr(); + let (stack, len, cap) = ( + frame.stack.as_mut_ptr(), + frame.stack.len(), + frame.stack.capacity(), + ); + self.blind_catch(frame, locals, stack, len, cap, raise_pc, &*cls) + }; + if let Some((n, end)) = caught { + // SAFETY: `blind_catch` left `n` initialized slots. + unsafe { frame.stack.set_len(n) }; + frame.pc = end + 1; + if let RuntimeError::PyException(mut exc) = err { + let instance = std::mem::replace(&mut exc.instance, Object::None); + self.release(instance); + } + // SAFETY: the flag is this thread's. + if unsafe { (*gc_trace::maybe_dead_flag()).get() } { + self.flush_lean(frame, shell) + .lasti + .store(end, std::sync::atomic::Ordering::Relaxed); + self.drain_if_maybe_dead(); + } + return Ok(()); + } + } + } + } + self.quiet_catch_seen(frame, shell, err) + } + + /// [`Self::quiet_catch`] past its blind lane (compiled code tried that + /// lane itself: see `frame_jit::h_catch`). + #[inline(never)] + fn quiet_catch_seen( + &mut self, + frame: &mut Frame, + shell: &mut QuietShell<'_>, + err: RuntimeError, ) -> Result<(), RuntimeError> { let RuntimeError::PyException(mut exc) = err else { return Err(err); @@ -38744,6 +45617,125 @@ impl Interpreter { err } + /// [`Self::quiet_unwind`] for an activation nothing ever looked at (a + /// lazily running direct callee: no shell, nothing on the spine or the + /// switch), which `exc` leaves at `raise_pc` with no handler covering + /// it and nothing observing frames. What the unwind leaves behind is + /// made directly: the traceback's entry for the activation, and a + /// shell that stands for it as a departed one's does (see + /// `FrameShell::depart`), holding its code, namespaces and locals + /// storage. `frame` takes fresh storage, empty. The shell's caller + /// link is the caller's to set. + pub(crate) fn unwind_unseen( + &mut self, + frame: &mut Frame, + exc: &mut PyException, + raise_pc: u32, + ) -> Rc { + use crate::object::FrameSlot; + self.chain_fresh_exception(exc); + let lineno = frame + .code + .linetable + .get(raise_pc as usize) + .copied() + .unwrap_or(0); + let pooled = self.frame_locals_pool.borrow_mut().pop(); + let fresh = match pooled.or_else(crate::object::take_spare_locals) { + Some(rc) => rc, + None => Rc::new(RefCell::new(Vec::new())), + }; + let locals = std::mem::replace( + &mut frame.locals, + frame_slots::FrameLocals::from_shared(fresh), + ) + .into_shared(); + // (The frame's handles are uncounted or its own: the shell takes + // counts of its own.) + let code = FrameSlot::new(frame.code.clone()); + let locals = FrameSlot::new(locals); + let cells = FrameSlot::new(frame.cells.clone()); + let globals = FrameSlot::new(frame.globals.clone()); + let builtins = FrameSlot::new(frame.builtins.clone()); + let pooled = self.frame_shell_pool.borrow_mut().pop(); + let mut pooled = pooled.or_else(crate::object::take_spare_shell); + let shell = match pooled.as_mut().and_then(Rc::get_mut) { + Some(m) => { + m.code = code; + m.locals = locals; + m.cells = cells; + m.globals = globals; + m.builtins = builtins; + m.builtins_obj = frame.builtins_obj().cloned(); + m.class_namespace = frame.class_namespace().cloned(); + m.class_namespace_obj = frame.class_namespace_obj().cloned(); + m.is_gen = false; + *m.gen_owner.get_mut() = frame.gen_owner.weak(); + m.lasti = std::sync::atomic::AtomicU32::new(raise_pc); + m.has_materialized = std::sync::atomic::AtomicBool::new(false); + *m.materialized.get_mut() = None; + pooled.expect("checked above") + } + None => Rc::new(crate::object::FrameShell { + code, + locals, + cells, + globals, + builtins, + builtins_obj: frame.builtins_obj().cloned(), + class_namespace: frame.class_namespace().cloned(), + class_namespace_obj: frame.class_namespace_obj().cloned(), + is_gen: false, + gen_owner: RefCell::new(frame.gen_owner.weak()), + lasti: std::sync::atomic::AtomicU32::new(raise_pc), + has_materialized: std::sync::atomic::AtomicBool::new(false), + materialized: RefCell::new(None), + tb_refs: std::sync::atomic::AtomicU32::new(0), + departed: crate::object::Departed::default(), + }), + }; + exc.traced = true; + Self::link_traceback(exc, PyTraceback::new_lazy(shell.clone(), lineno, raise_pc)); + shell + } + + /// The shell of the running activation `frame`, when it is the spine's + /// top one. + #[inline] + pub(crate) fn spine_top_for(&self, frame: &Frame) -> Option> { + // SAFETY: only this thread mutates its spine, and the read runs no + // code (as `append_traceback`'s). + let stack = unsafe { &*self.frame_stack.as_ptr() }; + stack + .last() + .filter(|s| Rc::ptr_eq(&s.locals, frame.locals.shared()) && !s.has_departed()) + .cloned() + } + + /// The activation `act`, just registered, gets its shell for the + /// callee that departed while it ran lazily (see + /// [`InlineAct::back_for`]). + #[cold] + #[inline(never)] + pub(crate) fn resolve_back_for(&mut self, act: &mut InlineAct) { + let Some((departed, call_pc)) = act.back_for.take() else { + return; + }; + if act.act.shell.is_none() { + // SAFETY: the activation's own frame, which nothing else + // touches while its helper runs. + let frame = unsafe { &mut *act.act.frame }; + self.settle_lazy(); + self.flush_lean_cold(frame, &mut act.act); + } + if let Some(shell) = act.act.shell.as_ref() { + shell + .lasti + .store(call_pc, std::sync::atomic::Ordering::Relaxed); + departed.depart(Some(shell)); + } + } + /// Whether an inline activation returning with `shell` needs nothing /// of the full epilogue: no frame object yet and no handled-exception /// entries left above its entry depth (`inline_finish`'s second arm). @@ -38975,6 +45967,13 @@ impl Interpreter { } } }; + Self::link_traceback(exc, new_tb); + } + + /// Make `new_tb` the head of `exc`'s traceback, the chain so far under + /// it. + #[inline] + fn link_traceback(exc: &PyException, new_tb: PyTraceback) { let new_tb = Rc::new(new_tb); // CPython chains outward: the catching frame ends up at the // *head*; `tb_next` walks toward the raise site. Each @@ -39592,18 +46591,7 @@ impl Interpreter { /// The dict-subclass instance registered (by `exec`/`eval`) as the /// owner of `globals`, if any. fn globals_missing_owner(&self, globals: &Rc>) -> Option { - // While the gate is up every builtin `LOAD_GLOBAL` asks here, and - // a program that runs no finalizers may never drain them to notice - // the last owner die: every so often, have the next safe point - // drain and prune (see `prune_globals_missing_hooks_sometimes`). - let n = self.globals_missing_asks.get(); - if n >= 1024 { - self.globals_missing_asks.set(0); - self.globals_missing_prune_in.set(0); - gc_trace::mark_maybe_dead(); - } else { - self.globals_missing_asks.set(n + 1); - } + self.globals_missing_ask(); let hooks = self.globals_missing_hooks.borrow(); if hooks.is_empty() { return None; @@ -39615,6 +46603,40 @@ impl Interpreter { .map(|(_, inst)| Object::Instance(inst.clone())) } + /// Whether a dict subclass's `__missing__` may serve builtin lookups + /// (see `globals_missing_hooks`): the fast paths' gate. While it is up, + /// each ask counts as the full lookup's asks do (see + /// [`Self::globals_missing_ask`]), so a loop that only takes fast paths, + /// and runs no finalizers, still has the owners that died pruned + /// rather than keeping the gate up for good. + #[inline(always)] + pub(crate) fn globals_missing_gate(&self) -> bool { + if !self.globals_missing_any.get() { + return false; + } + self.globals_missing_ask(); + true + } + + /// One ask of the `__missing__` gate while it is up: a program that + /// runs no finalizers (a loop that releases nothing reaches no drain) + /// may never notice the last owner die, so every 32nd ask prunes the + /// owners no code runs with. (Soon enough that a pure leaf whose + /// builtin reads decline while the gate is up keeps its verdict: 64 + /// declines revoke it for good.) Letting one go only queues what its + /// release finalizes, which the next safe point drains. + #[inline(never)] + fn globals_missing_ask(&self) { + let n = self.globals_missing_asks.get(); + if n >= 32 { + self.globals_missing_asks.set(0); + self.prune_globals_missing_hooks(); + gc_trace::mark_maybe_dead(); + } else { + self.globals_missing_asks.set(n + 1); + } + } + /// PEP 649 (RFC 0077 WS10) — CPython's `func_get_annotation_dict` /// plus the getter's empty-dict default: the stored /// `__annotations__` slot wins; otherwise a callable `__annotate__` @@ -39679,8 +46701,14 @@ impl Interpreter { return true; }; // The instance's own slot is the "unreferenced" baseline for - // the dict, and this table's for the instance. - Rc::strong_count(d) > 1 || Rc::strong_count(inst) > 1 + // the dict. Code runs with the dict as its globals only while + // a function or frame holds it (a new `exec` or function over + // the instance registers it again), so an owner whose dict + // nothing else holds serves no lookup, however many hold the + // instance: `annotationlib`'s `_StringifierDict` stays alive + // in a cycle with the stringifiers it made, which this + // table's reference would keep from any collection. + Rc::strong_count(d) > 1 }); // With no owner left, builtin lookups take their fast paths again // (a `@dataclass` whose annotations needed `annotationlib`'s @@ -39785,35 +46813,109 @@ impl Interpreter { } } } - // CPython's `PyObject_GetAttr` augments *any* propagating - // AttributeError — internal or user-raised (`__getattr__`, - // property getters) — with `.name`/`.obj` for the - // "Did you mean" machinery, provided neither is already set - // (`set_attribute_error_context` in Objects/object.c). - if self.is_attribute_error(err) { - if let RuntimeError::PyException(pe) = err { - if let Object::Instance(inst) = &pe.instance { - if attr_error_context_laid_out(inst, obj, name) { - return result; - } - let need = matches!( - crate::builtin_types::exc_attr(inst, "name"), - None | Some(Object::None) - ) && matches!( - crate::builtin_types::exc_attr(inst, "obj"), - None | Some(Object::None) - ); - if need { - inst.slot_set("name", Object::from_str(name)); - inst.slot_set("obj", obj.clone()); - } - } - } - } + self.attr_error_context(err, obj, name); } result } + /// CPython's `PyObject_GetAttr` augments *any* propagating + /// AttributeError — internal or user-raised (`__getattr__`, property + /// getters) — with `.name`/`.obj` for the "Did you mean" machinery, + /// provided neither is already set (`set_attribute_error_context` in + /// Objects/object.c): `err`, out of the read of `obj.name`. + fn attr_error_context(&self, err: &RuntimeError, obj: &Object, name: &str) { + if !self.is_attribute_error(err) { + return; + } + let RuntimeError::PyException(pe) = err else { + return; + }; + let Object::Instance(inst) = &pe.instance else { + return; + }; + if attr_error_context_laid_out(inst, obj, name) { + return; + } + let need = matches!( + crate::builtin_types::exc_attr(inst, "name"), + None | Some(Object::None) + ) && matches!( + crate::builtin_types::exc_attr(inst, "obj"), + None | Some(Object::None) + ); + if need { + inst.slot_set("name", Object::from_str(name)); + inst.slot_set("obj", obj.clone()); + } + } + + /// The receiver of the attribute hook `done` ran for its caller's + /// `LOAD_ATTR` (see [`Self::try_inline_attr_hook`]: a `__getattr__` or + /// `__getattribute__` of `(self, name)`, called at `caller`'s + /// instruction `done.call_pc`), when it is leaving with an exception: + /// held across the activation's unwinding for + /// [`Self::attr_hook_context`]. `None` for any other activation. + #[inline] + fn attr_hook_receiver(caller: &Frame, done: &InlineAct, raised: bool) -> Option { + if !raised || done.gen.is_some() { + return None; + } + let ins = caller.code.instructions.get(done.call_pc)?; + if ins.op != OpCode::LoadAttr { + return None; + } + let Object::Function(f) = &done.callable else { + return None; + }; + if f.code().arg_count != 2 { + return None; + } + // SAFETY: the activation's own locals, read while nothing runs. + match unsafe { done.frame.locals.slots() }.first() { + Some(recv @ Object::Instance(_)) => Some(recv.clone()), + _ => None, + } + } + + /// An attribute hook's exception `result` on its way to the read that + /// called the hook (`recv`: see [`Self::attr_hook_receiver`]): an + /// `AttributeError` takes the read's name and receiver, as the full + /// read's does (see [`Self::attr_error_context`]). + #[inline] + fn attr_hook_context( + &mut self, + caller: &Frame, + call_pc: usize, + result: &Result, + recv: Option, + ) { + if let Some(recv) = recv { + self.attr_hook_context_for(caller, call_pc, result, recv); + } + } + + /// [`Self::attr_hook_context`] for a hook's receiver `recv`. + #[inline(never)] + fn attr_hook_context_for( + &mut self, + caller: &Frame, + call_pc: usize, + result: &Result, + recv: Object, + ) { + if let Err(err) = result { + let name = caller + .code + .instructions + .get(call_pc) + .and_then(|ins| caller.code.names.get(ins.arg as usize)); + if let Some(name) = name { + self.attr_error_context(err, &recv, name); + } + } + self.release(recv); + } + fn load_attr_inner(&mut self, obj: &Object, name: &str) -> Result { if burst_stats::enabled() { burst_stats::note_generic("load", obj, name); @@ -40546,7 +47648,7 @@ impl Interpreter { if f.defaults.is_empty() { return Ok(Object::None); } - return Ok(Object::new_tuple(f.defaults.to_vec())); + return Ok(Object::tuple_from_slice(&f.defaults)); } "__kwdefaults__" => { if f.kw_defaults.is_empty() { @@ -40562,7 +47664,7 @@ impl Interpreter { if f.closure.is_empty() { return Ok(Object::None); } - return Ok(Object::new_tuple(f.closure.to_vec())); + return Ok(Object::tuple_from_slice(&f.closure)); } "__annotations__" => { // PEP 649 (`function___annotations___get_impl`): @@ -40831,6 +47933,11 @@ impl Interpreter { .map(Object::from_str) .unwrap_or(Object::None)); } + // (A native method keeps the docstring of the Python + // one it replaced.) + if let Some(doc) = crate::descr_registry::doc_of(obj) { + return Ok(doc); + } if let Some(doc) = builtin_doc(b.name) { return Ok(Object::from_static(doc)); } @@ -41008,6 +48115,9 @@ impl Interpreter { "__doc__" => match &bm.function { Object::Function(_) => self.load_attr(&bm.function, name), Object::Builtin(b) => { + if let Some(doc) = crate::descr_registry::doc_of(&bm.function) { + return Ok(doc); + } if let Some(doc) = builtin_doc(b.name) { return Ok(Object::from_static(doc)); } @@ -41446,39 +48556,17 @@ impl Interpreter { // iterator (CPython method-wrapper semantics; `heapq.merge` // does `yield from next.__self__`). The closures ignore the // prepended receiver argument. - if let Object::Iter(it) = obj { - match name { - "__next__" => { - let it = it.clone(); - return Ok(Object::BoundMethod(Rc::new(BoundMethod::new( - obj.clone(), - Object::Builtin(Rc::new(BuiltinFn { - name: "__next__", - binds_instance: true, - call: Box::new(move |_args| { - match it.borrow_mut().next_value_checked() { - Ok(Some(v)) => Ok(v), - Ok(None) => Err(crate::error::stop_iteration()), - Err(e) => Err(e), - } - }), - call_kw: None, - })), - )))); - } - "__iter__" => { - let me = obj.clone(); + // (The kind's memoized methods, which take the iterator as + // their first argument: the site's method slot keeps one, + // so `it.__next__()` stays in compiled code.) + if let Object::Iter(_) = obj { + if matches!(name, "__next__" | "__iter__") { + if let Some(f @ Object::Builtin(_)) = builtins::lookup_method(obj, name) { return Ok(Object::BoundMethod(Rc::new(BoundMethod::new( obj.clone(), - Object::Builtin(Rc::new(BuiltinFn { - name: "__iter__", - binds_instance: true, - call: Box::new(move |_args| Ok(me.clone())), - call_kw: None, - })), + f, )))); } - _ => {} } } // A monkeypatched per-instance attribute on a file shadows the @@ -41596,7 +48684,7 @@ impl Interpreter { // full lookup). if name == "__class__" && inst.c_body.get() == 0 { let cls = inst.cls(); - if !cls.flags.is_builtin && cls.class_attr_is_plain() { + if cls.class_read_is_plain() { return Ok(Object::Type(cls)); } } @@ -41825,7 +48913,7 @@ impl Interpreter { let Some(name) = code.names.get((arg >> 2) as usize) else { return Ok(None); }; - let Some(attr) = self.super_mro_attr(&obj_type, &receiver, &cls, name)? else { + let Some(attr) = self.super_attr_resolve(&obj_type, &receiver, &cls, name)? else { return Ok(None); }; let len = frame.stack.len(); @@ -41833,6 +48921,189 @@ impl Interpreter { Ok(Some(attr)) } + /// What a bound `super(thisclass, receiver)` reads for `name` from the + /// classes after `thisclass` in `obj_type`'s MRO: the MRO walk, then the + /// slots WeavePy keeps outside the type dicts (`object.__repr__`, ...). + /// `None` leaves the name to the proxy's own attributes. + fn super_attr_resolve( + &mut self, + obj_type: &Rc, + receiver: &Object, + thisclass: &Rc, + name: &str, + ) -> Result, RuntimeError> { + let (obj_type, receiver, thisclass) = + (obj_type.clone(), receiver.clone(), thisclass.clone()); + if let Some(v) = self.super_mro_attr(&obj_type, &receiver, &thisclass, name)? { + return Ok(Some(v)); + } + // `object.__repr__` / `object.__str__` are identity slots that + // WeavePy keeps as native behaviour rather than type-dict + // entries, so the MRO walk above can't find them. CPython's + // `super_getattro` resolves them to `object`'s slot wrappers + // (`object_repr` / `object_str`); mirror that so + // `super().__repr__()` / `super().__str__()` delegate to the + // base implementation instead of falling through to the super + // proxy's *own* repr. `__repr__` is the non-virtual + // `` (computed here directly); `__str__` is + // `PyObject_Repr(self)` (a *virtual* repr dispatch), routed via + // the `.object_str` sentinel that `Interpreter::call` + // intercepts. Only pure-Python receivers reach here — built-in + // bases (`dict`, `list`, …) were already served by the native + // payload probe just above. + // + // `object.__dir__` is likewise a native slot absent from + // `object`'s type dict, so the MRO walk above can't find it. + // pandas' `DirNamesMixin.__dir__` seeds its attribute set with + // `set(super().__dir__())`; without this the call fell through + // to the *proxy's* own `__dir__` (listing the super proxy's + // ~20 members, not the receiver's), so `dir(df)` / + // `inspect.getmembers(df)` lost every class-level property and + // method (GH38740). Bind the default `dir` namespace walk + // (`b_dir`, the same impl `object.__dir__` uses) to the + // receiver. + if name == "__dir__" { + return Ok(Some(Object::BoundMethod(Rc::new( + crate::object::BoundMethod::new( + receiver.clone(), + Object::Builtin(Rc::new(crate::object::BuiltinFn { + name: "__dir__", + binds_instance: true, + call: Box::new(crate::builtins::b_dir), + call_kw: None, + })), + ), + )))); + } + // `type.mro` is a native slot absent from `type`'s dict, so + // the MRO walk above can't find it. A metaclass method doing + // `super().mro()` (test_super.test___class___mro) must reach + // the default C3 recomputation bound to the receiver class. + if name == "mro" + && matches!(&receiver, Object::Type(_)) + && obj_type + .mro + .borrow() + .iter() + .any(|t| Rc::ptr_eq(t, &builtin_types().type_)) + { + return Ok(Some(Object::BoundMethod(Rc::new( + crate::object::BoundMethod::new( + receiver.clone(), + Object::Builtin(Rc::new(crate::object::BuiltinFn { + name: "mro", + binds_instance: true, + call: Box::new(|args| { + let recv = match args.first() { + Some(Object::Type(t)) => t.clone(), + _ => { + return Err(type_error( + "descriptor 'mro' requires a 'type' object", + )) + } + }; + let mro = crate::types::TypeObject::recompute_c3(&recv)?; + Ok(Object::new_list( + mro.into_iter().map(Object::Type).collect(), + )) + }), + call_kw: None, + })), + ), + )))); + } + // `type.__prepare__` lives in `type`'s dict but is marked + // surface-only (RFC 0056 WS4), so the walk above skipped it. + // A metaclass classmethod chaining `super().__prepare__(*args, + // **kwds)` (test_metaclass) must reach the default: return a + // fresh empty dict, ignoring all arguments like CPython. + if name == "__prepare__" + && obj_type + .mro + .borrow() + .iter() + .any(|t| Rc::ptr_eq(t, &builtin_types().type_)) + { + fn default_prepare(_args: &[Object]) -> Result { + Ok(Object::new_dict()) + } + return Ok(Some(Object::BoundMethod(Rc::new( + crate::object::BoundMethod::new( + receiver.clone(), + Object::Builtin(Rc::new(crate::object::BuiltinFn { + name: "__prepare__", + binds_instance: true, + call: Box::new(default_prepare), + call_kw: Some(Box::new(|args, _kwargs| default_prepare(args))), + })), + ), + )))); + } + if matches!(name, "__repr__" | "__str__") { + let func = if name == "__repr__" { + Object::Builtin(Rc::new(crate::object::BuiltinFn { + name: "__repr__", + binds_instance: true, + call: Box::new(|args: &[Object]| { + let o = args.first().ok_or_else(|| { + type_error("__repr__() takes exactly one argument (0 given)") + })?; + Ok(Object::from_str(object_base_repr_string(o))) + }), + call_kw: None, + })) + } else { + Object::Builtin(Rc::new(crate::object::BuiltinFn { + name: ".object_str", + binds_instance: true, + call: Box::new(|_| { + Err(crate::error::runtime_error( + "object.__str__ must be dispatched via Interpreter::call", + )) + }), + call_kw: None, + })) + }; + return Ok(Some(Object::BoundMethod(Rc::new( + crate::object::BoundMethod::new(receiver.clone(), func), + )))); + } + // The remaining native slot wrappers (`object.__getstate__`, + // `__format__`, `__sizeof__`, the rich comparisons, …) live in + // CPython's `tp_dict` and are found by `super_getattro`'s MRO + // walk, then bound to `su->obj` (or left unbound in the + // class-bound form). WeavePy synthesizes them on demand, so + // probe the built-in bases past `thisclass` here; otherwise the + // proxy's own generic lookup would bind them to the *proxy* + // (test_super test_special_methods: `super(C, e).__getstate__ + // == e.__getstate__`). + { + let tail: Vec> = { + let mro = obj_type.mro.borrow(); + let start = mro + .iter() + .position(|t| Rc::ptr_eq(t, &thisclass)) + .map_or(mro.len(), |i| i + 1); + mro[start..].to_vec() + }; + for base in tail.iter().filter(|b| b.flags.is_builtin) { + if let Some(f) = crate::builtins::builtin_type_dunder(&base.name, name) { + let class_bound = matches!( + &receiver, + Object::Type(r) if Rc::ptr_eq(r, &obj_type) + ); + if class_bound { + return Ok(Some(f)); + } + return Ok(Some(Object::BoundMethod(Rc::new( + crate::object::BoundMethod::new(receiver.clone(), f), + )))); + } + } + } + Ok(None) + } + /// The default `object.__getattribute__` body: data descriptor → instance /// dict → class attr → built-in-subclass payload, ending in /// `AttributeError`. Does **not** consult `__getattr__` (the caller does) @@ -41899,173 +49170,9 @@ impl Interpreter { None }; if let Some((obj_type, receiver, thisclass)) = super_fields { - if let Some(v) = self.super_mro_attr(&obj_type, &receiver, &thisclass, name)? { + if let Some(v) = self.super_attr_resolve(&obj_type, &receiver, &thisclass, name)? { return Ok(v); } - // `object.__repr__` / `object.__str__` are identity slots that - // WeavePy keeps as native behaviour rather than type-dict - // entries, so the MRO walk above can't find them. CPython's - // `super_getattro` resolves them to `object`'s slot wrappers - // (`object_repr` / `object_str`); mirror that so - // `super().__repr__()` / `super().__str__()` delegate to the - // base implementation instead of falling through to the super - // proxy's *own* repr. `__repr__` is the non-virtual - // `` (computed here directly); `__str__` is - // `PyObject_Repr(self)` (a *virtual* repr dispatch), routed via - // the `.object_str` sentinel that `Interpreter::call` - // intercepts. Only pure-Python receivers reach here — built-in - // bases (`dict`, `list`, …) were already served by the native - // payload probe just above. - // - // `object.__dir__` is likewise a native slot absent from - // `object`'s type dict, so the MRO walk above can't find it. - // pandas' `DirNamesMixin.__dir__` seeds its attribute set with - // `set(super().__dir__())`; without this the call fell through - // to the *proxy's* own `__dir__` (listing the super proxy's - // ~20 members, not the receiver's), so `dir(df)` / - // `inspect.getmembers(df)` lost every class-level property and - // method (GH38740). Bind the default `dir` namespace walk - // (`b_dir`, the same impl `object.__dir__` uses) to the - // receiver. - if name == "__dir__" { - return Ok(Object::BoundMethod(Rc::new( - crate::object::BoundMethod::new( - receiver.clone(), - Object::Builtin(Rc::new(crate::object::BuiltinFn { - name: "__dir__", - binds_instance: true, - call: Box::new(crate::builtins::b_dir), - call_kw: None, - })), - ), - ))); - } - // `type.mro` is a native slot absent from `type`'s dict, so - // the MRO walk above can't find it. A metaclass method doing - // `super().mro()` (test_super.test___class___mro) must reach - // the default C3 recomputation bound to the receiver class. - if name == "mro" - && matches!(&receiver, Object::Type(_)) - && obj_type - .mro - .borrow() - .iter() - .any(|t| Rc::ptr_eq(t, &builtin_types().type_)) - { - return Ok(Object::BoundMethod(Rc::new( - crate::object::BoundMethod::new( - receiver.clone(), - Object::Builtin(Rc::new(crate::object::BuiltinFn { - name: "mro", - binds_instance: true, - call: Box::new(|args| { - let recv = match args.first() { - Some(Object::Type(t)) => t.clone(), - _ => { - return Err(type_error( - "descriptor 'mro' requires a 'type' object", - )) - } - }; - let mro = crate::types::TypeObject::recompute_c3(&recv)?; - Ok(Object::new_list( - mro.into_iter().map(Object::Type).collect(), - )) - }), - call_kw: None, - })), - ), - ))); - } - // `type.__prepare__` lives in `type`'s dict but is marked - // surface-only (RFC 0056 WS4), so the walk above skipped it. - // A metaclass classmethod chaining `super().__prepare__(*args, - // **kwds)` (test_metaclass) must reach the default: return a - // fresh empty dict, ignoring all arguments like CPython. - if name == "__prepare__" - && obj_type - .mro - .borrow() - .iter() - .any(|t| Rc::ptr_eq(t, &builtin_types().type_)) - { - fn default_prepare(_args: &[Object]) -> Result { - Ok(Object::new_dict()) - } - return Ok(Object::BoundMethod(Rc::new( - crate::object::BoundMethod::new( - receiver.clone(), - Object::Builtin(Rc::new(crate::object::BuiltinFn { - name: "__prepare__", - binds_instance: true, - call: Box::new(default_prepare), - call_kw: Some(Box::new(|args, _kwargs| default_prepare(args))), - })), - ), - ))); - } - if matches!(name, "__repr__" | "__str__") { - let func = if name == "__repr__" { - Object::Builtin(Rc::new(crate::object::BuiltinFn { - name: "__repr__", - binds_instance: true, - call: Box::new(|args: &[Object]| { - let o = args.first().ok_or_else(|| { - type_error("__repr__() takes exactly one argument (0 given)") - })?; - Ok(Object::from_str(object_base_repr_string(o))) - }), - call_kw: None, - })) - } else { - Object::Builtin(Rc::new(crate::object::BuiltinFn { - name: ".object_str", - binds_instance: true, - call: Box::new(|_| { - Err(crate::error::runtime_error( - "object.__str__ must be dispatched via Interpreter::call", - )) - }), - call_kw: None, - })) - }; - return Ok(Object::BoundMethod(Rc::new( - crate::object::BoundMethod::new(receiver.clone(), func), - ))); - } - // The remaining native slot wrappers (`object.__getstate__`, - // `__format__`, `__sizeof__`, the rich comparisons, …) live in - // CPython's `tp_dict` and are found by `super_getattro`'s MRO - // walk, then bound to `su->obj` (or left unbound in the - // class-bound form). WeavePy synthesizes them on demand, so - // probe the built-in bases past `thisclass` here; otherwise the - // proxy's own generic lookup would bind them to the *proxy* - // (test_super test_special_methods: `super(C, e).__getstate__ - // == e.__getstate__`). - { - let tail: Vec> = { - let mro = obj_type.mro.borrow(); - let start = mro - .iter() - .position(|t| Rc::ptr_eq(t, &thisclass)) - .map_or(mro.len(), |i| i + 1); - mro[start..].to_vec() - }; - for base in tail.iter().filter(|b| b.flags.is_builtin) { - if let Some(f) = crate::builtins::builtin_type_dunder(&base.name, name) { - let class_bound = matches!( - &receiver, - Object::Type(r) if Rc::ptr_eq(r, &obj_type) - ); - if class_bound { - return Ok(f); - } - return Ok(Object::BoundMethod(Rc::new( - crate::object::BoundMethod::new(receiver.clone(), f), - ))); - } - } - } // Not found along the delegated MRO: fall through to normal // resolution so the proxy's *own* attributes (`__init__`, // `__get__`, `__repr__`, `__thisclass__`, `__self__`, @@ -42185,10 +49292,28 @@ impl Interpreter { // shared list, `c.bit_length()` reads the wrapped int, etc.). // Dunders are excluded: those route through dedicated protocol // paths and must not be hijacked here. + // + // A miss depends on the payload's class and the name alone: it is + // remembered there (for names that are no dunder at all), so the + // next read builds no second `AttributeError`, and `hasattr`, a + // `getattr` default and a caught miss none of the lookup either + // (see `default_lookup_misses`). if !(name.starts_with("__") && name.ends_with("__")) { - if let Some(native) = inst.native.get() { + if let Some(native) = inst + .native + .get() + .filter(|p| name.starts_with("__") || !payload_class_misses(p, name)) + { let native = native.clone(); - if let Ok(v) = self.load_attr(&native, name) { + let found = self.load_attr(&native, name); + if let Err(e) = &found { + if !name.starts_with("__") && self.is_attribute_error(e) { + if let Some(c) = builtin_value_class(&native) { + c.verdict_record(crate::types::Verdict::ValueAttrMissing, name, true); + } + } + } + if let Ok(v) = found { // The dict view methods rebind to the *instance* // (CPython's `A().keys().__self__` is the instance): // `dict_self` unwraps it again, and the view pins the @@ -42411,6 +49536,28 @@ impl Interpreter { { return Ok(Object::Str(s.clone())); } + // A class whose own `__init__` is a native method carrying + // a signature (`decimal.Context`'s, which replaces a Python + // method): the constructor's signature is that one without + // its receiver, as a static type's is its `tp_doc`'s. + if !ty.flags.is_builtin { + let init = ty + .dict + .borrow() + .get(&crate::object::StrKey("__init__")) + .cloned(); + if let Some(init @ Object::Builtin(_)) = init { + match crate::descr_registry::text_signature_of(&init) { + Some("($self, /)") => return Ok(Object::from_static("()")), + Some(sig) => { + if let Some(rest) = sig.strip_prefix("($self, /, ") { + return Ok(Object::from_str(format!("({rest}"))); + } + } + None => {} + } + } + } // A bridged extension type's `tp_doc` is mutable C state // that numpy-style `add_docstring` rewrites after ready — // re-read it live, exactly like CPython's @@ -42502,6 +49649,9 @@ impl Interpreter { { return Ok(orig.clone()); } + if let Some(t) = ty.links_tuple(true) { + return Ok(t); + } let bases = ty .bases .borrow() @@ -42548,13 +49698,9 @@ impl Interpreter { if ty.mro.borrow().is_empty() && !ty.flags.is_builtin { return Ok(Object::None); } - let mro = ty - .mro - .borrow() - .iter() - .map(|b| Object::Type(b.clone())) - .collect(); - return Ok(Object::new_tuple(mro)); + return Ok(ty + .links_tuple(false) + .unwrap_or_else(|| Object::new_tuple(Vec::new()))); } "__class__" => return Ok(Object::Type(meta)), // PEP 695: `type.__type_params__` is a getset defaulting to @@ -43397,6 +50543,393 @@ impl Interpreter { Ok(Object::None) } + /// The text the general `str(inst)` (`repr(inst)` when `repr`) finds + /// natively ahead of the class's Python method: an exact + /// `decimal.Decimal`'s, a number subclass's rendered as its base, an + /// enum member's `Enum.__str__`. The compiled code's direct calls of a + /// `__str__` or `__repr__` take these first. + pub(crate) fn native_text(inst: &crate::types::PyInstance, repr: bool) -> Option { + if crate::stdlib::decimal_native::is_decimal_instance(inst) { + return if repr { + crate::stdlib::decimal_native::leaf_repr(inst) + } else { + crate::stdlib::decimal_native::leaf_str(inst) + }; + } + if repr { + return None; + } + // (A number's text needs a native payload: a plain class's instance + // asks no verdict for it, nor, see `enum_str`, an enum's.) + if inst.native.get().is_some() { + if let Some(v) = Self::num_str_payload(inst) { + return Some(v); + } + } + Self::enum_str(inst) + } + + /// `str(inst)` of a `str` subclass's instance whose class keeps + /// `str`'s own `__str__` (no Python override, remembered per class + /// version): its payload, as [`Self::do_str_call`]'s last resort for + /// such an instance answers, without looking `__str__` up each time + /// (`email`'s `Terminal.value` is `str(self)`). `None` for anything + /// else. + pub(crate) fn str_payload(inst: &Rc) -> Option { + let native @ (Object::Str(_) | Object::WStr(_)) = inst.native.get()? else { + return None; + }; + let cls = inst.cls_raw(); + if !cls.memo_verdict(crate::types::Verdict::StrPayload, "", || { + Self::str_payload_class(inst) + }) { + return None; + } + Some(native.clone()) + } + + /// Whether `inst`'s class has no `__str__` dispatch reaches (see + /// [`Self::str_payload`]): `str`'s own is an introspection-only entry + /// that the walk passes over, so a mixed `str` enum's `Enum.__str__` + /// after it on the MRO answers. The checks [`Self::do_str_call`] makes. + fn str_payload_class(inst: &Rc) -> bool { + Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::STR_FN), + "__str__", + ) + .is_none() + && instance_method(&Object::Instance(inst.clone()), "__str__").is_none() + } + + /// `str(inst)` of an `int`, `float` or `str` subclass's instance whose + /// class renders it as the base does (see + /// [`Self::num_str_payload_class`], remembered per class version): the + /// payload's text. `None` for anything else. + pub(crate) fn num_str_payload(inst: &crate::types::PyInstance) -> Option { + let native @ (Object::Int(_) | Object::Long(_) | Object::Float(_) | Object::Str(_)) = + inst.native.get()? + else { + return None; + }; + let cls = inst.cls_raw(); + if !cls.memo_verdict(crate::types::Verdict::NumStrPayload, "", || { + Self::num_str_payload_class(cls, native) + }) { + return None; + } + match native { + Object::Str(_) => Some(native.clone()), + _ => crate::object::native_scalar_repr(native), + } + } + + /// Whether `cls`, whose instances carry a payload like `native`, gives + /// `str(x)` as the payload's own text. Its `__str__` may be the base + /// type's own method stored in a Python class (`ReprEnum` stores + /// `int.__repr__` or `str.__str__` so). Otherwise, for a number, + /// neither `__str__` nor `__repr__` may come from a Python class: + /// `object.__str__` then renders the base's `__repr__`, which reads + /// only the payload. (A `str` subclass's other cases are + /// [`Self::str_payload`]'s.) + fn num_str_payload_class(cls: &TypeObject, native: &Object) -> bool { + if cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || crate::object::exotic_str_keys_possible() + { + return false; + } + let base = crate::builtins::class_of(native); + let is_str = matches!(native, Object::Str(_)); + let name = if is_str { "__str__" } else { "__repr__" }; + let base_render = base + .lookup(name) + .or_else(|| builtin_slot_wrapper(&base, name)); + let s = cls.lookup_with_owner("__str__"); + if let (Some((Object::Builtin(b), owner)), Some(Object::Builtin(r))) = (&s, &base_render) { + if !owner.flags.is_builtin && Rc::ptr_eq(b, r) { + return true; + } + } + let builtin_or_absent = + |x: Option<(Object, Rc)>| x.is_none_or(|(_, owner)| owner.flags.is_builtin); + !is_str && builtin_or_absent(s) && builtin_or_absent(cls.lookup_with_owner("__repr__")) + } + + /// `str(inst)` of a `str`, `int` or `float` subclass's instance that + /// renders as its payload (see [`Self::str_payload`] and + /// [`Self::num_str_payload`]), as an exact `str`. `None` for anything + /// else. + pub(crate) fn payload_str(inst: &Rc) -> Option { + match inst.native.get()? { + Object::Str(_) => Self::str_payload(inst).or_else(|| Self::num_str_payload(inst)), + Object::Int(_) | Object::Long(_) | Object::Float(_) => Self::num_str_payload(inst), + _ => None, + } + } + + /// `str(inst)` with no code run: a `str`, `int` or `float` subclass's + /// payload text ([`Self::payload_str`]), or an enum member's + /// `Class.name` ([`Self::enum_str`]). `None` for anything else. + pub(crate) fn quick_str(inst: &Rc) -> Option { + Self::payload_str(inst).or_else(|| Self::enum_str(inst)) + } + + /// `str(member)` of an enum member whose class keeps `enum`'s own + /// `Enum.__str__` (`"%s.%s" % (self.__class__.__name__, self._name_)`) + /// under the default attribute access, with no `__class__`, `_name_` or + /// assigned `__name__` in the way (a verdict kept per class version): the + /// class's name and the member's `_name_`, read from its dict. `None` + /// for anything else (a `_name_` that isn't an exact `str`), or while a + /// tracer or profiler would see the method. + pub(crate) fn enum_str(inst: &crate::types::PyInstance) -> Option { + let cls = inst.cls_raw(); + // An enum member's class has a metaclass of its own (`EnumType`): a + // plain class (a `type` metaclass, unset or explicit) asks no + // verdict. + // SAFETY: a read of the class's metaclass cell that runs no code. + let plain = match unsafe { cls.metaclass.peek() } { + Some(None) => true, + Some(Some(m)) => Rc::ptr_eq(m, &crate::builtin_types::builtin_types().type_), + None => false, + }; + if plain || crate::trace::any_observers_active() { + return None; + } + if !cls.memo_verdict(crate::types::Verdict::EnumStr, "", || { + Self::enum_name_readable(cls) + // (An assigned `__name__` lives in the class dict.) + && cls.lookup("__name__").is_none() + && !cls + .lookup_with_owner("__class__") + .is_some_and(|(_, owner)| !owner.flags.is_builtin) + && matches!( + cls.lookup("__str__"), + Some(Object::Function(f)) if Self::stdlib_fn_is(&f, "enum", "Enum.__str__") + ) + }) { + return None; + } + let name = Self::enum_member_name(inst)?; + let mut out = String::with_capacity(cls.name.len() + 1 + name.len()); + out.push_str(&cls.name); + out.push('.'); + out.push_str(&name); + Some(Object::from_str(out)) + } + + /// `hash(member)` of an enum member whose class keeps `enum`'s own + /// `Enum.__hash__` (`hash(self._name_)`) under the default attribute + /// access (a verdict kept per class version): its `_name_`'s hash. + /// `None` for anything else, or while a tracer or profiler would see + /// the method. + pub(crate) fn enum_hash(inst: &crate::types::PyInstance) -> Option { + if crate::trace::any_observers_active() { + return None; + } + let cls = inst.cls_raw(); + if !cls.memo_verdict(crate::types::Verdict::EnumHash, "", || { + Self::enum_name_readable(cls) + && matches!( + cls.lookup("__hash__"), + Some(Object::Function(f)) if Self::stdlib_fn_is(&f, "enum", "Enum.__hash__") + ) + }) { + return None; + } + let name = Self::enum_member_name(inst)?; + crate::object::py_hash_value(&Object::Str(name)) + } + + /// Whether `self._name_` of `cls`'s instances is their dict's entry: + /// the default attribute access, and nothing named `_name_` on the + /// class (a descriptor would answer first). + fn enum_name_readable(cls: &TypeObject) -> bool { + !crate::object::exotic_str_keys_possible() + && cls.native_kind.get() == 0 + && cls.c_ext_ptr.get() == 0 + && cls + .dunder(crate::types::Dunder::GetAttribute) + .object_owner() + && cls.lookup("_name_").is_none() + } + + /// An enum member's `_name_` from its dict, when an exact `str`. + fn enum_member_name(inst: &crate::types::PyInstance) -> Option { + match Self::enum_member_field(inst, ENUM_NAME)? { + Object::Str(name) => Some(name), + _ => None, + } + } + + /// The entry [`ENUM_FIELDS`]`[field]` of an instance's dict: the name's + /// hash computed once, and its position in a split layout remembered + /// (see [`crate::inst_dict::PosMemo`]). + fn enum_member_field(inst: &crate::types::PyInstance, field: usize) -> Option { + struct FieldName { + hash: i64, + memo: crate::inst_dict::PosMemo, + } + static NAMES: std::sync::OnceLock<[FieldName; 3]> = std::sync::OnceLock::new(); + let names = NAMES.get_or_init(|| { + ENUM_FIELDS.map(|name| FieldName { + hash: crate::object::py_str_hash(name), + memo: crate::inst_dict::PosMemo::new(), + }) + }); + let (name, n) = (*ENUM_FIELDS.get(field)?, names.get(field)?); + match inst.dict.published() { + Some(dict) => dict + .try_borrow() + .ok()? + .get(&crate::object::StrKeyHashed { + s: name, + hash: n.hash, + }) + .cloned(), + None => inst + .dict + .split_cell() + .try_borrow() + .ok()? + .get_memo(name, n.hash, &n.memo) + .cloned(), + } + } + + /// `member.name` or `member.value` through `descr`, an `enum.property` + /// whose class keeps `enum`'s own `property.__get__` and whose `fget` + /// is `Enum.name` or `Enum.value` (`return self._name_` / + /// `return self._value_`), over a member whose class reads both + /// fields from its dict (verdicts kept per class version): the + /// field. `None` for anything else, or while a tracer or profiler + /// would see the calls. + pub(crate) fn enum_property_value(descr: &PyInstance, inst: &PyInstance) -> Option { + if crate::trace::any_observers_active() { + return None; + } + let dcls = descr.cls_raw(); + if !dcls.memo_verdict(crate::types::Verdict::EnumPropertyGet, "", || { + !crate::object::exotic_str_keys_possible() + && matches!( + dcls.lookup("__get__"), + Some(Object::Function(f)) if Self::stdlib_fn_is(&f, "enum", "property.__get__") + ) + }) { + return None; + } + let cls = inst.cls_raw(); + if !cls.memo_verdict(crate::types::Verdict::EnumFields, "", || { + Self::enum_name_readable(cls) && cls.lookup("_value_").is_none() + }) { + return None; + } + // (Which field the getter reads, remembered for the function.) + thread_local! { + static FGET: std::cell::RefCell, Option)>> = + const { std::cell::RefCell::new(None) }; + } + let Some(Object::Function(fget)) = Self::enum_member_field(descr, ENUM_FGET) else { + return None; + }; + let known = FGET.with(|m| { + m.borrow().as_ref().and_then(|(w, field)| { + std::ptr::eq(w.as_ptr(), Rc::as_ptr(&fget)).then_some(*field) + }) + }); + let field = match known { + Some(field) => field, + None => { + let field = if Self::stdlib_fn_is(&fget, "enum", "Enum.name") { + Some(ENUM_NAME) + } else if Self::stdlib_fn_is(&fget, "enum", "Enum.value") { + Some(ENUM_VALUE) + } else { + None + }; + FGET.with(|m| *m.borrow_mut() = Some((Rc::downgrade(&fget), field))); + field + } + }?; + Self::enum_member_field(inst, field) + } + + /// `format(inst, spec)` with no code run: the payload's own + /// `__format__` (see [`Self::format_payload`]), or `enum`'s own + /// `Enum.__format__` (`str.__format__(str(self), spec)`) over a + /// [`Self::quick_str`]. `None` for anything else; `Some(Err)` for a + /// spec the value rejects. + pub(crate) fn quick_format( + inst: &Rc, + spec: &str, + ) -> Option> { + if Self::format_payload(inst) { + if spec.is_empty() { + return match Self::payload_str(inst)? { + Object::Str(s) => Some(Ok(s.to_string())), + _ => None, + }; + } + let native = inst.native.get()?.clone(); + return Some(format_via_spec(&native, spec)); + } + if crate::trace::any_observers_active() { + return None; + } + let cls = inst.cls_raw(); + if !cls.memo_verdict(crate::types::Verdict::EnumFormat, "", || { + !crate::object::exotic_str_keys_possible() + && matches!( + cls.lookup("__format__"), + Some(Object::Function(f)) if Self::stdlib_fn_is(&f, "enum", "Enum.__format__") + ) + }) { + return None; + } + let text = Self::quick_str(inst)?; + if spec.is_empty() { + return Some(Ok(text.to_str())); + } + Some(format_via_spec(&text, spec)) + } + + /// Whether `inst`'s class formats it with its payload type's own + /// `__format__` (an `int`, `float` or `str` subclass's, `IntEnum`'s and + /// `StrEnum`'s), remembered per class version: `format(x, spec)` is + /// then the payload's for a non-empty spec, and `str(x)` for an empty + /// one. + pub(crate) fn format_payload(inst: &crate::types::PyInstance) -> bool { + let Some(native @ (Object::Int(_) | Object::Long(_) | Object::Float(_) | Object::Str(_))) = + inst.native.get() + else { + return false; + }; + let cls = inst.cls_raw(); + cls.memo_verdict(crate::types::Verdict::FormatPayload, "", || { + if cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || crate::object::exotic_str_keys_possible() + { + return false; + } + // (Nothing in a class dict, or a built-in's entry: the base's + // slot, which comes before `object`'s on the MRO.) + match cls.lookup_with_owner("__format__") { + None => true, + Some((_, owner)) if owner.flags.is_builtin => true, + Some((Object::Builtin(x), _)) => { + let base = crate::builtins::class_of(native); + matches!( + base.lookup("__format__") + .or_else(|| builtin_slot_wrapper(&base, "__format__")), + Some(Object::Builtin(y)) if Rc::ptr_eq(&x, &y) + ) + } + Some(_) => false, + } + }) + } + fn do_str_call( &mut self, v: &Object, @@ -43412,6 +50945,12 @@ impl Interpreter { return Ok(text); } if let Object::Instance(inst) = v { + if let Some(s) = Self::str_payload(inst) { + return Ok(s); + } + if let Some(s) = Self::num_str_payload(inst).or_else(|| Self::enum_str(inst)) { + return Ok(s); + } // An exact `decimal.Decimal` (see `stdlib::decimal_native`). if crate::stdlib::decimal_native::is_decimal_instance(inst) { if let Some(r) = crate::stdlib::decimal_native::leaf_str(inst) { @@ -43430,7 +50969,29 @@ impl Interpreter { "__str__", ) { Some(f) => Some(Ok(f)), - None => instance_method(v, "__str__").map(Err), + None if Self::class_lacks( + inst.cls_raw(), + crate::types::AttrKey::vm(crate::types::vm_key::STR_ABSENT), + "__str__", + ) => + { + None + } + None => { + // A native `__str__` (an exception's), called with the + // instance. + if let Some(b) = Self::instance_native_str(inst) { + let r = (b.call)(std::slice::from_ref(v))?; + if str_like_object(&r) { + return Ok(r); + } + return Err(type_error(format!( + "__str__ returned non-string (type {})", + r.type_name() + ))); + } + instance_method(v, "__str__").map(Err) + } }; if let Some(method) = method { let r = match method { @@ -43463,8 +51024,22 @@ impl Interpreter { // subclass overrides `__repr__` and the base has no `tp_str` of // its own (an `int`, `float` or container subclass: CPython's // `object_str` then calls the override). + // (A plain Python `__repr__`, called with the instance.) + if inst.native.get().is_none() { + if let Some(r) = self.instance_python_repr(v) { + let r = r?; + if str_like_object(&r) { + return Ok(r); + } + // (`object.__str__`'s own check, as CPython words it.) + return Err(type_error(format!( + "__str__ returned non-string (type {})", + r.type_name() + ))); + } + } if (inst.native.get().is_none() || native_subclass_own_repr(inst)) - && instance_method(v, "__repr__").is_some() + && inst.cls_raw().lookup("__repr__").is_some() { return self.do_repr_call(v, globals); } @@ -43761,6 +51336,39 @@ impl Interpreter { /// Format `value` with `spec`, dispatching to a user `__format__` /// when present (CPython's `PyObject_Format`). Built-in objects use /// the format mini-language. + /// `format(value, spec)` through `inst`'s class's Python `__format__` + /// (found once per class version) when it is a warm pure leaf of + /// `(self, spec)` that answers a `str`. `None` for anything else. + fn leaf_instance_format( + &self, + inst: &PyInstance, + value: &Object, + spec: &str, + ) -> Option { + if crate::object::exotic_str_keys_possible() || crate::trace::any_observers_active() { + return None; + } + let f = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::FORMAT_FN), + "__format__", + )?; + let code = f.code(); + if code.arg_count != 2 + || !code_is_pure_leaf(&code) + || !pure_leaf_warm(&code) + || crate::recursion::current_depth() >= crate::recursion::recursion_limit() + { + return None; + } + let spec = Object::from_str(spec); + let args = [std::ptr::from_ref(value), std::ptr::from_ref(&spec)]; + match self.pure_leaf_eval::(&code, &f, &args)? { + Object::Str(s) => Some(s.to_string()), + _ => None, + } + } + fn format_obj_str( &mut self, value: &Object, @@ -43774,17 +51382,44 @@ impl Interpreter { return Ok(r); } } - if let Some(method) = instance_method(value, "__format__") { + // The payload type's own `__format__` (an `IntEnum`'s, a plain + // `str` subclass's): the payload formatted, or `str(self)` for + // an empty spec, as that method does. + // (Or `Enum.__format__` over a member's name.) + if let Some(r) = Self::quick_format(inst, spec) { + return r; + } + if Self::format_payload(inst) && spec.is_empty() { + return self.stringify(value, globals); + } + let lacks_format = Self::class_lacks( + inst.cls_raw(), + crate::types::AttrKey::vm(crate::types::vm_key::FORMAT_LACKS), + "__format__", + ); + // A warm pure-leaf `__format__` (`return format(self.v, spec)`), + // evaluated in place with no bound method or frame; a result + // that isn't a `str` takes the full call, which raises. + if !lacks_format { + if let Some(r) = self.leaf_instance_format(inst, value, spec) { + return Ok(r); + } + } + if let Some(method) = (!lacks_format) + .then(|| instance_method(value, "__format__")) + .flatten() + { let r = self.call(&method, &[Object::from_str(spec)], &[], globals)?; // CPython's `PyObject_Format` rejects a non-str result // (test_builtin test_format BadFormatResult). return match &r { Object::Str(s) => Ok(s.to_string()), Object::WStr(_) => Ok(r.to_str()), + // A `str` subclass's instance: its text (not its repr). Object::Instance(i) if matches!(i.native.get(), Some(Object::Str(_) | Object::WStr(_))) => { - Ok(r.to_str()) + Ok(i.native.get().expect("checked").to_str()) } other => Err(type_error(format!( "__format__ must return a str, not {}", @@ -43814,6 +51449,16 @@ impl Interpreter { Err(unsupported_format_string(value)) }; } + // A `mappingproxy` has `object.__format__`: its `str()` for an + // empty spec. + if let Object::MappingProxy(_) | Object::MappingProxyObj(_) = value { + let s = self.stringify(value, globals)?; + return if spec.is_empty() { + Ok(s) + } else { + Err(unsupported_format_string(value)) + }; + } // `format(SomeClass)` — a class consults its *metaclass* // `__format__`, defaulting to `object.__format__` (str(cls), which // itself dispatches the metaclass `__str__`/`__repr__`). @@ -43897,7 +51542,21 @@ impl Interpreter { "__repr__", ) { Some(f) => Some(Ok(f)), - None => instance_method(v, "__repr__").map(Err), + None => { + // A native one (an exception's), called with the + // instance. + if let Some(b) = Self::instance_native_repr(inst) { + let r = (b.call)(std::slice::from_ref(v))?; + if str_like_object(&r) { + return Ok(r); + } + return Err(type_error(format!( + "__repr__ returned non-string (type {})", + r.type_name() + ))); + } + instance_method(v, "__repr__").map(Err) + } }; if let Some(method) = method { let r = match method { @@ -43960,7 +51619,11 @@ impl Interpreter { crate::types::AttrKey::vm(crate::types::vm_key::LEN_FN), "__len__", ) { - let r = self.call(&Object::Function(f), std::slice::from_ref(v), &[], globals)?; + // (Evaluated in place when a pure leaf.) + let r = match self.call_pure_leaf_with(&f, Some(v), &[]) { + Some(r) => r, + None => self.call_python(&f, std::slice::from_ref(v), &[])?, + }; return coerce_len_result(r).map(Object::Int); } } @@ -43982,7 +51645,21 @@ impl Interpreter { // attribute resolution synthesises it from the slot. Consult // that before giving up so `len(np.dtype('f8'))` answers `0` // (pandas' `Series.__init__` does `if len(data.dtype):` to - // detect compound dtypes). + // detect compound dtypes). A number, `None` or a function + // has none to find: `len(5)` raises its `TypeError` + // without building the lookup's `AttributeError` first. + if matches!( + v, + Object::Int(_) + | Object::Long(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Function(_) + | Object::Builtin(_) + ) { + return Err(e); + } if let Ok(lenf) = self.load_attr_public(v, "__len__") { let r = self.call(&lenf, &[], &[], globals)?; return coerce_len_result(r).map(Object::Int); @@ -44002,6 +51679,10 @@ impl Interpreter { v: &Object, globals: &Rc>, ) -> Result { + // (A native `__abs__`'s body directly: `abs(td)`, `abs(dec)`.) + if let Some(r) = instance_native_dunder(v, "__abs__", None) { + return r; + } if let Some(method) = instance_method(v, "__abs__") { return self.call(&method, &[], &[], globals); } @@ -44036,6 +51717,27 @@ impl Interpreter { globals: &Rc>, ) -> Result { if let Some(value) = args.first() { + // A plain instance's class's Python `__round__`, through the + // class's cache, called with the instance (in place when a + // leaf, its `ndigits` default bound). + if let Object::Instance(inst) = value { + if let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::ROUND_FN), + "__round__", + ) { + let call_args: &[Object] = if args.len() >= 2 { + &args[..2] + } else { + &args[..1] + }; + return self.call_dunder_function(f, call_args); + } + } + // (A native `__round__`'s body directly: `round(dec, 2)`.) + if let Some(r) = instance_native_dunder(value, "__round__", args.get(1)) { + return r; + } if let Some(method) = instance_method(value, "__round__") { let extra: &[Object] = if args.len() >= 2 { &args[1..2] } else { &[] }; return self.call(&method, extra, &[], globals); @@ -44866,6 +52568,15 @@ impl Interpreter { if let Object::MappingProxyObj(inner) = v { return self.obj_truthy(inner, globals); } + // A released view has no length to test (CPython's `memory_length` + // refuses, and `PyObject_IsTrue` asks it). + if let Object::MemoryView(mv) = v { + if mv.released.get() { + return Err(value_error( + "operation forbidden on released memoryview object", + )); + } + } if let Object::Instance(_) = v { // Issue #35712 / gh-79893: evaluating `NotImplemented` in a // boolean context is a TypeError since 3.14 (a @@ -44876,12 +52587,43 @@ impl Interpreter { "NotImplemented should not be used in a boolean context", )); } + // A plain instance's Python `__bool__` (remembered on its + // class) that evaluates as a pure leaf and answers a bool: + // evaluated in place, with no bound method made (`any(objs)`, + // `filter(None, objs)`). Any other answer, or none, leaves the + // protocol below to decide (a leaf has no effects to repeat). + if let Object::Instance(inst) = v { + if inst.native.get().is_none() && inst.cls_raw().native_kind.get() == 0 { + let f = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::BOOL_FN), + "__bool__", + ); + if let Some(f) = f { + if let Some(Object::Bool(b)) = self.call_pure_leaf_with(&f, Some(v), &[]) { + return Ok(b); + } + } + } + } let native = instance_native_dunder(v, "__bool__", None); let method = if native.is_none() { instance_method(v, "__bool__") } else { None }; + // `__bool__ = None` blocks the protocol (CPython's + // `slot_nb_bool` finds no callable). + if let (None, Some(Object::BoundMethod(bm)), Object::Instance(inst)) = + (&native, &method, v) + { + if matches!(bm.function, Object::None) { + return Err(type_error(format!( + "'{}' cannot be interpreted as a boolean", + inst.cls().name + ))); + } + } if native.is_some() || method.is_some() { let r = match (native, method) { (Some(r), _) => r?, @@ -45019,6 +52761,10 @@ impl Interpreter { if let Object::Foreign(s) = other { return self.check_int_result(other, "__int__", crate::foreign::as_int(s)?); } + // (A native `__int__`'s body directly: `int(dec)`.) + if let Some(r) = instance_native_dunder(other, "__int__", None) { + return self.check_int_result(other, "__int__", r?); + } if let Some(method) = instance_method(other, "__int__") { let r = self.call(&method, &[], &[], globals)?; return self.check_int_result(other, "__int__", r); @@ -45147,7 +52893,23 @@ impl Interpreter { // CPython's `PyNumber_Float`: try `__float__` (which must // return a float; a strict subclass is accepted with a // DeprecationWarning), then `__index__` (an int, converted with - // an overflow check). + // an overflow check). A plain Python `__float__` + // (`Fraction`'s) is called with the instance, no bound method + // built for it. + if let Object::Instance(inst) = other { + if let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::FLOAT_FN), + "__float__", + ) { + let r = self.call_dunder_function(f, std::slice::from_ref(other))?; + return self.check_float_result(other, r); + } + } + // (A native `__float__`'s body directly: `float(dec)`.) + if let Some(r) = instance_native_dunder(other, "__float__", None) { + return self.check_float_result(other, r?); + } if let Some(method) = instance_method(other, "__float__") { let r = self.call(&method, &[], &[], globals)?; return self.check_float_result(other, r); @@ -45341,75 +53103,24 @@ impl Interpreter { self.make_iter(v, globals) } - /// `iter(callable, sentinel)` — returns a *lazy* callable-iterator - /// (CPython's `calliterobject`). Each `next()` invokes the callable - /// once and stops when a result equals the sentinel. Driving it - /// lazily (rather than eagerly draining into a list) is required for - /// correctness, not just performance: an exception raised by the - /// callable must surface mid-stream, a `StopIteration` it raises must - /// end iteration, and an unbounded source must not hang at - /// construction. The behaviour lives in the frozen `_CallableIter` - /// helper, driven through the normal `__next__` dispatch. - fn do_iter_callable_sentinel( - &mut self, - args: &[Object], - globals: &Rc>, - ) -> Result { + /// `iter(callable, sentinel)`: a lazy `callable_iterator` (CPython's + /// `calliterobject`), a native adapter that calls `callable` once a + /// step and stops at a result equal to the sentinel (see + /// `Interpreter::calliter_step`). Lazy matters for correctness: an + /// exception the callable raises surfaces mid-stream, a + /// `StopIteration` it raises ends the iteration, and an unbounded + /// source never hangs at construction. + fn do_iter_callable_sentinel(&mut self, args: &[Object]) -> Result { // CPython's `builtin_iter` validates up front: `iter(42, 42)` is a // TypeError at construction, not on first `next()` (test_builtin // test_iter). if !crate::builtins::object_is_callable(&args[0]) { return Err(type_error("iter(v, w): v must be callable")); } - if let Some(it) = self.make_callable_iterator(&args[0], &args[1], globals)? { - return Ok(it); - } - // Fallback (helper module unavailable): eagerly drain. Retains the - // historical behaviour for the common finite-sentinel case. - let callable = args[0].clone(); - let sentinel = args[1].clone(); - let mut out: Vec = Vec::new(); - for _ in 0_i64..i64::MAX { - let v = self.call(&callable, &[], &[], globals)?; - if self.dispatch_compare_op(&v, &sentinel, CompareKind::Eq, globals)? { - break; - } - out.push(v); - } - let list = Object::new_list(out); - self.make_iter(&list, globals) - } - - /// Instantiate the frozen `_CallableIter` for `iter(callable, sentinel)`. - /// Returns `None` if the helper module can't be imported, letting the - /// caller fall back to eager draining. - fn make_callable_iterator( - &mut self, - callable: &Object, - sentinel: &Object, - globals: &Rc>, - ) -> Result, RuntimeError> { - let module = match self.do_import("_seqtools", &Object::None, 0, globals) { - Ok(m) => m, - Err(_) => return Ok(None), - }; - let cls = match &module { - Object::Module(m) => m - .dict - .borrow() - .get(&DictKey(Object::from_static("_CallableIter"))) - .cloned(), - _ => None, - }; - match cls { - Some(cls) => Ok(Some(self.call( - &cls, - &[callable.clone(), sentinel.clone()], - &[], - globals, - )?)), - None => Ok(None), - } + Ok(crate::seqiter::callable_iter( + args[0].clone(), + args[1].clone(), + )) } /// Resolve `string.templatelib.` for the PEP 750 t-string @@ -45486,7 +53197,7 @@ impl Interpreter { // literal and `b_list` paths, or a cycle closed through the // result (`x = list(...); x[0].back = x`) is never collected. let obj = Object::new_list(collected); - gc_trace::track(&obj); + gc_trace::track_built(&obj); Ok(obj) } else { Ok(Object::new_tuple(collected)) @@ -45558,21 +53269,31 @@ impl Interpreter { let Object::Instance(inst) = v else { return Ok(None); }; + // An exact `OrderedDict` (`dict(od)`): its entries in its own + // order, read with no code run. + if let Some(entries) = crate::stdlib::collections_odict::ordered_entries(v) { + let mut d = + DictData::with_capacity_and_hasher(entries.len(), crate::fasthash::FxBuildHasher); + for (k, val) in entries { + d.insert(DictKey(k), val); + } + return Ok(Some(Object::Dict(Rc::new(RefCell::new(d))))); + } // A subclass of `dict` (`class C(dict)`) wraps a native dict; copy // its entries directly rather than walking keys via subscript — - // but only when the subclass doesn't override the iteration order - // (`keys` / `__iter__`). CPython's `dict_merge` fast path is gated - // the same way after bpo-34320: `dict(OrderedDict(...))` (whose - // `keys` walks the linked list, reflecting `move_to_end`) and a - // subclass with reversed `keys` must go through the mapping - // protocol below (test_dict `test_dict_copy_order`). + // but only when the subclass keeps dict's `__iter__`. CPython's + // `dict_merge` fast path is gated the same way after bpo-34320 + // (`tp_iter == dict_iter`, its own `keys` and `__getitem__` + // unread): `dict(OrderedDict(...))` (whose iteration walks the + // linked list, reflecting `move_to_end`) and a subclass with a + // reversed `__iter__` go through the mapping protocol below + // (test_dict `test_dict_copy_order`). if let Some(Object::Dict(inner)) = inst.native.get() { let overrides_order = inst.cls().mro.borrow().iter().any(|t| { !t.flags.is_builtin - && (t.dict.borrow().contains_key(&crate::object::StrKey("keys")) - || t.dict - .borrow() - .contains_key(&crate::object::StrKey("__iter__"))) + && t.dict + .borrow() + .contains_key(&crate::object::StrKey("__iter__")) }); if !overrides_order { return Ok(Some(Object::Dict(Rc::new(RefCell::new( @@ -45580,6 +53301,11 @@ impl Interpreter { ))))); } } + // A mapping that only wraps one dict: a copy of that dict. + if let Some(d) = self.thin_mapping_dict(v, true) { + let copy = d.borrow().clone(); + return Ok(Some(Object::Dict(Rc::new(RefCell::new(copy))))); + } // Prefer the instance's own `keys` (rare), then walk the MRO. // `inst.cls().lookup` already handles inheritance, which is // how `_MappingMixin` subclasses (defaultdict, Counter, …) @@ -45605,12 +53331,13 @@ impl Interpreter { .unwrap_or_else(|_| self.maybe_bind(v, keys_fn)); let keys = self.call(&bound, &[], &[], globals)?; let mut d = DictData::default(); - let it = self.make_iter(&keys, globals)?; - while let Some(k) = self.iter_next(&it, globals)? { + for k in self.listed_keys(&keys, globals)? { // Use `__getitem__` if it's defined (the typical case for // user mappings); fall back to native subscript for the // few built-in iterables that might land here. - let val = if let Some(getitem) = instance_method(v, "__getitem__") { + let val = if let Some(val) = self.mapping_value_fn(v, &k) { + val? + } else if let Some(getitem) = instance_method(v, "__getitem__") { self.call(&getitem, std::slice::from_ref(&k), &[], globals)? } else { self.binary_subscr(v, &k)? @@ -45621,6 +53348,243 @@ impl Interpreter { Ok(Some(Object::Dict(Rc::new(RefCell::new(d))))) } + /// `collections.abc.Mapping.keys`, while it is the stdlib's own + /// (`return KeysView(self)`, over a `KeysView` whose `__iter__` is the + /// stdlib's `yield from self._mapping`): what iterating `m.keys()` + /// gives is then what iterating `m` gives. Verified by the two + /// functions' code (their names and file) when first asked and after + /// either class changes; `None` when `_collections_abc` isn't the + /// stdlib's or isn't imported. + fn abc_keys_fn( + &mut self, + globals: &Rc>, + ) -> Option> { + if let Some(c) = &*self.abc_keys.borrow() { + if (c.mapping.attr_version.get(), c.view.attr_version.get()) == c.versions + && c.others.iter().all(|(t, ver)| t.attr_version.get() == *ver) + { + return Some(c.keys.clone()); + } + } + *self.abc_keys.borrow_mut() = None; + let module = self + .do_import("_collections_abc", &Object::None, 0, globals) + .ok()?; + let Object::Module(m) = &module else { + return None; + }; + let class = |name: &'static str| match m.dict.borrow().get(&crate::object::StrKey(name)) { + Some(Object::Type(t)) => Some(t.clone()), + _ => None, + }; + let (mapping, view) = (class("Mapping")?, class("KeysView")?); + let own = |t: &Rc, name: &'static str, qualname: &str| { + let Some(Object::Function(f)) = + t.dict.borrow().get(&crate::object::StrKey(name)).cloned() + else { + return None; + }; + let code = f.code(); + (&*code.qualname == qualname && code.filename.ends_with("_collections_abc.py")) + .then_some(f) + }; + let keys = own(&mapping, "keys", "Mapping.keys")?; + own(&view, "__iter__", "KeysView.__iter__")?; + let (values, items) = (class("ValuesView")?, class("ItemsView")?); + own(&values, "__iter__", "ValuesView.__iter__")?; + own(&items, "__iter__", "ItemsView.__iter__")?; + let versions = (mapping.attr_version.get(), view.attr_version.get()); + let others = [values, items].map(|t| { + let ver = t.attr_version.get(); + (t, ver) + }); + if versions.0 == 0 || versions.1 == 0 || others.iter().any(|(_, ver)| *ver == 0) { + return None; + } + *self.abc_keys.borrow_mut() = Some(AbcKeys { + keys: keys.clone(), + mapping, + view, + versions, + others, + }); + Some(keys) + } + + /// The dict a plain mapping instance only wraps: its class's `__iter__` + /// is a pure leaf answering a fresh key iterator of an exact dict + /// (`return iter(self._d)`), and its `__getitem__` only delegates to + /// that same dict (`return self._d[key]`, see + /// [`Self::delegate_item`]; or it is `collections.UserDict`'s own, + /// over `self.data`). Walking such a mapping by the mapping + /// protocol reads exactly that dict's entries, in its order, and runs + /// nothing that could raise or be seen. With `via_keys` (a walk that + /// starts at `m.keys()`: `dict(m)`, `**m`), its class must also take + /// `keys` from `collections.abc.Mapping` unchanged (a view whose + /// iterator only delegates to `iter(m)`, see [`Self::abc_keys_fn`]), + /// the instance having none of its own. `None`, nothing observable + /// done, for any other object, or under an observer. + fn thin_mapping_dict(&mut self, v: &Object, via_keys: bool) -> Option>> { + use crate::types::{vm_key, AttrKey}; + let Object::Instance(inst) = v else { + return None; + }; + let cls = inst.cls_raw(); + let ver = cls.attr_version.get(); + if inst.native.get().is_some() + || cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || ver == 0 + || crate::trace::any_observers_active() + { + return None; + } + if via_keys { + let globals = self.builtins.clone(); + let abc = self.abc_keys_fn(&globals)?; + let at = (std::ptr::from_ref(cls) as usize, ver); + if self.abc_keys_class.get() != at { + if !matches!(cls.lookup("keys"), Some(Object::Function(f)) if Rc::ptr_eq(&f, &abc)) + { + return None; + } + self.abc_keys_class.set(at); + } + // (An instance's own `keys` shadows the class's.) + if inst.attr_get_str("keys").is_some() { + return None; + } + } + let getitem = + Self::instance_dunder_function(inst, AttrKey::vm(vm_key::GETITEM_FN), "__getitem__")?; + // (Only the body's shape is asked: it isn't run, so it needn't + // have warmed, as a mapping only ever listed never warms it.) + let code = getitem.code(); + if code.arg_count != 2 { + return None; + } + let field = match Self::delegate_field(&code, v, inst) { + Some(field) => field, + // `collections.UserDict.__getitem__`: `self.data[key]` for a + // key `self.data` holds (the only keys a walk of `iter(self)` + // asks for, `self.data` being the dict it walks), `data` read + // as a plain instance attribute. + None if &*code.qualname == "UserDict.__getitem__" + && code.filename.ends_with("collections/__init__.py") + && cls.lookup("data").is_none() => + { + inst.attr_get_str("data")? + } + None => return None, + }; + let Object::Dict(d) = field else { + return None; + }; + let iter = Self::iter_dunder(v)?; + let Object::Iter(it) = self.call_pure_leaf_with(&iter, Some(v), &[])? else { + return None; + }; + let same = matches!(&*it.try_borrow().ok()?, + crate::object::PyIterator::DictKeys { + kind: crate::object::DictViewKind::Keys, + index: 0, + dict: Some(walked), + reverse: false, + odict: None, + .. + } if Rc::ptr_eq(walked, &d)); + same.then_some(d) + } + + /// The items a consumer that takes all of them (`list`, `sorted`, + /// `set`, a `join`) gets from `v`, a `collections.abc` `KeysView`, + /// `ValuesView` or `ItemsView` of the stdlib's own class over a + /// mapping that only wraps one dict (see + /// [`Self::thin_mapping_dict`]): what the view's `__iter__` generator + /// yields is that dict's keys, values or pairs, in its order, with + /// nothing to run. `None`, nothing done, for anything else. + fn collect_mapping_view(&mut self, v: &Object) -> Option> { + let Object::Instance(inst) = v else { + return None; + }; + if inst.native.get().is_some() || crate::trace::any_observers_active() { + return None; + } + let globals = self.builtins.clone(); + self.abc_keys_fn(&globals)?; + let cls = inst.cls_raw(); + let kind = match &*self.abc_keys.borrow() { + Some(c) if std::ptr::eq(cls, Rc::as_ptr(&c.view)) => 0, + Some(c) if std::ptr::eq(cls, Rc::as_ptr(&c.others[0].0)) => 1, + Some(c) if std::ptr::eq(cls, Rc::as_ptr(&c.others[1].0)) => 2, + _ => return None, + }; + let mapping = inst + .slot_get("_mapping") + .filter(|m| !matches!(m, Object::Unbound))?; + let d = self.thin_mapping_dict(&mapping, false)?; + let d = d.try_borrow().ok()?; + Some(match kind { + 0 => d.keys().map(|k| k.0.clone()).collect(), + 1 => d.values().cloned().collect(), + _ => d + .iter() + .map(|(k, v)| Object::new_tuple_array([k.0.clone(), v.clone()])) + .collect(), + }) + } + + /// `v[k]` for a walk of the mapping protocol (`dict(m)`, `{**m}`) by + /// an instance's Python `__getitem__`, with no bound method made (a + /// body that only delegates, with no call). `None` for an object + /// without one. + fn mapping_value_fn(&mut self, v: &Object, k: &Object) -> Option> { + use crate::types::{vm_key, AttrKey}; + let Object::Instance(inst) = v else { + return None; + }; + // (An observer follows the call the general walk makes.) + if inst.native.get().is_some() || crate::trace::any_observers_active() { + return None; + } + let f = + Self::instance_dunder_function(inst, AttrKey::vm(vm_key::GETITEM_FN), "__getitem__")?; + if let Some(val) = Self::delegate_subscr(&f, v, k) { + return Some(Ok(val)); + } + Some(self.call_dunder_function(f, &[v.clone(), k.clone()])) + } + + /// [`Self::mapping_value_fn`], anything else as + /// [`Self::subscr_via_protocol`] reads it. + fn mapping_value( + &mut self, + v: &Object, + k: &Object, + globals: &Rc>, + ) -> Result { + match self.mapping_value_fn(v, k) { + Some(r) => r, + None => self.subscr_via_protocol(v, k, globals), + } + } + + /// Every item of `keys`'s iterator, listed before any value is read: + /// CPython's `PyMapping_Keys` lists a mapping's keys first, and + /// nothing asks the mapping (or the view) its length. + fn listed_keys( + &mut self, + keys: &Object, + globals: &Rc>, + ) -> Result, RuntimeError> { + let it = self.make_iter(keys, globals)?; + let mut out = Vec::new(); + while let Some(k) = self.iter_next(&it, globals)? { + out.push(k); + } + Ok(out) + } + pub(crate) fn collect_iterable( &mut self, v: &Object, @@ -45629,11 +53593,165 @@ impl Interpreter { if let Some(items) = crate::object::collect_small_int_range(v) { return items; } + // A `str`'s characters (`list("abc")`, `set(word)`), each made as + // its iterator makes it, with no iterator stepped. + if let Object::Str(s) = v { + return Ok(s.chars().map(Object::from_char).collect()); + } + if let Some(items) = crate::stdlib::struct_mod::array_items(v) { + return Ok(items); + } + if let Some(items) = crate::stdlib::struct_mod::unpack_iter_items(v) { + return Ok(items); + } + // A deque's items (`list(d)`, `sorted(d)`), copied off its backing + // list with no iterator made. + if let Some(items) = crate::stdlib::collections_native::deque_items(v) { + return Ok(items); + } + // A list, tuple or dict subclass's instance that inherits + // `__iter__` (`list(counter)`, `sorted(defaultdict)`): its + // payload's items, as iterating it yields them. + if let Object::Instance(inst) = v { + if let Some( + native @ (Object::List(_) + | Object::Tuple(_) + | Object::Dict(_) + | Object::Set(_) + | Object::FrozenSet(_)), + ) = inst.native.get() + { + let cls = inst.cls_raw(); + if cls.native_kind.get() == 0 + && cls.c_ext_ptr.get() == 0 + && cls.dunder(crate::types::Dunder::Iter).builtin_owner() + { + let native = native.clone(); + return self.collect_iterable(&native, globals); + } + } + } + if let Object::Type(t) = v { + if let Some(items) = Self::enum_members(t) { + return Ok(items); + } + } + if let Object::LazyIter(l) = v { + if let Some(items) = crate::seqiter::islice_collect(l) { + return Ok(items); + } + if let Some(items) = crate::seqiter::accumulate_collect(l) { + return Ok(items); + } + if let Some(items) = crate::seqiter::machine_collect(l) { + return Ok(items); + } + if let Some(items) = crate::seqiter::window_collect(l) { + return Ok(items); + } + } + if let Some(items) = crate::seqiter::enumerate_seq_collect(v) { + return Ok(items); + } + // `list(reversed(xs))`: the rest of the reversed list at once, + // the iterator left exhausted and detached as its last step leaves + // it (what that releases drops once the iterator is free again). + if let Object::Iter(it) = v { + if let Ok(mut cursor) = it.try_borrow_mut() { + // A list's or tuple's iterator: the rest at once (cloning + // items runs no code), then the step that finds the end, so + // the iterator records its exhaustion as stepping it would. + let rest = match &mut *cursor { + crate::object::PyIterator::List { items, index, .. } => items + .try_borrow() + .ok() + .map(|xs| xs.get(*index..).map_or_else(Vec::new, <[Object]>::to_vec)) + .inspect(|r| *index += r.len()), + crate::object::PyIterator::Tuple { items, index } => { + let r = items + .get(*index..) + .map_or_else(Vec::new, <[Object]>::to_vec); + *index += r.len(); + Some(r) + } + // A range's iterator (`list(reversed(range(n)))`): the + // rest of its ints at once, presized, the iterator moved + // to where its steps would leave it. + crate::object::PyIterator::Range { + current, + stop, + step, + } if *step != 0 => { + let (c, s, st) = + (i128::from(*current), i128::from(*stop), i128::from(*step)); + let len = if st > 0 && c < s { + (s - c - 1) / st + 1 + } else if st < 0 && c > s { + (c - s - 1) / -st + 1 + } else { + 0 + }; + let end = c + len * st; + match (usize::try_from(len), i64::try_from(end)) { + (Ok(n), Ok(end)) if n <= 1 << 24 => { + let out: Vec = (0..n as i128) + .map(|k| Object::Int((c + k * st) as i64)) + .collect(); + *current = end; + Some(out) + } + _ => None, + } + } + _ => None, + }; + if let Some(rest) = rest { + let end = cursor.next_value(); + drop(cursor); + debug_assert!(end.is_none()); + drop(end); + return Ok(rest); + } + if let crate::object::PyIterator::Reversed { + items, + index, + owner, + } = &mut *cursor + { + let out: Vec = { + let v = items.borrow(); + match usize::try_from(*index) { + Ok(i) if i < v.len() => v[..=i].iter().rev().cloned().collect(), + _ => Vec::new(), + } + }; + let detached = ( + std::mem::replace(items, crate::object::detached_store()), + owner.take(), + ); + *index = -1; + drop(cursor); + drop(detached); + return Ok(out); + } + } + } match v { - Object::List(items) => Ok(items.borrow().clone()), - Object::Tuple(items) => Ok(items.to_vec()), + Object::List(items) => Ok(crate::object::cloned_vec(&items.borrow())), + Object::Tuple(items) => Ok(crate::object::cloned_vec(items)), + // (A byte string's or buffer's bytes, as the ints its iterator + // would give.) + Object::Bytes(b) => Ok(b.iter().map(|&x| Object::Int(i64::from(x))).collect()), + Object::ByteArray(b) => Ok(b + .borrow() + .iter() + .map(|&x| Object::Int(i64::from(x))) + .collect()), Object::Set(s) => Ok(s.borrow().iter().map(|k| k.0.clone()).collect()), Object::FrozenSet(s) => Ok(s.iter().map(|k| k.0.clone()).collect()), + // A dict's keys, as its iterator would give them (cloning them + // runs no code). + Object::Dict(d) => Ok(d.borrow().keys().map(|k| k.0.clone()).collect()), // Draining a view runs no code (the entries' clones and the // pairs' tuples), so the dict can't change under it: its entries // in order, as its iterator would give them. @@ -45656,49 +53774,27 @@ impl Interpreter { // the size, but the *lookup and call* are observable // (test_descr exercises a recording descriptor there), so // run the hook and propagate non-TypeError exceptions. + // A plain instance whose `__iter__` (and `__len__`, if any) + // evaluates as a pure leaf: the length hint ran with no + // effect to observe, and the native iterator it returns + // drains directly. + if let Some(it) = self.leaf_instance_iter(v) { + return self.collect_iterable(&it, globals); + } + // An exact `OrderedDict`'s keys, in order. if let Object::Instance(inst) = v { - let cls = inst.cls(); - if !cls.flags.is_builtin { - let err_is_type_error = |vm: &mut Self, e: &RuntimeError| match e { - RuntimeError::PyException(pe) => vm - .exception_matches( - &pe.instance, - &Object::Type(builtin_types().type_error.clone()), - ) - .unwrap_or(false), - RuntimeError::Internal(_) => false, - }; - // `PyObject_LengthHint` order: `__len__` first; a - // raising `__len__` propagates unless it's a - // TypeError (test_iterlen.test_issue1242657's - // `list(BadLen())` must surface the RuntimeError). - let mut need_hint = cls.lookup("__length_hint__").is_some(); - if cls.lookup("__len__").is_some() { - if let Some(len_m) = instance_method(v, "__len__") { - match self.call(&len_m, &[], &[], globals) { - Ok(_) => need_hint = false, - Err(e) => { - if !err_is_type_error(self, &e) { - return Err(e); - } - } - } - } - } - if need_hint { - if let Some(hint) = instance_method(v, "__length_hint__") { - match self.call(&hint, &[], &[], globals) { - Ok(_) => {} - Err(e) => { - if !err_is_type_error(self, &e) { - return Err(e); - } - } - } - } - } + if let Some(keys) = crate::stdlib::collections_odict::exact_keys(inst) + .or_else(|| crate::stdlib::collections_odict::exact_view_entries(inst)) + { + return Ok(keys); } } + self.probe_length_hint(v, globals)?; + // A `collections.abc` mapping view: what its generator + // would yield, with none made. + if let Some(items) = self.collect_mapping_view(v) { + return Ok(items); + } let it = self.make_iter(v, globals)?; let mut out = Vec::new(); if let Object::Generator(g) = &it { @@ -45719,6 +53815,54 @@ impl Interpreter { } } } + // A deque's iterator: the rest of its items at once. + if let Object::Instance(inst) = &it { + if let Some(items) = crate::stdlib::collections_native::deque_iter_rest(inst) { + out.extend(items); + return Ok(out); + } + } + // A native `__next__` with a fast half (`struct.iter_unpack`'s + // iterator, an array's): its steps in a row, the half found + // once (it runs no code, so the class stays as it was); a + // declined step goes on through the general loop. + if let Object::Instance(inst) = &it { + if !crate::gil::free_threading_enabled() + && !crate::trace::any_observers_active() + { + if let Some(fast) = self.core_leaf_next_fast(inst) { + loop { + match fast(std::slice::from_ref(&it)) { + Some(Ok(x)) => out.push(x), + Some(Err(e)) if crate::seqiter::is_stop_iteration(&e) => { + return Ok(out); + } + Some(Err(e)) => return Err(e), + None => break, + } + } + } + } + } + // A native iterator (an `__iter__` returning `iter(range(n))` + // or a list's): its steps run no code, so one borrow for the + // whole drain, as below for other objects. + if let Object::Iter(cell) = &it { + let mut cur = cell.borrow_mut(); + if let Some(n) = cur.remaining() { + out.reserve(n.min(1 << 16)); + } + // (A plain cursor's items as compiled loops step them; + // its end, and any other iterator, checked.) + while let Some(x) = cur.pure_peek() { + cur.pure_skip(); + out.push(x); + } + while let Some(x) = cur.next_value_checked()? { + out.push(x); + } + return Ok(out); + } while let Some(x) = self.iter_next(&it, globals)? { out.push(x); } @@ -45727,13 +53871,25 @@ impl Interpreter { Object::LazyIter(l) => { let mut out = Vec::new(); if !self.seq_drain(l, &mut out, globals)? { + // (A declined pure step consumes nothing; after four in + // a row, a source that never steps purely, a generator + // say, the general step alone.) + let mut declines = if crate::seqiter::lazy_has_generator_source(l) { + 4 + } else { + 0u8 + }; loop { - if let Some(r) = self.lazy_core_next(l) { - match r { - Some(x) => out.push(x), - None => break, + if declines < 4 { + if let Some(r) = self.lazy_core_next(l) { + declines = 0; + match r { + Some(x) => out.push(x), + None => break, + } + continue; } - continue; + declines += 1; } match self.lazy_iter_next(l, globals)? { Some(x) => out.push(x), @@ -45765,7 +53921,374 @@ impl Interpreter { } } - /// Pull at most `n + 1` items from `v` for `UNPACK_SEQUENCE`. CPython's + /// `cls[name]` for an enum class whose metaclass keeps `enum`'s own + /// `EnumType.__getitem__` (`return cls._member_map_[name]`): the member, + /// read from the map with no code run. `None` for a miss (the method + /// raises its `KeyError`), a key that hashes in Python, or while a + /// tracer would see the method. + pub(crate) fn enum_getitem(cls: &Rc, key: &Object) -> Option { + // The class's verdict and map, by its version and its metaclass's + // (a class or metaclass change moves one of them). + type Memo = Option<(usize, u64, u64, crate::sync::Weak>)>; + thread_local! { + static MEMO: std::cell::RefCell = const { std::cell::RefCell::new(None) }; + } + if crate::trace::any_observers_active() { + return None; + } + let probe = crate::object::LeafProbe::new(key)?; + let id = Rc::as_ptr(cls) as usize; + let ver = cls.attr_version.get(); + let hit = MEMO.with(|m| { + let m = m.try_borrow().ok()?; + match &*m { + Some((i, v, mv, map)) if *i == id && *v == ver => Some((*mv, map.upgrade()?)), + _ => None, + } + }); + let map = match hit { + Some((mv, map)) if mv == cls.metaclass_or_type().attr_version.get() => map, + _ => { + if cls.metaclass_is_type() { + return None; + } + let meta = cls.metaclass_or_type(); + let Some(Object::Function(f)) = meta.lookup("__getitem__") else { + return None; + }; + if !Self::stdlib_fn_is(&f, "enum", "EnumType.__getitem__") { + return None; + } + let Some(Object::Dict(map)) = cls.lookup("_member_map_") else { + return None; + }; + let mv = meta.attr_version.get(); + MEMO.with(|m| { + if let Ok(mut m) = m.try_borrow_mut() { + *m = Some((id, ver, mv, Rc::downgrade(&map))); + } + }); + map + } + }; + let m = map.try_borrow().ok()?; + m.get(&probe).cloned() + } + + /// `value in cls` for an enum class whose metaclass keeps `enum`'s own + /// `EnumType.__contains__`, answered as it answers with no code run: a + /// member of the class, else a scan of its unhashable and hashable + /// value lists. `None` for a `Flag` class (its `_missing_` runs), a + /// comparison that could run Python, or while a tracer would see the + /// method. + fn enum_contains(cls: &Rc, item: &Object) -> Option { + // The class's verdict and value lists, by its version and its + // metaclass's (see `enum_getitem`). + type Lists = [crate::sync::Weak>>; 2]; + type Memo = Option<(usize, u64, u64, Lists)>; + thread_local! { + static MEMO: std::cell::RefCell = const { std::cell::RefCell::new(None) }; + } + if crate::trace::any_observers_active() { + return None; + } + let id = Rc::as_ptr(cls) as usize; + let ver = cls.attr_version.get(); + let hit = MEMO.with(|m| { + let m = m.try_borrow().ok()?; + match &*m { + Some((i, v, mv, [a, b])) if *i == id && *v == ver => { + Some((*mv, [a.upgrade()?, b.upgrade()?])) + } + _ => None, + } + }); + let lists = match hit { + Some((mv, lists)) if mv == cls.metaclass_or_type().attr_version.get() => lists, + _ => { + let meta = cls.metaclass_or_type(); + let Some(Object::Function(f)) = meta.lookup("__contains__") else { + return None; + }; + if !Self::stdlib_fn_is(&f, "enum", "EnumType.__contains__") { + return None; + } + let flag = f + .globals + .try_borrow() + .ok()? + .get(&crate::object::StrKey("Flag")) + .cloned(); + match flag { + Some(Object::Type(flag)) if !cls.is_subclass_of(&flag) => {} + _ => return None, + } + let (Some(Object::List(a)), Some(Object::List(b))) = ( + cls.lookup("_unhashable_values_"), + cls.lookup("_hashable_values_"), + ) else { + return None; + }; + let mv = meta.attr_version.get(); + MEMO.with(|m| { + if let Ok(mut m) = m.try_borrow_mut() { + *m = Some((id, ver, mv, [Rc::downgrade(&a), Rc::downgrade(&b)])); + } + }); + [a, b] + } + }; + match Self::core_isinstance(&[item.clone(), Object::Type(cls.clone())])? { + Ok(Object::Bool(true)) => return Some(true), + Ok(Object::Bool(false)) => {} + _ => return None, + } + for values in &lists { + let values = values.try_borrow().ok()?; + for v in values.iter() { + if Self::leaf_contains_eq(v, item)? { + return Some(true); + } + } + } + Some(false) + } + + /// Whether `f` is the function `qualname` of the frozen stdlib module + /// `module` (its globals' `__name__`). + fn stdlib_fn_is(f: &crate::object::PyFunction, module: &str, qualname: &str) -> bool { + // SAFETY: GIL-serialized raw read of the function's code cell. + let code: &CodeObject = unsafe { &*f.code.as_ptr() }; + code.qualname == qualname + && f.globals.try_borrow().is_ok_and(|g| { + matches!( + g.get(&crate::object::StrKey("__name__")), + Some(Object::Str(n)) if &**n == module + ) + }) + } + + /// `os.fspath(p)` of a `pathlib` path whose class keeps `pathlib`'s own + /// `__fspath__` (`f`) and `__str__`, once its string is cached in the + /// `_str` slot: that string, as those two methods return it. `None` + /// for anything else, or while a tracer or profiler would see them. + /// [`Self::pathlib_cached_str`] of an instance, its class's + /// `__fspath__` looked up first. + pub(crate) fn pathlib_fspath(inst: &PyInstance) -> Option { + match inst.cls_raw().lookup("__fspath__") { + Some(Object::Function(f)) => Self::pathlib_cached_str(inst, &f), + _ => None, + } + } + + fn pathlib_cached_str(inst: &PyInstance, f: &crate::object::PyFunction) -> Option { + if crate::trace::any_observers_active() + || !Self::stdlib_fn_is(f, "pathlib", "PurePath.__fspath__") + { + return None; + } + match inst.cls_raw().lookup("__str__") { + Some(Object::Function(g)) if Self::stdlib_fn_is(&g, "pathlib", "PurePath.__str__") => {} + _ => return None, + } + match inst.slots.try_borrow().ok()?.get("_str") { + Some(s @ Object::Str(_)) => Some(s.clone()), + _ => None, + } + } + + /// The members of an enum class whose metaclass iterates it with + /// `enum`'s own `EnumType.__iter__` (`list(Color)`): its + /// `_member_map_` entries in `_member_names_` order, as that + /// generator yields them, read with no code run. `None` for anything + /// else (a name the map lacks, whose `KeyError` the generator + /// raises), or while a tracer or profiler would see the generator. + fn enum_members(cls: &Rc) -> Option> { + let (map, names) = Self::enum_tables(cls)?; + let (map, names) = (map.try_borrow().ok()?, names.try_borrow().ok()?); + names + .iter() + .map(|n| match n { + Object::Str(_) => map.get(&DictKey(n.clone())).cloned(), + _ => None, + }) + .collect() + } + + /// `iter(SomeEnum)` for a compiled loop's `GET_ITER`, where the + /// iterator is never seen: `map(cls._member_map_.__getitem__, + /// cls._member_names_)`, which yields what `EnumType.__iter__`'s + /// generator does, read as lazily from the same live tables, without + /// the call and the generator's resumes. `None` as for + /// [`Self::enum_members`]. + #[cfg(feature = "jit")] + pub(crate) fn enum_iter_lazy(cls: &Rc) -> Option { + let (map, names) = Self::enum_tables(cls)?; + let map = Object::Dict(map); + let getitem @ Object::Builtin(_) = crate::builtins::lookup_method(&map, "__getitem__")? + else { + return None; + }; + let func = Object::BoundMethod(Rc::new(BoundMethod::new(map, getitem))); + let names = Object::List(names).make_iter().ok()?; + Some(crate::seqiter::lazy_map1( + func, + Object::Iter(Rc::new(RefCell::new(names))), + )) + } + + /// The `_member_map_` dict and `_member_names_` list of an enum class + /// whose metaclass iterates it with `enum`'s own `EnumType.__iter__`, + /// unless a tracer or profiler would see that generator. + fn enum_tables( + cls: &Rc, + ) -> Option<(Rc>, Rc>>)> { + if cls.metaclass_is_type() || crate::trace::any_observers_active() { + return None; + } + let meta = cls.metaclass_or_type(); + let Some(Object::Function(f)) = meta.lookup("__iter__") else { + return None; + }; + // SAFETY: GIL-serialized raw read of the function's code cell. + let code: &CodeObject = unsafe { &*f.code.as_ptr() }; + if code.qualname != "EnumType.__iter__" + || !f.globals.try_borrow().is_ok_and(|g| { + matches!( + g.get(&crate::object::StrKey("__name__")), + Some(Object::Str(n)) if &**n == "enum" + ) + }) + { + return None; + } + let (Some(Object::Dict(map)), Some(Object::List(names))) = + (cls.lookup("_member_map_"), cls.lookup("_member_names_")) + else { + return None; + }; + Some((map, names)) + } + + /// CPython's `PyObject_LengthHint` probe of a plain instance before a + /// container is built or extended from it: `__len__` first, then the + /// `__length_hint__` special lookup, their call observable (and an + /// error other than `TypeError` raised from it), the size unused. + fn probe_length_hint( + &mut self, + v: &Object, + globals: &Rc>, + ) -> Result<(), RuntimeError> { + if let Object::Instance(inst) = v { + let cls = inst.cls(); + if !cls.flags.is_builtin { + let err_is_type_error = |vm: &mut Self, e: &RuntimeError| match e { + RuntimeError::PyException(pe) => vm + .exception_matches( + &pe.instance, + &Object::Type(builtin_types().type_error.clone()), + ) + .unwrap_or(false), + RuntimeError::Internal(_) => false, + }; + // `PyObject_LengthHint` order: `__len__` first; a + // raising `__len__` propagates unless it's a + // TypeError (test_iterlen.test_issue1242657's + // `list(BadLen())` must surface the RuntimeError). + // (Each absence remembered per class version.) + let mut need_hint = !Self::class_lacks( + &cls, + crate::types::AttrKey::vm(crate::types::vm_key::LENGTH_HINT_ABSENT), + "__length_hint__", + ); + if !Self::class_lacks( + &cls, + crate::types::AttrKey::vm(crate::types::vm_key::LEN_ABSENT), + "__len__", + ) { + if let Some(len_m) = instance_method(v, "__len__") { + match self.call(&len_m, &[], &[], globals) { + Ok(_) => need_hint = false, + Err(e) => { + if !err_is_type_error(self, &e) { + return Err(e); + } + } + } + } + } + if need_hint { + if let Some(hint) = instance_method(v, "__length_hint__") { + match self.call(&hint, &[], &[], globals) { + Ok(_) => {} + Err(e) => { + if !err_is_type_error(self, &e) { + return Err(e); + } + } + } + } + } + } + } + Ok(()) + } + + /// Whether `b` is the exact `list`'s or `set`'s own method of its name + /// (`recv` one of them), not another type's body of the same name + /// called on it. + fn is_container_method(b: &Rc, recv: &Object) -> bool { + matches!(recv, Object::List(_) | Object::Set(_)) + && matches!( + crate::builtins::lookup_method(recv, b.name), + Some(Object::Builtin(m)) if Rc::ptr_eq(&m, b) + ) + } + + /// `recv.extend(src)` (a list) or `recv.update(src)` (a set) over an + /// iterable the interpreter steps: each item added as it comes, so the + /// items before an error stay added and the source sees the receiver + /// grow, as in CPython. + fn extend_live( + &mut self, + recv: &Object, + src: &Object, + globals: &Rc>, + ) -> Result { + // (`list.extend` asks the source's length first, as CPython's + // `list_extend` does; `set.update` doesn't.) + if matches!(recv, Object::List(_)) { + self.probe_length_hint(src, globals)?; + } + let it = self.make_iter(src, globals)?; + // A generator's yields go straight into the receiver from its lean + // resume (each as it's yielded, with no code run in between), what + // the sink can't take coming back here. + let sink = match (recv, &it) { + (Object::List(l), Object::Generator(_)) => Some(FoldSink::Collect(l.as_ptr())), + (Object::Set(s), Object::Generator(_)) if !crate::builtins::set_ops_deferred() => { + Some(FoldSink::AddTo(Rc::as_ptr(s))) + } + _ => None, + }; + loop { + let x = match &it { + Object::Generator(g) => self.gen_drain_next(g, sink, false)?, + _ => self.iter_next(&it, globals)?, + }; + let Some(x) = x else { + return Ok(Object::None); + }; + match recv { + Object::List(l) => l.borrow_mut().push(x), + _ => { + crate::builtins::set_add(&[recv.clone(), x])?; + } + } + } + } + + /// Pull at most `n + 1` items from `v` for `UNPACK_SEQUENCE`. /// Pull at most `n + 1` items from `v` for `UNPACK_SEQUENCE`. CPython's /// `unpack_iterable` walks the iterator protocol directly (no `__len__` /// or `__length_hint__` probe) and stops at the first surplus item, so /// a too-long iterator keeps its remaining items and an unbounded @@ -45810,6 +54333,9 @@ impl Interpreter { .cloned(), _ => None, }; + if let (Some(Object::Type(t)), "_ReversedIter") = (&cls, class_name) { + note_seqiter_class(t, true); + } match cls { Some(cls) => Ok(Some(self.call(&cls, args, kwargs, globals)?)), None => Ok(None), @@ -45877,6 +54403,47 @@ impl Interpreter { if let Some(total) = builtins::sum_exact_int_range(&args[0], &acc) { return Ok(total); } + // An `array.array`, a deque, or a list, tuple or set subclass's + // instance that inherits `__iter__`: its items, which collect with + // no code run, summed as a list's while they are plain numbers + // (anything else is the loop's below, over the live iterable). + if let Object::Instance(inst) = &args[0] { + // An array of machine ints, added off its buffer. + if let Some(total) = crate::stdlib::struct_mod::array_int_sum(&args[0], &acc) { + return Ok(total); + } + let items = crate::stdlib::struct_mod::array_items(&args[0]) + .or_else(|| crate::stdlib::collections_native::deque_items(&args[0])) + .or_else(|| { + let native = inst.native.get()?; + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || !cls.dunder(crate::types::Dunder::Iter).builtin_owner() + { + return None; + } + match native { + Object::List(l) => Some(l.try_borrow().ok()?.clone()), + Object::Tuple(t) => Some(t.to_vec()), + // SAFETY: a read that runs no code, ending with the + // copy. + Object::Set(s) => { + Some(unsafe { s.peek() }?.iter().map(|k| k.0.clone()).collect()) + } + _ => None, + } + }); + if let Some(items) = items { + let items = Object::new_list(items); + if let Some(total) = builtins::sum_small_int_sequence(&items, &acc) { + return Ok(total); + } + if let Some(total) = builtins::sum_numeric_sequence(&items, &acc) { + return total; + } + } + } // Accumulate through the interpreter's binary dispatch so reflected // operands fire: `sum([Fraction(3,5), Fraction(4,5)])` starts at the // int `0`, and `int.__add__(0, Fraction)` returns NotImplemented — @@ -45906,6 +54473,22 @@ impl Interpreter { } return Ok(total.finish()); } + // A native adapter (`sum(map(f, xs, ys))`): each step that runs no + // code taken straight, the rest through the adapter's full step. + if let Object::LazyIter(l) = &iter { + loop { + let x = match self.lazy_core_next(l) { + Some(Some(x)) => x, + Some(None) => break, + None => match self.lazy_iter_next(l, globals)? { + Some(x) => x, + None => break, + }, + }; + total.add(self, x)?; + } + return Ok(total.finish()); + } // Stream the live iterator. Addition can mutate the source or // raise, so don't consume later elements or request a length hint. while let Some(x) = self.iter_next(&iter, globals)? { @@ -45958,7 +54541,65 @@ impl Interpreter { return default .ok_or_else(|| value_error(format!("{name}() iterable argument is empty"))); } - let key_of = |slf: &mut Self, item: &Object| -> Result { + // A leaf builtin key (`key=abs`, `key=len`): its body called + // directly, as a call site runs it (the general call otherwise). + let leaf = match &key_fn { + Some(Object::Builtin(b)) if !b.binds_instance => { + self.leaf_call_kind(b).map(|k| (b.clone(), k)) + } + _ => None, + }; + // A key that runs no code (`attrgetter("x")`, `itemgetter(1)`, a + // pure-leaf function) evaluates in place, as `sort_with_key` + // evaluates one; after one decline the rest take the full call. + let mut pure = key_fn + .as_ref() + .is_some_and(|f| leaf.is_none() && crate::seqiter::pure_callback_maybe(f)); + let call_fast = match &key_fn { + Some(f) if pure => self.instance_call_fast(f), + _ => None, + }; + let mut key_of = |slf: &mut Self, item: &Object| -> Result { + if let (Some(fast), Some(f)) = (call_fast, &key_fn) { + // SAFETY: bitwise views of the live key function and item, + // never dropped (the fast half clones what it keeps). + let views = std::mem::ManuallyDrop::new(unsafe { + [std::ptr::read(f), std::ptr::read(item)] + }); + if let Some(Ok(k)) = fast(&views[..]) { + return Ok(k); + } + } + if pure { + if let Some(f) = &key_fn { + if let Some(k) = slf.pure_callback(f, std::slice::from_ref(item), true) { + return Ok(k); + } + pure = false; + } + } + if let Some((b, kind)) = &leaf { + let arg = std::slice::from_ref(item); + match kind { + LeafKind::Fast(f) => { + if let Some(r) = f(arg) { + return r; + } + } + LeafKind::Opaque => return (b.call)(arg), + LeafKind::Scalar + if matches!(item, Object::Int(_) | Object::Float(_) | Object::Bool(_)) => + { + return (b.call)(arg); + } + // (`key=len` and the other leaf kinds' bodies.) + kind => { + if let Some(r) = slf.leaf_builtin_call(*kind, b, arg) { + return r; + } + } + } + } if let Some(f) = &key_fn { slf.call(f, std::slice::from_ref(item), &[], globals) } else { @@ -45974,10 +54615,28 @@ impl Interpreter { // `__gt__` — `Fraction`, `Decimal`, any rich-comparable type — // drives selection (`test_statistics` `approx_equal`). Strict // comparison keeps the *first* extremum on ties, as CPython does. - let take = if want_max { - self.op_compare(&candidate_key, &best_key, CompareKind::Gt)? - } else { - self.op_compare(&candidate_key, &best_key, CompareKind::Lt)? + let take = match (&candidate_key, &best_key) { + // (Two machine ints compare natively.) + (Object::Int(c), Object::Int(b)) => { + if want_max { + c > b + } else { + c < b + } + } + _ => { + let op = if want_max { + CompareKind::Gt + } else { + CompareKind::Lt + }; + // (Keys that compare without running code, two + // `(len(w), w)` tuples among them, natively.) + match plain_compare(&candidate_key, &best_key, op) { + Some(t) => t, + None => self.op_compare(&candidate_key, &best_key, op)?, + } + } }; if take { best_value = item.clone(); @@ -46017,6 +54676,20 @@ impl Interpreter { } return Ok(Object::Bool(!want_any)); } + // A native adapter's items stepped and tested natively (see + // `lazy_any_all`), the rest through the general loop. + if let Object::LazyIter(l) = &args[0] { + while let Some(r) = self.lazy_any_all(l, want_any) { + match r { + Ok(answer) => return Ok(Object::Bool(answer)), + Err(x) => { + if self.obj_truthy(&x, globals)? == want_any { + return Ok(Object::Bool(want_any)); + } + } + } + } + } let it = self.make_iter(&args[0], globals)?; while let Some(x) = self.iter_next(&it, globals)? { // `PyObject_IsTrue` per element (a foreign multi-element array @@ -46082,6 +54755,16 @@ impl Interpreter { let res = check(&[Object::Type(cls.clone()), obj.clone()])?; return Ok(Object::Bool(res.is_truthy())); } + // A plain function (`typing._ProtocolMeta`'s): called + // with the class first, as its bound method would be, + // without building one. + if let Object::Function(f) = &hook { + let res = self.call_dunder_function( + f.clone(), + &[Object::Type(cls.clone()), obj.clone()], + )?; + return Ok(Object::Bool(res.is_truthy())); + } // `dispatch` (not `new`) so a descriptor-wrapped hook // honours its `__get__`: pandas builds `ABCSeries` etc. // from a metaclass whose `__instancecheck__` is a @@ -46132,6 +54815,16 @@ impl Interpreter { // as `typing` aliases (`typing.List`, `int | typing.List`) and ABC // shims implemented as ordinary instances. if let Object::Instance(inst) = classinfo { + // A plain Python function (found once per class version, the + // `typing` aliases' own): called with the alias, unbound. + if let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::INSTANCECHECK_FN), + "__instancecheck__", + ) { + let res = self.call_dunder_function(f, &[classinfo.clone(), obj.clone()])?; + return Ok(Object::Bool(res.is_truthy())); + } if let Some(hook) = inst.cls().lookup("__instancecheck__") { // `dispatch` so a descriptor `__instancecheck__` honours its // `__get__` (test_descr test_special_method_lookup). @@ -46249,6 +54942,15 @@ impl Interpreter { let res = check(&[Object::Type(info_cls.clone()), cls.clone()])?; return Ok(Object::Bool(res.is_truthy())); } + // A plain function: called with the class first, as + // its bound method would be, without building one. + if let Object::Function(f) = &hook { + let res = self.call_dunder_function( + f.clone(), + &[Object::Type(info_cls.clone()), cls.clone()], + )?; + return Ok(Object::Bool(res.is_truthy())); + } // `dispatch` so a `@classmethod` (pandas' ABC shims) or // other descriptor-wrapped hook honours its `__get__`; // plain functions still take the receiver-prepend path. @@ -46296,6 +54998,15 @@ impl Interpreter { // PEP 3119: a `__subclasscheck__` on `type(classinfo)` overrides the // default (class-like instances such as `typing` aliases / unions). if let Object::Instance(inst) = classinfo { + // (As `__instancecheck__` above.) + if let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::SUBCLASSCHECK_FN), + "__subclasscheck__", + ) { + let res = self.call_dunder_function(f, &[classinfo.clone(), cls.clone()])?; + return Ok(Object::Bool(res.is_truthy())); + } if let Some(hook) = inst.cls().lookup("__subclasscheck__") { // `dispatch` so a descriptor `__subclasscheck__` honours its // `__get__` (test_descr test_special_method_lookup). @@ -46390,7 +55101,7 @@ impl Interpreter { /// Narrow a Python hash-method result without invoking integer /// conversion hooks. CPython preserves any value that fits the hash /// word, hashes larger integers, and reserves -1 for errors. - fn normalize_hash_result(&mut self, result: Object) -> Result { + pub(crate) fn normalize_hash_result(&mut self, result: Object) -> Result { // Exact integers are the common result and have no finalizers or // collector handles. Keep them out of the temporary-object reaper. if let Object::Int(value) = result { @@ -46467,6 +55178,16 @@ impl Interpreter { let fs = Object::new_frozenset_from(members); return self.do_hash_call(&fs, globals); } + // A tuple subclass that keeps `tuple`'s `__hash__` (a named tuple): + // its tuple's hash, with no method looked up. + if let Object::Instance(inst) = obj { + if crate::object::tuple_like_value(inst).is_some() { + if let Some(payload) = inst.native.get() { + let payload = payload.clone(); + return self.do_hash_call(&payload, globals); + } + } + } // A tuple hashes by combining `hash(element)` for each element // (CPython `tuplehash` calls `PyObject_Hash` per lane), so an // unhashable element — `__hash__ = None` (pandas `Index`) or a @@ -46517,6 +55238,9 @@ impl Interpreter { return Ok(Object::Int(h)); } } + if let Some(h) = Self::enum_hash(inst) { + return Ok(Object::Int(h)); + } if let Some(f) = Self::instance_dunder_function( inst, crate::types::AttrKey::vm(crate::types::vm_key::HASH), @@ -46736,7 +55460,8 @@ impl Interpreter { return Ok(args[2].clone()); } } - let value_class = builtin_value_class(&args[0]); + let value_class = + builtin_value_class(&args[0]).or_else(|| function_miss_class(&args[0], &name)); if let Some(c) = &value_class { if c.verdict_cached(crate::types::Verdict::ValueAttrMissing, &name) == Some(true) { return Ok(args[2].clone()); @@ -46797,7 +55522,8 @@ impl Interpreter { return Ok(Object::Bool(false)); } } - let value_class = builtin_value_class(&args[0]); + let value_class = + builtin_value_class(&args[0]).or_else(|| function_miss_class(&args[0], &name)); if let Some(c) = &value_class { if c.verdict_cached(crate::types::Verdict::ValueAttrMissing, &name) == Some(true) { return Ok(Object::Bool(false)); @@ -46823,10 +55549,13 @@ impl Interpreter { /// attribute-lookup failures. fn is_attribute_error(&self, err: &RuntimeError) -> bool { match err { - RuntimeError::PyException(pe) => crate::builtin_types::instance_is_subclass( - &pe.instance, - &builtin_types().attribute_error, - ), + RuntimeError::PyException(pe) => { + let class = &builtin_types().attribute_error; + // (The class itself, the commonest, by identity.) + matches!(&pe.instance, Object::Instance(inst) + if std::ptr::eq(inst.cls_raw(), Rc::as_ptr(class))) + || crate::builtin_types::instance_is_subclass(&pe.instance, class) + } RuntimeError::Internal(_) => false, } } @@ -46868,7 +55597,7 @@ impl Interpreter { .find_map(|(k, v)| (k == "key").then(|| v.clone())); self.sort_with_key(&mut items, key_fn.as_ref(), reverse, globals)?; let obj = Object::new_list(items); - gc_trace::track(&obj); + gc_trace::track_built(&obj); Ok(obj) } @@ -46913,33 +55642,48 @@ impl Interpreter { } /// [`Self::dict_merge_from`]'s plain case: merge `src` into `dst` - /// (distinct dicts) when no key on either side can run Python code to - /// hash or compare (see [`crate::object::dict_key_is_reentrant`]), with - /// the same effects as one insert per key. `false` touches nothing. - fn dict_merge_plain(&self, dst: &Rc>, src: &Rc>) -> bool { - // A destination this large is merged key by key: checking its keys - // could cost more than the merge saves. - const DST_CHECK_CAP: usize = 32; + /// (distinct dicts) while each key settles by native equality (one + /// probe finds its entry or proves no stored key could equal it, see + /// [`crate::object::LeafProbe`]), with the same effects as one insert + /// per key. `false` when a key needs more than that: the keys before it + /// are merged, and merging them again changes nothing (each already + /// holds its value). + pub(crate) fn dict_merge_plain( + dst: &Rc>, + src: &Rc>, + ) -> bool { let (Ok(s), Ok(mut d)) = (src.try_borrow(), dst.try_borrow_mut()) else { return false; }; - if s.keys().any(|k| crate::object::dict_key_is_reentrant(&k.0)) { - return false; - } let was = d.len(); - if was > DST_CHECK_CAP || d.keys().any(|k| crate::object::dict_key_is_reentrant(&k.0)) { - return false; - } - let mut changed = false; + let (mut changed, mut whole) = (false, true); if was == 0 { // The source's table, hashes and all (through `DerefMut`, which - // stamps the dict and tracks a deferred owner). + // stamps the dict and tracks a deferred owner): no key is hashed + // or compared. **d = crate::object::DictMap::clone(&s); } else { - d.reserve(s.len()); for (k, v) in s.iter() { - if let Some(old) = d.insert(k.clone(), v.clone()) { - changed |= !old.is_same(v); + let Some(probe) = crate::object::LeafProbe::new(&k.0) else { + whole = false; + break; + }; + match d.probe_entry(&probe) { + crate::dictmap::ProbeEntry::Occupied(e) => { + let slot = e.into_mut(); + // (Re-storing the identical object is no change.) + if !slot.is_same(v) { + changed = true; + *slot = v.clone(); + } + } + crate::dictmap::ProbeEntry::Vacant(e) => { + if !probe.miss_is_exact() { + whole = false; + break; + } + e.insert(k.clone(), v.clone()); + } } } } @@ -46954,7 +55698,243 @@ impl Interpreter { if added || changed { crate::object::dict_mutation_event(dst); } - true + whole + } + + /// The pairs at the front of the list or tuple `pairs` stored into + /// `dst` under one borrow of each, while each is an exact two-item + /// tuple or list whose key settles natively: how many were stored (the + /// rest are the caller's), with what one insert per pair reports. + fn dict_store_pairs(dst: &Rc>, pairs: &Object) -> usize { + let Ok(mut m) = dst.try_borrow_mut() else { + return 0; + }; + let was = m.len(); + let (stored, changed) = match pairs { + Object::Tuple(t) => crate::builtins::table_store_pairs(&mut m, t), + Object::List(l) => match l.try_borrow() { + Ok(l) => crate::builtins::table_store_pairs(&mut m, &l), + Err(_) => (0, false), + }, + _ => (0, false), + }; + let added = m.len() != was; + drop(m); + if added { + crate::object::dict_watch_bump(dst); + } + if added || changed { + crate::object::dict_mutation_event(dst); + } + stored + } + + /// The dict payload of `v` when it is a `dict` subclass's instance + /// that merges as its payload does: a `defaultdict`, a `Counter` or a + /// plain subclass that keeps dict's `__iter__` (remembered per class + /// version). CPython's `dict_merge` reads any such source straight off + /// its table (`tp_iter == dict_iter`), whatever its own `keys` and + /// `__getitem__`. + pub(crate) fn plain_dict_payload(v: &Object) -> Option<&Rc>> { + let Object::Instance(inst) = v else { + return None; + }; + let Some(Object::Dict(d)) = inst.native.get() else { + return None; + }; + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 { + return None; + } + cls.memo_verdict(crate::types::Verdict::DictPayloadPlain, "", || { + cls.dunder(crate::types::Dunder::Iter).builtin_owner() + }) + .then_some(d) + } + + /// `a + b` or `a * n` where an operand is an instance of a `list` or + /// `tuple` subclass that keeps its base's arithmetic (see + /// [`Self::plain_seq_payload`]) and the other a list, tuple or int + /// that fits: the payloads' concatenation or repetition, a plain list + /// or tuple, as the base's method returns. `None` for anything else + /// (a mismatch raises on the general path). + pub(crate) fn seq_payload_binop( + a: &Object, + b: &Object, + op: BinOpKind, + ) -> Option> { + if !matches!(op, BinOpKind::Add | BinOpKind::Mult) + || !(matches!(a, Object::Instance(_)) || matches!(b, Object::Instance(_))) + { + return None; + } + let part = |o: &Object| match o { + Object::List(_) + | Object::Tuple(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::Int(_) => Some(o.clone()), + _ => Self::plain_seq_payload(o).cloned(), + }; + let (x, y) = (part(a)?, part(b)?); + matches!( + (&x, &y, op), + (Object::List(_), Object::List(_), BinOpKind::Add) + | (Object::Tuple(_), Object::Tuple(_), BinOpKind::Add) + | (Object::Str(_), Object::Str(_), BinOpKind::Add) + | (Object::Bytes(_), Object::Bytes(_), BinOpKind::Add) + | ( + Object::List(_) | Object::Tuple(_) | Object::Str(_) | Object::Bytes(_), + Object::Int(_), + BinOpKind::Mult + ) + | ( + Object::Int(_), + Object::List(_) | Object::Tuple(_) | Object::Str(_) | Object::Bytes(_), + BinOpKind::Mult + ) + ) + .then(|| binary_op(&x, &y, op)) + } + + /// The list or tuple payload of `v` when it is an instance of a + /// `list` or `tuple` subclass that concatenates and repeats as its + /// payload does: the class keeps its base's `__add__`, `__mul__` and + /// `__rmul__` and defines no `__radd__` (remembered per class + /// version). + pub(crate) fn plain_seq_payload(v: &Object) -> Option<&Object> { + let Object::Instance(inst) = v else { + return None; + }; + let payload = inst.native.get()?; + let cls = inst.cls_raw(); + if !matches!( + payload, + Object::List(_) | Object::Tuple(_) | Object::Str(_) | Object::Bytes(_) + ) || cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + { + return None; + } + cls.memo_verdict(crate::types::Verdict::SeqArithPlain, "", || { + let bt = crate::builtin_types::builtin_types(); + let base = match payload { + Object::List(_) => &bt.list_, + Object::Tuple(_) => &bt.tuple_, + Object::Str(_) => &bt.str_, + _ => &bt.bytes_, + }; + ["__add__", "__mul__", "__rmul__"].iter().all(|name| { + matches!((cls.lookup(name), base.lookup(name)), (Some(a), Some(b)) if a.is_same(&b)) + }) && cls.lookup("__radd__").is_none() + }) + .then_some(payload) + } + + /// The list, tuple, `str` or `bytes` payload of `v` when it is an + /// instance of a subclass of one of those that compares as its + /// payload does (a named tuple, a `StrEnum` member): the class keeps + /// its base's six comparison methods (remembered per class version). + pub(crate) fn plain_cmp_payload(v: &Object) -> Option<&Object> { + let Object::Instance(inst) = v else { + return None; + }; + let payload = inst.native.get()?; + let cls = inst.cls_raw(); + if !matches!( + payload, + Object::List(_) | Object::Tuple(_) | Object::Str(_) | Object::Bytes(_) + ) || cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + { + return None; + } + cls.memo_verdict(crate::types::Verdict::SeqComparePlain, "", || { + let bt = crate::builtin_types::builtin_types(); + let base = match payload { + Object::List(_) => &bt.list_, + Object::Tuple(_) => &bt.tuple_, + Object::Str(_) => &bt.str_, + _ => &bt.bytes_, + }; + ["__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"] + .iter() + .all(|name| { + matches!((cls.lookup(name), base.lookup(name)), (Some(a), Some(b)) if a.is_same(&b)) + }) + }) + .then_some(payload) + } + + /// `a OP b` for a list, tuple, `str` or `bytes` subclass's instance + /// that compares as its payload does ([`Self::plain_cmp_payload`]) + /// against another such instance or a plain value of its kind: the + /// payloads, to compare in their place, with the comparison to make of + /// them: the right operand's against the left's, mirrored, when the + /// right operand's class is a proper subclass of the left's, whose + /// reflected method runs first (so the items' own comparisons see the + /// right operand's first). `None` for any other pair. + #[inline] + fn seq_cmp_payloads<'a>( + a: &'a Object, + b: &'a Object, + op: CompareKind, + ) -> Option<(&'a Object, &'a Object, CompareKind)> { + if !matches!(a, Object::Instance(_)) && !matches!(b, Object::Instance(_)) { + return None; + } + let side = |v: &'a Object| match v { + Object::Instance(_) => Self::plain_cmp_payload(v), + Object::List(_) | Object::Tuple(_) | Object::Str(_) | Object::Bytes(_) => Some(v), + _ => None, + }; + let (x, y) = match (a, b) { + // Two instances of one class (a sort's items): one verdict. + (Object::Instance(ia), Object::Instance(ib)) + if std::ptr::eq(ia.cls_raw(), ib.cls_raw()) => + { + (side(a)?, ib.native.get()?) + } + _ => (side(a)?, side(b)?), + }; + if !matches!( + (x, y), + (Object::Tuple(_), Object::Tuple(_)) + | (Object::List(_), Object::List(_)) + | (Object::Str(_), Object::Str(_)) + | (Object::Bytes(_), Object::Bytes(_)) + ) { + return None; + } + let reflected = match (a, b) { + (Object::Instance(ia), Object::Instance(ib)) => { + !std::ptr::eq(ia.cls_raw(), ib.cls_raw()) + && ib.cls_raw().is_subclass_of(ia.cls_raw()) + } + (_, Object::Instance(_)) => true, + _ => false, + }; + Some(if reflected { + (y, x, cmp_swapped(op)) + } else { + (x, y, op) + }) + } + + /// `a OP b` (a comparison) where either is an `int` or `float` + /// subclass's instance whose class keeps its base's methods for `op` + /// (an `IntEnum` member; see [`Self::compare_number_payload`]) and the + /// other such an instance or a plain number: the numbers, to compare + /// in their place. + #[inline] + fn num_cmp_payloads(a: &Object, b: &Object, op: CompareKind) -> Option<(Object, Object)> { + if !matches!(a, Object::Instance(_)) && !matches!(b, Object::Instance(_)) { + return None; + } + Some(( + Self::compare_number_payload(a, op)?, + Self::compare_number_payload(b, op)?, + )) } pub(crate) fn dict_merge_from( @@ -46963,6 +55943,23 @@ impl Interpreter { other: &Object, globals: &Rc>, ) -> Result<(), RuntimeError> { + // A dict subclass's instance that reads as its payload does (a + // `defaultdict`, a `Counter`): merged as that dict. + if let Some(payload) = Self::plain_dict_payload(other) { + let payload = Object::Dict(payload.clone()); + return self.dict_merge_from(dst, &payload, globals); + } + // An exact `OrderedDict`: its entries in its own order, read with + // no code run, merged as a dict holding them. + if let Some(entries) = crate::stdlib::collections_odict::ordered_entries(other) { + let mut ordered = + DictData::with_capacity_and_hasher(entries.len(), crate::fasthash::FxBuildHasher); + for (k, v) in entries { + ordered.insert(DictKey(k), v); + } + let ordered = Object::Dict(Rc::new(RefCell::new(ordered))); + return self.dict_merge_from(dst, &ordered, globals); + } // A plain dict into a plain dict whose keys' hashing and equality // run no Python code: one pass under the borrows, the destination // sized once (cloned outright when empty), instead of a guarded @@ -46970,7 +55967,7 @@ impl Interpreter { if let (Object::Dict(dd), Object::Dict(src)) = (dst, other) { if !Rc::ptr_eq(dd, src) && !crate::capi_watchers::dicts_active() - && self.dict_merge_plain(dd, src) + && Self::dict_merge_plain(dd, src) { return Ok(()); } @@ -47024,13 +56021,58 @@ impl Interpreter { } return Ok(()); } + // Pairs from sources that run no code. An items view of a dict + // merges as that dict does (a partial merge is finished, harmlessly + // again, by the walk below); `zip` of two plain sequences with + // simple keys builds its dict first; a list or tuple of pairs is + // walked in place while each pair is an exact one whose key settles + // natively. + let mut walked = 0; + if let Object::Dict(dd) = dst { + if !crate::capi_watchers::dicts_active() { + match other { + Object::DictView(view) + if matches!(view.kind, crate::object::DictViewKind::Items) => + { + if Rc::ptr_eq(dd, &view.dict) || Self::dict_merge_plain(dd, &view.dict) { + return Ok(()); + } + } + Object::LazyIter(l) => { + if let Some(built) = crate::seqiter::dict_from_zip_pure(l) { + let built = Object::Dict(Rc::new(RefCell::new(built))); + return self.dict_merge_from(dst, &built, globals); + } + } + Object::List(_) | Object::Tuple(_) => { + walked = Self::dict_store_pairs(dd, other); + let all = match other { + Object::Tuple(t) => t.len(), + Object::List(l) => l.try_borrow().map_or(usize::MAX, |l| l.len()), + _ => usize::MAX, + }; + if walked == all { + return Ok(()); + } + } + _ => {} + } + } + } + // A mapping that only wraps one dict: merged as that dict. + if let Some(d) = self.thin_mapping_dict(other, true) { + return self.dict_merge_from(dst, &Object::Dict(d), globals); + } // Mapping protocol: `if hasattr(other, "keys")`. - let keys_fn = self.load_attr(other, "keys").ok(); + let keys_fn = if matches!(other, Object::List(_) | Object::Tuple(_)) { + None + } else { + self.load_attr(other, "keys").ok() + }; if let Some(keys_fn) = keys_fn { let keys = self.call(&keys_fn, &[], &[], globals)?; - let it = self.make_iter(&keys, globals)?; - while let Some(k) = self.iter_next(&it, globals)? { - let v = self.subscr_via_protocol(other, &k, globals)?; + for k in self.listed_keys(&keys, globals)? { + let v = self.mapping_value(other, &k, globals)?; self.store_subscr(dst, &k, v, globals)?; } return Ok(()); @@ -47047,7 +56089,29 @@ impl Interpreter { } })?; let mut idx: usize = 0; + // (The pairs already stored are passed over: reading them again runs + // nothing.) + while idx < walked { + if self.iter_next(&it, globals)?.is_none() { + return Ok(()); + } + idx += 1; + } while let Some(pair) = self.iter_next(&it, globals)? { + // An exact two-item tuple or list is read in place (CPython's + // `PySequence_Fast` takes it as it is), and a key that settles + // natively is stored with one probe. + if let Some((k, v)) = crate::builtins::exact_pair(&pair) { + let rest = match dst { + Object::Dict(dd) => crate::builtins::dict_insert_exact(dd, k, v).err(), + _ => Some((k, v)), + }; + if let Some((k, v)) = rest { + self.store_subscr(dst, &k, v, globals)?; + } + idx += 1; + continue; + } let inner = self .make_iter(&pair, globals) .map_err(|e| crate::builtins::dict_update_element_error(e, idx))?; @@ -47142,8 +56206,20 @@ impl Interpreter { return self.make_iter(&Object::new_list(out), globals); } // A built-in container subclass with no overrides reverses - // the native payload it wraps. - if let Some(native) = inst.native.get() { + // the native payload it wraps (a sequence or a dict's keys; a + // native iterator's payload, an endless `itertools.count()`'s + // say, isn't reversible). + if let Some(native) = inst.native.get().filter(|n| { + matches!( + n, + Object::List(_) + | Object::Tuple(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::ByteArray(_) + | Object::Dict(_) + ) + }) { let native = native.clone(); let items = self.collect_iterable(&native, globals)?; let reversed: Vec = items.into_iter().rev().collect(); @@ -47154,11 +56230,9 @@ impl Interpreter { obj.type_name() ))); } - // Generators / coroutines aren't reversible; everything else - // (lists, tuples, ranges, …) has a native reverse. - let items = self.collect_iterable(obj, globals)?; - let reversed: Vec = items.into_iter().rev().collect(); - self.make_iter(&Object::new_list(reversed), globals) + // Generators, iterators and sets aren't reversible; everything + // else (lists, tuples, ranges, …) has a native reverse. + crate::builtins::b_reversed(args) } fn do_list_sort_call( @@ -47249,6 +56323,18 @@ impl Interpreter { } return result; }; + // `key=cmp_to_key(mycmp)`: the items compare by `mycmp(a, b) < 0`, + // what the key wrappers' `<` would run, without a wrapper per item. + if let Some(mycmp) = crate::stdlib::functools_mod::cmp_key_func(f) { + if reverse { + items.reverse(); + } + let result = self.sort_by_cmp(items, &mycmp, globals); + if reverse { + items.reverse(); + } + return result; + } let mut decorated: Vec<(Object, Object)> = Vec::with_capacity(items.len()); // `key=len`: each length as `len(x)` takes it, without the general // call's dispatch per item (as the call arms recognize the builtin). @@ -47257,9 +56343,64 @@ impl Interpreter { // evaluates in place, as `map`'s callback does; after one decline // the rest take the full call. let mut pure = !len_key && crate::seqiter::pure_callback_maybe(f); + // An instance whose native `__call__` has a fast half, resolved once. + let call_fast = if pure { + self.instance_call_fast(f) + } else { + None + }; + // A leaf builtin key (`key=abs`): its body directly (see + // `do_min_max_call`). + let leaf = match f { + Object::Builtin(b) if !len_key && !b.binds_instance => { + self.leaf_call_kind(b).map(|k| (b.clone(), k)) + } + _ => None, + }; for item in items.iter() { - let k = if len_key { - self.do_len_call(item, globals)? + let leaf_key = leaf.as_ref().and_then(|(b, kind)| { + let arg = std::slice::from_ref(item); + match kind { + LeafKind::Fast(fast) => fast(arg), + LeafKind::Opaque => Some((b.call)(arg)), + LeafKind::Scalar + if matches!(item, Object::Int(_) | Object::Float(_) | Object::Bool(_)) => + { + Some((b.call)(arg)) + } + _ => None, + } + }); + let fast_key = match leaf_key { + Some(r) => Some(r?), + None => call_fast.and_then(|fast| { + // SAFETY: bitwise views of the live key function and + // item, never dropped (the fast half clones what it + // keeps). + let views = std::mem::ManuallyDrop::new(unsafe { + [std::ptr::read(f), std::ptr::read(item)] + }); + match fast(&views[..]) { + Some(Ok(k)) => Some(k), + _ => None, + } + }), + }; + let k = if let Some(k) = fast_key { + k + } else if len_key { + // (A built-in container's or string's length natively; an + // instance's `__len__` through the full call.) + match item { + Object::Str(_) + | Object::List(_) + | Object::Tuple(_) + | Object::Dict(_) + | Object::Set(_) + | Object::FrozenSet(_) + | Object::Bytes(_) => Object::Int(item.len()? as i64), + _ => self.do_len_call(item, globals)?, + } } else if let Some(k) = pure .then(|| self.pure_callback(f, std::slice::from_ref(item), true)) .flatten() @@ -47282,19 +56423,59 @@ impl Interpreter { // CPython decrefs the keys inside `list.sort` while the list is // still detached, so a key `__del__` that mutates the list is caught // by the caller's mutation check (test_sort.test_key_with_mutating_del). - let mut dead_keys: Vec = Vec::with_capacity(decorated.len()); - *items = decorated - .into_iter() - .map(|(k, v)| { - dead_keys.push(k); - v - }) - .collect(); - drop(dead_keys); + // (Each item goes back to its place in the detached vector, which + // still holds the items in their old order; the keys and those old + // references leave together after.) + if items.len() == decorated.len() { + for (slot, pair) in items.iter_mut().zip(decorated.iter_mut()) { + std::mem::swap(slot, &mut pair.1); + } + drop(decorated); + } else { + let mut dead_keys: Vec = Vec::with_capacity(decorated.len()); + *items = decorated + .into_iter() + .map(|(k, v)| { + dead_keys.push(k); + v + }) + .collect(); + drop(dead_keys); + } self.run_pending_finalizers(); result } + /// Sort `items` stably by an old-style comparison function, `a` before + /// `b` when `mycmp(a, b) < 0` (see `functools_mod::cmp_key_func`). A + /// pure-leaf `mycmp` evaluates in place; after one decline the rest + /// take the full call. + fn sort_by_cmp( + &mut self, + items: &mut [Object], + mycmp: &Object, + globals: &Rc>, + ) -> Result<(), RuntimeError> { + let mut pure = crate::seqiter::pure_callback_maybe(mycmp); + crate::timsort::sort(items, |a, b| { + let args = [a.clone(), b.clone()]; + let r = match pure + .then(|| self.pure_callback(mycmp, &args, true)) + .flatten() + { + Some(r) => r, + None => { + pure = false; + self.call(mycmp, &args, &[], globals)? + } + }; + match r { + Object::Int(n) => Ok(n < 0), + r => self.dispatch_compare_op(&r, &Object::Int(0), CompareKind::Lt, globals), + } + }) + } + /// Sort `v` stably by the keys `key` projects, with the comparison /// CPython's `list.sort` pre-sort check picks for the keys' types: a /// native one for `str`, `int` or `float` keys (and for tuples whose @@ -47345,12 +56526,54 @@ impl Interpreter { }, } }), - SortKind::General => crate::timsort::sort(v, |a, b| { - self.dispatch_compare_op(key(a), key(b), CompareKind::Lt, globals) - }), + SortKind::General => { + // Instances of one exact class whose `__lt__` is a Python + // function that evaluates as a pure leaf: the function, + // resolved once, called on each pair as `<` would (any + // answer but a `bool` takes the full protocol). + let lt_fn = Self::common_instance_dunder( + v.iter().map(key), + crate::types::vm_key::LT_FN, + "__lt__", + ); + crate::timsort::sort(v, |a, b| { + let (x, y) = (key(a), key(b)); + if let Some(f) = <_fn { + if let Some(Object::Bool(lt)) = + self.call_pure_leaf_with(f, Some(x), std::slice::from_ref(y)) + { + return Ok(lt); + } + } + self.dispatch_compare_op(x, y, CompareKind::Lt, globals) + }) + } } } + /// The Python function `name` resolves to on the one exact class every + /// one of `objs` is a plain instance of, if they share one and it is + /// a function (cached on the class under `key`). + fn common_instance_dunder<'a>( + mut objs: impl Iterator, + key: u32, + name: &str, + ) -> Option> { + let Some(Object::Instance(first)) = objs.next() else { + return None; + }; + let cls = std::ptr::from_ref(first.cls_raw()); + if first.native.get().is_some() + || !objs.all(|o| { + matches!(o, Object::Instance(i) + if std::ptr::eq(i.cls_raw(), cls) && i.native.get().is_none()) + }) + { + return None; + } + Self::instance_dunder_function(first, crate::types::AttrKey::vm(key), name) + } + /// Run `__str__` on instances, falling back to `__repr__` then /// the default. Built-in types use their existing `to_str`. /// CPython `PyObject_Str`/`PyObject_Repr` result check: a user @@ -47901,12 +57124,66 @@ impl Interpreter { self.stringify(v, globals) } + /// `format(v, '')` of a plain instance (no native payload) whose class + /// has a Python `__str__` and no `__format__`: that `__str__`'s + /// unchecked result, evaluated in place when a pure leaf. `None` for + /// any other value. + fn format_plain_instance(&mut self, v: &Object) -> Option> { + let Object::Instance(inst) = v else { + return None; + }; + if inst.native.get().is_some() + || !Self::class_lacks( + inst.cls_raw(), + crate::types::AttrKey::vm(crate::types::vm_key::FORMAT_LACKS), + "__format__", + ) + { + return None; + } + let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::STR_FN), + "__str__", + ) else { + // A native `__str__` (an exception's), called with the instance. + let b = Self::instance_native_str(inst)?; + return Some((b.call)(std::slice::from_ref(v))); + }; + Some(match self.call_pure_leaf_with(&f, Some(v), &[]) { + Some(r) => Ok(r), + None => self.call_python(&f, std::slice::from_ref(v), &[]), + }) + } + fn stringify( &mut self, v: &Object, globals: &Rc>, ) -> Result { if let Object::Instance(inst) = v { + // A subclass of `str`, `int` or `float` that renders as its + // payload. + if let Some(Object::Str(s)) = Self::quick_str(inst) { + return Ok(s.to_string()); + } + // A Python `__str__` (cached on the class): evaluated in place + // when a pure leaf, else called with the instance, without a + // bound method. + if inst.native.get().is_none() { + // (Or the `__repr__` that `object.__str__` calls.) + if let Some(f) = Self::instance_str_function(inst) { + let r = match self.call_pure_leaf_with(&f, Some(v), &[]) { + Some(r) => r, + None => self.call_python(&f, std::slice::from_ref(v), &[])?, + }; + return Self::require_str_result(r, "__str__"); + } + } + if let Some(b) = Self::instance_native_str(inst) { + let r = (b.call)(std::slice::from_ref(v))?; + return Self::require_str_result(r, "__str__"); + } if let Some(method) = instance_method(v, "__str__") { let r = self.call(&method, &[], &[], globals)?; return Self::require_str_result(r, "__str__"); @@ -47945,6 +57222,15 @@ impl Interpreter { } return self.repr_of(v, globals); } + // A `mappingproxy`'s is its mapping's (`mappingproxy_str`). + match v { + Object::MappingProxy(d) => return self.stringify(&Object::Dict(d.clone()), globals), + Object::MappingProxyObj(inner) => { + let inner = (**inner).clone(); + return self.stringify(&inner, globals); + } + _ => {} + } // `str(SomeClass)` consults the metaclass (`EnumType.__str__`). if let Object::Type(_) = v { if let Some(method) = metaclass_method(v, "__str__") { @@ -47979,6 +57265,16 @@ impl Interpreter { globals: &Rc>, ) -> Result { if let Object::Instance(inst) = v { + // A plain Python `__repr__`: called with the instance, with no + // bound method built for it. + if let Some(r) = self.instance_python_repr(v) { + return Self::require_str_result(r?, "__repr__"); + } + // A native one (an exception's, `object`'s), likewise. + if let Some(b) = Self::instance_native_repr(inst) { + let r = (b.call)(std::slice::from_ref(v))?; + return Self::require_str_result(r, "__repr__"); + } if let Some(method) = instance_method(v, "__repr__") { let r = self.call(&method, &[], &[], globals)?; return Self::require_str_result(r, "__repr__"); @@ -48160,7 +57456,8 @@ impl Interpreter { "__contains__", ) { let r = self.call_dunder_function(f, &[container.clone(), item.clone()])?; - return Ok(r.is_truthy()); + // (`PyObject_IsTrue` of the answer: its own `__bool__` too.) + return self.obj_truthy(&r, globals); } // A dict subclass inheriting `dict.__contains__`, of a key that // settles by native equality. @@ -48183,11 +57480,23 @@ impl Interpreter { } } } + // A class whose Python metaclass defines `__contains__` as a plain + // function (`member in SomeEnum`): called with the class, no bound + // method made. + if let Object::Type(t) = &container { + let meta = t.metaclass_or_type(); + if !Rc::ptr_eq(&meta, &builtin_types().type_) { + if let Some(Object::Function(f)) = meta.lookup("__contains__") { + let r = self.call_dunder_function(f, &[container.clone(), item.clone()])?; + return self.obj_truthy(&r, globals); + } + } + } let found = if let Some(method) = instance_method(&container, "__contains__") .or_else(|| metaclass_method(&container, "__contains__")) { let r = self.call(&method, std::slice::from_ref(item), &[], globals)?; - r.is_truthy() + self.obj_truthy(&r, globals)? } else if let Object::Instance(inst) = &container { if let Some(native) = inst.native.get().cloned() { // Subclass of a built-in container (`class C(dict)`, @@ -48219,6 +57528,9 @@ impl Interpreter { // (a comparison may mutate it): one element handle at a // time, the borrow released before each comparison. Object::List(items) => { + // (An instance's pure-leaf `__eq__`, resolved once for + // the scan: see `seq_contains_rich`.) + let eq_fn = Self::instance_eq_leaf(item); let mut i = 0usize; loop { let x = { @@ -48228,16 +57540,25 @@ impl Interpreter { None => break false, } }; - if self.seq_member_eq(&x, item, globals)? { + let hit = match self.member_eq_leaf(eq_fn.as_ref(), &x, item) { + Some(hit) => hit, + None => self.seq_member_eq(&x, item, globals)?, + }; + if hit { break true; } i += 1; } } Object::Tuple(items) => { + let eq_fn = Self::instance_eq_leaf(item); let mut found = false; for x in items.iter() { - if self.seq_member_eq(x, item, globals)? { + let hit = match self.member_eq_leaf(eq_fn.as_ref(), x, item) { + Some(hit) => hit, + None => self.seq_member_eq(x, item, globals)?, + }; + if hit { found = true; break; } @@ -48284,15 +57605,70 @@ impl Interpreter { self.seq_contains_rich(std::slice::from_ref(x), item, globals) } + /// A plain instance's `__eq__` function and its class, for comparing + /// it as a pure leaf with members of that exact class (see + /// [`Self::member_eq_leaf`]). + fn instance_eq_leaf( + item: &Object, + ) -> Option<(*const crate::types::TypeObject, Rc)> { + match item { + Object::Instance(inst) if inst.native.get().is_none() => { + Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::EQ_FN), + "__eq__", + ) + .map(|f| (std::ptr::from_ref(inst.cls_raw()), f)) + } + _ => None, + } + } + + /// `x == item` as a container's membership test takes it, when it + /// settles without the full protocol: the same object, or `x` of the + /// class of `eq_fn` ([`Self::instance_eq_leaf`] of `item`) whose + /// `__eq__` evaluates as a pure leaf to a `bool`. `None` otherwise (a + /// pure leaf has no effects to repeat). + #[inline] + fn member_eq_leaf( + &mut self, + eq_fn: Option<&(*const crate::types::TypeObject, Rc)>, + x: &Object, + item: &Object, + ) -> Option { + if x.is_same(item) { + return Some(true); + } + let ((cls, f), Object::Instance(xi)) = (eq_fn?, x) else { + return None; + }; + if !std::ptr::eq(xi.cls_raw(), *cls) || xi.native.get().is_some() { + return None; + } + match self.call_pure_leaf_with(f, Some(x), std::slice::from_ref(item)) { + Some(Object::Bool(b)) => Some(b), + _ => None, + } + } + fn seq_contains_rich( &mut self, items: &[Object], item: &Object, globals: &Rc>, ) -> Result { + // An instance of a class whose `__eq__` is a Python function that + // evaluates as a pure leaf, compared with elements of its exact + // class: the function, resolved once for the scan, called on each + // (element, item) pair as `list.__contains__` calls it. Any answer + // but a `bool` goes through the full protocol (a pure leaf has no + // effects to repeat). + let eq_fn = Self::instance_eq_leaf(item); for x in items { - if x.is_same(item) { - return Ok(true); + match self.member_eq_leaf(eq_fn.as_ref(), x, item) { + Some(true) => return Ok(true), + Some(false) => continue, + None => {} } // Escalate to the full rich-comparison protocol whenever either // operand can carry custom `__eq__` semantics the native @@ -48355,6 +57731,9 @@ impl Interpreter { .cloned(), _ => None, }; + if let Some(Object::Type(t)) = &cls { + note_seqiter_class(t, false); + } match cls { Some(cls) => Ok(Some(self.call( &cls, @@ -48373,6 +57752,11 @@ impl Interpreter { ) -> Result { match v { Object::Generator(_) | Object::Iter(_) | Object::LazyIter(_) => Ok(v.clone()), + // A list's or tuple's cursor, without the default arm's checks. + Object::List(_) | Object::Tuple(_) => { + let it = v.make_iter()?; + Ok(Object::Iter(Rc::new(RefCell::new(it)))) + } // An object-backed `mappingproxy` iterates as the wrapped // mapping does — overridden `__iter__` included (CPython's // `mappingproxy_getiter`; test_types.MappingProxyTests). @@ -48396,11 +57780,33 @@ impl Interpreter { self.call(&method, &[], &[], globals) } Object::Instance(_) => { + // A class remembered as a legacy sequence: its iterator, + // with none of the lookups below. + if let Object::Instance(inst) = v { + let cls = inst.cls_raw(); + if self.legacy_seq.get() + == (std::ptr::from_ref(cls) as usize, cls.attr_version.get()) + && inst.native.get().is_none() + { + if let Some(it) = seqiter_new(v) { + return Ok(it); + } + } + } // A list or tuple subclass inheriting `__iter__` (a named // tuple's unpacking): its value's iterator, with no bound // method and no call. + // (A dict subclass's too: a `defaultdict`'s or `Counter`'s + // keys, as `dict.__iter__` walks them.) if let Object::Instance(inst) = v { - if let Some(native @ (Object::List(_) | Object::Tuple(_))) = inst.native.get() { + if let Some( + native @ (Object::List(_) + | Object::Tuple(_) + | Object::Dict(_) + | Object::Set(_) + | Object::FrozenSet(_)), + ) = inst.native.get() + { let cls = inst.cls_raw(); if cls.native_kind.get() == 0 && cls.c_ext_ptr.get() == 0 @@ -48410,6 +57816,34 @@ impl Interpreter { } } } + // An `__iter__` that is a plain generator function of `self` + // alone (`def __iter__(self): yield self.x; yield self.y`): + // its generator, made as a compiled `for` loop's `GET_ITER` + // makes it, with no frame for the call. + if let Some(gen) = self.instance_gen_call(v, "__iter__") { + return Ok(gen); + } + // A Python `__iter__` (found once per class version): called + // with the instance, without a bound method (a warm leaf, + // `return iter(self.d)`, evaluates in place). + if let Object::Instance(inst) = v { + if let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::ITER_FN), + "__iter__", + ) { + let result = self.call_dunder_function(f, std::slice::from_ref(v))?; + if let Object::Instance(_) = &result { + if instance_method(&result, "__next__").is_none() { + return Err(type_error(format!( + "iter() returned non-iterator of type '{}'", + result.type_name_owned() + ))); + } + } + return iter_result(result); + } + } // `__iter__ = None` disables the slot (CPython's // "anti-registration" convention — typing's special forms // use it so `iter(Union[int, str])` raises "not iterable" @@ -48436,7 +57870,7 @@ impl Interpreter { ))); } } - return Ok(result); + return iter_result(result); } // An `xml.etree` element (no `__iter__`; a native // `__getitem__`) walks its children natively. @@ -48486,6 +57920,20 @@ impl Interpreter { )) && instance_method(v, "__getitem__").is_some() { + // (Every check above was the class's alone: a + // plain one with a Python `__getitem__` is + // remembered.) + let cls = inst.cls_raw(); + if !c_sequence + && inst.native.get().is_none() + && cls.native_kind.get() == 0 + && cls.c_ext_ptr.get() == 0 + && cls.attr_version.get() != 0 + && matches!(cls.lookup("__getitem__"), Some(Object::Function(_))) + { + self.legacy_seq + .set((std::ptr::from_ref(cls) as usize, cls.attr_version.get())); + } if let Some(it) = self.make_seq_iterator(v, globals)? { return Ok(it); } @@ -48799,6 +58247,13 @@ impl Interpreter { globals: &Rc>, coerce: bool, ) -> Result { + let no_anext = |aiter: &Object| { + type_error(format!( + "'async for' received an object from __aiter__ that does not implement \ + __anext__: {}", + aiter.type_name_owned() + )) + }; match aiter { Object::AsyncGenerator(_) => { // A deferred `async_generator_asend` awaitable, like @@ -48812,8 +58267,10 @@ impl Interpreter { vec![Object::None], )) } - Object::Instance(_) if instance_method(aiter, "__anext__").is_some() => { - let method = instance_method(aiter, "__anext__").expect("checked"); + Object::Instance(_) => { + let Some(method) = instance_method(aiter, "__anext__") else { + return Err(no_anext(aiter)); + }; let res = self.call(&method, &[], &[], globals)?; if coerce { self.get_awaitable(res, 3) @@ -48821,11 +58278,7 @@ impl Interpreter { Ok(res) } } - _ => Err(type_error(format!( - "'async for' received an object from __aiter__ that does not implement \ - __anext__: {}", - aiter.type_name_owned() - ))), + _ => Err(no_anext(aiter)), } } @@ -48843,6 +58296,15 @@ impl Interpreter { Object::LazyIter(l) => self.lazy_iter_next(l, globals), // (Its end builds no `StopIteration` just to catch it.) Object::Generator(g) => self.gen_drain_next(g, None, false), + // A frameless Python `__next__`, its bare `raise StopIteration` + // an end with no exception built (`list(it)`'s drain). + Object::Instance(inst) => match self.leaf_python_step(iter, inst) { + Some(r) => Ok(r), + None => match self.iter_step(iter, globals) { + Err(e) if crate::seqiter::is_stop_iteration(&e) => Ok(None), + r => r, + }, + }, _ => match self.iter_step(iter, globals) { Err(e) if crate::seqiter::is_stop_iteration(&e) => Ok(None), r => r, @@ -48868,6 +58330,26 @@ impl Interpreter { // ``next()`` must advance it with ``send(None)`` like a generator. Object::Coroutine(_) => self.gen_method_send(iter, Object::None).map(Some), Object::Instance(inst) => { + // A legacy sequence's iterator steps with no frame of its + // own. + if let Some(rev) = seqiter_kind(inst) { + if let Some(r) = self.seqiter_next(inst, rev) { + return r; + } + } + // A Python `__next__` (cached on the class; it overrides a + // built-in iterator payload's): called with the instance, + // without a bound method. + if let Some(f) = Self::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::NEXT_FN), + "__next__", + ) { + // (A warm pure or effect leaf evaluates in place.) + return self + .call_dunder_function(f, std::slice::from_ref(iter)) + .map(Some); + } // A registered native leaf `__next__` (the class cache the // core loop's `FOR_ITER` uses): called directly. if !crate::gil::free_threading_enabled() && !crate::trace::any_observers_active() { @@ -48878,6 +58360,17 @@ impl Interpreter { return (b.call)(std::slice::from_ref(iter)).map(Some); } } + // A native `__next__` (an `io.StringIO`'s line), found once + // per class version. + if !crate::trace::any_observers_active() { + if let Some(b) = Self::instance_native_next(inst) { + return match b.call_kw.as_ref() { + Some(ckw) => ckw(std::slice::from_ref(iter), &[]), + None => (b.call)(std::slice::from_ref(iter)), + } + .map(Some); + } + } if let Some(r) = instance_native_dunder(iter, "__next__", None) { return r.map(Some); } @@ -48963,17 +58456,30 @@ impl Interpreter { } /// [`Self::lazy_iter_next`]'s step. + #[inline] fn lazy_iter_step( &mut self, l: &Rc, globals: &Rc>, ) -> Result, RuntimeError> { - use crate::object::LazyIterKind; // Steps that run no code first (pure state machines, native // sources with an item ready, pure callbacks), under one borrow. if let Some(r) = self.lazy_core_next(l) { return Ok(r); } + self.lazy_iter_step_general(l, globals) + } + + /// [`Self::lazy_iter_step`] past the steps that run no code. + fn lazy_iter_step_general( + &mut self, + l: &Rc, + globals: &Rc>, + ) -> Result, RuntimeError> { + use crate::object::LazyIterKind; + if let Some(r) = self.calliter_step(l, globals) { + return r; + } // The builtin `map`/`filter`/`zip`/`enumerate` adapters. if l.is_builtin_kind() { if let Some(r) = self.seq_lazy_next(l, globals) { @@ -49175,7 +58681,8 @@ impl Interpreter { | LazyIterKind::Zip { .. } | LazyIterKind::Enumerate { .. } | LazyIterKind::GroupBy { .. } - | LazyIterKind::Grouper { .. } => unreachable!("handled above"), + | LazyIterKind::Grouper { .. } + | LazyIterKind::CallIter { .. } => unreachable!("handled above"), }; match snap { Snap::Count { current, step } => { @@ -49276,8 +58783,12 @@ impl Interpreter { Ok(None) => { active = None; } + // The active source raised: the chain keeps it + // (and what follows), as CPython's `chain_next` + // returns with nothing cleared, so a later step + // goes on from there. Err(e) => { - write_back(&None, &None); + write_back(&source, &active); return Err(e); } } @@ -49358,7 +58869,7 @@ impl Interpreter { return Ok(None); }; let call_args: Vec = match &item { - Object::Tuple(items) => items.to_vec(), + Object::Tuple(items) => crate::object::cloned_vec(items), other => self.collect_iterable(other, globals)?, }; if let Object::Function(f) = &func { @@ -49440,9 +58951,20 @@ impl Interpreter { for slot in iters.iter_mut() { let value = match slot { None => fillvalue.clone(), - Some(it) => match self.iter_next(it, globals)? { - Some(v) => v, - None => { + Some(it) => match self.iter_next(it, globals) { + // A source that raises ends the adapter for + // good (CPython's `zip_longest_next` zeroes + // `numactive` on any error). + Err(e) => { + if let LazyIterKind::ZipLongest { numactive: na, .. } = + &mut *l.state.borrow_mut() + { + *na = 0; + } + return Err(e); + } + Ok(Some(v)) => v, + Ok(None) => { numactive -= 1; if numactive == 0 { if let LazyIterKind::ZipLongest { numactive: na, .. } = @@ -49509,9 +59031,19 @@ impl Interpreter { }; let mut batch = Vec::with_capacity(n); while batch.len() < n { - match self.iter_next(&src, globals)? { - Some(v) => batch.push(v), - None => { + match self.iter_next(&src, globals) { + // A source that raises ends the adapter for good + // (CPython's `batched_next` clears its iterator). + Err(e) => { + if let LazyIterKind::Batched { source: s, .. } = + &mut *l.state.borrow_mut() + { + *s = None; + } + return Err(e); + } + Ok(Some(v)) => batch.push(v), + Ok(None) => { if let LazyIterKind::Batched { source: s, .. } = &mut *l.state.borrow_mut() { @@ -49872,17 +59404,7 @@ impl Interpreter { let Object::AsyncGenerator(g) = &a.agen else { return None; }; - // Mid-await suspension *or* the agen's own body executing right - // now (e.g. `await anext(me)` from inside the body) both count - // as "already running" in CPython's `ag_running_async` sense. - let mid_await = matches!( - &*g.state().borrow(), - GeneratorState::Suspended(frame) if !frame.agen_yielded_value - ) || matches!( - &*g.state().borrow(), - GeneratorState::Running | GeneratorState::Delegating(_) - ); - if !mid_await { + if !Self::agen_running_async(g) { return None; } a.consumed.set(true); @@ -49893,11 +59415,195 @@ impl Interpreter { })) } + /// Whether async generator `g` is "already running" in CPython's + /// `ag_running_async` sense: suspended mid-`await`, or its own body + /// executing right now (`await anext(me)` from inside the body). + fn agen_running_async(g: &Rc) -> bool { + match &*g.state().borrow() { + GeneratorState::Suspended(frame) => !frame.agen_yielded_value, + GeneratorState::Running | GeneratorState::Delegating(_) => true, + _ => false, + } + } + + /// `GET_ANEXT` of the async generator `g` (`aiter`, atop `frame`'s + /// stack) together with the `LOAD_CONST None; SEND` that awaits it at + /// once (`async for`, an async comprehension), `frame.pc` just past the + /// `GET_ANEXT`: the generator resumes from here, as the first drive of + /// its deferred `asend(None)` awaitable resumes it + /// ([`Self::step_agen_await`]), with no awaitable made and no + /// `StopIteration` built to carry the item to the `END_SEND`, which the + /// item skips. A suspension on an inner `await` leaves what the `SEND` + /// would: the awaitable, driven once, and the value passed through, at + /// the `YIELD_VALUE`. `None` touched nothing (another shape, or an + /// observer that is owed the `StopIteration`). + fn anext_in_place( + &mut self, + frame: &mut Frame, + g: &Rc, + aiter: &Object, + ) -> Option> { + let pc = frame.pc as usize - 1; + let exit = anext_send_exit(&frame.code, pc)?; + if crate::trace::any_observers_active() { + return None; + } + Some(self.anext_resume(g, aiter).map(|step| match step { + AnextStep::Item(v) => { + frame.push(v); + frame.pc = exit as u32 + 1; + } + AnextStep::Passed(aw, v) => { + frame.push(aw); + frame.push(v); + frame.pc = pc as u32 + 3; + } + })) + } + + /// [`Self::anext_in_place`]'s resume of the async generator `g` + /// (`aiter`): its item, or what a suspension on an inner `await` passes + /// on; its end is `StopAsyncIteration`. + pub(crate) fn anext_resume( + &mut self, + g: &Rc, + aiter: &Object, + ) -> Result { + self.agen_init_hooks(aiter)?; + if Self::agen_running_async(g) { + return Err(crate::error::runtime_error( + "anext(): asynchronous generator is already running", + )); + } + match self.generator_resume(g, Object::None) { + Ok(GenResume::Yielded(v)) => { + if Self::agen_yielded_a_value(g) { + return Ok(AnextStep::Item(v)); + } + let aw = make_agen_await( + aiter, + crate::object::AgenAwaitKind::Send, + vec![Object::None], + ); + if let Object::AsyncGenAwait(a) = &aw { + a.started.set(true); + } + Ok(AnextStep::Passed(aw, v)) + } + Ok(GenResume::Returned(_)) => Err(stop_async_iteration()), + Err(RuntimeError::PyException(exc)) if exc.type_name() == "StopIteration" => { + Err(stop_async_iteration()) + } + Err(e) => Err(e), + } + } + + /// A compiled consumer's `SEND` at `pc` of `sw`'s running activation + /// `frame` (synced, the awaitable `a` on top, `sent` popped) to an + /// async generator's `asend` / `athrow` / `aclose` awaitable: its drive + /// ([`Self::step_agen_await_raw`]) with the activation waiting on the + /// pending list, or, `lazy`, running lazily (as + /// [`Self::core_native_body`] runs a builtin's body). + /// + /// # Safety + /// + /// As [`Self::core_native_body`]'s, `lazy` null or the running lazy + /// activation's state. + #[cfg(feature = "jit")] + #[inline(never)] + pub(crate) unsafe fn core_agen_await( + &mut self, + sw: &mut CoreSwitch, + frame: &mut Frame, + pc: usize, + a: &Rc, + sent: Object, + lazy: *mut frame_jit::State, + ) -> Result { + frame.pc = pc as u32 + 1; + // SAFETY: the caller's contract (as `core_native_body`'s). + unsafe { + let pending = if lazy.is_null() { + self.core_pending_enter_fast(sw, frame, pc) + } else { + (*lazy).wait_pc = pc; + None + }; + let result = self.step_agen_await_raw(a, sent); + let pending = if lazy.is_null() { + pending + } else { + (*lazy).wait_pc = usize::MAX; + (*lazy).wait_pending.take() + }; + self.core_pending_exit(sw, pending); + result + } + } + + /// A compiled consumer's `GET_ANEXT` at `pc` of `sw`'s running + /// activation `frame` (synced, the async generator `g`, `aiter`, on + /// top), the shape [`Self::anext_in_place`] takes: the generator's + /// resume ([`Self::anext_resume`]) with the activation waiting on the + /// pending list, or, `lazy`, running lazily (as + /// [`Self::core_native_body`] runs a builtin's body). + /// + /// # Safety + /// + /// As [`Self::core_native_body`]'s, `lazy` null or the running lazy + /// activation's state. + #[cfg(feature = "jit")] + #[inline(never)] + pub(crate) unsafe fn core_anext( + &mut self, + sw: &mut CoreSwitch, + frame: &mut Frame, + pc: usize, + g: &Rc, + aiter: &Object, + lazy: *mut frame_jit::State, + ) -> Result { + frame.pc = pc as u32 + 1; + // SAFETY: the caller's contract (as `core_native_body`'s). + unsafe { + let pending = if lazy.is_null() { + self.core_pending_enter_fast(sw, frame, pc) + } else { + (*lazy).wait_pc = pc; + None + }; + let result = self.anext_resume(g, aiter); + let pending = if lazy.is_null() { + pending + } else { + (*lazy).wait_pc = usize::MAX; + (*lazy).wait_pending.take() + }; + self.core_pending_exit(sw, pending); + result + } + } + fn step_agen_await( &mut self, a: &Rc, send_value: Object, ) -> Result { + match self.step_agen_await_raw(a, send_value)? { + AgenAwaitStep::Passed(v) => Ok(v), + AgenAwaitStep::Done(None) => Err(stop_iteration()), + AgenAwaitStep::Done(Some(v)) => Err(stop_iteration_with(v)), + } + } + + /// [`Self::step_agen_await`] with the awaitable's completion as a value + /// ([`AgenAwaitStep::Done`]) instead of the `StopIteration` that carries + /// it: what the `SEND` driving it wants. + fn step_agen_await_raw( + &mut self, + a: &Rc, + send_value: Object, + ) -> Result { use crate::object::AgenAwaitKind; if a.consumed.get() { return Err(Self::agen_await_reuse_error(a.kind)); @@ -49938,7 +59644,7 @@ impl Interpreter { Object::AsyncGenerator(g) if g.is_finished() ) { a.consumed.set(true); - return Err(stop_iteration()); + return Ok(AgenAwaitStep::Done(None)); } let bt = crate::builtin_types::builtin_types(); let exc_inst = crate::builtin_types::make_exception_with_class( @@ -49961,7 +59667,7 @@ impl Interpreter { // drivable for the next resume. if let Object::AsyncGenerator(g) = &a.agen { if !Self::agen_yielded_a_value(g) { - return Ok(value); + return Ok(AgenAwaitStep::Passed(value)); } } a.consumed.set(true); @@ -49972,10 +59678,9 @@ impl Interpreter { "async generator ignored GeneratorExit", )); } - // The agen yielded a consumer value / the op completed: - // express completion as `StopIteration(value)` so the SEND - // handler short-circuits. - Err(stop_iteration_with(value)) + // The agen yielded a consumer value / the op completed + // (`StopIteration(value)` to anything but a `SEND`). + Ok(AgenAwaitStep::Done(Some(value))) } // `StopAsyncIteration` (agen finished) and genuine exceptions // raised in the agen body propagate out of the await. @@ -49991,7 +59696,7 @@ impl Interpreter { ) { // Clean exit: awaiting `aclose()` completes with None. - return Err(stop_iteration()); + return Ok(AgenAwaitStep::Done(None)); } Err(e) } @@ -50182,6 +59887,16 @@ impl Interpreter { ) -> Result { let prev_state = std::mem::replace(&mut *gen.state().borrow_mut(), GeneratorState::Running); let mut frame = match prev_state { + // A `StopIteration` thrown into a generator that never started + // escapes as it is: CPython's PEP 479 conversion is a handler + // over the body past its start, which the throw never enters. + GeneratorState::Created(_) + if matches!(gen.kind, crate::object::CoroutineKind::Generator) + && exc.type_name() == "StopIteration" => + { + *gen.state().borrow_mut() = GeneratorState::Finished; + return Err(RuntimeError::PyException(exc)); + } GeneratorState::Created(boxed) | GeneratorState::Suspended(boxed) => *boxed, GeneratorState::Finished => { *gen.state().borrow_mut() = GeneratorState::Finished; @@ -50812,7 +60527,7 @@ impl Interpreter { let bt = crate::builtin_types::builtin_types(); let call_args: Vec = match val { Object::None => vec![], - Object::Tuple(items) => items.to_vec(), + Object::Tuple(items) => crate::object::cloned_vec(items), other => vec![other.clone()], }; let globals = self.builtins.clone(); @@ -51043,6 +60758,18 @@ impl Interpreter { { return None; } + // Resting in a `yield from` over a range, tuple or list + // iterator with an item left, sent `None`: the item, the frame + // untouched (see `yield_from_iter_item`). + if let (false, None, Object::None, Some(Object::Iter(it))) = + (first_resume, &fold, sent, frame.stack.last()) + { + if let Some(v) = + Self::yield_from_iter_item(frame, &frame.code, frame.pc as usize, it) + { + return Some(Ok(v)); + } + } } let guard = match crate::recursion::enter() { crate::recursion::Enter::Ok(g) => g, @@ -51357,6 +61084,16 @@ impl Interpreter { fire: bool, ) -> Result, RuntimeError> { let raw = !crate::trace::any_observers_active(); + // A sequence walk steps on its frame (a folding resume would run + // its reads as calls). + #[cfg(feature = "jit")] + if fold.is_some() && raw { + match self.gen_walk_next(g) { + Some(gen_fast::GenNext::Yielded(v)) => return Ok(Some(v)), + Some(gen_fast::GenNext::Exhausted(_)) => return Ok(None), + _ => {} + } + } let result = if fold.is_none() { self.generator_next_raw(g, raw) } else { @@ -51549,6 +61286,161 @@ impl Interpreter { /// Implement `MATCH_CLASS`: check `isinstance(subject, cls)` and /// pull out positional + keyword sub-values into a single tuple. /// Returns `None` if the type test or any attribute access fails. + /// `MATCH_CLASS` (`nargs` positional sub-patterns, the keyword ones' + /// `names`) of `subject` against `cls` when nothing about it runs code: + /// a class whose metaclass is `type` (so the instance check is the + /// MRO's), positional names from a tuple `__match_args__` (or a + /// builtin's self match), and attributes the subject holds in its own + /// dictionary under the default attribute access, with at most plain + /// data under the name on its class (a dataclass field's default). The + /// tuple of sub-pattern subjects, or `None` for no match; + /// `Option::None` leaves anything else, every error among it, to + /// [`Self::match_class`]. + pub(crate) fn match_class_plain( + subject: &Object, + cls: &Object, + nargs: usize, + names: &Object, + ) -> Option { + let (Object::Type(ty), Object::Tuple(kw)) = (cls, names) else { + return None; + }; + if !ty.metaclass_is_type() || crate::object::exotic_str_keys_possible() { + return None; + } + let scls = crate::builtins::class_of(subject); + if !scls.is_subclass_of(ty) { + // (An instance may still answer through a `__class__` of its + // own making: the full check's to ask.) + let plain_class = match scls.lookup_with_owner("__class__") { + Some((_, owner)) => Rc::ptr_eq(&owner, &builtin_types().object_), + None => false, + }; + return plain_class.then_some(Object::None); + } + if nargs == 0 && kw.is_empty() { + return Some(Object::new_tuple(Vec::new())); + } + let mut values: Vec = Vec::with_capacity(nargs + kw.len()); + let mut taken: Vec<&str> = Vec::with_capacity(nargs + kw.len()); + let positional = + if nargs == 0 { + None + } else { + match ty.lookup("__match_args__") { + Some(Object::Tuple(args)) if nargs <= args.len() => Some(args), + Some(_) => return None, + None => { + // A builtin's self match: `int(n)`, `str(s)`. + const SELF_MATCH: &[&str] = &[ + "bool", + "bytearray", + "bytes", + "dict", + "float", + "frozenset", + "int", + "list", + "set", + "str", + "tuple", + ]; + let own = + ty.mro.try_borrow().ok()?.iter().any(|t| { + t.flags.is_builtin && SELF_MATCH.contains(&t.name.as_str()) + }); + if !own || nargs != 1 { + return None; + } + values.push(subject.clone()); + None + } + } + }; + let Object::Instance(inst) = subject else { + // (A builtin value has no attribute sub-pattern to read here.) + return (positional.is_none() && kw.is_empty()).then(|| Object::new_tuple(values)); + }; + if (positional.is_some() || !kw.is_empty()) && !Self::default_getattribute(&scls) { + return None; + } + let args: &[Object] = match &positional { + Some(args) => &args[..nargs], + None => &[], + }; + for name in args.iter().chain(kw.iter()) { + let Object::Str(name) = name else { + return None; + }; + let name: &str = name; + if taken.contains(&name) { + return None; + } + taken.push(name); + // The class supplies nothing under the name, or plain data the + // instance's own value shadows. + let on_class = match scls.lookup(name) { + None => None, + Some( + v @ (Object::None + | Object::Bool(_) + | Object::Int(_) + | Object::Float(_) + | Object::Str(_) + | Object::Tuple(_)), + ) => Some(v), + Some(_) => return None, + }; + let own = match inst.dict.published() { + Some(d) => d + .try_borrow() + .ok()? + .get(&crate::object::StrKey(name)) + .cloned(), + None => inst + .dict + .split_cell() + .try_borrow() + .ok()? + .get_str(name) + .cloned(), + }; + // (A name found nowhere may still come from `__getattr__`.) + values.push(own.or(on_class)?); + } + Some(Object::new_tuple(values)) + } + + /// `MATCH_KEYS` of the exact dict `subject` for the tuple `keys` of + /// plain keys (strings, small ints, floats: their lookups run no code) + /// with no two equal: the tuple of their values, or `None` when one is + /// missing. `Option::None` leaves any other shape to the full handler. + pub(crate) fn match_keys_plain(subject: &Object, keys: &Object) -> Option { + let (Object::Dict(d), Object::Tuple(keys)) = (subject, keys) else { + return None; + }; + if keys.len() > 8 { + return None; + } + for (i, k) in keys.iter().enumerate() { + if !matches!(k, Object::Str(_) | Object::Int(_)) { + return None; + } + if keys[..i].iter().any(|other| other.eq_value(k)) { + return None; + } + } + let d = d.try_borrow().ok()?; + let mut values = Vec::with_capacity(keys.len()); + for k in keys.iter() { + match d.find_object_native(k)? { + (_, Ok(i)) => values.push(d.get_index(i)?.1.clone()), + (_, Err(_)) => return Some(Object::None), + } + } + Some(Object::new_tuple(values)) + } + fn match_class( &mut self, subject: &Object, @@ -51775,6 +61667,16 @@ impl Interpreter { } } (Object::Dict(dst), BinOpKind::BitOr) => { + // A plain dict's entries go in under one borrow of each + // dict while their keys settle natively (and a dict merged + // into itself is left as it is). + if let Object::Dict(s) = b { + if Rc::ptr_eq(dst, s) + || (!crate::capi_watchers::dicts_active() && Self::dict_merge_plain(dst, s)) + { + return Ok(a.clone()); + } + } let src: Vec<(DictKey, Object)> = match b { Object::Dict(s) => s .borrow() @@ -51865,6 +61767,11 @@ impl Interpreter { Object::Set(_), BinOpKind::BitOr | BinOpKind::BitAnd | BinOpKind::Sub | BinOpKind::BitXor, ) => { + // In place on the set itself, walking the side the + // operation needs (see `setalg::update`). + if matches!(b, Object::Set(_) | Object::FrozenSet(_)) && setalg::update(a, b, op) { + return Ok(a.clone()); + } let r = self.dispatch_binary_op(a, b, op, globals)?; if let (Object::Set(dst), Object::Set(src)) = (a, &r) { let new_items = src.borrow().clone(); @@ -51977,6 +61884,19 @@ impl Interpreter { } _ => {} } + self.inplace_binop_fallback(a, b, op, globals) + } + + /// `a = b` past the in-place method (none, or its `NotImplemented`) + /// for an `a` the built-in containers' in-place arms don't take: the + /// regular operator, its failure naming the augmented one. + pub(crate) fn inplace_binop_fallback( + &mut self, + a: &Object, + b: &Object, + op: BinOpKind, + globals: &Rc>, + ) -> Result { // CPython's `binary_iop1` reports the *augmented* operator in the // failure message ("unsupported operand type(s) for **=: …"). match self.dispatch_binary_op(a, b, op, globals) { @@ -52025,39 +61945,65 @@ impl Interpreter { return self.dispatch_binary_op(&a2, &b2, op, globals); } } - let (dunder, rdunder) = binop_dunders(op); - // Two plain instances of one class whose `op` is a plain Python - // method and that has no reflected one: CPython calls the method - // alone, and a `NotImplemented` from it is the TypeError below. The - // method is called with the instances, with no bound method built. - if let (Object::Instance(ai), Object::Instance(bi)) = (a, b) { - let k = op as usize; - if std::ptr::eq(ai.cls_raw(), bi.cls_raw()) - && ai.native.get().is_none() - && Self::class_lacks( - ai.cls_raw(), - crate::types::AttrKey::vm(crate::types::vm_key::RBINOP + k as u32), - rdunder, - ) - { - if let Some(f) = Self::instance_dunder_function( - ai, - crate::types::AttrKey::vm(crate::types::vm_key::BINOP + k as u32), - dunder, - ) { - let r = self.call_dunder_function(f, &[a.clone(), b.clone()])?; - if !r.is_same(&crate::vm_singletons::not_implemented()) { - return Ok(r); - } - return Err(type_error(format!( - "unsupported operand type(s) for {}: '{}' and '{}'", - op.as_str(), - a.type_name_owned(), - b.type_name_owned() - ))); + // A `list` or `tuple` subclass's instance that keeps its base's + // arithmetic (`L(xs) + L(ys)`, `T(xs) * 2`): its payload's + // concatenation or repetition, a plain list or tuple as the + // base's method returns. + if let Some(r) = Self::seq_payload_binop(a, b, op) { + return r; + } + // An `int` or `float` subclass's instance that keeps its base's + // methods for the operator (an `IntEnum` member) with another, or + // with a plain number: the numbers' operation, which the base's + // method comes to (`sum`, `functools.reduce`, the `operator` + // functions). + if matches!(a, Object::Instance(_)) || matches!(b, Object::Instance(_)) { + if let (Some(x), Some(y)) = ( + Self::binop_number_payload(a, op), + Self::binop_number_payload(b, op), + ) { + return self.dispatch_binary_op(&x, &y, op, globals); + } + } + // A natively served left operand (a `datetime`, `date`, + // `timedelta` or `Decimal`): the operation in place, as compiled + // code's `BINARY_OP` has it (`sum`, `functools.reduce`, the + // `operator` functions). + if let Object::Instance(ia) = a { + if ia.cls_raw().native_kind.get() != 0 { + if let Some(r) = Self::core_native_binop(op, a, b) { + return r; } } } + let (dunder, rdunder) = binop_dunders(op); + // The one Python method CPython's `binary_op1` would run (see + // `binop_instance_dunder`: two plain instances of one class, whose + // reflected method is never tried, or an instance over a built-in + // scalar; and `binop_reflected_dunder`: a plain number over an + // instance), found through the class's cache and called with the + // operands, with no bound method built. Its `NotImplemented` is the + // TypeError below. + let direct = Self::binop_instance_dunder(a, b, op, false) + .map(|f| (f, false)) + .or_else(|| Self::binop_reflected_dunder(a, b, op).map(|f| (f, true))); + if let Some((f, reflected)) = direct { + let args = if reflected { + [b.clone(), a.clone()] + } else { + [a.clone(), b.clone()] + }; + let r = self.call_dunder_function(f, &args)?; + if !r.is_same(&crate::vm_singletons::not_implemented()) { + return Ok(r); + } + return Err(type_error(format!( + "unsupported operand type(s) for {}: '{}' and '{}'", + op.as_str(), + a.type_name_owned(), + b.type_name_owned() + ))); + } if tsdbg() { eprintln!( "[TSDBG] vm dispatch_binary_op {op:?} a={} ({:?}) b={} ({:?})", @@ -52343,8 +62289,46 @@ impl Interpreter { op, BinOpKind::BitOr | BinOpKind::BitAnd | BinOpKind::Sub | BinOpKind::BitXor ) { + // A keys view against a view or a set: on their tables. + if let Some(v) = keys_view_algebra(a, b, op) { + return Ok(v); + } let a_elems = dict_view_set_elems(a); let b_elems = dict_view_set_elems(b); + if op == BinOpKind::BitAnd && (a_elems.is_some() || b_elems.is_some()) { + // CPython's `_PyDictView_Intersect` keeps the elements of + // the operand it walks: the view's when the other is a + // `set` at least as long (`set.intersection(view)`) or a + // longer view, else the other's. + let (view_elems, other, other_elems) = match a_elems { + Some(e) => (e, b, b_elems), + None => (b_elems.expect("one is a view"), a, None), + }; + let (keep_view, other_elems) = match other_elems { + Some(e) => (e.len() > view_elems.len(), e), + None => { + let set_len = match other { + Object::Set(s) => Some(s.borrow().len()), + _ => None, + }; + let e = self.collect_iterable(other, globals)?; + (set_len.is_some_and(|n| view_elems.len() <= n), e) + } + }; + let (walk, probe) = if keep_view { + (view_elems, other_elems) + } else { + (other_elems, view_elems) + }; + let probe = Object::new_set_from(probe); + let mut kept = Vec::new(); + for x in walk { + if probe.contains(&x)? { + kept.push(x); + } + } + return Ok(Object::new_set_from(kept)); + } if a_elems.is_some() || b_elems.is_some() { let left = match a_elems { Some(e) => Object::new_set_from(e), @@ -52396,6 +62380,25 @@ impl Interpreter { if let Some(out) = percent_render_plain_value(t, b) { return Ok(Object::from_str(out)); } + // A tuple subclass's instance (a namedtuple's `repr_fmt % + // self`) of scalars and strings: the native engine over its + // tuple (an error is the general engine's to raise). + if let Object::Instance(inst) = b { + if let Some(args @ Object::Tuple(_)) = inst.native.get() { + if percent_leaf_args(args) && !percent_args_need_bridge(args) { + if let Ok(out) = percent_format(t, args) { + return Ok(Object::from_str(out)); + } + } + } + } + // (Plain instances first: the payloads' path takes none.) + if let Some(out) = self.percent_bare_s(t, b, globals) { + return out.map(Object::from_str); + } + if let Some(out) = percent_format_payloads_checked(t, b) { + return Ok(Object::from_str(out)); + } } if a.is_str() { // Surrogate-aware printf: a `WStr` template (and any `WStr` @@ -52435,6 +62438,11 @@ impl Interpreter { _ => return Ok(None), }; Ok(Some(s)) + } else if let (Object::MappingProxy(_) | Object::MappingProxyObj(_), 's') = + (obj, kind) + { + // A `mappingproxy`'s `str()` is its mapping's. + Ok(Some(self.stringify(obj, globals)?)) } else { Ok(None) } @@ -52449,6 +62457,71 @@ impl Interpreter { self.bytes_percent_format(a, b, globals) } + /// `template % args` for a `template` whose conversions are all bare + /// `%s` (or a literal `%%`), one for each argument (`args` a tuple of + /// them, or one object), each a `str`, an `int`, or a plain instance, + /// at least one an instance: the text in one pass, an instance's as the + /// general engine renders it ([`Self::stringify`], its `__str__` + /// frameless when a pure leaf). `None` for anything else (a count that + /// doesn't match, another kind of argument), which the general engine + /// formats or raises for. + fn percent_bare_s( + &mut self, + template: &str, + args: &Object, + globals: &Rc>, + ) -> Option> { + let items: &[Object] = match args { + Object::Tuple(t) => &t[..], + other => std::slice::from_ref(other), + }; + let plain = |o: &Object| matches!(o, Object::Instance(i) if i.native.get().is_none()); + if !items.iter().any(plain) + || !items + .iter() + .all(|o| plain(o) || matches!(o, Object::Str(_) | Object::Int(_))) + { + return None; + } + let b = template.as_bytes(); + let (mut n, mut i) = (0, 0); + while let Some(at) = memchr::memchr(b'%', &b[i..]) { + match b.get(i + at + 1) { + Some(b's') => n += 1, + Some(b'%') => {} + _ => return None, + } + i += at + 2; + } + if n != items.len() { + return None; + } + let mut out = String::with_capacity(template.len() + 8 * n); + let (mut k, mut i) = (0, 0); + while let Some(at) = memchr::memchr(b'%', &b[i..]) { + out.push_str(&template[i..i + at]); + if b[i + at + 1] == b'%' { + out.push('%'); + } else { + match &items[k] { + Object::Str(s) => out.push_str(s), + Object::Int(v) => { + use std::fmt::Write as _; + let _ = write!(out, "{v}"); + } + obj => match self.stringify(obj, globals) { + Ok(text) => out.push_str(&text), + Err(e) => return Some(Err(e)), + }, + } + k += 1; + } + i += at + 2; + } + out.push_str(&template[i..]); + Some(Ok(out)) + } + /// PEP 461 `bytes % args` / `bytearray % args`. The template is decoded /// latin-1 so it can share the text `%`-engine, then re-encoded; the /// result type follows the left operand. `%s`/`%b` dispatch `__bytes__` @@ -52459,6 +62532,11 @@ impl Interpreter { b: &Object, globals: &Rc>, ) -> Result { + if let Object::Bytes(t) = a { + if let Some(out) = bytes_percent_simple(t, b) { + return Ok(Object::new_bytes(out)); + } + } let template: String = match a { Object::Bytes(t) => t.iter().map(|x| *x as char).collect(), Object::ByteArray(t) => t.borrow().iter().map(|x| *x as char).collect(), @@ -52574,6 +62652,40 @@ impl Interpreter { /// Python function, from the class's cache (see /// [`Self::instance_dunder_function`]): called with `x` first, it is /// what [`Self::cmp_method`] binds. + /// Whether `x`'s method for the ordering `op` (`<`, `<=`, `>`, `>=`) + /// is `object`'s own, which always answers `NotImplemented`: the + /// comparison goes straight on to the other operand's, with no bound + /// method built and called. Cached on the class per version. + fn cmp_object_default(x: &Object, op: CompareKind) -> bool { + use crate::types::LeafAttrKind as K; + if matches!(op, CompareKind::Eq | CompareKind::NotEq) { + return false; + } + let Object::Instance(inst) = x else { + return false; + }; + let cls = inst.cls_raw(); + let key = crate::types::AttrKey::vm(crate::types::vm_key::CMP_OBJECT + op as u32); + let ver = cls.attr_version.get(); + match cls.leaf_attrs.get(key, ver) { + Some(K::InstanceOnly) => true, + Some(_) => false, + None => { + if crate::object::exotic_str_keys_possible() { + return false; + } + let default = matches!( + cls.lookup_with_owner(cmp_dunder(op).0), + Some((Object::Builtin(_), owner)) + if Rc::ptr_eq(&owner, &builtin_types().object_) + ); + cls.leaf_attrs + .set(key, ver, if default { K::InstanceOnly } else { K::Other }); + default + } + } + } + fn cmp_function(x: &Object, op: CompareKind) -> Option> { let Object::Instance(inst) = x else { return None; @@ -52624,6 +62736,38 @@ impl Interpreter { if let Some(r) = native_scalar_compare(a, b, op) { return Ok(r); } + // (The two lanes below need an instance that carries a payload: a + // pair of plain instances, a heap's or a sort's items, skips them.) + let carries = |v: &Object| matches!(v, Object::Instance(i) if i.native.get().is_some()); + if carries(a) || carries(b) { + // A named tuple (or another list or tuple subclass that keeps + // its base's comparisons) against one, or a plain list or + // tuple: the payloads' comparison. + if let Some((x, y, op)) = Self::seq_cmp_payloads(a, b, op) { + return self.dispatch_compare_op(x, y, op, globals); + } + // Likewise an `IntEnum` member (or another `int` or `float` + // subclass's instance that keeps its base's comparisons) + // against one, or a plain number. + if let Some((x, y)) = Self::num_cmp_payloads(a, b, op) { + return self.dispatch_compare_op(&x, &y, op, globals); + } + } + // A natively served pair (see `rich_compare_obj`), ahead of the + // layers between here and there. + if let Object::Instance(ia) = a { + if ia.cls_raw().native_kind.get() != 0 { + if let Some(Ok(Object::Bool(r))) = Self::core_native_compare(op, a, b) { + return Ok(r); + } + } + } + // A plain instance's pure-leaf comparison method, evaluated in + // place (`min`/`max`, `in` and `list.index` over a class's + // instances), ahead of the protocol's lookups and call layers. + if let Some(r) = self.leaf_compare_dunder(a, b, op) { + return Ok(r); + } // CPython's `PyObject_RichCompareBool` truth-tests the comparison // *result* with `PyObject_IsTrue`, so `arr == x` yielding a // multi-element numpy bool array raises "truth value ... ambiguous" @@ -52734,6 +62878,40 @@ impl Interpreter { if let Some(r) = plain_compare(a, b, op) { return Ok(Object::Bool(r)); } + // A named tuple (or another list or tuple subclass that keeps its + // base's comparisons) against one, or a plain list or tuple: the + // payloads' comparison, which the base's method comes to. + if let Some((x, y, op)) = Self::seq_cmp_payloads(a, b, op) { + return self.rich_compare_obj(x, y, op, globals); + } + // Likewise an `IntEnum` member (or another `int` or `float` + // subclass's instance that keeps its base's comparisons) against + // one, or a plain number. + if let Some((x, y)) = Self::num_cmp_payloads(a, b, op) { + return self.rich_compare_obj(&x, &y, op, globals); + } + // A natively served pair (two `datetime`s, `date`s, `time`s, + // `timedelta`s or `Decimal`s): compared in place, as compiled + // code's `COMPARE_OP` compares them, for the native algorithms + // (`sorted`, `max`, `in`, `bisect`, a tuple's items). + if let Object::Instance(ia) = a { + if ia.cls_raw().native_kind.get() != 0 { + if let Some(Ok(r @ Object::Bool(_))) = Self::core_native_compare(op, a, b) { + return Ok(r); + } + } + } + // A struct sequence compares as its tuple, against a tuple or one + // of its own type (`sys.version_info >= (3, 8)`). (A struct + // sequence's class is a builtin one: a user class's instances skip + // the check.) + let builtin_instance = + |o: &Object| matches!(o, Object::Instance(i) if i.cls_raw().flags.is_builtin); + if builtin_instance(a) || builtin_instance(b) { + if let Some((ta, tb)) = crate::stdlib::os::struct_seq_compare_operands(a, b) { + return self.rich_compare_obj(&ta, &tb, op, globals); + } + } // Two instances whose left one's comparison dunder is a Python // function, and whose right one's class doesn't subclass the left's // (which would try its reflected dunder first): the forward call @@ -52754,9 +62932,172 @@ impl Interpreter { } } } + // `a > b` of a class that defines only `__lt__`: the reflected + // method directly (see `compare_reflected_dunder`). + if !forward_ran { + if let Some(f) = Self::compare_reflected_dunder(a, b, op) { + let r = self.call_dunder_function(f, &[b.clone(), a.clone()])?; + if !r.is_same(&crate::vm_singletons::not_implemented()) { + return Ok(r); + } + } + } self.rich_compare_rest(a, b, op, globals, forward_ran) } + /// The reflected Python method a comparison of two instances of one + /// plain class calls when the class's method for `op` is `object`'s + /// own (which answers `NotImplemented`): `a > b` of a class defining + /// only `__lt__` is `b.__lt__(a)`, CPython's `do_richcompare` order. + pub(crate) fn compare_reflected_dunder( + a: &Object, + b: &Object, + op: CompareKind, + ) -> Option> { + let (Object::Instance(ia), Object::Instance(ib)) = (a, b) else { + return None; + }; + let cls = ia.cls_raw(); + if !std::ptr::eq(cls, ib.cls_raw()) + || ia.native.get().is_some() + || ib.native.get().is_some() + || cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || !Self::cmp_object_default(a, op) + { + return None; + } + Self::cmp_function(b, cmp_swapped(op)) + } + + /// Whether `x`'s class's `__ne__` is `object`'s, which answers + /// `not a.__eq__(b)` for a bool (`a != b` of a class defining only + /// `__eq__`), remembered for the class's version. + pub(crate) fn ne_inverts_eq(x: &Object) -> bool { + use crate::types::LeafAttrKind as K; + let Object::Instance(inst) = x else { + return false; + }; + let cls = inst.cls_raw(); + if inst.native.get().is_some() || cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 { + return false; + } + // (`cmp_object_default` keeps no entry under this key: it answers + // `false` for `==` and `!=`.) + let key = + crate::types::AttrKey::vm(crate::types::vm_key::CMP_OBJECT + CompareKind::NotEq as u32); + let ver = cls.attr_version.get(); + match cls.leaf_attrs.get(key, ver) { + Some(K::InstanceOnly) => true, + Some(_) => false, + None => { + if crate::object::exotic_str_keys_possible() { + return false; + } + let default = matches!( + cls.lookup_with_owner("__ne__"), + Some((Object::Builtin(_), owner)) + if Rc::ptr_eq(&owner, &builtin_types().object_) + ); + cls.leaf_attrs + .set(key, ver, if default { K::InstanceOnly } else { K::Other }); + default + } + } + } + + /// The Python method `a b` runs first for a plain instance `a`, + /// as `(method, swapped, inverted)`: `a`'s own, the reflected one of a + /// class defining only the other ordering (called as `f(b, a)`), or + /// `__eq__` for a `!=` that `object.__ne__` answers (its bool answer + /// inverted). `None` for anything else. + fn compare_dunder_target( + a: &Object, + b: &Object, + op: CompareKind, + ) -> Option<(Rc, bool, bool)> { + if !matches!(a, Object::Instance(_)) { + return None; + } + if let Some(f) = Self::compare_instance_dunder(a, b, op) { + Some((f, false, false)) + } else if let Some(f) = Self::compare_reflected_dunder(a, b, op) { + Some((f, true, false)) + } else if matches!(op, CompareKind::NotEq) && Self::ne_inverts_eq(a) { + Some(( + Self::compare_instance_dunder(a, b, CompareKind::Eq)?, + false, + true, + )) + } else { + None + } + } + + /// `a b` of two plain instances inside a leaf evaluation at call + /// nesting `nest` (`self != other` in `total_ordering`'s `__gt__`): + /// the method [`Self::compare_dunder_target`] names, evaluated as a + /// nested leaf call is, when it answers a bool. `None` (nothing run + /// that matters) for anything else, which declines the evaluation. + pub(crate) fn leaf_compare_nested( + &self, + a: &Object, + b: &Object, + op: CompareKind, + nest: u8, + ) -> Option { + if nest >= leaf_plan::NEST || !matches!(b, Object::Instance(_)) { + return None; + } + let (f, swap, invert) = Self::compare_dunder_target(a, b, op)?; + // SAFETY: GIL-serialized raw read of the function's code cell. + let code: &Rc = unsafe { &*f.code.as_ptr() }; + if !code_is_pure_leaf(code) + || !Self::leaf_code_ok(code) + || leaf_arity(code) != 2 + || code.has_varkeywords + || crate::recursion::current_depth() + usize::from(nest) + 1 + >= crate::recursion::recursion_limit() + { + return None; + } + let (x, y) = if swap { (b, a) } else { (a, b) }; + let ptrs = [std::ptr::from_ref(x), std::ptr::from_ref(y)]; + match self.leaf_eval_nested(code, &f, &ptrs, nest + 1)? { + leaf_plan::LeafRet::Borrowed(leaf_plan::V::B(r)) => Some(r != invert), + leaf_plan::LeafRet::Owned(Object::Bool(r)) => Some(r != invert), + _ => None, + } + } + + /// `a b`'s truth when it is a plain instance's comparison method + /// that is a warm pure leaf answering a bool: `a`'s own method, the + /// reflected one of a class defining only the other ordering (`max` of + /// a class with `__lt__`), or `__eq__` inverted for a `!=` that + /// `object.__ne__` answers. `None` (nothing run that matters: a leaf + /// has no effects) for anything else, which the full protocol decides. + fn leaf_compare_dunder(&self, a: &Object, b: &Object, op: CompareKind) -> Option { + let (f, swap, invert) = Self::compare_dunder_target(a, b, op)?; + // SAFETY: GIL-serialized raw read of the function's code cell. + let code = unsafe { &*f.code.as_ptr() }; + if code.arg_count != 2 + || !crate::code_is_pure_leaf(code) + || !crate::pure_leaf_warm(code) + || crate::recursion::current_depth() >= crate::recursion::recursion_limit() + { + return None; + } + let (x, y) = if swap { (b, a) } else { (a, b) }; + let ptrs = [std::ptr::from_ref(x), std::ptr::from_ref(y)]; + match self.pure_leaf_eval::(code, &f, &ptrs)? { + Object::Bool(r) => Some(r != invert), + v => { + drop(v); + None + } + } + } + /// [`Self::rich_compare_obj`] past its first steps: the whole protocol, /// or, with `forward_ran`, what follows `a`'s own method (a plain /// function, see [`Self::cmp_function`]) having answered @@ -52935,6 +63276,9 @@ impl Interpreter { if !r.is_same(¬_impl) { return Ok(r); } + } else if Self::cmp_object_default(a, op) { + // (`object`'s ordering answers `NotImplemented`.) + a_slot_ran = true; } else if let Some(method) = self.cmp_method(a, dunder, globals) { a_slot_ran = true; let r = self.call(&method, std::slice::from_ref(b), &[], globals)?; @@ -52968,6 +63312,8 @@ impl Interpreter { if !r.is_same(¬_impl) { return Ok(r); } + } else if Self::cmp_object_default(b, cmp_swapped(op)) { + b_slot_ran = true; } else if let Some(method) = self.cmp_method(b, swapped, globals) { b_slot_ran = true; let r = self.call(&method, std::slice::from_ref(a), &[], globals)?; @@ -53141,6 +63487,7 @@ impl Interpreter { match y { Object::DictView(v) => match v.kind { crate::object::DictViewKind::Keys => { + crate::builtins::ensure_dict_key(item)?; Ok(crate::builtins::dict_lookup(&v.dict, item)?.is_some()) } crate::object::DictViewKind::Items => { @@ -53150,6 +63497,7 @@ impl Interpreter { if t.len() != 2 { return Ok(false); } + crate::builtins::ensure_dict_key(&t[0])?; match crate::builtins::dict_lookup(&v.dict, &t[0])? { None => Ok(false), Some(found) => Ok(found.is_same(&t[1]) @@ -54859,7 +65207,7 @@ impl Interpreter { // generic path detaches but this fast path leaks a // live cursor (test_list.test_exhausted_iterator, // test_tier2_invalidates_iterator). - *items = Rc::new(RefCell::new(Vec::new())); + *items = crate::object::detached_store(); drop(it); frame.pop()?; frame.pc += jump_arg; @@ -55232,6 +65580,50 @@ impl Interpreter { } } + /// [`Self::dicts_equal`] where no code runs: every key of `xs` settles + /// by native equality in `ys` (see [`crate::object::LeafProbe`]) and + /// each pair of values is the same object or two plain scalars of one + /// kind, compared in place under one view of each dict. `None` + /// (nothing decided, nothing touched) at the first key or value that + /// needs more. + fn dicts_equal_native(xs: &Rc>, ys: &Rc>) -> Option { + // SAFETY: reads that run no code; the views end with this call. + let (a, b) = unsafe { (xs.peek()?, ys.peek()?) }; + if a.len() != b.len() { + return Some(false); + } + for ((hash, k), (_, v)) in a.hashed_keys().zip(a.iter()) { + // (A tuple of plain scalars is probed by the hash its entry + // stores, the one the probe would compute again.) + let probe = match &k.0 { + Object::Tuple(t) + if t.iter().all(|x| { + matches!(x, Object::Int(_) | Object::Str(_) | Object::Bytes(_)) + }) => + { + crate::object::LeafProbe::with_hash(&k.0, hash) + } + key => crate::object::LeafProbe::new(key)?, + }; + let Some(w) = b.get(&probe) else { + return probe.miss_is_exact().then_some(false); + }; + if v.is_same(w) { + continue; + } + let eq = match (v, w) { + (Object::None, Object::None) => true, + (Object::Bool(p), Object::Bool(q)) => p == q, + (Object::Bytes(p), Object::Bytes(q)) => p[..] == q[..], + _ => native_scalar_compare(v, w, CompareKind::Eq)?, + }; + if !eq { + return Some(false); + } + } + Some(true) + } + /// `dict == dict` (CPython `dict_equal`): same length, same keys, each /// key mapping to an equal value. Both mappings are snapshotted before /// recursing so a user `__eq__` that mutates a dict can't invalidate a @@ -55243,6 +65635,9 @@ impl Interpreter { ys: &Rc>, globals: &Rc>, ) -> Result { + if let Some(eq) = Self::dicts_equal_native(xs, ys) { + return Ok(eq); + } let xs: Vec<(DictKey, Object)> = xs .borrow() .iter() @@ -55478,6 +65873,9 @@ impl Interpreter { }; *ty.qualname.borrow_mut() = Some(s.to_string()); ty.forget_display_names(); + // (Sites that remember what the class's names read hold them + // for its version.) + ty.bump_attr_version(); return Ok(()); } // The `type.__dict__` / `type.__mro__` getsets have no setter in @@ -55530,14 +65928,43 @@ impl Interpreter { } return Ok(()); } - ty.dict + // The object the name already holds, stored again (a flag set per + // instance: `finalize._dirty = True`): nothing a lookup resolves + // changes, so the class keeps its version, and every site that + // remembered a resolution of it keeps that. (A watcher is still + // owed the store.) + if !crate::capi_watchers::types_active() + && ty.dict.try_borrow().is_ok_and(|d| { + d.get(&crate::object::StrKey(name)) + .is_some_and(|held| held.is_same(&value)) + }) + { + return Ok(()); + } + let inert = ty.dict.try_borrow().is_ok_and(|d| { + d.get(&crate::object::StrKey(name)) + .is_some_and(|held| inert_class_values(held, &value)) + }); + let replaced = ty + .dict .borrow_mut() - .insert(DictKey(Object::from_str(name)), value); + .insert(DictKey(Object::from_str(name)), value) + .is_some(); // Any class-attribute write can change what instance attribute // lookups resolve to (e.g. installing a `property` over a name // instances carry in `__dict__`); advance the resolution version - // so specialised LOAD_ATTR/STORE_ATTR sites deopt. - ty.bump_attr_version(); + // so specialised LOAD_ATTR/STORE_ATTR sites deopt. (A heap class's + // plain name whose entry's value was replaced in place moves no + // name on the MRO: the lookup cache stands.) + if replaced && !ty.flags.is_builtin && !name.starts_with("__") { + if inert { + ty.bump_attr_version_inert(); + } else { + ty.bump_attr_version_values(); + } + } else { + ty.bump_attr_version(); + } // PyType_Watch dispatch (test_capi.test_watchers): a modification // of this type fires watchers on it and on any watched subclass, // with CPython's version-tag aggregation. @@ -55883,10 +66310,28 @@ impl Interpreter { // ambient lookup namespace (RFC 0052 WS5), so no // mirroring is needed: this plain insert is immediately // visible to every frame's name resolution. - let old = m - .dict - .borrow_mut() - .insert(DictKey(Object::from_str(name)), value); + // (A name the module already holds is rebound in place, as + // `STORE_GLOBAL` rebinds it: the keys stay put, so the dict + // isn't stamped and the module's cached global loads + // stand; the value epoch moves instead. Not the builtins: + // sites that fuse a builtin's call, `len(x)` say, hold + // only that dict's stamp against `builtins.len = f`.) + let in_place = !Rc::ptr_eq(&m.dict, &self.builtins); + let old = { + let mut d = m.dict.borrow_mut(); + match d + .get_index_of(&crate::object::StrKey(name)) + .filter(|_| in_place) + { + Some(i) => { + crate::object::bump_global_value_epoch(); + d.map_mut_value_store() + .get_index_mut(i) + .map(|(_, slot)| std::mem::replace(slot, value)) + } + None => d.insert(DictKey(Object::from_str(name)), value), + } + }; // CPython decrefs the displaced attribute at store time // (`module_setattro` → dict insert), and a module attr // store is just a global rebind spelled from outside, so @@ -55943,6 +66388,7 @@ impl Interpreter { self.settle_lazy(); f.kwonly_memo.set(0); crate::frame_jit::retire_code(f.code.replace(c)); + crate::rare_events::note_func_edit(); f.names_kept.set(0); crate::rare_events::bump(crate::rare_events::FUNC_MODIFICATION); if crate::capi_watchers::funcs_active() { @@ -56428,6 +66874,19 @@ impl Interpreter { self.generic_setattr_instance_with_name(inst, obj, name, value, None) } + /// [`Self::generic_setattr_instance`] for a name held as a `str` + /// object (`object.__setattr__`'s argument): no copy of its text, and + /// the object itself goes to the intern pool. + pub(crate) fn generic_setattr_instance_shared( + &mut self, + inst: &Rc, + obj: &Object, + name: &SharedStr, + value: Object, + ) -> Result<(), RuntimeError> { + self.generic_setattr_instance_with_name(inst, obj, name, value, Some(name)) + } + fn generic_setattr_instance_with_name( &mut self, inst: &Rc, @@ -56692,7 +67151,10 @@ impl Interpreter { } else { None }; - let key = crate::stdlib::sys::intern_name(name); + let key = match shared_name { + Some(shared) => Object::Str(crate::stdlib::sys::intern_shared_memo(shared)), + None => crate::stdlib::sys::intern_name(name), + }; let mut value = Some(value); let old = 'store: { // The split layout, while the instance keeps one (and no @@ -57196,6 +67658,14 @@ impl Interpreter { Object::Instance(i) => i.cls().lookup("__fspath__"), _ => None, }; + // A `pathlib` path whose string is cached: `pathlib`'s own + // `__fspath__` returns `str(self)`, which its own `__str__` + // answers from the `_str` slot, with no code to run. + if let (Object::Instance(inst), Some(Object::Function(f))) = (obj, &raw) { + if let Some(s) = Self::pathlib_cached_str(inst, f) { + return Ok(s); + } + } match raw { Some(m) if !matches!(m, Object::None) => { let method = @@ -57408,6 +67878,33 @@ impl Interpreter { // (`range(-maxsize, maxsize)[maxsize + 1]`, // `range(0, maxsize**10, 2*maxsize)[maxsize + 1]` — // test_large_range). + // (A range and an index of machine ints whose item is one + // too: the same arithmetic at machine width, and anything + // that doesn't fit goes on below.) + if let (None, Object::Int(i)) = (&r.big, index) { + let (start, stop, step) = (r.start, r.stop, r.step); + let span = if step > 0 { + stop.checked_sub(start) + } else { + start.checked_sub(stop) + }; + let item = span.and_then(|span| { + let len = if span > 0 { + (span - 1) / step.abs() + 1 + } else { + 0 + }; + let idx = i128::from(*i) + if *i < 0 { len } else { 0 }; + if idx < 0 || idx >= len { + return Some(Err(index_error("range object index out of range"))); + } + let v = idx.checked_mul(step)?.checked_add(start)?; + Some(Ok(Object::Int(i64::try_from(v).ok()?))) + }); + if let Some(item) = item { + return item; + } + } use num_bigint::BigInt; let len = crate::object::range_len_bigint(r); let i = match index { @@ -57428,8 +67925,13 @@ impl Interpreter { // exactly (`len()` would truncate/overflow — CPython's // `compute_slice` works on PyLongs; test_slice // test_indices sweeps ±2**100). - let len = crate::object::range_len_bigint(r); - range_slice(r, len, slc) + match range_slice_small(r, slc) { + Some(sliced) => Ok(sliced), + None => { + let len = crate::object::range_len_bigint(r); + range_slice(r, len, slc) + } + } } (Object::Bytes(buf), Object::Int(i)) => { let idx = normalize_index(*i, buf.len())?; @@ -57454,6 +67956,10 @@ impl Interpreter { "operation forbidden on released memoryview object", )); } + // (A plain view of bytes: the byte, read where it is.) + if let Some(byte) = mv_plain_byte(mv, *i) { + return Ok(Object::Int(i64::from(byte))); + } let shape = mv.shape_dims(); // CPython `memory_item`: integer indexing is 1-D only — // 0-dim is a TypeError, deeper views NotImplementedError. @@ -57544,7 +68050,8 @@ impl Interpreter { "operation forbidden on released memoryview object", )); } - if mv.shape_dims().is_empty() { + // (No dimensions exactly when the view is a scalar one.) + if mv.zero_dim.get() { return Err(type_error("invalid indexing of 0-dim memory")); } // `mv[i:j:k]` is a *sub-view* sharing the same buffer, not a @@ -57717,7 +68224,7 @@ impl Interpreter { // full VM iteration protocol so objects that are only // legacy-iterable (`__getitem__`, no `__iter__`) work. let replacement = match &value { - Object::List(l) => l.borrow().clone(), + Object::List(l) => crate::object::cloned_vec(&l.borrow()), Object::Tuple(t) => t.iter().cloned().collect::>(), Object::Str(txt) => txt .chars() @@ -57781,54 +68288,43 @@ impl Interpreter { } }; let mut data = b.borrow_mut(); + let (start, stop, step, count) = adjust_slice(data.len() as i64, s)?; + // A plain slice is spliced in the bytes themselves: one move + // of the tail when the length changes, none when it doesn't + // (the buffer's address then stays what ctypes handed out, + // see `_ctypes_native::addressof_buffer`). + if step == 1 { + let start = start as usize; + let stop = (stop as usize).max(start); + if replacement.len() == stop - start { + data[start..stop].copy_from_slice(&replacement); + } else { + crate::object::bytearray_check_resizable(b)?; + data.splice(start..stop, replacement); + } + return Ok(()); + } // CPython (`bytearray_ass_subscript`): assigning an *empty* - // buffer to an extended slice is a deletion — and the + // buffer to an extended slice is a deletion, and the // resizability check runs before the no-op early-out, so an // exported bytearray raises BufferError even for zero-width // slices. - let step = match &s.step { - Object::Int(k) => *k, - _ => 1, - }; - if replacement.is_empty() && step != 1 { + if replacement.is_empty() { crate::object::bytearray_check_resizable(b)?; - let mut indices = slice_indices(data.len(), s)?; - indices.sort_unstable(); - for idx in indices.into_iter().rev() { - data.remove(idx); - } + bytes_delete_strided(&mut data, start, step, count); return Ok(()); } - let mut objs: Vec = data - .iter() - .map(|byte| Object::Int(i64::from(*byte))) - .collect(); - let repl_objs: Vec = replacement - .iter() - .map(|byte| Object::Int(i64::from(*byte))) - .collect(); - apply_slice_assignment(&mut objs, s, repl_objs)?; - if objs.len() == data.len() { - // Same-length write: mutate in place so the backing - // buffer's data pointer stays stable. ctypes - // (`_ctypes_native::addressof_buffer`) hands out raw - // addresses into bytearray storage that must survive - // subsequent same-size writes. - for (dst, o) in data.iter_mut().zip(objs) { - *dst = match o { - Object::Int(v) => v as u8, - _ => unreachable!("bytearray slice splice produced non-int"), - }; - } - } else { - crate::object::bytearray_check_resizable(b)?; - *data = objs - .into_iter() - .map(|o| match o { - Object::Int(v) => v as u8, - _ => unreachable!("bytearray slice splice produced non-int"), - }) - .collect(); + if replacement.len() as i64 != count { + return Err(value_error(format!( + "attempt to assign bytes of size {} to extended slice of size {}", + replacement.len(), + count + ))); + } + let mut at = start; + for byte in replacement { + data[at as usize] = byte; + at += step; } Ok(()) } @@ -57845,6 +68341,21 @@ impl Interpreter { "operation forbidden on released memoryview object", )); } + // (A byte stored into a plain writable view of bytes, where + // it lives.) + if let (false, Object::Int(v @ 0..=255)) = (mv.readonly.get(), &value) { + if let Some(at) = mv_plain_bytes(mv).and_then(|(start, len)| { + let at = if *i < 0 { *i + len as i64 } else { *i }; + (0..len as i64).contains(&at).then(|| start + at as usize) + }) { + let stored = mv + .buffer + .with_write(|all| all.get_mut(at).map(|slot| *slot = *v as u8)); + if stored.flatten().is_some() { + return Ok(()); + } + } + } // CPython `memory_ass_sub` runs `adjust_fmt` *before* the // read-only check: an unsupported format raises // NotImplementedError even on a read-only view. @@ -57940,6 +68451,19 @@ impl Interpreter { "memoryview assignment: lvalue and rvalue have different structures", )); } + // (A run of a plain view of bytes is written at once.) + if step == 1 && slicelen > 0 { + if let Some((start, _)) = mv_plain_bytes(mv) { + let at = start + start_i.max(0) as usize; + let stored = mv.buffer.with_write(|all| { + all.get_mut(at..at + src.len()) + .map(|run| run.copy_from_slice(&src)) + }); + if stored.flatten().is_some() { + return Ok(()); + } + } + } for k in 0..slicelen { let elem = (start_i + k * step).max(0) as usize; let s = k as usize * itemsize; @@ -58166,18 +68690,19 @@ impl Interpreter { } (Object::ByteArray(b), Object::Slice(s)) => { let mut data = b.borrow_mut(); - let mut indices = slice_indices(data.len(), s)?; - indices.sort_unstable(); - indices.dedup(); + let (start, stop, step, count) = adjust_slice(data.len() as i64, s)?; // CPython checks resizability before the zero-width early-out // on the extended-slice path, so `del exported[1:1:2]` raises // BufferError even though nothing would be removed. - let extended = !matches!(&s.step, Object::None | Object::Int(1)); - if extended || !indices.is_empty() { + if step != 1 || count > 0 { crate::object::bytearray_check_resizable(b)?; } - for idx in indices.into_iter().rev() { - data.remove(idx); + // One move of what follows the run (a `remove` per byte moved + // the tail once for each byte deleted). + if step != 1 { + bytes_delete_strided(&mut data, start, step, count); + } else if count > 0 { + data.drain(start as usize..stop as usize); } Ok(()) } @@ -58243,6 +68768,16 @@ impl Interpreter { // chain takes. match (b.name, args.len()) { ("len", 1) => return self.do_len_call(&args[0], outer_globals), + // (The consumers of an iterable the interpreter steps, + // `sum(gen)` and its kin: the chain's arms for them.) + ("sum", _) => return self.do_sum_call(args, kwargs, outer_globals), + ("list" | "tuple", 1) => { + return self.do_list_or_tuple_call(b.name, &args[0], outer_globals) + } + ("min" | "max", _) if !b.binds_instance => { + return self.do_min_max_call(b.name, args, kwargs, outer_globals) + } + ("any" | "all", _) => return self.do_any_all_call(b.name, args, outer_globals), ("hash", 1) => return self.do_hash_call(&args[0], outer_globals), ("isinstance", 2) => { return self.do_isinstance_call(&args[0], &args[1], outer_globals) @@ -58502,12 +69037,9 @@ impl Interpreter { return self.do_iter_call(&args[0], outer_globals); } if b.name == "iter" && !b.binds_instance && args.len() == 2 { - // ``iter(callable, sentinel)`` — return a small - // VM-aware iterator that re-invokes ``callable`` - // each step. Modelled as a Python-side - // generator so the existing FOR_ITER / - // for-loop machinery just works. - return self.do_iter_callable_sentinel(args, outer_globals); + // `iter(callable, sentinel)`: a native + // `callable_iterator`. + return self.do_iter_callable_sentinel(args); } // ``aiter(async_iterable)`` / ``anext(async_iterator[, default])`` // — the PEP 525 async builtins (3.10+). Routed through the @@ -58798,9 +69330,10 @@ impl Interpreter { } } names.sort(); - return Ok(Object::new_list( - names.into_iter().map(Object::from_str).collect(), - )); + let out = + Object::new_list(names.into_iter().map(Object::from_str).collect()); + gc_trace::track_built(&out); + return Ok(out); } if b.name == "breakpoint" { return self.do_breakpoint_call(args, kwargs, outer_globals); @@ -58912,7 +69445,12 @@ impl Interpreter { let globals_arg = args.get(1).cloned().or_else(|| kwarg("globals")); let import_globals = match globals_arg { Some(Object::Dict(d)) => d, - Some(Object::None) | None if level > 0 => { + // CPython's `resolve_name`: any other object + // given for a relative import's `globals`. + Some(_) if level > 0 => { + return Err(type_error("globals must be a dict")) + } + None if level > 0 => { return Err(RuntimeError::PyException( crate::error::PyException::from_builtin( "KeyError", @@ -59051,6 +69589,19 @@ impl Interpreter { // first iterate them into out-of-range int items. `list.extend` // always iterates, so this is restricted to a bytearray // receiver. + // `list.extend(it)` / `set.update(it)` of an exact list + // or set over an iterable only the interpreter can step: + // each item added as it comes, as CPython's + // `list_extend_iter` and `set_update_internal` add them + // (a generator that reads the receiver sees it grow). + if args.len() == 2 + && object_needs_vm_iter(&args[1]) + && ((b.name == "extend" && matches!(args[0], Object::List(_))) + || (b.name == "update" && matches!(args[0], Object::Set(_)))) + && Self::is_container_method(b, &args[0]) + { + return self.extend_live(&args[0], &args[1], outer_globals); + } if b.name == "extend" && matches!(args.first(), Some(Object::ByteArray(_))) && args.get(1).is_some_and(|a| { @@ -59071,6 +69622,13 @@ impl Interpreter { { return (b.call)(args); } + // (A plain instance's method of one of these names, a + // native method of a class written in Python such as + // `deque.extend`, takes its iterable as it comes.) + let plain_receiver = matches!( + args.first(), + Some(Object::Instance(i)) if i.native.get().is_none() + ); if matches!( b.name, "join" @@ -59089,6 +69647,7 @@ impl Interpreter { | "isdisjoint" | "writelines" ) && !(b.name == "update" && !receiver_is_native_set(args.first())) + && !(plain_receiver && b.binds_instance) { // `fromkeys` may take its iterable in slot 0 (unbound // classmethod form); the others iterate args[1..]. @@ -59145,7 +69704,10 @@ impl Interpreter { // `Object::make_iter`, which can't drive generator frames or // a user `__iter__` — materialise those eagerly, like the // free-function consumers above. - if b.name == "extend" && args.get(1).is_some_and(needs_vm_iter) { + if b.name == "extend" + && !(plain_receiver && b.binds_instance) + && args.get(1).is_some_and(needs_vm_iter) + { let collected = self.collect_iterable(&args[1], outer_globals)?; let mut new_args = args.to_vec(); new_args[1] = Object::new_list(collected); @@ -59350,9 +69912,7 @@ impl Interpreter { ))) } }; - if let (Object::WStr(_), Some(d)) = - (&args[1], crate::builtins::wstr_attr_dict(&args[0])) - { + if let Some(d) = crate::builtins::wstr_name_dict(&args[1], &args[0]) { d.borrow_mut() .insert(DictKey(args[1].clone()), args[2].clone()); return Ok(Object::None); @@ -59370,9 +69930,7 @@ impl Interpreter { ))) } }; - if let (Object::WStr(_), Some(d)) = - (&args[1], crate::builtins::wstr_attr_dict(&args[0])) - { + if let Some(d) = crate::builtins::wstr_name_dict(&args[1], &args[0]) { if d.borrow_mut() .shift_remove(&DictKey(args[1].clone())) .is_some() @@ -59479,7 +70037,16 @@ impl Interpreter { } } None => String::new(), - Some(_) => return Err(type_error("format() spec must be a string")), + Some(other) => { + let name = if matches!(other, Object::None) { + "None".to_owned() + } else { + other.type_name().to_string() + }; + return Err(type_error(format!( + "format() argument 2 must be str, not {name}" + ))); + } }; let bridged = matches!(args.first(), Some(Object::WStr(_))) || matches!(args.get(1), Some(Object::WStr(_))); @@ -60087,6 +70654,18 @@ impl Interpreter { return None; } let bt = builtin_types(); + // A struct sequence from a tuple or list (`os.terminal_size((80, + // 24))`), filled directly. (The core containers aren't: their + // calls skip the registry scan.) + if matches!(arg, Object::Tuple(_) | Object::List(_)) + && ![&bt.list_, &bt.tuple_, &bt.dict_, &bt.set_, &bt.frozenset_] + .iter() + .any(|c| Rc::ptr_eq(ty, c)) + { + if let Some(v) = crate::stdlib::os::struct_seq_from_sequence(ty, arg) { + return Some(Ok(v)); + } + } // `str(x)`: `x`'s `__str__` (see `type_call_default`). if Rc::ptr_eq(ty, &bt.str_) { let globals = self.builtins.clone(); @@ -60100,6 +70679,13 @@ impl Interpreter { }; let globals = self.builtins.clone(); self.do_list_or_tuple_call(name, arg, &globals) + } else if Rc::ptr_eq(ty, &bt.dict_) { + // `dict(x)`: a mapping or a lazy iterable of pairs through the + // VM, an eager container of pairs by the plain builtin. + match self.dict_from_one(arg) { + Some(r) => r, + None => crate::builtins::b_dict(std::slice::from_ref(arg)), + } } else if Rc::ptr_eq(ty, &bt.set_) || Rc::ptr_eq(ty, &bt.frozenset_) { let is_set = Rc::ptr_eq(ty, &bt.set_); if matches!( @@ -60153,7 +70739,7 @@ impl Interpreter { } // CPython tracks every set (as `b_set` does). let obj = Object::Set(Rc::new(RefCell::new(out))); - gc_trace::track(&obj); + gc_trace::track_built(&obj); Ok(obj) } @@ -61163,7 +71749,7 @@ impl Interpreter { }; let ns_obj: Option = match prep { Some(p) => { - let bases_tuple = Object::new_tuple(bases.to_vec()); + let bases_tuple = Object::tuple_from_slice(bases); let result = self.call( &p, &[Object::from_str(name), bases_tuple], @@ -61238,7 +71824,7 @@ impl Interpreter { // the metaclass (typing's `_generic_init_subclass` relies on // it to tell `Generic[T]` from plain `Generic`). if let Some(ob) = orig_bases { - let ob_tuple = Object::new_tuple(ob.to_vec()); + let ob_tuple = Object::tuple_from_slice(ob); if let Some(obj) = &ns_obj { let g = body_fn.globals.clone(); self.class_ns_store(obj, "__orig_bases__", ob_tuple, &g)?; @@ -61256,7 +71842,7 @@ impl Interpreter { }; let call_args = vec![ Object::from_str(name), - Object::new_tuple(bases.to_vec()), + Object::tuple_from_slice(bases), ns_for_call, ]; let result = self.call(&meta, &call_args, subclass_kwargs, &body_fn.globals)?; @@ -62505,7 +73091,7 @@ impl Interpreter { /// The flag reports whether the instance was tracked now (and so /// counts toward an automatic collection). #[inline] - fn alloc_plain_instance_obj(&self, cls: &Rc) -> (Object, bool) { + pub(crate) fn alloc_plain_instance_obj(&self, cls: &Rc) -> (Object, bool) { if cls.native_kind.get() != 0 { // A natively served class's instances are never tracked // (see `stdlib::datetime_native`). @@ -62653,9 +73239,404 @@ impl Interpreter { plan } + /// The plan a call of `ty` with `argc` positional arguments (and no + /// keywords) goes by: `plan` (the class's current one), or, while the + /// class's trivial `__new__` holds for the call (see + /// [`crate::types::TrivialNew`]), the plan with `object.__new__` in + /// its place. + #[inline(always)] + pub(crate) fn call_plan<'a>( + &self, + plan: &'a Rc, + ty: &TypeObject, + argc: usize, + ) -> &'a Rc { + match plan.trivial_new.as_deref() { + Some(tn) if self.trivial_new_holds(plan, tn, ty, argc) => &tn.plan, + _ => plan, + } + } + + /// Whether `plan`'s trivial `__new__` `tn` holds for a call of `ty` + /// with `argc` positional arguments (see [`Self::call_plan`]): the + /// function still runs the code matched, the call binds, nothing + /// observes calls, and the names resolve as matched, read where + /// [`Self::trivial_new_locate`] found them. + #[inline(never)] + fn trivial_new_holds( + &self, + plan: &crate::types::InstancePlan, + tn: &crate::types::TrivialNew, + ty: &TypeObject, + argc: usize, + ) -> bool { + let Some(Object::Function(f)) = &plan.user_new else { + return false; + }; + if tn.fixed.is_some_and(|n| n as usize != argc + 1) || crate::trace::any_observers_active() + { + return false; + } + let relaxed = std::sync::atomic::Ordering::Relaxed; + // SAFETY: GIL-serialized raw reads of the function's code cell and + // namespaces; nothing runs while the references live. + unsafe { + if Rc::as_ptr(&*f.code.as_ptr()) as usize != tn.code { + return false; + } + let (g, b) = (&*f.globals.as_ptr(), &*f.builtins.as_ptr()); + if (tn.memo[0].load(relaxed) != g.mutation_stamp() + || tn.memo[1].load(relaxed) != b.mutation_stamp()) + && !self.trivial_new_locate(f, tn, g, b) + { + return false; + } + let at = |loc: u64| -> Option<&Object> { + let i = usize::try_from((loc >> 1).checked_sub(1)?).ok()?; + let found = if loc & 1 == 0 { + g.get_index(i) + } else { + b.get_index(i) + }; + found.map(|(_, v)| v) + }; + matches!(at(tn.memo[2].load(relaxed)), + Some(Object::Type(o)) if Rc::ptr_eq(o, &builtin_types().object_)) + && (tn.swap.is_none() + || at(tn.memo[3].load(relaxed)).is_some_and( + |x| !matches!(x, Object::Type(t) if std::ptr::eq(Rc::as_ptr(t), ty)), + )) + } + } + + /// For a call of `ty` (`argc` positional arguments) whose plan's + /// trivial `__new__` takes its `if cls is X: cls = ...` branch (`X` is + /// `ty`, `pathlib.Path`): the class the reassignment picks, when it + /// only reads names and module attributes and compares strings, and + /// the class is a subclass of `ty` whose `__new__` is the same + /// function (`PosixPath`). The call is then that class's call: the + /// function would allocate an instance of it, and `__init__` is its. + /// The pick stands while what it read does (see + /// [`crate::types::TrivialNew::swap_memo`]). + #[inline(never)] + pub(crate) fn trivial_new_retarget( + &self, + plan: &crate::types::InstancePlan, + ty: &Rc, + argc: usize, + ) -> Option> { + let tn = plan.trivial_new.as_deref()?; + tn.swap?; + let Some(Object::Function(f)) = &plan.user_new else { + return None; + }; + if tn.fixed.is_some_and(|n| n as usize != argc + 1) || crate::trace::any_observers_active() + { + return None; + } + let relaxed = std::sync::atomic::Ordering::Relaxed; + let sm = &tn.swap_memo; + // SAFETY: GIL-serialized raw reads; nothing runs while they're + // used. A remembered module dict is alive: its module is the value + // an earlier read found, unchanged. + let picked = unsafe { + if Rc::as_ptr(&*f.code.as_ptr()) as usize != tn.code { + return None; + } + let (g, b) = (&*f.globals.as_ptr(), &*f.builtins.as_ptr()); + let key = [ + g.mutation_stamp(), + b.mutation_stamp(), + crate::object::global_value_epoch(), + ]; + let verdict = sm[3].load(relaxed); + let same = + verdict != 0 && sm[0].load(relaxed) == key[0] && sm[1].load(relaxed) == key[1]; + if same && sm[2].load(relaxed) == key[2] { + sm[4].load(relaxed) as usize as *const TypeObject + } else if same && verdict == 2 && Self::swap_reads_stand(sm, g, b) { + // (A value stored in place elsewhere moved the epoch.) + sm[2].store(key[2], relaxed); + sm[4].load(relaxed) as usize as *const TypeObject + } else { + let mut reads = [[0u64; 4]; crate::types::SWAP_READS]; + let mut n = 0usize; + let m = self.trivial_new_swap_read(f, tn, ty, &mut reads, &mut n); + let picked = m.as_ref().map_or(std::ptr::null(), Rc::as_ptr); + let head = [ + key[0], + key[1], + key[2], + if m.is_some() { 2 } else { 1 }, + picked as usize as u64, + n as u64, + ]; + for (w, v) in sm + .iter() + .zip(head.into_iter().chain(reads.into_iter().flatten())) + { + w.store(v, relaxed); + } + picked + } + }; + if picked.is_null() { + return None; + } + // SAFETY: the class is bound where the reassignment read it. + let m = unsafe { + Rc::increment_strong_count(picked); + Rc::from_raw(picked) + }; + // (Its own call runs the same function, past the reassignment.) + let m_plan = self.instance_plan(&m); + (m.is_subclass_of(ty) + && matches!(&m_plan.user_new, Some(Object::Function(g)) if Rc::ptr_eq(g, f))) + .then_some(m) + } + + /// Whether the values a remembered reading read (see + /// [`crate::types::TrivialNew::swap_memo`]) are where they were, + /// with the function's globals `g` and builtins `b` keyed as they + /// were. + /// + /// # Safety + /// + /// GIL-serialized; nothing runs meanwhile. + unsafe fn swap_reads_stand( + sm: &[std::sync::atomic::AtomicU64], + g: &DictData, + b: &DictData, + ) -> bool { + let relaxed = std::sync::atomic::Ordering::Relaxed; + let n = sm[5].load(relaxed); + if n > crate::types::SWAP_READS as u64 { + return false; + } + // SAFETY: the caller's contract; a module dict is read only after + // the read that found its module stood. + unsafe { + (0..n as usize).all(|k| { + let e = &sm[6 + 4 * k..10 + 4 * k]; + let d: &DictData = match e[0].load(relaxed) { + 0 => g, + 1 => b, + p => { + let d = &*(*(p as usize as *const RefCell)).as_ptr(); + if d.mutation_stamp() != e[1].load(relaxed) { + return false; + } + d + } + }; + usize::try_from(e[2].load(relaxed)) + .ok() + .and_then(|i| d.get_index(i)) + .is_some_and(|(_, v)| { + v.strong_word().map_or(0, |w| w as usize as u64) == e[3].load(relaxed) + }) + }) + } + } + + /// [`Self::trivial_new_retarget`]'s reading of the reassignment: the + /// class it picks (a strict subclass of `ty`), each value it read + /// noted in `reads` (`n` of them; more than fit, or one without an + /// identity, sets `n` past them, see + /// [`crate::types::TrivialNew::swap_memo`]). + #[cold] + #[inline(never)] + fn trivial_new_swap_read( + &self, + f: &crate::object::PyFunction, + tn: &crate::types::TrivialNew, + ty: &Rc, + reads: &mut [[u64; 4]; crate::types::SWAP_READS], + n: &mut usize, + ) -> Option> { + // (A dict subclass's `__missing__` or `__getitem__` could answer.) + if self.globals_missing_gate() { + return None; + } + let code = f.code(); + // (A read past the room, or of a value without an identity, can't + // be rechecked.) + let note = |reads: &mut [[u64; 4]; crate::types::SWAP_READS], + n: &mut usize, + at: u64, + stamp: u64, + i: usize, + v: &Object| { + match (reads.get_mut(*n), v.strong_word()) { + (Some(e), Some(w)) if *n != usize::MAX => { + *e = [at, stamp, i as u64, w as usize as u64]; + *n += 1; + } + _ => *n = usize::MAX, + } + }; + let lookup = |idx: u32, + reads: &mut [[u64; 4]; crate::types::SWAP_READS], + n: &mut usize| + -> Option { + let key = crate::object::StrKey(code.names.get(idx as usize)?.as_str()); + for (at, d) in [(0, &f.globals), (1, &f.builtins)] { + let d = d.borrow(); + if let Some(i) = d.get_index_of(&key) { + let v = d.get_index(i)?.1.clone(); + note(reads, n, at, 0, i, &v); + return Some(v); + } + } + None + }; + // `object` and `X` as the function reads them. + let (Some(Object::Type(object)), Some(Object::Type(x))) = + (lookup(tn.object_name, reads, n), lookup(tn.swap?, reads, n)) + else { + return None; + }; + if !Rc::ptr_eq(&object, &builtin_types().object_) || !Rc::ptr_eq(&x, ty) { + return None; + } + // The reassignment, run on a small stack of the values it reads. + let (start, end) = (tn.swap_body.0 as usize, tn.swap_body.1 as usize); + let ins = &code.instructions; + let mut stack: Vec = Vec::with_capacity(4); + let mut pc = start; + let mut picked = None; + for _ in 0..32 { + if pc >= end { + break; + } + let i = *ins.get(pc)?; + pc += 1; + match i.op { + OpCode::Resume | OpCode::Nop | OpCode::NotTaken => {} + OpCode::LoadGlobal => stack.push(lookup(i.arg, reads, n)?), + OpCode::LoadAttr => { + let name = code.names.get(i.arg as usize)?.as_str(); + let Some(Object::Module(m)) = stack.pop() else { + return None; + }; + // (A module's own namespace; the module type's + // attributes are dunders.) + if name.starts_with("__") { + return None; + } + let d = m.dict.borrow(); + let at = d.get_index_of(&crate::object::StrKey(name))?; + let v = d.get_index(at)?.1.clone(); + let dict = Rc::as_ptr(&m.dict) as usize as u64; + note(reads, n, dict, d.mutation_stamp(), at, &v); + drop(d); + stack.push(v); + } + OpCode::LoadConst => match code.constants.get(i.arg as usize)? { + weavepy_compiler::Constant::Str(s) => stack.push(Object::from_str(s)), + _ => return None, + }, + OpCode::CompareOp => { + let kind = i.arg & !weavepy_compiler::COMPARE_OP_TO_BOOL_FLAG; + let (Some(Object::Str(b)), Some(Object::Str(a))) = (stack.pop(), stack.pop()) + else { + return None; + }; + let eq = a.as_str() == b.as_str(); + stack.push(Object::Bool(match kind { + k if k == weavepy_compiler::CompareKind::Eq as u32 => eq, + k if k == weavepy_compiler::CompareKind::NotEq as u32 => !eq, + _ => return None, + })); + } + OpCode::PopJumpIfFalse | OpCode::PopJumpIfTrue => { + let Some(Object::Bool(v)) = stack.pop() else { + return None; + }; + if v == (i.op == OpCode::PopJumpIfTrue) { + pc += i.arg as usize; + } + } + OpCode::JumpForward => pc += i.arg as usize, + OpCode::StoreFast if i.arg == 0 && stack.len() == 1 => { + picked = stack.pop(); + // (What's left up to the `object.__new__` line does + // nothing.) + if !ins + .get(pc..end)? + .iter() + .all(|i| matches!(i.op, OpCode::Resume | OpCode::Nop | OpCode::NotTaken)) + { + return None; + } + break; + } + _ => return None, + } + } + let Some(Object::Type(m)) = picked else { + return None; + }; + (!Rc::ptr_eq(&m, ty) && m.is_subclass_of(ty)).then_some(m) + } + + /// Where `tn`'s names (`object`, `X`) are bound in `f`'s globals or + /// builtins (`g`, `b`), remembered with the two namespaces' stamps: a + /// value stored in place leaves them standing and the reads at those + /// positions see it. `false` (nothing remembered) when a dict + /// subclass's hooks could answer instead. + #[cold] + #[inline(never)] + fn trivial_new_locate( + &self, + f: &crate::object::PyFunction, + tn: &crate::types::TrivialNew, + g: &DictData, + b: &DictData, + ) -> bool { + if self.globals_missing_gate() { + return false; + } + let code = f.code(); + // (`(position + 1) << 1`, the low bit for the builtins; `0` + // unbound.) + let locate = |idx: Option| -> u64 { + let Some(name) = idx.and_then(|i| code.names.get(i as usize)) else { + return 0; + }; + let key = crate::object::StrKey(name.as_str()); + match g.get_index_of(&key) { + Some(i) => (i as u64 + 1) << 1, + None => b.get_index_of(&key).map_or(0, |i| (i as u64 + 1) << 1 | 1), + } + }; + let memo = [ + g.mutation_stamp(), + b.mutation_stamp(), + locate(Some(tn.object_name)), + locate(tn.swap), + ]; + for (m, v) in tn.memo.iter().zip(memo) { + m.store(v, std::sync::atomic::Ordering::Relaxed); + } + true + } + /// Resolve everything about `type(cls).__call__` that is a pure /// function of the class dict / MRO (see [`crate::types::InstancePlan`]). fn build_instance_plan(&self, cls: &Rc) -> crate::types::InstancePlan { + self.build_instance_plan_as(cls, false) + } + + /// [`Self::build_instance_plan`], as though the class's `__new__` were + /// `object.__new__` when `default_new` (a trivial `__new__`'s plan, + /// see [`crate::types::TrivialNew`]). + #[allow(clippy::self_only_used_in_recursion)] + fn build_instance_plan_as( + &self, + cls: &Rc, + default_new: bool, + ) -> crate::types::InstancePlan { use crate::types::NativeKind; // PEP 3119 abstract guard (see `instantiate` for the rationale). let abstract_error = cls.lookup("__abstractmethods__").and_then(|abstracts| { @@ -62732,7 +73713,7 @@ impl Interpreter { } _ => false, }; - let user_new = if is_object_new { + let user_new = if is_object_new || default_new { None } else { new_fn.map(|found| match found { @@ -62748,6 +73729,8 @@ impl Interpreter { }) }; + let is_object_new = is_object_new || default_new; + // Native payload classification (the per-args construction stays // in `instantiate`). let bt = builtin_types(); @@ -62945,6 +73928,33 @@ impl Interpreter { && !cls.is_subclass_of(&bt.module_) && !cls.is_subclass_of(&bt.generic_alias_); + // A Python `__new__` that only allocates, before a Python + // `__init__`: the plan as though it were `object.__new__`, for the + // calls `Self::call_plan` finds it holds for. + let trivial_new = match &user_new { + Some(Object::Function(f)) + if !default_new + && object_new_plain + && !init_from_object + && matches!(init_fn, Some(Object::Function(_))) => + { + let code = f.code(); + trivial_new_shape(&code).map(|(object_name, swap, swap_body, fixed)| { + Box::new(crate::types::TrivialNew { + code: Rc::as_ptr(&code) as usize, + object_name, + swap, + swap_body, + swap_memo: Default::default(), + fixed, + plan: Rc::new(self.build_instance_plan_as(cls, true)), + memo: Default::default(), + }) + }) + } + _ => None, + }; + crate::types::InstancePlan { abstract_error, user_new, @@ -62962,7 +73972,101 @@ impl Interpreter { object_new_plain, store_init: std::sync::atomic::AtomicU8::new(0), slot_members: std::sync::OnceLock::new(), + trivial_new, + } + } + + /// `dict(arg)` (one positional, no keywords) where the plain builtin + /// can't build it: a mapping (anything with `keys()`), or a lazy + /// iterable of pairs (a generator, a `zip`/`map`/`filter` view, an + /// instance) through the VM-aware collector. `None` for an eager + /// container of pairs, which `builtins::b_dict` builds. + fn dict_from_one(&mut self, arg: &Object) -> Option> { + let globals = self.builtins_dict(); + match self.try_dict_from_mapping(arg, &globals) { + Ok(Some(d)) => return Some(Ok(d)), + Ok(None) => {} + Err(e) => return Some(Err(e)), + } + if !(matches!( + arg, + Object::Generator(_) | Object::Iter(_) | Object::Instance(_) + ) || object_needs_vm_iter(arg)) + { + return None; + } + Some(self.dict_from_lazy_pairs(arg)) + } + + /// [`Self::dict_from_one`]'s lazy iterable of pairs. + fn dict_from_lazy_pairs(&mut self, arg: &Object) -> Result { + let globals = self.builtins_dict(); + // While every key compares natively (as all so far have), an + // insert runs no Python comparison to catch. + fn insert( + d: &mut DictData, + native: &mut bool, + key: Object, + value: Object, + ) -> Result<(), RuntimeError> { + crate::builtins::ensure_dict_key(&key)?; + *native &= matches!( + key, + Object::Str(_) + | Object::Int(_) + | Object::Bool(_) + | Object::None + | Object::Float(_) + | Object::Bytes(_) + ); + if *native { + d.insert(DictKey(key), value); + } else { + crate::object::key_cmp_scope(|| d.insert(DictKey(key), value))?; + } + Ok(()) } + let mut native = true; + // `dict(zip(ks, vs))`: the pairs straight from the two sources, in + // the order the zip would step them, with no tuple between. + let d = match self.zip2_pairs(arg, &globals) { + Some(pairs) => { + let pairs = pairs?; + let mut d = + DictData::with_capacity_and_hasher(pairs.len(), crate::fasthash::FxBuildHasher); + for (key, value) in pairs { + insert(&mut d, &mut native, key, value)?; + } + d + } + None => { + let items = self.collect_iterable(arg, &globals)?; + let mut d = + DictData::with_capacity_and_hasher(items.len(), crate::fasthash::FxBuildHasher); + for (i, pair) in items.into_iter().enumerate() { + // A 2-tuple is its own pair. + let (key, value) = match &pair { + Object::Tuple(t) if t.len() == 2 => (t[0].clone(), t[1].clone()), + _ => { + let kv = self.collect_iterable(&pair, &globals)?; + if kv.len() != 2 { + return Err(value_error(format!( + "dictionary update sequence element #{i} has length {}; 2 is required", + kv.len() + ))); + } + let mut kv = kv.into_iter(); + (kv.next().expect("two"), kv.next().expect("two")) + } + }; + insert(&mut d, &mut native, key, value)?; + } + d + } + }; + let out = Object::Dict(Rc::new(RefCell::new(d))); + crate::gc_trace::track_built(&out); + Ok(out) } /// Allocate an instance of `cls`, then run the `__new__` / @@ -62980,6 +74084,18 @@ impl Interpreter { args: &[Object], kwargs: &[(String, Object)], ) -> Result { + // `bool(x)` of an instance is its truth (`PyObject_IsTrue`): the + // in-place `__bool__`/`__len__` evaluation the truth test uses, + // else the full protocol, without the type call's dispatch. + if let ([arg @ Object::Instance(_)], true) = (args, kwargs.is_empty()) { + if Rc::ptr_eq(&cls, &builtin_types().bool_) { + if let Some(b) = self.leaf_instance_truth(arg) { + return Ok(Object::Bool(b)); + } + let globals = self.builtins.clone(); + return self.obj_truthy(arg, &globals).map(Object::Bool); + } + } // A natively served class's common constructor shapes. if cls.native_kind.get() != 0 { if let Some(r) = crate::stdlib::datetime_native::construct(&cls, args, kwargs) { @@ -62999,10 +74115,12 @@ impl Interpreter { return r; } } - if kwargs.is_empty() && !cls.flags.is_builtin { - if let Some(r) = self.instantiate_named_tuple(&cls, args) { + if !cls.flags.is_builtin { + if let Some(r) = self.instantiate_named_tuple(&cls, args, kwargs) { return Ok(r); } + } + if kwargs.is_empty() && !cls.flags.is_builtin { if let Some(r) = self.instantiate_plain_lean(&cls, args) { return r; } @@ -63283,53 +74401,25 @@ impl Interpreter { return self.do_list_or_tuple_call(cls.name.as_str(), &args[0], &global_dummy); } // CPython's `dict(obj)` accepts a mapping (anything with - // `keys()`); recognise that path before falling through to - // the simple "iter of pairs" builtin. + // `keys()`) or a lazy iterable of pairs (see `dict_from_one`). if cls.name == "dict" && args.len() == 1 && kwargs.is_empty() { - let global_dummy = Rc::new(RefCell::new(DictData::default())); - if let Some(d) = self.try_dict_from_mapping(&args[0], &global_dummy)? { - return Ok(d); + if let Some(r) = self.dict_from_one(&args[0]) { + return r; } } - // `set(it)` / `frozenset(it)` / `dict(iter-of-pairs)` must - // route lazy iterables (generators, `zip`/`map`/`filter` - // views, genexprs) through the VM-aware collector — the plain - // builtins below can only drive eager containers (RFC 0033). + // `set(it)` / `frozenset(it)` must route lazy iterables + // (generators, `zip`/`map`/`filter` views, genexprs) through + // the VM-aware collector — the plain builtins below can only + // drive eager containers (RFC 0033). if (matches!( &args.first(), Some(Object::Generator(_) | Object::Iter(_) | Object::Instance(_)) ) || args.first().is_some_and(object_needs_vm_iter)) && args.len() == 1 && kwargs.is_empty() + && (cls.name == "set" || cls.name == "frozenset") { - if cls.name == "set" || cls.name == "frozenset" { - return self.set_from_vm_iter(&args[0], cls.name == "set"); - } - if cls.name == "dict" { - let global_dummy = Rc::new(RefCell::new(DictData::default())); - let items = self.collect_iterable(&args[0], &global_dummy)?; - let mut d = DictData::default(); - for (i, pair) in items.into_iter().enumerate() { - // A 2-tuple (`dict(zip(ks, vs))`) is its own pair. - let kv = match &pair { - Object::Tuple(t) if t.len() == 2 => t.to_vec(), - _ => self.collect_iterable(&pair, &global_dummy)?, - }; - if kv.len() != 2 { - return Err(type_error(format!( - "dictionary update sequence element #{i} has length {}; 2 is required", - kv.len() - ))); - } - crate::builtins::ensure_dict_key(&kv[0])?; - crate::object::key_cmp_scope(|| { - d.insert(DictKey(kv[0].clone()), kv[1].clone()) - })?; - } - let out = Object::Dict(Rc::new(RefCell::new(d))); - crate::gc_trace::track(&out); - return Ok(out); - } + return self.set_from_vm_iter(&args[0], cls.name == "set"); } // `dict(**kw)` / `dict(mapping, **kw)` / `dict(pairs, **kw)`: // CPython seeds the dict from at most one positional (a mapping @@ -63347,16 +74437,20 @@ impl Interpreter { let global_dummy = Rc::new(RefCell::new(DictData::default())); let mut d = DictData::default(); if let Some(arg0) = args.first() { - if let Some(Object::Dict(inner)) = + if let Object::Dict(src) = arg0 { + // (An exact dict: its table copied once.) + d = src.borrow().clone(); + } else if let Some(Object::Dict(inner)) = self.try_dict_from_mapping(arg0, &global_dummy)? { - d = inner.borrow().clone(); + // (The copy just made is this call's own.) + d = std::mem::take(&mut *inner.borrow_mut()); } else { let items = self.collect_iterable(arg0, &global_dummy)?; for (i, pair) in items.into_iter().enumerate() { let kv = self.collect_iterable(&pair, &global_dummy)?; if kv.len() != 2 { - return Err(type_error(format!( + return Err(value_error(format!( "dictionary update sequence element #{i} has length {}; 2 is required", kv.len() ))); @@ -63368,13 +74462,18 @@ impl Interpreter { } } } + // (Keyword names are interned strings, hashed once.) + let str_keys = d.keys().all(|k| matches!(k.0, Object::Str(_))); for (k, v) in kwargs { - crate::object::key_cmp_scope(|| { - d.insert(DictKey(Object::Str(SharedStr::from(k.as_str()))), v.clone()) - })?; + let key = DictKey(crate::stdlib::sys::intern_name(k)); + if str_keys { + d.insert(key, v.clone()); + } else { + crate::object::key_cmp_scope(|| d.insert(key, v.clone()))?; + } } let out = Object::Dict(Rc::new(RefCell::new(d))); - crate::gc_trace::track(&out); + crate::gc_trace::track_built(&out); return Ok(out); } // `int(x)` / `float(x)` honour the user's `__int__` / @@ -63611,7 +74710,7 @@ impl Interpreter { // (test_exceptions NaiveException). if plan.seeds_exception_args { if let Object::Instance(i) = &inst { - i.slot_set("args", Object::new_tuple(args.to_vec())); + i.slot_set("args", Object::tuple_from_slice(args)); } } // RFC 0024: auto-track every fresh user instance with @@ -63837,9 +74936,21 @@ impl Interpreter { // family shapes construction, so `args` is the only slot, built // in place without the per-slot probes below. if families & !(EXC_CUSTOM_INIT | EXC_FAM_GROUP) == 0 { - let args_tuple = Object::tuple_from_exact(args.iter().cloned()); - let inst = - PyInstance::with_slots(cls, crate::types::SlotStorage::exception(args_tuple, [])); + let args_tuple = Object::tuple_from_slice(args); + // (An `AttributeError`'s `name` and `obj` are laid out unset, + // as a natively built one's are: the attribute read it + // propagates through, a `__getattr__`'s caller, stores them in + // place. See `attr_error_context_laid_out`.) + let slots = if Rc::ptr_eq(&cls, &crate::builtin_types::builtin_types().attribute_error) + { + crate::types::SlotStorage::exception( + args_tuple, + [("name", Object::Unbound), ("obj", Object::Unbound)], + ) + } else { + crate::types::SlotStorage::exception(args_tuple, []) + }; + let inst = PyInstance::with_slots(cls, slots); let obj = Object::Instance(Rc::new(inst)); // See the GC note at the end. if args.iter().any(|x| !crate::gc_trace::is_atomic(x)) { @@ -63847,6 +74958,50 @@ impl Interpreter { } return obj; } + // `OSError(errno, strerror[, filename])` of a plain `OSError` + // family class, every field given: `args` keeps the first two and + // the fields go in with it, in one step. + if families & !(EXC_CUSTOM_INIT | EXC_FAM_GROUP | exc_family_bit("OSError")) == 0 + && (2..=3).contains(&args.len()) + && !args.iter().any(|a| matches!(a, Object::None)) + && cls.fresh_slots().is_empty_default() + { + let args_tuple = Object::tuple_from_slice(&args[..2]); + let (e, s) = (args[0].clone(), args[1].clone()); + let slots = match args.get(2) { + Some(f) => crate::types::SlotStorage::exception( + args_tuple, + [("errno", e), ("strerror", s), ("filename", f.clone())], + ), + None => crate::types::SlotStorage::exception( + args_tuple, + [("errno", e), ("strerror", s)], + ), + }; + let inst = PyInstance::with_slots(cls, slots); + let obj = Object::Instance(Rc::new(inst)); + if args.iter().any(|x| !crate::gc_trace::is_atomic(x)) { + crate::gc_trace::track(&obj); + } + return obj; + } + // `StopIteration` or `StopIteration(value)` (a Python `__next__`'s + // end): `value` goes in with `args`, in one step. + if families & !(EXC_CUSTOM_INIT | EXC_FAM_GROUP | exc_family_bit("StopIteration")) == 0 + && cls.fresh_slots().is_empty_default() + { + let value = args.first().cloned().unwrap_or(Object::None); + let slots = crate::types::SlotStorage::exception( + Object::tuple_from_slice(args), + [("value", value)], + ); + let inst = PyInstance::with_slots(cls, slots); + let obj = Object::Instance(Rc::new(inst)); + if args.iter().any(|x| !crate::gc_trace::is_atomic(x)) { + crate::gc_trace::track(&obj); + } + return obj; + } let mro_has = |name: &str| families & exc_family_bit(name) != 0; let is_stop_iteration = mro_has("StopIteration"); let inst = PyInstance::new(cls.clone()); @@ -63861,9 +75016,9 @@ impl Interpreter { && args.len() == 3 && matches!(args[2], Object::Int(_) | Object::Long(_)); let args_tuple = if is_os_error && !written_from_filename && (2..=5).contains(&args.len()) { - Object::new_tuple(args[..2].to_vec()) + Object::tuple_from_slice(&args[..2]) } else { - Object::new_tuple(args.to_vec()) + Object::tuple_from_slice(args) }; // (No `message` mirror: CPython has none, and `str()` and the Rust // display derive the text from `args`.) @@ -63895,7 +75050,7 @@ impl Interpreter { let code = match args.len() { 0 => Object::None, 1 => args[0].clone(), - _ => Object::new_tuple(args.to_vec()), + _ => Object::tuple_from_slice(args), }; inst.slot_set("code", code); } @@ -63943,8 +75098,8 @@ impl Interpreter { } if args.len() == 2 { let info: Vec = match &args[1] { - Object::Tuple(t) => t.to_vec(), - Object::List(l) => l.borrow().clone(), + Object::Tuple(t) => crate::object::cloned_vec(t), + Object::List(l) => crate::object::cloned_vec(&l.borrow()), _ => Vec::new(), }; if info.len() == 4 || info.len() == 6 { @@ -64029,8 +75184,13 @@ impl Interpreter { if let Some(ctor) = crate::builtins::builtin_type_constructor(&cls.name) { return Some(ctor); } - let key = DictKey(Object::from_str(&cls.name)); - match self.builtins.borrow().get(&key).cloned() { + // (Probed by the name itself: no string built for the key.) + match self + .builtins + .borrow() + .get(&crate::object::StrKey(&cls.name)) + .cloned() + { Some(Object::Builtin(b)) => Some(b), _ => None, } @@ -64088,10 +75248,17 @@ impl Interpreter { args: &[Object], ) -> Option { const MAX_ARGS: usize = 6; + // (A warm general leaf called with exactly its parameters: its + // native code, every check made once.) + #[cfg(feature = "jit")] + if let Some(r) = self.leaf_fast_call(f, recv, args, false) { + return r; + } // SAFETY: a function's code is only replaced under the GIL, and // nothing here runs code that could replace it. let code = unsafe { &*f.code.as_ptr() }; let n = args.len() + usize::from(recv.is_some()); + let depth = crate::recursion::current_depth(); // (A surplus positional must raise, not bind a keyword-only // parameter: the full binder's.) if n > MAX_ARGS @@ -64100,15 +75267,169 @@ impl Interpreter { || !pure_leaf_warm(code) || crate::trace::any_observers_active() || !self.inline_calls_ok() - || crate::recursion::current_depth() >= crate::recursion::recursion_limit() + || depth >= crate::recursion::recursion_limit() { return None; } - let mut ptrs = [std::ptr::null::(); MAX_ARGS]; + let mut ptrs = [std::ptr::null::(); 8]; for (p, a) in ptrs.iter_mut().zip(recv.into_iter().chain(args)) { *p = a; } - self.pure_leaf_eval::(code, f, &ptrs[..n]) + // Trailing positional parameters the call leaves out take the + // function's defaults (`map(scale, xs)` of `def scale(x, + // factor=2)`), and its keyword-only parameters theirs (`def + // shift(x, *, by=1)`); `**kwargs` is the full binder's, as are + // replaced `__defaults__` and `__kwdefaults__`. + let mut n = n; + let nargs = code.arg_count as usize; + if n < nargs { + let defs = &f.defaults; + let missing = nargs - n; + if code.has_varkeywords + || nargs > MAX_ARGS + || defs.len() < missing + || f.defaults_maybe_overridden() + { + return None; + } + for (p, d) in ptrs[n..nargs].iter_mut().zip(&defs[defs.len() - missing..]) { + *p = d; + } + n = nargs; + } + if code.kwonly_count != 0 { + n += code.kwonly_count as usize; + if code.has_varkeywords || n > ptrs.len() { + return None; + } + leaf_kwonly_defaults(f, code, &mut ptrs, 0)?; + } + // (A warm callee's compiled plan is entered directly.) + self.pure_leaf_call(code, f, &ptrs[..n], false, depth) + } + + /// A native caller's call of the placeholder-free `functools.partial` + /// `inst` over `extra` (`map(partial(scale, by=3), xs)`, a `key=` + /// partial) when its function is a warm pure leaf: evaluated in place, + /// the stored positionals first and the stored keywords bound by name, + /// as the core loop's call of one is (see `leaf_bind_keywords`). `None` + /// leaves the call to the full machinery, nothing having happened (a + /// keyword that names no parameter, or one a positional fills, is the + /// full call's to raise). + pub(crate) fn call_partial_leaf( + &self, + inst: &crate::types::PyInstance, + extra: &[Object], + ) -> Option { + let depth = crate::recursion::current_depth(); + if crate::trace::any_observers_active() + || !self.inline_calls_ok() + || depth >= crate::recursion::recursion_limit() + { + return None; + } + crate::stdlib::functools_mod::with_partial_call(inst, |func, stored, kw| { + let Object::Function(f) = func else { + return None; + }; + // SAFETY: GIL-serialized raw read of the function's code cell; + // the partial holds the function. + let code = unsafe { &*f.code.as_ptr() }; + if !code_is_pure_leaf(code) || !pure_leaf_warm(code) { + return None; + } + let mut ptrs = [std::ptr::null::(); 8]; + let kws = kw.iter().map(|(k, v)| (&k.0, v)); + let arity = Self::leaf_bind_keywords(f, code, stored, extra, kws, &mut ptrs)?; + self.pure_leaf_call(code, f, &ptrs[..arity], false, depth) + }) + } + + /// A keyword call (`p(x, c=1)`) of a placeholder-free + /// `functools.partial` whose function is a warm pure leaf, as + /// [`Self::call_partial_leaf`] makes a positional one: `ops` is the + /// partial's native `__call__`, the instance in the self slot (see + /// `core_instance_callee`), `argc` positionals, the keyword values and + /// the names tuple. The call's keywords override stored ones of the + /// same name, as `{**self.keywords, **keywords}` merges them, and all + /// are bound by name with no `String` made. `None`, nothing done, for + /// anything else and for anything the leaf binder or the evaluation + /// declines (errors included: the full call raises them). + pub(crate) fn partial_leaf_kw(&self, ops: &[Object], argc: usize) -> Option { + let (Object::Builtin(b), Object::Instance(inst), Some(Object::Tuple(names))) = + (ops.first()?, ops.get(1)?, ops.last()) + else { + return None; + }; + if !crate::stdlib::functools_mod::is_partial_call(b) { + return None; + } + let depth = crate::recursion::current_depth(); + if ops.len() != argc + names.len() + 3 + || crate::trace::any_observers_active() + || !self.inline_calls_ok() + || depth >= crate::recursion::recursion_limit() + || !Self::core_all_droppable(ops) + { + return None; + } + let pos = &ops[2..2 + argc]; + let vals = &ops[2 + argc..ops.len() - 1]; + let same = |a: &Object, b: &Object| matches!((a, b), (Object::Str(x), Object::Str(y)) if **x == **y); + crate::stdlib::functools_mod::with_partial_call(inst, |func, stored, kw| { + let Object::Function(f) = func else { + return None; + }; + // SAFETY: GIL-serialized raw read of the function's code cell; + // the partial holds the function. + let code = unsafe { &*f.code.as_ptr() }; + if !code_is_pure_leaf(code) || !pure_leaf_warm(code) { + return None; + } + let kws = kw + .iter() + .map(|(k, v)| (&k.0, v)) + .filter(|(k, _)| !names.iter().any(|n| same(k, n))) + .chain(names.iter().zip(vals)); + let mut ptrs = [std::ptr::null::(); 8]; + let arity = Self::leaf_bind_keywords(f, code, stored, pos, kws, &mut ptrs)?; + self.pure_leaf_call(code, f, &ptrs[..arity], false, depth) + }) + } + + /// `CALL_KW` of a builtin type's method on its exact receiver (`ops`: + /// the method, the receiver, `argc` positionals, the keyword values and + /// the names tuple) whose keywords name, in order, the parameters after + /// the positional ones ([`builtin_method_kw_params`]): the positional + /// call's result, as `CALL`'s leaf lane runs it on the operands where + /// they are (the receiver, positionals and keyword values are its + /// arguments in order). `None`, nothing done, for anything else, for a + /// builtin the leaf registry doesn't vouch for or whose admission + /// declines the arguments, and for an error (the full call raises it). + pub(crate) fn core_method_kw_positional(&self, ops: &[Object], argc: usize) -> Option { + let (Object::Builtin(b), recv, Some(Object::Tuple(names))) = + (ops.first()?, ops.get(1)?, ops.last()) + else { + return None; + }; + let params = builtin_method_kw_params(recv, b.name)?; + if !b.binds_instance + || names.is_empty() + || ops.len() != argc + names.len() + 3 + || argc + names.len() > params.len() + || !names.iter().enumerate().all(|(j, n)| { + let p = params[argc + j]; + !p.starts_with('/') && matches!(n, Object::Str(s) if s.as_ref() == p) + }) + { + return None; + } + let args = &ops[1..ops.len() - 1]; + if !Self::core_all_droppable(args) { + return None; + } + let kind = self.leaf_call_kind(b)?; + self.leaf_builtin_call(kind, b, args)?.ok() } /// The full argument binder for [`Self::call_python_owned`]: CPython's @@ -64332,7 +75653,12 @@ impl Interpreter { return Err(type_error(msg)); } if let Some(slot) = kwargs_slot { - positional[slot] = Object::Dict(Rc::new(RefCell::new(extra_kwargs))); + // (The function may keep it: tracked, as CPython's dicts are.) + let d = Object::Dict(Rc::new(RefCell::new(extra_kwargs))); + if !varkw_stays_local(code) { + gc_trace::track_built(&d); + } + positional[slot] = d; filled[slot] = true; } // Defaults plug remaining holes among positional args. CPython @@ -64542,6 +75868,14 @@ impl Interpreter { let mut positional = args; positional.resize(code.varnames.len(), Object::Unbound); positional + } else if let Some(positional) = self.lean_bind_owned(f, &code, &args, kwargs.is_empty()) { + // (The bound locals hold their own references.) + let mut args = args; + for v in args.drain(..).rev() { + self.release(v); + } + self.recycle_scratch(args); + positional } else { self.bind_python_args( f, @@ -64561,6 +75895,75 @@ impl Interpreter { self.call_python_bound(f, code, positional) } + /// The fast locals of a call of `f` with the positionals `args` and no + /// keywords that leaves parameters to their defaults (`def shift(v, *, + /// by=1)` called as `shift(v)`, from `map` or a `key=`), bound as the + /// core loop binds one (see [`Self::lean_bind_keywords`]: no name + /// lists, no scan bitmap). `None` for anything the full binder must + /// see: keywords (`plain` false), a missing argument, surplus + /// positionals, replaced defaults. + #[inline] + fn lean_bind_owned( + &mut self, + f: &Rc, + code: &Rc, + args: &[Object], + plain: bool, + ) -> Option> { + if !plain + || self.pending_raw_kwargs.borrow().is_some() + || (f.defaults_maybe_overridden() + && (f.slot("__defaults__").is_some() || f.slot("__kwdefaults__").is_some())) + { + return None; + } + let mut positional: Vec = self.pooled_scratch(); + if Self::lean_bind_keywords(f, code, &[], args, std::iter::empty(), &mut positional) + .is_some() + { + fill_unbound(&mut positional, code.varnames.len()); + return Some(positional); + } + positional.clear(); + self.recycle_scratch(positional); + None + } + + /// `f(*stored, *args, **kw)` for a `functools.partial`'s call of a + /// Python function with no call-site keywords: bound by name from the + /// stored dictionary as the core loop's keyword calls bind (no `String` + /// per keyword, no general binder), then run on those locals. `None`, + /// nothing run, for anything that binder declines (errors included: + /// the full call raises them). + pub(crate) fn call_python_partial( + &mut self, + f: &Rc, + stored: &[Object], + args: &[Object], + kw: &Rc>, + ) -> Option> { + if self.pending_raw_kwargs.borrow().is_some() + || (f.defaults_maybe_overridden() + && (f.slot("__defaults__").is_some() || f.slot("__kwdefaults__").is_some())) + { + return None; + } + let code = f.code(); + let mut positional: Vec = self.pooled_scratch(); + let bound = { + let kw = kw.try_borrow().ok()?; + let kws = kw.iter().map(|(k, v)| (&k.0, v)); + Self::lean_bind_keywords(f, &code, stored, args, kws, &mut positional) + }; + if bound.is_none() { + positional.clear(); + self.recycle_scratch(positional); + return None; + } + fill_unbound(&mut positional, code.varnames.len()); + Some(self.call_python_bound(f, code, positional)) + } + /// A keyword call of `f`: the positional `args`, then `kwvals` named by /// `names` (the call site's `str` objects, one per value). Bound by /// name as the core loop's keyword calls bind ([`Self::lean_bind_keywords`]: @@ -64893,14 +76296,31 @@ impl Interpreter { /// call of `f` (its code `code`) with `given` positional arguments: /// the `RETURN_GENERATOR` it starts past, if so. fn generator_start(&self, f: &PyFunction, code: &CodeObject, given: usize) -> Option { + if code.has_varargs { + return None; + } + self.generator_start_spread(f, code, given) + } + + /// [`Self::generator_start`] for a caller that binds a `*args` + /// parameter's surplus itself (`Self::lazy_coro_bind`): such a body + /// starts when every positional parameter is given (its defaults stay + /// the full binder's to mix with a surplus). + pub(crate) fn generator_start_spread( + &self, + f: &PyFunction, + code: &CodeObject, + given: usize, + ) -> Option { let ext = code_vm_ext(code)?; let start = match ext.gen_start.load(std::sync::atomic::Ordering::Relaxed) { 0 => Self::generator_start_scan(code, ext)?, u32::MAX => return None, - at => (at & !GEN_DELEGATES) as usize - 1, + at => (at & !(GEN_DELEGATES | GEN_VARARGS)) as usize - 1, }; let nargs = code.arg_count as usize; - if given > nargs + if (given > nargs && !code.has_varargs) + || (given < nargs && code.has_varargs) || (code.is_coroutine && crate::stdlib::sys::coroutine_origin_tracking_depth() > 0) || crate::trace::eval_frame_record_active() || crate::trace::any_observers_active() @@ -64908,7 +76328,7 @@ impl Interpreter { { return None; } - let missing = nargs - given; + let missing = nargs.saturating_sub(given); if missing > 0 && (missing > f.defaults.len() || f.defaults_maybe_overridden()) { return None; } @@ -64924,17 +76344,22 @@ impl Interpreter { fn generator_start_scan(code: &CodeObject, ext: &CodeConstObjects) -> Option { let shaped = (code.is_generator || code.is_coroutine || code.is_async_generator) && code.kwonly_count == 0 - && !code.has_varargs && !code.has_varkeywords; - let start = code - .instructions - .iter() - .position(|i| !matches!(i.op, OpCode::MakeCell | OpCode::CopyFreeVars)) - .filter(|&start| shaped && code.instructions[start].op == OpCode::ReturnGenerator); - let delegates = code.instructions.iter().any(|i| i.op == OpCode::Send); + // (Any other code's verdict needs no scan of its body.) + let start = shaped + .then(|| { + code.instructions + .iter() + .position(|i| !matches!(i.op, OpCode::MakeCell | OpCode::CopyFreeVars)) + }) + .flatten() + .filter(|&start| code.instructions[start].op == OpCode::ReturnGenerator); + let delegates = start.is_some() && code.instructions.iter().any(|i| i.op == OpCode::Send); ext.gen_start.store( start.map_or(u32::MAX, |at| { - (at as u32 + 1) | if delegates { GEN_DELEGATES } else { 0 } + (at as u32 + 1) + | if delegates { GEN_DELEGATES } else { 0 } + | if code.has_varargs { GEN_VARARGS } else { 0 } }), std::sync::atomic::Ordering::Relaxed, ); @@ -65224,6 +76649,36 @@ impl Interpreter { } } + /// The deferred awaitable a `CALL` with `callee` and `slot` below its + /// `args` makes when it is `agen.asend(v)`, `agen.aclose()` or + /// `agen.__anext__()` of an async generator whose first-iteration hooks + /// were already taken (so making it runs no code): the bound method + /// with an empty self slot, as `core_gen_method` loads it. `None` for + /// any other call. + pub(crate) fn agen_method_await( + callee: &Object, + slot: &Object, + args: &[Object], + ) -> Option { + use crate::object::AgenAwaitKind; + let (Object::BoundMethod(bm), Object::Unbound) = (callee, slot) else { + return None; + }; + let (Object::Builtin(b), Object::AsyncGenerator(g)) = (&bm.function, &bm.receiver) else { + return None; + }; + if !g.hooks_inited.get() { + return None; + } + let (kind, payload) = match (b.name, args) { + (".agen_anext", []) => (AgenAwaitKind::Send, vec![Object::None]), + (".agen_send", [v]) => (AgenAwaitKind::Send, vec![v.clone()]), + (".agen_close", []) => (AgenAwaitKind::Close, Vec::new()), + _ => return None, + }; + Some(make_agen_await(&bm.receiver, kind, payload)) + } + /// Whether a `CALL` of one argument with `callee` and `slot` below it /// is `gen.send(v)` or `coro.send(v)`: the bound method with an empty /// self slot, or the method form `gen.send` loads (see @@ -65522,15 +76977,25 @@ impl Interpreter { // SAFETY: a parked box's locals are its own, and empty. let v = unsafe { fr.locals.storage() }; v.reserve(nlocals); + // (A `*args` body's surplus moves into its tuple, which sits + // just past the positional parameters.) + let fixed = nargs.min(code.arg_count as usize); // SAFETY: the caller's contract. unsafe { - std::ptr::copy_nonoverlapping(args, v.as_mut_ptr(), nargs); - v.set_len(nargs); + std::ptr::copy_nonoverlapping(args, v.as_mut_ptr(), fixed); + v.set_len(fixed); } - let missing = (code.arg_count as usize).saturating_sub(nargs); + let missing = code.arg_count as usize - fixed; if missing > 0 { v.extend(f.defaults[f.defaults.len() - missing..].iter().cloned()); } + if code.has_varargs { + // SAFETY: the caller's contract: the stack forgets them. + let surplus: Vec = (fixed..nargs) + .map(|k| unsafe { args.add(k).read() }) + .collect(); + v.push(Object::new_tuple(surplus)); + } fill_unbound(v, nlocals); } fr.pc = start as u32 + 1; @@ -66722,7 +78187,7 @@ impl Interpreter { // takes the parameters spread. intr::SUBSCRIPT_GENERIC => { let params = match &value { - Object::Tuple(t) => t.to_vec(), + Object::Tuple(t) => crate::object::cloned_vec(t), other => { return Err(RuntimeError::Internal(format!( "INTRINSIC_SUBSCRIPT_GENERIC expects a tuple, got {}", @@ -67656,20 +79121,26 @@ impl Interpreter { return None; } let cls = inst.cls(); - // (A pure function of the class's attributes: memoized.) - let plain = cls.memo_verdict(crate::types::Verdict::PlainNewobj, "", || { + let has_slots = |cls: &TypeObject| { let slots_key = crate::object::StrKey("__slots__"); - if cls - .mro + cls.mro .borrow() .iter() .any(|c| c.dict.borrow().get(&slots_key).is_some()) - { + }; + // (A pure function of the class's attributes: memoized.) + let default_shape = |cls: &TypeObject, slotted: bool| { + if has_slots(cls) != slotted { return false; } if cls.lookup("__getnewargs_ex__").is_some() || cls.lookup("__getnewargs__").is_some() { return false; } + // (The slotted state reads `obj.__dict__`: the instance's + // own dictionary unless the class says otherwise.) + if slotted && cls.lookup("__dict__").is_some() { + return false; + } let Some(default_getstate) = builtin_types() .object_ .dict @@ -67686,9 +79157,67 @@ impl Interpreter { (Some(Object::Builtin(a)), Object::Builtin(b)) => Rc::ptr_eq(&a, b), _ => false, } + }; + let plain = cls.memo_verdict(crate::types::Verdict::PlainNewobj, "", || { + default_shape(&cls, false) }); if !plain { - return None; + // A class with `__slots__`: `copyreg._default_getstate`'s + // pair of the instance dictionary (or `None`) and the slots + // that hold values, by the names `copyreg._slotnames` left on + // the class (the Python helper computes them the first time). + if !cls.memo_verdict(crate::types::Verdict::SlottedNewobj, "", || { + default_shape(&cls, true) + }) { + return None; + } + let names = match cls + .dict + .borrow() + .get(&crate::object::StrKey("__slotnames__")) + { + Some(Object::List(names)) => names.try_borrow().ok()?.clone(), + _ => return None, + }; + if !names.iter().all(|n| matches!(n, Object::Str(_))) { + return None; + } + let newobj = self.module_attr("copyreg", "__newobj__")?; + let mut slot_state = DictData::default(); + for name in &names { + let Object::Str(s) = name else { + return None; + }; + match self.load_attr(recv, s) { + Ok(v) => { + slot_state.insert(DictKey(name.clone()), v); + } + // (A slot holding nothing is left out.) + Err(e) if self.is_attribute_error(&e) => {} + Err(_) => return None, + } + } + let dict_state = match inst.dict.get() { + Some(dict) if !dict.try_borrow().ok()?.is_empty() => { + Object::Dict(inst.dict_shared()) + } + _ => Object::None, + }; + let state = if slot_state.is_empty() { + dict_state + } else { + Object::new_tuple(vec![ + dict_state, + Object::Dict(Rc::new(RefCell::new(slot_state))), + ]) + }; + return Some(Object::new_tuple(vec![ + newobj, + Object::new_tuple(vec![Object::Type(cls)]), + state, + Object::None, + Object::None, + ])); } let newobj = self.module_attr("copyreg", "__newobj__")?; let dict = inst.dict_shared(); @@ -67706,6 +79235,50 @@ impl Interpreter { ])) } + /// The builtin `name` an iterator's `__reduce__` names (`iter`, + /// `reversed`, `enumerate`), looked up as CPython's + /// `_PyEval_GetBuiltin` does. + pub(crate) fn reduce_builtin( + &mut self, + builtin_name: &'static str, + ) -> Result { + // CPython fetches the builtin via `_PyEval_GetBuiltin`, which reads the + // live `builtins` *module* dict — a namespace user code can mutate. + // Resolve there first (not the VM's private fast-path map) so a + // hash-colliding custom key runs its Python `__eq__`, both returning + // the current binding and letting side effects fire before we read the + // iterator's remaining state (issue gh-101765). No iterator borrow is + // held across this lookup. + let key = DictKey(Object::from_static(builtin_name)); + // A sandboxed eval/exec frame with a mapping `__builtins__` + // replaces the builtins namespace for `_PyEval_GetBuiltin` too: + // resolve against the *calling frame's* mapping, a miss raising + // AttributeError with the bare name (test_builtin + // test_eval_builtins_mapping_reduce). + let top_builtins_obj = self + .frame_stack + .borrow() + .last() + .and_then(|s| s.builtins_obj.clone()); + if let Some(bobj) = top_builtins_obj { + let g = self.builtins.clone(); + match self.class_ns_load(&bobj, builtin_name, &g)? { + Some(v) => Ok(v), + None => Err(attribute_error(builtin_name)), + } + } else { + let module_dict = match self.cache.get("builtins") { + Some(Object::Module(m)) => Some(m.dict.clone()), + _ => None, + }; + module_dict + .as_ref() + .and_then(|d| d.borrow().get(&key).cloned()) + .or_else(|| self.builtins.borrow().get(&key).cloned()) + .ok_or_else(|| runtime_error(format!("builtin '{builtin_name}' unavailable"))) + } + } + /// `.__reduce__()` → `(iter, (remaining_items,))`. /// Mirrors CPython's reduction of built-in iterators: the /// not-yet-yielded items are snapshotted into a list, and re-applying @@ -67779,41 +79352,7 @@ impl Interpreter { } else { "iter" }; - // CPython fetches the builtin via `_PyEval_GetBuiltin`, which reads the - // live `builtins` *module* dict — a namespace user code can mutate. - // Resolve there first (not the VM's private fast-path map) so a - // hash-colliding custom key runs its Python `__eq__`, both returning - // the current binding and letting side effects fire before we read the - // iterator's remaining state (issue gh-101765). No iterator borrow is - // held across this lookup. - let key = DictKey(Object::from_static(builtin_name)); - // A sandboxed eval/exec frame with a mapping `__builtins__` - // replaces the builtins namespace for `_PyEval_GetBuiltin` too: - // resolve against the *calling frame's* mapping, a miss raising - // AttributeError with the bare name (test_builtin - // test_eval_builtins_mapping_reduce). - let top_builtins_obj = self - .frame_stack - .borrow() - .last() - .and_then(|s| s.builtins_obj.clone()); - let builtin = if let Some(bobj) = top_builtins_obj { - let g = self.builtins.clone(); - match self.class_ns_load(&bobj, builtin_name, &g)? { - Some(v) => v, - None => return Err(attribute_error(builtin_name)), - } - } else { - let module_dict = match self.cache.get("builtins") { - Some(Object::Module(m)) => Some(m.dict.clone()), - _ => None, - }; - module_dict - .as_ref() - .and_then(|d| d.borrow().get(&key).cloned()) - .or_else(|| self.builtins.borrow().get(&key).cloned()) - .ok_or_else(|| runtime_error(format!("builtin '{builtin_name}' unavailable")))? - }; + let builtin = self.reduce_builtin(builtin_name)?; // A bytearray iterator reduces to `(iter, (live_bytearray,), index)` // — the *same* object, so co-pickling `(iter(b), b)` memoizes to a // shared buffer and post-unpickle mutations are visible through @@ -68907,8 +80446,9 @@ impl Interpreter { /// of `name`'s first segment). `None`, with nothing done, for anything /// that needs the full import: a relative import, a module still /// loading or missing, a from-list name that may be a submodule or - /// `*`, a replaced `__import__` or builtins, an audit hook, `-X - /// importtime`, the interpreter's own loads, and interpreter shutdown. + /// `*`, a replaced `__import__` or builtins, `-X importtime`, the + /// interpreter's own loads, and interpreter shutdown. (An import + /// `sys.modules` answers raises no audit event, as in CPython.) pub(crate) fn cached_import( &self, frame: &Frame, @@ -68916,15 +80456,7 @@ impl Interpreter { level: &Object, fromlist: &Object, ) -> Option { - if !matches!(level, Object::Int(0)) - || name.is_empty() - || self.internal_import_depth != 0 - || frame.builtins_obj().is_some() - || !Rc::ptr_eq(&frame.builtins, &self.builtins) - || crate::trace::any_audit_active() - || crate::import_time::reports_cached() - || crate::vm_singletons::modules_torn_down() - { + if frame.builtins_obj().is_some() || !Rc::ptr_eq(&frame.builtins, &self.builtins) { return None; } // (Only the interpreter's own `__import__` is skipped.) @@ -68936,13 +80468,65 @@ impl Interpreter { Some(Object::Builtin(b)) if b.name == "__vm:__import__" => {} _ => return None, } + self.cached_module(name, None, level, fromlist) + } + + /// A direct call of the interpreter's `__import__` with positional + /// `args` (`__import__("os")`, `__import__(name, globals(), None, + /// ["x"])`) when [`Self::cached_module`] answers it: what + /// [`Self::do_import`] returns, without the call's dispatch. (An + /// absolute import ignores `globals` and `locals`.) `None` for any + /// other call. + pub(crate) fn cached_dunder_import(&self, args: &[Object]) -> Option { + let (Some(Object::Str(name)), true) = (args.first(), args.len() <= 5) else { + return None; + }; + let fromlist = match args.get(3) { + // A list from-list's names as a tuple's: `do_import` reads + // either the same way. + Some(Object::List(l)) => { + let items = l.try_borrow().ok()?; + if items.is_empty() { + Object::None + } else { + Object::new_tuple(items.to_vec()) + } + } + Some(f @ (Object::Tuple(_) | Object::None)) => f.clone(), + None => Object::None, + Some(_) => return None, + }; + let level = args.get(4).unwrap_or(&Object::Int(0)); + let hash = crate::shared_value::SharedStr::hash_cached(name); + self.cached_module(name, Some(hash), level, &fromlist) + } + + /// The import-cache answer [`Self::cached_import`] and + /// [`Self::cached_dunder_import`] share, past their own checks on how + /// the import was reached. `hash` is `name`'s, when the caller has it. + fn cached_module( + &self, + name: &str, + hash: Option, + level: &Object, + fromlist: &Object, + ) -> Option { + if !matches!(level, Object::Int(0)) + || name.is_empty() + || self.internal_import_depth != 0 + || crate::import_time::reports_cached() + || crate::vm_singletons::modules_torn_down() + { + return None; + } if self.cache.initializing_holder(name).is_some() { return None; } - let leaf = self - .cache - .get(name) - .filter(|m| !matches!(m, Object::None))?; + let leaf = match hash { + Some(h) => self.cache.get_hashed(name, h), + None => self.cache.get(name), + } + .filter(|m| !matches!(m, Object::None))?; match fromlist { Object::Tuple(names) if !names.is_empty() => { let Object::Module(m) = &leaf else { @@ -69019,19 +80603,6 @@ impl Interpreter { None }; let absolute = resolve_relative(package.as_deref(), name, level).map_err(import_error)?; - // PEP 578 — `import(name, globals, locals, fromlist, level)` - // audit event. CPython only fires once per import name, at - // the point IMPORT_NAME runs. - crate::stdlib::sys::audit_event( - "import", - &[ - Object::from_str(absolute.clone()), - Object::None, - Object::None, - fromlist.clone(), - Object::Int(i64::from(level)), - ], - )?; // CPython (`PyImport_ImportModuleLevelObject`) consults sys.modules // *before* any loading: an existing entry — of any type, even a // plain dict — short-circuits the walk entirely (gh-134100's @@ -69057,7 +80628,25 @@ impl Interpreter { } m } - _ => self.import_path(&absolute)?, + hit => { + // PEP 578's `import` audit event: CPython raises it in + // `import_find_and_load`, so only for a name `sys.modules` + // doesn't answer (or holds as `None`), not for an import of + // a module already there. + if !matches!(hit, Some(ref m) if !matches!(m, Object::None)) { + crate::stdlib::sys::audit_event( + "import", + &[ + Object::from_str(absolute.clone()), + Object::None, + Object::None, + fromlist.clone(), + Object::Int(i64::from(level)), + ], + )?; + } + self.import_path(&absolute)? + } }; // CPython: with a falsy fromlist (None/empty), return the *base* @@ -69100,7 +80689,7 @@ impl Interpreter { // any iterable from direct `__import__(..., fromlist=…)` calls // (import_.test_fromlist passes lists, tuples, and iterators). let fromlist_items: Option> = match fromlist { - Object::Tuple(t) => Some(t.to_vec()), + Object::Tuple(t) => Some(crate::object::cloned_vec(t)), Object::List(l) => Some(l.borrow().to_vec()), _ => Some(self.collect_iterable(fromlist, current_globals)?), }; @@ -69616,6 +81205,21 @@ impl Interpreter { }; let spec = pair.first().cloned().unwrap_or(Object::None); let loader = pair.get(1).cloned().unwrap_or(Object::None); + // CPython's `_load_unlocked` leaves `spec._initializing` False once + // the body has run (every module but the import system's own and + // `sys`/`builtins`), which `_find_and_load`'s + // `getattr(module.__spec__, "_initializing", False)` reads on every + // `importlib.import_module` of an imported module. + if !self.cache.is_initializing(&module.name) + && !matches!( + module.name.as_str(), + "sys" | "builtins" | "_imp" | "_frozen_importlib" | "importlib._bootstrap" + ) + { + if matches!(spec, Object::Instance(_)) { + let _ = self.store_attr(&spec, "_initializing", Object::Bool(false)); + } + } { let mut dict = module.dict.borrow_mut(); dict.entry(DictKey(Object::from_static("__spec__"))) @@ -69653,8 +81257,8 @@ impl Interpreter { other => self.load_attr(other, "__path__").ok(), }?; let entries = match &path_obj { - Object::List(l) => l.borrow().clone(), - Object::Tuple(t) => t.to_vec(), + Object::List(l) => crate::object::cloned_vec(&l.borrow()), + Object::Tuple(t) => crate::object::cloned_vec(t), other => { let globals = self.builtins.clone(); self.collect_iterable(other, &globals).ok()? @@ -73169,11 +84773,33 @@ fn mv_slice_subview( mv: &Rc, slc: &PySlice, ) -> Result { + let itemsize = mv.itemsize.get(); + // A one-dimensional view in its derived layout (no stored shape or + // strides), sliced with step 1: the sub-view's layout is derived too, + // from its own start and length, with no vectors built. + // SAFETY: guard-free reads, each ending at once. + if itemsize > 0 + && !mv.zero_dim.get() + && unsafe { mv.shape.peek() }.is_some_and(Vec::is_empty) + && unsafe { mv.strides.peek() }.is_some_and(Vec::is_empty) + { + let n = (mv.len.get() / itemsize) as i64; + let (start_i, _stop, step, slicelen) = adjust_slice(n, slc)?; + if step == 1 { + let count = slicelen.max(0) as usize; + let sub = mv.shallow_clone(); + sub.released.set(false); + if count > 0 { + sub.start.set(mv.start.get() + start_i as usize * itemsize); + } + sub.len.set(count * itemsize); + return Ok(mv_tracked_subview(sub)); + } + } let shape = mv.shape_dims(); let strides = mv.stride_bytes(); let n = shape[0] as i64; let (start_i, _stop, step, slicelen) = adjust_slice(n, slc)?; - let itemsize = mv.itemsize.get(); let stride0 = strides[0]; let base = mv.start.get() as isize; let new_start = if slicelen > 0 { @@ -73192,18 +84818,139 @@ fn mv_slice_subview( sub.len.set(nbytes); *sub.shape.borrow_mut() = new_shape; *sub.strides.borrow_mut() = new_strides; - let exporter = sub.exporter.borrow().clone(); + Ok(mv_tracked_subview(sub)) +} + +/// A one-dimensional view of unsigned bytes in its derived layout (no +/// stored shape, strides or suboffsets): where its first byte is in the +/// buffer, and how many it spans. (Whether the view is live is the +/// caller's to check.) +pub(crate) fn mv_plain_bytes(mv: &crate::object::PyMemoryView) -> Option<(usize, usize)> { + // SAFETY: guard-free reads, each ending at once (nothing here runs + // code); a cell borrowed mutably reads as not plain. + let plain = unsafe { + mv.itemsize.get() == 1 + && !mv.zero_dim.get() + && mv.shape.peek()?.is_empty() + && mv.strides.peek()?.is_empty() + && mv.suboffsets.peek()?.is_empty() + && mv.format.peek()?.as_str() == "B" + }; + plain.then(|| (mv.start.get(), mv.len.get())) +} + +/// `view[i]` of such a view ([`mv_plain_bytes`]): the byte, for an index +/// in range (anything else is the full subscript's to answer or refuse). +fn mv_plain_byte(mv: &crate::object::PyMemoryView, i: i64) -> Option { + let (start, len) = mv_plain_bytes(mv)?; + let at = if i < 0 { i + len as i64 } else { i }; + if !(0..len as i64).contains(&at) { + return None; + } + mv.buffer + .with_read(|all| all.get(start + at as usize).copied()) +} + +/// Whether freeing `mv` runs no code: its buffer is bytes or a +/// `bytearray`'s (whose export count drops natively), and what it holds of +/// its exporter is bytes, a `bytearray`, or a view that is itself freed +/// quietly or kept alive elsewhere. +fn mv_frees_quietly(mv: &crate::object::PyMemoryView, depth: u32) -> bool { + use crate::object::MemoryViewBuffer; + if !matches!( + mv.buffer, + MemoryViewBuffer::Bytes(_) | MemoryViewBuffer::ByteArray(_) + ) { + return false; + } + // SAFETY: a guard-free read that ends at once (nothing here runs code); + // a cell borrowed mutably reads as not quiet. + match unsafe { mv.exporter.peek() } { + Some(None | Some(Object::Bytes(_) | Object::ByteArray(_))) => true, + Some(Some(Object::MemoryView(inner))) => { + Rc::strong_count(inner) > 1 || (depth < 4 && mv_frees_quietly(inner, depth + 1)) + } + _ => false, + } +} + +/// `view[i]` of a live view: the byte of a plain view +/// ([`mv_plain_byte`]), or the element of a 1-D view of a simple format +/// (`memoryview(b).cast("I")[i]`) as CPython's `memory_subscript` unpacks +/// it, for an index in range. `None` for anything else, which the full +/// subscript answers or refuses. +fn mv_leaf_item(mv: &crate::object::PyMemoryView, i: i64) -> Option { + if let Some(b) = mv_plain_byte(mv, i) { + return Some(Object::Int(i64::from(b))); + } + if mv.zero_dim.get() { + return None; + } + // SAFETY: guard-free reads, each ending at once (nothing here runs + // code); a cell borrowed mutably reads as declined. + let (n, fmt) = unsafe { + if !mv.suboffsets.peek()?.is_empty() { + return None; + } + let n = match mv.shape.peek()?.as_slice() { + [] => mv.len.get() / mv.itemsize.get().max(1), + [n] => *n, + _ => return None, + }; + (n, mv_adjust_fmt(mv.format.peek()?.as_str()).ok()?) + }; + if !matches!( + fmt, + 'b' | 'B' | '?' | 'h' | 'H' | 'i' | 'I' | 'l' | 'q' | 'n' | 'L' | 'Q' | 'N' | 'f' | 'd' + ) { + return None; + } + let at = if i < 0 { i.checked_add(n as i64)? } else { i }; + let idx = usize::try_from(at).ok().filter(|&k| k < n)?; + mv.read_element(&[idx], |b| mv_unpack_single(fmt, b).ok())? +} + +/// The sub-view `sub` as an object. It inherits the exporter edge, so it +/// can close the same cycles the parent can (test_memoryview.test_gc +/// slices a view of a bytes-subclass and cycles it through an attribute). +fn mv_tracked_subview(sub: crate::object::PyMemoryView) -> Object { let obj = Object::MemoryView(Rc::new(sub)); - // The sub-view inherits the exporter edge, so it can close the same - // cycles the parent can (test_memoryview.test_gc slices a view of a - // bytes-subclass and cycles it through an attribute). - if let Some(exp) = &exporter { - crate::gc_trace::track_memoryview_exporter(&obj, exp); + if let Object::MemoryView(view) = &obj { + if let Some(exp) = &*view.exporter.borrow() { + crate::gc_trace::track_memoryview_exporter(&obj, exp); + } } - Ok(obj) + obj +} + +/// Delete from `data` the `count` bytes an extended slice names, from +/// `start` by `step` (as [`adjust_slice`] reports them), closing the gaps +/// in one pass. +fn bytes_delete_strided(data: &mut Vec, start: i64, step: i64, count: i64) { + if count <= 0 { + return; + } + // (A descending slice names the same bytes as an ascending one.) + let (first, step) = if step < 0 { + (start + step * (count - 1), -step) + } else { + (start, step) + }; + let (first, step) = (first as usize, step as usize); + let (mut next, mut left, mut to) = (first, count as usize, first); + for from in first..data.len() { + if left > 0 && from == next { + left -= 1; + next += step; + } else { + data[to] = data[from]; + to += 1; + } + } + data.truncate(to); } -fn adjust_slice(len: i64, s: &PySlice) -> Result<(i64, i64, i64, i64), RuntimeError> { +pub(crate) fn adjust_slice(len: i64, s: &PySlice) -> Result<(i64, i64, i64, i64), RuntimeError> { let step = match &s.step { Object::None => 1i64, Object::Int(i) => *i, @@ -73273,6 +85020,65 @@ fn range_unpack_items(r: &crate::object::Range) -> Vec { out } +/// [`range_slice`] for a range of machine ints sliced by machine ints (or +/// defaults), the commonest shape: the same arithmetic in `i128`, which +/// 64-bit operands can't overflow, with no length built first. `None` for +/// anything wider, a zero step (the general path raises) or an index +/// object. +pub(crate) fn range_slice_small(r: &crate::object::Range, s: &PySlice) -> Option { + if r.big.is_some() { + return None; + } + let fits = |v: i128| i64::try_from(v).ok().map(i128::from); + let (r_start, r_stop, r_step) = (fits(r.start)?, fits(r.stop)?, fits(r.step)?); + let len = if r_step > 0 && r_start < r_stop { + (r_stop - r_start - 1) / r_step + 1 + } else if r_step < 0 && r_start > r_stop { + (r_start - r_stop - 1) / -r_step + 1 + } else { + 0 + }; + let member = |o: &Object| match o { + Object::None => Some(None), + Object::Int(i) => Some(Some(i128::from(*i))), + _ => None, + }; + let step = member(&s.step)?.unwrap_or(1); + if step == 0 { + return None; + } + let backwards = step < 0; + let (lower, upper) = if backwards { (-1, len - 1) } else { (0, len) }; + // Defaults apply directly; explicit bounds wrap and clamp (CPython's + // `_PySlice_GetLongIndices`). + let resolve = |o: &Object, default: i128| { + Some(match member(o)? { + None => default, + Some(v) if v < 0 => (v + len).max(lower), + Some(v) => v.min(upper), + }) + }; + let start = resolve(&s.start, if backwards { upper } else { lower })?; + let stop = resolve(&s.stop, if backwards { lower } else { upper })?; + let slicelen = if backwards { + if stop < start { + (start - stop - 1) / -step + 1 + } else { + 0 + } + } else if start < stop { + (stop - start - 1) / step + 1 + } else { + 0 + }; + let new_start = r_start.checked_add(start.checked_mul(r_step)?)?; + let new_step = r_step.checked_mul(step)?; + let new_stop = new_start.checked_add(slicelen.checked_mul(new_step)?)?; + Some(Object::Range(Rc::new(crate::object::Range::new( + new_start, new_stop, new_step, + )))) +} + /// `range(...)[slice]` → a new range, mirroring CPython `compute_slice`. /// Arbitrary-precision arithmetic throughout: the range length and the /// slice bounds may exceed `i64`/`i128` (`range(2**100)[:2**100]`, @@ -73345,6 +85151,24 @@ pub(crate) fn range_slice( /// returning them so the caller can prompt-reap (mirrors /// [`apply_slice_assignment`]). fn apply_slice_deletion(data: &mut Vec, s: &PySlice) -> Result, RuntimeError> { + // A unit step's run, from its bounds alone (`del items[-k:]`). + if matches!(s.step, Object::None | Object::Int(1)) { + let len = data.len() as i64; + let bound = |o: &Object, default: i64| match o { + Object::None => Some(default), + Object::Int(i) => Some(if *i < 0 { i.saturating_add(len) } else { *i }.clamp(0, len)), + _ => None, + }; + if let (Some(lo), Some(hi)) = (bound(&s.start, 0), bound(&s.stop, len)) { + // (Last first: the order CPython's `list_ass_slice` releases + // them in, which finalizers see.) + return Ok(if lo < hi { + data.drain(lo as usize..hi as usize).rev().collect() + } else { + Vec::new() + }); + } + } let mut indices = slice_indices(data.len(), s)?; indices.sort_unstable(); indices.dedup(); @@ -73444,6 +85268,39 @@ pub(crate) fn str_subscript_slice(s: &SharedStr, slc: &PySlice) -> Result = s.chars().collect(); Ok(Object::from_str( @@ -73454,7 +85311,29 @@ pub(crate) fn str_subscript_slice(s: &SharedStr, slc: &PySlice) -> Result(seq: &[T], s: &PySlice) -> Result, RuntimeError> { +/// A vector of clones of `run`: objects through their two-pass copy (see +/// [`crate::object::clone_objects_into`]), anything else as `to_vec` does. +fn clone_run(run: &[T]) -> Vec { + if std::any::TypeId::of::() == std::any::TypeId::of::() { + // SAFETY: `T` is `Object` (the same type under both names). + let run = unsafe { &*(std::ptr::from_ref(run) as *const [Object]) }; + let mut items = std::mem::ManuallyDrop::new(crate::object::cloned_vec(run)); + // SAFETY: as above; the vector's parts change hands whole. + return unsafe { + Vec::from_raw_parts( + items.as_mut_ptr().cast::(), + items.len(), + items.capacity(), + ) + }; + } + run.to_vec() +} + +pub(crate) fn slice_seq( + seq: &[T], + s: &PySlice, +) -> Result, RuntimeError> { let len = seq.len() as i64; let step = match &s.step { Object::None => 1i64, @@ -73530,13 +85409,43 @@ pub(crate) fn slice_seq(seq: &[T], s: &PySlice) -> Result, Runt if step == 1 { // Both bounds are within `0..=len` here: one contiguous copy. return Ok(if start < stop { - seq[start as usize..stop as usize].to_vec() + clone_run(&seq[start as usize..stop as usize]) } else { Vec::new() }); } + // `[::-1]`: the whole sequence reversed, at once. + if step == -1 && start == len - 1 && stop == -1 { + return Ok(seq.iter().rev().cloned().collect()); + } let mut i = start; - let mut out = Vec::new(); + // (The slice's length, as `PySlice_AdjustIndices` computes it.) + let count = if step > 0 { + if start < stop { + (stop - start - 1) / step + 1 + } else { + 0 + } + } else if stop < start { + (start - stop - 1) / (-step) + 1 + } else { + 0 + }; + let mut out = Vec::with_capacity(usize::try_from(count).unwrap_or(0).min(seq.len())); + // (A forward stride inside the sequence: one bounds check for the run, + // not one per item.) + if step > 0 && 0 <= start && start < stop && stop <= len { + if let (Ok(stride), Ok(n)) = (usize::try_from(step), usize::try_from(count)) { + // (An exact-length range, so the items are written in place + // with no per-item capacity check.) + let run = &seq[start as usize..stop as usize]; + debug_assert!(n == 0 || (n - 1) * stride < run.len()); + // SAFETY: the last item taken, `(n - 1) * stride`, is below + // `stop - start` by the count's construction. + out.extend((0..n).map(|k| unsafe { run.get_unchecked(k * stride) }.clone())); + return Ok(out); + } + } if step > 0 { while i < stop { if (0..len).contains(&i) { @@ -73951,7 +85860,7 @@ enum LeafAttr { // tested for), so the function-pointer equality the derive brings is moot. #[allow(unpredictable_function_pointer_comparisons)] #[derive(Clone, Copy, PartialEq, Eq)] -enum LeafKind { +pub(crate) enum LeafKind { /// A registered builtin's pure fast half (see /// `leaf_builtins::register_fast`). Fast(leaf_builtins::Fast), @@ -74097,6 +86006,10 @@ impl LeafKind { | Self::StrReplace | Self::StrFormat | Self::Scalar + // (`getattr(obj, name[, default])` answers only what runs + // no code, or a pure leaf getter's value, and declines the + // rest.) + | Self::GetAttr ) || matches!(self, Self::Fast(f) if pure_fast_half(f)) } } @@ -74112,10 +86025,7 @@ fn checks_like_type(cls: &TypeObject, hook: &str) -> bool { return true; } let meta = cls.metaclass_or_type(); - meta.c_ext_ptr.get() == 0 - && meta - .lookup_with_owner(hook) - .is_some_and(|(_, owner)| Rc::ptr_eq(&owner, &builtin_types().type_)) + meta.c_ext_ptr.get() == 0 && meta_check_is_type(&meta, hook == "__subclasscheck__") } fn leaf_issubclass(args: &[Object]) -> Option> { @@ -74146,29 +86056,51 @@ fn leaf_issubclass(args: &[Object]) -> Option> { /// effect (a module's may have one: `getrandbits` advances its state), so a /// frameless evaluation that declines after calling it did nothing. fn pure_fast_half(f: leaf_builtins::Fast) -> bool { - let pure: [leaf_builtins::Fast; 18] = [ - leaf_issubclass, - crate::seqiter::hash_fast, - Interpreter::leaf_hasattr, - crate::seqiter::min_fast, - crate::seqiter::max_fast, - crate::seqiter::sum_fast, - crate::seqiter::any_fast, - crate::seqiter::all_fast, - crate::seqiter::abs_fast, - crate::seqiter::ord_fast, - crate::seqiter::chr_fast, - crate::seqiter::divmod_fast, - crate::builtins::int_bit_length_leaf, - crate::builtins::int_to_bytes_leaf, - crate::builtins::int_from_bytes_leaf, - crate::builtins::str_encode_leaf, - crate::builtins::bytes_decode_leaf, - crate::builtins::dict_getitem_leaf, - ]; - pure.iter().any(|&p| std::ptr::fn_addr_eq(p, f)) - || crate::stdlib::math::is_fast_half(f) - || crate::stdlib::operator_accel::is_fast_half(f) + // (The halves' addresses in one set, built once: a leaf call asks for + // every builtin it runs, most of which are none of these.) + static PURE: std::sync::OnceLock< + std::collections::HashSet, + > = std::sync::OnceLock::new(); + let pure = PURE.get_or_init(|| { + let listed: [leaf_builtins::Fast; 26] = [ + leaf_issubclass, + // (A new string; a bad spec's error declines, the full call raises.) + leaf_format, + // (Of native numbers or strings only: a new value each.) + crate::seqiter::round_fast, + crate::seqiter::pow_fast, + crate::seqiter::repr_fast, + crate::builtins::hex_fast, + crate::builtins::oct_fast, + crate::builtins::bin_fast, + // (A new iterator over its argument, which it leaves alone.) + crate::seqiter::iter_fast, + crate::seqiter::hash_fast, + Interpreter::leaf_hasattr, + crate::seqiter::min_fast, + crate::seqiter::max_fast, + crate::seqiter::sum_fast, + crate::seqiter::any_fast, + crate::seqiter::all_fast, + crate::seqiter::abs_fast, + crate::seqiter::ord_fast, + crate::seqiter::chr_fast, + crate::seqiter::divmod_fast, + crate::builtins::int_bit_length_leaf, + crate::builtins::int_to_bytes_leaf, + crate::builtins::int_from_bytes_leaf, + crate::builtins::str_encode_leaf, + crate::builtins::bytes_decode_leaf, + crate::builtins::dict_getitem_leaf, + ]; + listed + .into_iter() + .chain(crate::stdlib::math::fast_halves()) + .chain(crate::stdlib::operator_accel::fast_halves()) + .map(|p| p as usize) + .collect() + }); + pure.contains(&(f as usize)) } /// A receiver's builtin variant, for the method table. @@ -74179,7 +86111,9 @@ enum LeafRecv { Set, Str, Int, + Float, Bytes, + ByteArray, } /// A builtin receiver's tag in a method site's slot (see @@ -74194,7 +86128,9 @@ fn leaf_recv_tag(recv: &Object) -> Option { | Object::Set(_) | Object::Str(_) | Object::Int(_) - | Object::Bytes(_) => builtin_recv_tag(recv), + | Object::Float(_) + | Object::Bytes(_) + | Object::ByteArray(_) => builtin_recv_tag(recv), _ => None, } } @@ -74204,11 +86140,22 @@ fn leaf_recv_tag(recv: &Object) -> Option { /// of the builtin types (the same bodies a bound method calls, without /// the type-dict descriptor's receiver check, which the burst's variant /// match makes redundant). +// (A thread's fork shares the builtins, and so this table: see +// `Interpreter::fork_for_thread`.) struct LeafFns { /// Function address → kind, for pointer-identity dispatch at `CALL`. calls: std::collections::HashMap, /// The builtin `len`'s address (for the fused `len(x)`), or 0. len_ptr: usize, + /// The builtin `hash`'s address (a leaf plan's fused `hash((a, b))`), + /// or 0. + hash_ptr: usize, + /// The builtin `isinstance`'s address (a leaf plan's direct + /// `isinstance(x, C)`), or 0. + isinstance_ptr: usize, + /// `dict.get`'s address (a leaf plan's direct `d.get(k[, default])`), + /// or 0. + dict_get_ptr: usize, /// The builtin `next`'s address (an inline generator resume), or 0. next_ptr: usize, /// The builtin `range` and `list` types, whose calls with leaf @@ -74221,6 +86168,12 @@ struct LeafFns { /// `(receiver variant, name, method)` for `LOAD_METHOD_ATTR` on a /// builtin receiver. methods: Vec<(LeafRecv, &'static str, Rc)>, + /// The same methods by name, for a lookup without the scan. + method_names: std::collections::HashMap< + &'static str, + Vec<(LeafRecv, Rc)>, + crate::fasthash::FxBuildHasher, + >, } /// A *lean* activation: a plain Python-to-Python call made from the quiet @@ -74261,6 +86214,151 @@ pub(crate) enum MethodOp { /// the operands wait under the call on the caller's stack, and the /// result goes through [`Interpreter::compare_finish`]. Compare(u32), + /// A `GET_ITER`'s `__iter__` (see `Interpreter::iter_dunder`): its + /// result goes through [`iter_result`]. + Iter, + /// A `STORE_ATTR`'s Python `__setattr__` or property setter, or a + /// `STORE_SUBSCR`'s `__setitem__`, called on the store's operands (see + /// `frame_jit::setter_call` and `frame_jit::h_setitem_dunder`): its + /// result is dropped, the store leaving nothing on the stack. + Store, + /// A `TO_BOOL`'s Python `__bool__` (or, `true`, `__len__`, for a class + /// without `__bool__`): its result becomes the truth (see + /// [`truth_result`]). + Truth(bool), + /// A `CONTAINS_OP`'s Python `__contains__` (`true` for `not in`): the + /// result's truth, inverted for `not in`. + Contains(bool), + /// `len(obj)`'s Python `__len__`: its result becomes the length (see + /// [`coerce_len_result`]). + Len, + /// An augmented assignment's Python in-place method (`__iadd__`, …) on + /// these operands: its `NotImplemented` goes on to the regular + /// operator ([`Interpreter::inplace_binop_fallback`]). + Inplace(BinOpKind, Object, Object), + /// A `FORMAT_VALUE`'s Python `__format__`: its result must be a string + /// (see [`format_result`]). + Format, + /// `str(obj)`'s Python `__str__`: its result must be a string. + Str, + /// `repr(obj)`'s Python `__repr__`: its result must be a string (see + /// [`repr_result`]). + Repr, + /// `hash(obj)`'s Python `__hash__`: its result must be an integer, and + /// becomes the hash (see [`Interpreter::normalize_hash_result`]). + Hash, + /// `hasattr(obj, name)`'s Python `__getattr__` (see + /// `frame_jit::attr_probe_call`): any result is `True`, and an + /// `AttributeError` it raises is `False`. + HasAttr, + /// `getattr(obj, name, default)`'s Python `__getattr__`: an + /// `AttributeError` it raises is the default. + GetAttrOr(Object), +} + +/// A `__str__` result `r` as `str(obj)` takes it: a string (a `str` +/// subclass's instance as it is), or the protocol's `TypeError`. +pub(crate) fn str_result(r: Object) -> Result { + if str_like_object(&r) { + return Ok(r); + } + Err(type_error(format!( + "__str__ returned non-string (type {})", + r.type_name() + ))) +} + +/// A `__repr__` result `r` as `repr(obj)` takes it: a string (a `str` +/// subclass's instance as it is), or the protocol's `TypeError`. +pub(crate) fn repr_result(r: Object) -> Result { + if str_like_object(&r) { + return Ok(r); + } + Err(type_error(format!( + "__repr__ returned non-string (type {})", + r.type_name() + ))) +} + +/// A `__format__` result `r` as `PyObject_Format` takes it: a string (a +/// `str` subclass's instance as its text), or the protocol's `TypeError`. +pub(crate) fn format_result(r: Object) -> Result { + match r { + r @ (Object::Str(_) | Object::WStr(_)) => Ok(r), + Object::Instance(ref i) + if matches!(i.native.get(), Some(Object::Str(_) | Object::WStr(_))) => + { + Ok(i.native.get().cloned().expect("checked")) + } + other => Err(type_error(format!( + "__format__ must return a str, not {}", + other.type_name() + ))), + } +} + +/// How a compiled `STORE_ATTR`'s Python function takes the store (see +/// `Interpreter::store_attr_function`). +pub(crate) enum StoreCall { + /// The class's `__setattr__`: `f(obj, name, value)`. + Hook, + /// A `property`'s setter: `f(obj, value)`. + Setter, + /// This data descriptor's `__set__`: `f(descriptor, obj, value)`. + Descriptor(Object), +} + +/// The truth a `__bool__` (or, `from_len`, a `__len__`) result `r` gives, as +/// `Interpreter::obj_truthy` takes one: an exact `bool` from `__bool__`, a +/// length from `__len__`. +pub(crate) fn truth_result(r: Object, from_len: bool) -> Result { + if from_len { + return coerce_len_result(r).map(|n| n != 0); + } + match r { + Object::Bool(b) => Ok(b), + other => Err(type_error(format!( + "__bool__ should return bool, returned {}", + other.type_name() + ))), + } +} + +/// `__iter__`'s result `v` as `GET_ITER` takes it: an instance without +/// `__next__` is the `TypeError` `Interpreter::make_iter` raises. +pub(crate) fn iter_result(v: Object) -> Result { + iter_result_check(&v)?; + Ok(v) +} + +/// [`iter_result`]'s test, on a borrowed result. +pub(crate) fn iter_result_check(v: &Object) -> Result<(), RuntimeError> { + let not_iterator = match v { + Object::Instance(inst) => inst.cls().lookup("__next__").is_none(), + // The builtin containers and scalars have no `__next__`. + Object::List(_) + | Object::Tuple(_) + | Object::Dict(_) + | Object::Set(_) + | Object::FrozenSet(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::ByteArray(_) + | Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Range(_) + | Object::Complex(_) => true, + _ => false, + }; + if not_iterator { + return Err(type_error(format!( + "iter() returned non-iterator of type '{}'", + v.type_name_owned() + ))); + } + Ok(()) } /// A lean activation the quiet loop runs *inline*: its frame lives in @@ -74344,6 +86442,13 @@ struct InlineAct { /// result goes on to the class's `__init__` as `type_call` runs it, /// not straight to the caller. new_init: Option>, + /// A callee of this activation that an exception ended while both ran + /// lazily (see `Interpreter::unwind_unseen`): its departed shell, + /// whose caller link waits for this activation's own shell, and the + /// call's pc. This activation's own departure gives it one, or its + /// registration (`Interpreter::resolve_back_for`); a record with one + /// pending never returns cleanly. + back_for: Option<(Rc, u32)>, } /// The rest of a constructor call whose Python `__new__` an inline @@ -74482,6 +86587,7 @@ impl InlineAct { chain: None, lru: None, new_init: None, + back_for: None, }); act.act.frame = std::ptr::from_mut::(&mut act.frame); act @@ -74656,8 +86762,7 @@ thread_local! { /// (see `generator_send_fold`). static GEN_RAW_RETURN: std::cell::Cell = const { std::cell::Cell::new(false) }; /// The value a raw resume's generator returned. - static GEN_RETURN_VALUE: std::cell::RefCell> = - const { std::cell::RefCell::new(None) }; + static GEN_RETURN_VALUE: crate::gil::ReleaseUnderGil>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(None)) }; } enum GenStep { @@ -74837,14 +86942,19 @@ impl CoreSwitch { /// for everything after (each phase is left for good). /// A draining consumer's sink for a lean generator resume's yields (see /// [`Interpreter::sum_fold`]): `sum()`'s running total, which takes -/// scalars, `list()`'s item buffer, which takes anything, or `all()` / -/// `any()`'s scan, which takes an item whose truth is known natively and -/// isn't the deciding one (`Truth(true)` for `any`). +/// scalars and, once the total is a list of its own, exact lists; +/// `list()`'s item buffer, which takes anything; or `all()` / `any()`'s +/// scan, which takes an item whose truth is known natively and isn't the +/// deciding one (`Truth(true)` for `any`): a scalar, or a heap value +/// [`fold_heap_truth`] knows. #[derive(Clone, Copy)] enum FoldSink { Sum(*mut SumState), Collect(*mut Vec), Truth(bool), + /// `set.update()`'s set, which takes a `str`, `int` or tuple of them + /// that it can hash and compare with no code run. + AddTo(*const RefCell), } impl FoldSink { @@ -74859,21 +86969,57 @@ impl FoldSink { #[inline(always)] unsafe fn fold(self, top: *mut Object) -> bool { match self { - // A scalar has no drop glue. + // A scalar has no drop glue; a list's items are copied to the + // total before the list is released, so nothing dies with it. // SAFETY: the caller's contract. - Self::Sum(acc) => unsafe { (*acc).add_scalar(&*top) }, + Self::Sum(acc) => unsafe { (*acc).add_scalar(&*top) || (*acc).fold_list(top) }, Self::Collect(out) => { // SAFETY: the yielded value moves out. unsafe { (*out).push(top.read()) }; true } + Self::AddTo(set) => { + // SAFETY: the caller's contract; the set is the consumer's, + // alive while the resume runs, and a view of it that no + // other borrow holds runs no code. + unsafe { + let k = &*top; + if !matches!(k, Object::Str(_) | Object::Int(_) | Object::Tuple(_)) { + return false; + } + let Some(probe) = crate::object::LeafProbe::new(k) else { + return false; + }; + let Some(m) = (*set).peek_mut() else { + return false; + }; + if m.get_index_of(&probe).is_some() { + // (Present: the yielded value, a plain one, drops.) + drop(top.read()); + } else if probe.miss_is_exact() { + m.insert(DictKey(top.read())); + } else { + // (A key of another kind that may equal it.) + return false; + } + true + } + } // SAFETY: the caller's contract. Self::Truth(decides) => match unsafe { &*top } { Object::Bool(b) => *b != decides, Object::Int(i) => (*i != 0) != decides, Object::Float(x) => (*x != 0.0) != decides, Object::None => decides, - _ => false, + v => match fold_heap_truth(v) { + Some(truth) if truth != decides => { + // SAFETY: the value moves out; its release runs no + // code (see `fold_heap_truth`). + drop(unsafe { top.read() }); + true + } + _ => false, + }, }, } } @@ -74884,11 +87030,66 @@ impl FoldSink { // between threads never carries a live one. unsafe impl Send for FoldSink {} +/// The truth of a yielded heap value `v`, for `all()` / `any()`'s sink +/// (see [`FoldSink::Truth`]): known with no code run, of a value whose +/// release here runs none either: a `str`, or a container or plain +/// instance another owner keeps alive (the list the generator walks, say), +/// while nothing observes releases. `None` for the rest, which go back to +/// the consumer. +#[inline(never)] +fn fold_heap_truth(v: &Object) -> Option { + if !Interpreter::core_drops_plain() { + return None; + } + if let Object::Str(s) = v { + return Some(!s.is_empty()); + } + let word = v.strong_word()?; + // SAFETY: a counted variant's word, live while `v` is. + if unsafe { &*word }.load(std::sync::atomic::Ordering::Relaxed) <= 1 { + return None; + } + Some(match v { + Object::Tuple(t) => !t.is_empty(), + Object::Bytes(b) => !b.is_empty(), + Object::FrozenSet(s) => !s.is_empty(), + // SAFETY: (each) a read between two instructions. + Object::List(l) => !unsafe { l.peek() }?.is_empty(), + Object::Dict(d) => !unsafe { d.peek() }?.is_empty(), + Object::Set(s) => !unsafe { s.peek() }?.is_empty(), + Object::Instance(inst) if instance_always_true(inst) => true, + _ => return None, + }) +} + +/// Whether `inst` is true whatever it holds: a plain instance (no native +/// payload or body) of a Python class under the default attribute access +/// that has neither `__bool__` nor `__len__`, as `native_truth_of` finds +/// one always true. Memoized per class until it or a base changes. +fn instance_always_true(inst: &PyInstance) -> bool { + let cls = inst.cls_raw(); + inst.native.get().is_none() + && inst.c_body.get() == 0 + && cls.memo_verdict(crate::types::Verdict::AlwaysTrue, "", || { + cls.native_kind.get() == 0 + && cls.c_ext_ptr.get() == 0 + && !cls.flags.is_builtin + && !crate::object::exotic_str_keys_possible() + && Interpreter::default_getattribute(cls) + && cls.lookup("__bool__").is_none() + && cls.lookup("__len__").is_none() + }) +} + enum SumState { Int(i64), Float(CompensatedSum), Complex(CompensatedSum, CompensatedSum), Generic(Object), + /// A list the sum built itself (`sum(lists, [])` past its first + /// item), which nothing else can reach: a further list item extends + /// it in place, as the new list `total + item` would read. + OwnList(Object), } /// CPython's `CompensatedSum`: Neumaier's improved Kahan–Babuška sum. @@ -74971,14 +87172,77 @@ impl SumState { sum.add(value); true } - SumState::Generic(_) => false, + SumState::Generic(_) | SumState::OwnList(_) => false, } } + /// [`FoldSink::Sum`]'s fold of a yielded exact list at `top` onto a + /// total that is a list of the sum's own (see [`SumState::OwnList`]), + /// as [`Self::add`] extends it: the items are copied, then the list is + /// released, which frees no item (the total holds each) and so runs no + /// code. `false` touches nothing. + /// + /// # Safety + /// + /// `top` holds the yielded value. + #[inline(never)] + unsafe fn fold_list(&mut self, top: *mut Object) -> bool { + let SumState::OwnList(Object::List(total)) = self else { + return false; + }; + // SAFETY: the caller's contract. + let Object::List(item) = (unsafe { &*top }) else { + return false; + }; + if Rc::ptr_eq(item, total) || !Interpreter::core_drops_plain() { + return false; + } + // SAFETY: views dropped before anything else runs; the two lists + // are distinct. + let (Some(src), Some(dst)) = (unsafe { item.peek() }, unsafe { total.peek_mut() }) else { + return false; + }; + dst.extend(src.iter().cloned()); + // SAFETY: the value moves out. + drop(unsafe { top.read() }); + true + } + fn add(&mut self, interp: &mut Interpreter, x: Object) -> Result<(), RuntimeError> { if self.add_scalar(&x) { return Ok(()); } + // Exact lists concatenate natively (no reflected operand can take + // part): the first into a new list, the rest onto it. + if let Object::List(item) = &x { + let built = match &*self { + SumState::OwnList(Object::List(total)) => { + if let (Ok(src), Ok(mut dst)) = (item.try_borrow(), total.try_borrow_mut()) { + dst.extend(src.iter().cloned()); + return Ok(()); + } + None + } + SumState::Generic(Object::List(start)) => { + match (start.try_borrow(), item.try_borrow()) { + (Ok(a), Ok(b)) => { + let mut v = Vec::with_capacity(a.len() + b.len()); + v.extend(a.iter().cloned()); + v.extend(b.iter().cloned()); + Some(v) + } + _ => None, + } + } + _ => None, + }; + if let Some(v) = built { + let out = Object::new_list(v); + crate::gc_trace::track_built(&out); + *self = SumState::OwnList(out); + return Ok(()); + } + } // A big int in a compensated phase converts (or overflows). if let (SumState::Float(re) | SumState::Complex(re, _), Object::Long(v)) = (&mut *self, &x) { @@ -75017,7 +87281,7 @@ impl SumState { return Ok(()); } SumState::Complex(re, im) => Object::new_complex(re.value(), im.value()), - SumState::Generic(t) => t, + SumState::Generic(t) | SumState::OwnList(t) => t, }; *self = SumState::Generic(interp.op_binary(&total, &x, BinOpKind::Add)?); Ok(()) @@ -75028,7 +87292,7 @@ impl SumState { SumState::Int(i) => Object::Int(i), SumState::Float(re) => crate::object::fresh_float(re.value()), SumState::Complex(re, im) => Object::new_complex(re.value(), im.value()), - SumState::Generic(t) => t, + SumState::Generic(t) | SumState::OwnList(t) => t, } } } @@ -75184,6 +87448,66 @@ pub(crate) fn await_send_after(code: &CodeObject, pc: usize) -> Option { .then_some(pc + 3) } +/// Whether a class attribute's value `held` and the value `new` stored +/// over it are plain data of one kind: values no attribute access binds, +/// calls or asks for `__get__`, whatever class holds them, so that +/// nothing which depends on what the name binds, or on its value's kind, +/// can tell the store happened (see `TypeObject::bind_version`). +fn inert_class_values(held: &Object, new: &Object) -> bool { + std::mem::discriminant(held) == std::mem::discriminant(new) + && matches!( + new, + Object::None + | Object::Bool(_) + | Object::Int(_) + | Object::Long(_) + | Object::Float(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::Tuple(_) + | Object::List(_) + | Object::Dict(_) + | Object::Set(_) + | Object::FrozenSet(_) + ) +} + +/// The `END_SEND` that the `GET_ANEXT` at `pc` of `code` ends at when the +/// `LOAD_CONST None; SEND` awaiting its awaitable at once follows it (an +/// `async for`'s step, an async comprehension's): what an async generator's +/// item skips to (see `Interpreter::anext_in_place`). +pub(crate) fn anext_send_exit(code: &CodeObject, pc: usize) -> Option { + let (none, send) = ( + code.instructions.get(pc + 1)?, + code.instructions.get(pc + 2)?, + ); + let exit = pc + 3 + send.arg as usize; + (none.op == OpCode::LoadConst + && send.op == OpCode::Send + && matches!(code.constants.get(none.arg as usize), Some(Constant::None)) + && code.instructions.get(exit).map(|i| i.op) == Some(OpCode::EndSend)) + .then_some(exit) +} + +/// How a drive of an `asend` / `athrow` / `aclose` awaitable ended (see +/// `Interpreter::step_agen_await_raw`). +pub(crate) enum AgenAwaitStep { + /// The generator suspended on an inner `await`: its value, passed on. + Passed(Object), + /// The operation completed: its value (`aclose`'s has none). + Done(Option), +} + +/// How an async generator's resume for an `async for`'s step ended (see +/// `Interpreter::anext_resume`). +pub(crate) enum AnextStep { + /// Its own `yield`: the item. + Item(Object), + /// A suspension on an inner `await`: the `asend(None)` awaitable, + /// driven once, and the value passed through. + Passed(Object, Object), +} + /// Move the object at `src` to `dst` as one 16-byte copy: a move through /// a typed value (`pop` then `push`) splits it at the tag byte, and the /// 16-byte reload that follows stalls on store forwarding. @@ -75339,15 +87663,110 @@ enum QuietShell<'a> { thread_local! { /// The `**kwargs` dictionary of the last keyword leaf call, emptied, /// when nothing kept it (see [`recycle_kw_dict`]). - static SPARE_KW_DICT: std::cell::Cell>>> = - const { std::cell::Cell::new(None) }; + static SPARE_KW_DICT: crate::gil::ReleaseUnderGil>>>> = const { crate::gil::ReleaseUnderGil::new(std::cell::Cell::new(None)) }; } /// An empty `**kwargs` dictionary with room for `n` keys: the spare one, /// if any, else a fresh one. +/// Whether `code`'s `**kwargs` dict can only be read in its call: every use +/// of its slot loads it straight into a `DICT_MERGE` or `DICT_UPDATE` +/// (`fn(*a, **k)`), which copy it, no closure captures it, and nothing can +/// read the frame's locals (`locals()`, `vars()`, `eval`, `exec`, a frame). +/// Such a dict can't close a cycle that outlives the call, so its binder +/// needn't register it with the collector. Cached in the code's extension +/// table. +fn varkw_stays_local(code: &CodeObject) -> bool { + use std::sync::atomic::Ordering; + let Some(ext) = code_vm_ext(code) else { + return false; + }; + match ext.varkw_local.load(Ordering::Relaxed) { + 1 => return true, + 2 => return false, + _ => {} + } + let slot = code.arg_count as usize + code.kwonly_count as usize + usize::from(code.has_varargs); + let captured = code + .varnames + .get(slot) + .is_none_or(|n| code.cellvars.iter().any(|c| c == n)); + let introspects = code.names.iter().any(|n| { + matches!( + n.as_str(), + "locals" | "vars" | "eval" | "exec" | "_getframe" | "f_locals" | "currentframe" + ) + }); + let ins = &code.instructions; + let local = !captured + && !introspects + && ins.iter().enumerate().all(|(pc, i)| match i.op { + OpCode::LoadFast | OpCode::LoadFastBorrow | OpCode::LoadFastCheck + if i.arg as usize == slot => + { + varkw_use_reads(code, pc) + } + OpCode::LoadFastAndClear | OpCode::StoreFast | OpCode::DeleteFast => { + i.arg as usize != slot + } + OpCode::LoadFastLoadFast + | OpCode::LoadFastBorrowLoadFastBorrow + | OpCode::StoreFastLoadFast + | OpCode::StoreFastStoreFast => { + (i.arg >> 4) as usize != slot && (i.arg & 15) as usize != slot + } + _ => true, + }); + ext.varkw_local + .store(if local { 1 } else { 2 }, Ordering::Relaxed); + local +} + +/// Whether the load of a `**kwargs` dict at `pc` of `code` only reads it +/// (see [`varkw_stays_local`]): a `DICT_UPDATE` that copies it, a truth +/// test, `in`, a `for` over its keys, `len(kw)`, or a call of one of the +/// dict's own methods that return neither it nor a view of it +/// (`kw.get(k)`, `kw.pop(k, d)`). +fn varkw_use_reads(code: &CodeObject, pc: usize) -> bool { + let ins = &code.instructions; + let op = |k: usize| ins.get(k).map(|i| i.op); + match op(pc + 1) { + Some( + OpCode::DictUpdate + | OpCode::ToBool + | OpCode::PopJumpIfFalse + | OpCode::PopJumpIfTrue + | OpCode::ContainsOp, + ) => true, + // (The iterator only lives on the stack through its loop.) + Some(OpCode::GetIter) => op(pc + 2) == Some(OpCode::ForIter), + // (A method-call site: the bound method goes to its call.) + Some(OpCode::LoadMethodAttr) => { + let name = code.names.get(ins[pc + 1].arg as usize); + name.is_some_and(|n| { + matches!( + n.as_str(), + "get" | "pop" | "setdefault" | "__contains__" | "__getitem__" | "__len__" + ) + }) + } + // (`LOAD_GLOBAL len`, `PUSH_NULL`, the dict, `CALL 1`.) + Some(OpCode::Call) => { + ins[pc + 1].arg == 1 + && pc >= 2 + && ins[pc - 1].op == OpCode::PushNull + && ins[pc - 2].op == OpCode::LoadGlobal + && code + .names + .get(ins[pc - 2].arg as usize) + .is_some_and(|n| n == "len") + } + _ => false, + } +} + fn spare_kw_dict(n: usize) -> Rc> { SPARE_KW_DICT - .try_with(std::cell::Cell::take) + .try_with(|c| c.take()) .ok() .flatten() .unwrap_or_else(|| { @@ -75446,6 +87865,99 @@ type CoreNext = ( /// beyond what it returns (the full `CALL` marks after every native call; /// the leaf burst relies on the body instead). The leaf burst may call /// them directly. +/// [`Interpreter::kw_bind_plan`]'s marker for an optional parameter the +/// call leaves out. +const KW_UNBOUND: u8 = u8::MAX; + +/// The most parameters a registered keyword half binds (`datetime.replace` +/// takes eight). +const KW_MAX: usize = 8; + +/// A keyword call site's binding to a registered builtin's leaf half, as +/// [`kw_bind_memo`] remembers it. +struct KwBind { + /// The builtin and the names tuple, held (so no other object takes + /// either's address while the entry lives). + builtin: Rc, + names: Object, + argc: usize, + generation: u64, + map: [u8; KW_MAX], + n: usize, + fast: leaf_builtins::Fast, +} + +/// Recent keyword call sites' bindings, per thread: a site calls the same +/// builtin with the same names tuple again and again, and binding them by +/// name each time cost more than the builtin's own work. (Leaked at thread +/// exit: dropping objects then could outlive their interpreter.) +struct KwBindMemo([Option; 4]); + +impl Drop for KwBindMemo { + fn drop(&mut self) { + for e in &mut self.0 { + std::mem::forget(e.take()); + } + } +} + +/// The binding of a `CALL_KW` of `b` with `argc` positionals and the +/// keywords tuple `names`: the memo's, or `plan`'s, remembered (`None`, a +/// site the half doesn't serve, isn't). +#[inline] +fn kw_bind_memo( + b: &Rc, + names: &Object, + argc: usize, + plan: impl FnOnce() -> Option<([u8; KW_MAX], usize, leaf_builtins::Fast)>, +) -> Option<([u8; KW_MAX], usize, leaf_builtins::Fast)> { + thread_local! { + static MEMO: std::cell::RefCell = + const { std::cell::RefCell::new(KwBindMemo([const { None }; 4])) }; + } + let Object::Tuple(t) = names else { + return None; + }; + let key = t.as_ptr() as usize; + let way = ((key >> 4) ^ (key >> 10)) & 3; + let generation = leaf_builtins::fast_kw_generation(); + let hit = MEMO + .try_with(|m| { + let m = m.try_borrow().ok()?; + let e = m.0[way].as_ref()?; + let Object::Tuple(en) = &e.names else { + return None; + }; + (en.as_ptr() as usize == key + && Rc::ptr_eq(&e.builtin, b) + && e.argc == argc + && e.generation == generation) + .then_some((e.map, e.n, e.fast)) + }) + .ok() + .flatten(); + if hit.is_some() { + return hit; + } + let (map, n, fast) = plan()?; + let _ = MEMO.try_with(|m| { + if let Ok(mut m) = m.try_borrow_mut() { + // (The entry it replaces releases a builtin and a tuple, which + // runs no code.) + m.0[way] = Some(KwBind { + builtin: b.clone(), + names: names.clone(), + argc, + generation, + map, + n, + fast, + }); + } + }); + Some((map, n, fast)) +} + pub(crate) mod leaf_builtins { use std::sync::atomic::{AtomicU64, Ordering}; @@ -75474,8 +87986,10 @@ pub(crate) mod leaf_builtins { Scalar, } - static REGISTRY: parking_lot::Mutex, Entry)>> = - parking_lot::Mutex::new(Vec::new()); + /// The registrations by address (a dead builtin's entry is replaced by + /// whatever registers at its address next, and dropped at a sweep, see + /// `push`). + static REGISTRY: parking_lot::Mutex> = parking_lot::Mutex::new(None); static GENERATION: AtomicU64 = AtomicU64::new(1); /// Vouch for `b` (by identity): its whole body is a leaf. @@ -75496,12 +88010,35 @@ pub(crate) mod leaf_builtins { } fn push(b: &Rc, entry: Entry) { + // (Dead entries are dropped when the map has doubled since the last + // sweep, not at every push, which made registering a module's + // builtins quadratic. Until then a dead one only holds its + // allocation, which keeps any other builtin from its address, and + // `lookup` checks that the entry's builtin is alive.) + static SWEPT_AT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let mut reg = REGISTRY.lock(); - reg.retain(|(w, _)| w.strong_count() > 0); - reg.push((Rc::downgrade(b), entry)); + let reg = reg.get_or_insert_with(LeafMap::default); + if reg.len() >= (2 * SWEPT_AT.load(Ordering::Relaxed)).max(256) { + reg.retain(|_, (w, _)| w.strong_count() > 0); + SWEPT_AT.store(reg.len(), Ordering::Relaxed); + } + reg.insert(Rc::as_ptr(b) as usize, (Rc::downgrade(b), entry)); GENERATION.fetch_add(1, Ordering::Release); } + /// The registration at `b`'s address, if it is `b`'s. + pub(crate) fn lookup( + b: &Rc, + ) -> Option<(Weak, Entry)> { + let reg = REGISTRY.lock(); + let (w, e) = reg.as_ref()?.get(&(Rc::as_ptr(b) as usize))?; + std::ptr::eq(w.as_ptr(), Rc::as_ptr(b)) + .then(|| w.upgrade()) + .flatten() + .filter(|live| Rc::ptr_eq(live, b)) + .map(|_| (w.clone(), *e)) + } + pub(crate) fn generation() -> u64 { GENERATION.load(Ordering::Acquire) } @@ -75522,15 +88059,43 @@ pub(crate) mod leaf_builtins { let mut reg = FAST_KW.lock(); reg.retain(|(w, _, _)| w.strong_count() > 0); reg.push((Rc::downgrade(b), names, fast)); + FAST_KW_GEN.fetch_add(1, Ordering::Release); } /// `b`'s keyword binding and leaf half, if registered (by identity). pub(crate) fn fast_kw(b: &Rc) -> Option<(KwNames, Fast)> { - FAST_KW + // (The last answer per thread, by the builtin's address and the + // registrations' count: a keyword call site asks about one builtin + // again and again. The registry's weak handle keeps a registered + // builtin's allocation, so no other builtin lives at its address + // until a registration prunes it, which a new count marks.) + thread_local! { + static LAST: std::cell::Cell<(usize, u64, Option<(KwNames, Fast)>)> = + const { std::cell::Cell::new((0, 0, None)) }; + } + let at = Rc::as_ptr(b) as usize; + let gen = FAST_KW_GEN.load(Ordering::Acquire); + if let Ok((p, g, found)) = LAST.try_with(std::cell::Cell::get) { + if p == at && g == gen { + return found; + } + } + let found = FAST_KW .lock() .iter() - .find(|(w, _, _)| std::ptr::eq(w.as_ptr(), Rc::as_ptr(b)) && w.strong_count() > 0) - .map(|&(_, names, fast)| (names, fast)) + .find(|(w, _, _)| std::ptr::eq(w.as_ptr(), at as *const _) && w.strong_count() > 0) + .map(|&(_, names, fast)| (names, fast)); + let _ = LAST.try_with(|c| c.set((at, gen, found))); + found + } + + /// Bumped by every [`register_fast_kw`] (see [`fast_kw`]'s cache). + static FAST_KW_GEN: AtomicU64 = AtomicU64::new(1); + + /// The registrations' count (see [`fast_kw`]'s cache). + #[inline] + pub(crate) fn fast_kw_generation() -> u64 { + FAST_KW_GEN.load(Ordering::Acquire) } /// Builtins opted into the JIT's native method lane (see @@ -75562,16 +88127,6 @@ pub(crate) mod leaf_builtins { .map(|&(_, op)| op) } - /// The live registrations, keyed by address. - pub(crate) fn snapshot() -> LeafMap { - REGISTRY - .lock() - .iter() - .filter(|(w, _)| w.strong_count() > 0) - .map(|(w, f)| (w.as_ptr() as usize, (w.clone(), *f))) - .collect() - } - pub(crate) type LeafMap = std::collections::HashMap< usize, (Weak, Entry), @@ -75579,6 +88134,10 @@ pub(crate) mod leaf_builtins { >; } +/// Builtins found unregistered as leaves, by address (see +/// [`Interpreter::leaf_call_kind`]). +type LeafMisses = std::collections::HashSet; + /// `WEAVEPY_BURST_STATS=1`: which opcodes the quiet loop still runs /// through the full handlers (that is, outside the leaf burst), printed /// at shutdown. A tuning aid: the counts say where the burst's coverage @@ -76079,6 +88638,13 @@ fn class_dunder_new(cls: &TypeObject) -> Option { None } +/// The instance-dict names the enum fast paths read (see +/// `Interpreter::enum_member_field`), by index. +const ENUM_FIELDS: [&str; 3] = ["_name_", "_value_", "fget"]; +const ENUM_NAME: usize = 0; +const ENUM_VALUE: usize = 1; +const ENUM_FGET: usize = 2; + /// Whether `inst`, a subclass instance of a built-in type with no `tp_str` /// of its own (`int`, `float`, `complex`, `list`, `dict`, `tuple`), /// overrides `__repr__` below the built-in base: `str(inst)` then renders @@ -76105,7 +88671,7 @@ fn native_subclass_own_repr(inst: &crate::types::PyInstance) -> bool { /// proved `object.__new__(cls)` the plain allocation (as `object_new` /// reads it): no abstract methods, built-in base or special allocator. #[inline] -fn object_new_plain_memo(cls: &TypeObject) -> bool { +pub(crate) fn object_new_plain_memo(cls: &TypeObject) -> bool { // SAFETY: a guard-free read of the memoized plan; nothing runs before // its last use. unsafe { cls.instance_plan.peek() } @@ -76191,7 +88757,7 @@ fn is_object_init(b: &crate::object::BuiltinFn) -> bool { } /// Whether `b` is `object.__new__` (the process-wide builtin). -fn is_object_new(b: &Rc) -> bool { +pub(crate) fn is_object_new(b: &Rc) -> bool { thread_local! { static OBJECT_NEW: std::cell::Cell = const { std::cell::Cell::new(0) }; } @@ -76722,9 +89288,9 @@ thread_local! { /// `builtin_type_dunder` results (misses included) by built-in type /// address, then name. #[allow(clippy::type_complexity)] - static SLOT_WRAPPER_CACHE: std::cell::RefCell< + static SLOT_WRAPPER_CACHE: crate::gil::ReleaseUnderGil, Option>>, - > = std::cell::RefCell::new(crate::fasthash::FxHashMap::default()); + >> = crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(crate::fasthash::FxHashMap::default())); } /// The built-in class whose attributes are all of `obj`'s: a value of a @@ -76749,6 +89315,15 @@ fn builtin_value_class(obj: &Object) -> Option> { .then(|| crate::builtins::class_of(obj)) } +/// Whether a built-in subclass instance's payload is known to lack the +/// attribute `name`: a value of a built-in type whose class an earlier +/// full read found without it (see `Verdict::ValueAttrMissing`). +fn payload_class_misses(payload: &Object, name: &str) -> bool { + builtin_value_class(payload).is_some_and(|c| { + c.verdict_cached(crate::types::Verdict::ValueAttrMissing, name) == Some(true) + }) +} + /// Whether `obj.name` certainly raises `AttributeError` without running /// any code: an ordinary instance under the default attribute protocol, /// with no class attribute of that name and none in its `__dict__`. A @@ -76758,6 +89333,27 @@ fn attr_certainly_missing(obj: &Object, name: &str) -> bool { default_lookup_misses(obj, name, false) } +/// How `getattr(cls, name[, default])` resolves without the full path (see +/// [`Interpreter::leaf_type_getattr_how`]). +enum TypeGetattr { + /// The value the class's MRO supplies, and whether a Python class's + /// dictionary holds it (for as long as the class's version stands). + Found(Object, bool), + /// Nothing supplies the name, certainly: the default answers. + Missing, + /// The full path decides. + Decline, +} + +/// An answer [`Interpreter::leaf_type_getattr_memo`] keeps. +enum TypeGetattrKept { + Missing, + /// A value whose lifetime nothing observes. + Owned(Object), + /// A value's two words, held by a class on the MRO. + Borrowed([u64; 2]), +} + /// Whether the full path may remember class `t`'s miss of `name` per class /// version (see [`crate::types::Verdict::TypeAttrMissing`]): a builtin /// class's, or a Python class's under plain `type` with no entry for the @@ -76885,9 +89481,20 @@ fn default_lookup_misses(obj: &Object, name: &str, hooked: bool) -> bool { return false; }; let dunder = name.starts_with("__"); - if inst.native.get().is_some() || inst.c_body.get() != 0 { + if inst.c_body.get() != 0 { return false; } + // A built-in subclass's instance (`class TokenList(list)`) also reads + // its payload's attributes (`load_attr_instance_default`'s step 3c), + // which depend on the payload's class and the name alone: a name the + // full read found that class to lack (it records the miss there) + // misses for good. Dunders, which the payload supplies in other ways, + // never qualify. + if let Some(payload) = inst.native.get() { + if dunder || !payload_class_misses(payload, name) { + return false; + } + } let cls = inst.cls(); if cls.native_kind.get() != 0 { return false; @@ -76929,10 +89536,21 @@ fn default_lookup_misses(obj: &Object, name: &str, hooked: bool) -> bool { if !class_missing { return !dunder && slot_member_unset(&cls, inst, name); } + inst_dict_misses(inst, name) +} + +/// Whether `inst`'s own `__dict__` certainly lacks `name` (see +/// [`default_lookup_misses`], whose class half its caller settled). +fn inst_dict_misses(inst: &PyInstance, name: &str) -> bool { match inst.dict.published() { - Some(d) => d - .try_borrow() - .is_ok_and(|d| !d.contains_key(&crate::object::StrKey(name))), + // (Probed without running Python: a stored key that only a user + // `__eq__` could equate to the name leaves the miss uncertain, for + // the full lookup, which runs that comparison from a frame its + // caller can see.) + Some(d) => d.try_borrow().is_ok_and(|d| { + let probe = crate::object::LeafNameProbe::new(name, crate::object::py_str_hash(name)); + !d.contains_key(&probe) && !probe.saw_exotic() + }), None => inst .dict .split_cell() @@ -76962,6 +89580,336 @@ pub(crate) fn certain_miss_error_obj( } } +/// What [`Interpreter::leaf_getattr_parts`] found on an instance's class +/// for a name, under the default `__getattribute__`. +#[derive(Clone, Copy)] +enum InstGetattrClass { + /// Nothing: the instance's own value decides. + Nothing, + /// A `__slots__` member without a default. + Slot, + /// A plain value or a function (nothing with a `__set__`): an + /// instance's own value shadows it (a dataclass field's default, a + /// class-level default an `__init__` overwrites), and an instance + /// without one reads the class's. + Shadowed, +} + +/// Entries of [`INST_GETATTR_MEMO`]. +const INST_GETATTR_SLOTS: usize = 64; + +/// One [`INST_GETATTR_MEMO`] answer: the class attribute version (unique +/// in the process, and moved by any change to the class, a base, or the +/// MRO), the name as two words and its length (see [`inst_getattr_key`]), +/// and the answer (`0` none). +#[derive(Clone, Copy)] +struct InstGetattrEntry { + ver: u64, + words: [u64; 2], + len: u8, + kind: u8, + /// For a name the class supplies nothing for: one past its position + /// among the class's shared instance names, once a read found it + /// there (`0` not looked for yet, [`PLACE_NONE`] not there). + place: u32, +} + +/// An [`InstGetattrEntry`] place that was looked for and not found. +const PLACE_NONE: u32 = u32::MAX; + +thread_local! { + /// [`InstGetattrClass`] answers by class version and name. + /// `getattr(obj, name, default)`, `hasattr` and `attrgetter` ask the + /// same question of each instance of a class, and the class lookup + /// cost more than the rest of the read. (Plain entries in the thread's + /// static block: a probe is a few loads, with no destructor to + /// register and no name to keep alive.) + static INST_GETATTR_MEMO: [std::cell::Cell; INST_GETATTR_SLOTS] = const { + [const { + std::cell::Cell::new(InstGetattrEntry { + ver: 0, + words: [0; 2], + len: 0, + kind: 0, + place: 0, + }) + }; INST_GETATTR_SLOTS] + }; +} + +/// `name` as [`InstGetattrEntry`] words, for a name of at most 16 bytes: +/// its first and last eight bytes (overlapping, so with the length they +/// determine the name), or for a shorter one its first and last four, +/// two or one (likewise). +#[inline] +fn inst_getattr_key(name: &str) -> Option<([u64; 2], u8)> { + let b = name.as_bytes(); + let n = b.len(); + let w8 = |at: usize| u64::from_le_bytes(b[at..at + 8].try_into().expect("8 bytes")); + let w4 = |at: usize| { + u64::from(u32::from_le_bytes( + b[at..at + 4].try_into().expect("4 bytes"), + )) + }; + let w2 = |at: usize| { + u64::from(u16::from_le_bytes( + b[at..at + 2].try_into().expect("2 bytes"), + )) + }; + let words = match n { + 17.. => return None, + 8.. => [w8(0), w8(n - 8)], + 4.. => [w4(0), w4(n - 4)], + 2.. => [w2(0), w2(n - 2)], + 1 => [u64::from(b[0]), 0], + 0 => [0, 0], + }; + Some((words, n as u8)) +} + +#[inline] +fn inst_getattr_slot(ver: u64, words: &[u64; 2]) -> usize { + let x = (ver ^ words[0] ^ words[1].rotate_left(17)).wrapping_mul(0x9E37_79B9_7F4A_7C15); + (x >> (u64::BITS - INST_GETATTR_SLOTS.trailing_zeros())) as usize +} + +/// The remembered [`InstGetattrClass`] of `name` on `cls`, if any (none +/// for a class without a version, or while types are watched). +#[inline] +fn instance_getattr_memo(cls: &TypeObject, name: &str) -> Option { + instance_getattr_entry(cls, name).map(|(kind, _)| kind) +} + +/// [`instance_getattr_memo`] with the entry's place (see +/// [`InstGetattrEntry::place`]). +#[inline] +fn instance_getattr_entry(cls: &TypeObject, name: &str) -> Option<(InstGetattrClass, u32)> { + let ver = cls.attr_version.get(); + if ver == 0 || crate::capi_watchers::types_active() { + return None; + } + let (words, len) = inst_getattr_key(name)?; + let e = INST_GETATTR_MEMO + .try_with(|m| m[inst_getattr_slot(ver, &words)].get()) + .ok()?; + if e.ver != ver || e.len != len || e.words != words { + return None; + } + match e.kind { + 1 => Some((InstGetattrClass::Nothing, e.place)), + 2 => Some((InstGetattrClass::Slot, 0)), + 3 => Some((InstGetattrClass::Shadowed, e.place)), + _ => None, + } +} + +/// Remember where `inst` holds `name` among its class's shared names (a +/// name the class supplies nothing for, which the memo already says): +/// every instance of the class whose attributes are still split over +/// those names holds it there (see `PyInstance::split_field`). An +/// instance laid out another way settles that the place isn't looked for +/// again under this class version. +#[cold] +#[inline(never)] +fn note_instance_getattr_place(cls: &TypeObject, name: &str, inst: &PyInstance) { + let ver = cls.attr_version.get(); + let Some((words, len)) = inst_getattr_key(name) else { + return; + }; + let place = inst + .attr_position_str(name) + // SAFETY: a read that runs no code. + .filter(|&i| unsafe { inst.split_field(i as usize) }.is_some()) + .map_or(PLACE_NONE, |i| i + 1); + let _ = INST_GETATTR_MEMO.try_with(|m| { + let slot = &m[inst_getattr_slot(ver, &words)]; + let mut e = slot.get(); + if e.ver == ver && e.len == len && e.words == words && matches!(e.kind, 1 | 3) { + e.place = place; + slot.set(e); + } + }); +} + +/// Remember `kind` for `name` on `cls` (see [`instance_getattr_memo`]). +fn note_instance_getattr(cls: &TypeObject, name: &str, kind: InstGetattrClass) { + let ver = cls.attr_version.get(); + if ver == 0 || crate::capi_watchers::types_active() { + return; + } + let Some((words, len)) = inst_getattr_key(name) else { + return; + }; + let kind = match kind { + InstGetattrClass::Nothing => 1, + InstGetattrClass::Slot => 2, + InstGetattrClass::Shadowed => 3, + }; + let _ = INST_GETATTR_MEMO.try_with(|m| { + m[inst_getattr_slot(ver, &words)].set(InstGetattrEntry { + ver, + words, + len, + kind, + place: 0, + }); + }); +} + +/// What a `__getitem__` that only delegates comes to (see +/// `Interpreter::delegate_item`). +pub(crate) enum Delegated { + /// The field's item. + Item(Object), + /// A list's or tuple's index out of range: the `IndexError` the read + /// raises, worded as the field's kind words it. + IndexMiss(&'static str), + /// A plain dict without the (natively hashed) key: the read's + /// `KeyError`. + KeyMiss, +} + +/// `collections.abc.Mapping.keys` and the two classes whose attribute +/// versions say it still does what it did (see +/// `Interpreter::abc_keys_fn`). +struct AbcKeys { + keys: Rc, + mapping: Rc, + view: Rc, + versions: (u64, u64), + /// `ValuesView` and `ItemsView`, whose `__iter__` are the stdlib's + /// own generators too, with their attribute versions. + others: [(Rc, u64); 2], +} + +/// `_seqtools._SeqIter` (and, second, `_ReversedIter`) as +/// [`Interpreter::make_seq_iterator`] (`make_seqtools_iter`) last found +/// it: the class's address and its attribute version then (unique in the +/// process, so a patched or a different class at the address never +/// matches). +static SEQITER_CLASS: [std::sync::atomic::AtomicUsize; 2] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; +static SEQITER_VERSION: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +fn note_seqiter_class(t: &Rc, rev: bool) { + use std::sync::atomic::Ordering; + let ver = t.attr_version.get(); + if ver != 0 { + if SEQITER_CLASS[usize::from(rev)].load(Ordering::Relaxed) != Rc::as_ptr(t) as usize { + SEQITER_TYPES.with(|held| held.borrow_mut()[usize::from(rev)] = Some(t.clone())); + } + SEQITER_VERSION[usize::from(rev)].store(ver, Ordering::Relaxed); + SEQITER_CLASS[usize::from(rev)].store(Rc::as_ptr(t) as usize, Ordering::Relaxed); + } +} + +thread_local! { + /// The two helper classes [`note_seqiter_class`] noted, held for + /// [`seqiter_new`]. + static SEQITER_TYPES: crate::gil::ReleaseUnderGil>; 2]>> = + const { crate::gil::ReleaseUnderGil::new(RefCell::new([None, None])) }; +} + +/// A new `_SeqIter` over `seq` as its `__init__` leaves it (`_seq`, and +/// `_index` at 0), built with no call: `None` when the class isn't the +/// one noted, unchanged since, with its two slots laid out in that order. +fn seqiter_new(seq: &Object) -> Option { + use std::sync::atomic::Ordering; + SEQITER_TYPES.with(|held| { + let held = held.try_borrow().ok()?; + let cls = held[0].as_ref()?; + if cls.attr_version.get() != SEQITER_VERSION[0].load(Ordering::Relaxed) { + return None; + } + let layout = cls.own_slot_layout()?; + let named = |k: usize, name: &str| { + matches!(layout.get(k), Some(DictKey(Object::Str(s))) if s.as_ref() == name) + }; + if layout.len() != 2 || !named(0, "_seq") || !named(1, "_index") { + return None; + } + let inst = PyInstance::with_slots( + cls.clone(), + crate::types::SlotStorage::from_layout_array( + layout.clone(), + [seq.clone(), Object::Int(0)], + ), + ); + let obj = Object::Instance(Rc::new(inst)); + crate::gc_trace::track(&obj); + Some(obj) + }) +} + +/// Which of the legacy sequence protocol's iterators `inst` is, of a +/// class [`note_seqiter_class`] noted, unchanged since: `false` a +/// `_SeqIter` (`iter(seq)`), `true` a `_ReversedIter` (`reversed(seq)`). +#[inline] +fn seqiter_kind(inst: &PyInstance) -> Option { + use std::sync::atomic::Ordering; + let cls = inst.cls_raw(); + let at = std::ptr::from_ref(cls) as usize; + let rev = if at == SEQITER_CLASS[0].load(Ordering::Relaxed) { + false + } else if at == SEQITER_CLASS[1].load(Ordering::Relaxed) { + true + } else { + return None; + }; + (cls.attr_version.get() == SEQITER_VERSION[usize::from(rev)].load(Ordering::Relaxed)) + .then_some(rev) +} + +/// The `__slots__` layouts of the two helper iterators, found led by +/// `_seq` and `_index` (see `SlotStorage::leading_memo`). +static SEQITER_LAYOUT: [crate::types::LayoutMemo; 2] = [ + crate::types::LayoutMemo::new(), + crate::types::LayoutMemo::new(), +]; + +thread_local! { + /// The interned names of a helper iterator's two slots. + static SEQITER_KEYS: crate::gil::ReleaseUnderGil<[crate::shared_value::SharedStr; 2]> = + crate::gil::ReleaseUnderGil::new(["_seq", "_index"].map(|name| { + match crate::stdlib::sys::intern_name(name) { + Object::Str(s) => s, + _ => unreachable!("interned names are strs"), + } + })); +} + +/// A helper iterator's `_seq` and `_index` slots (see [`seqiter_kind`]), +/// in place, both set: `None` while anything borrows its slots or cells +/// are shared across threads. +/// +/// # Safety +/// +/// The references must not outlive anything that could borrow the +/// instance's slots (no Python code runs while they're used). +#[inline(always)] +#[allow(clippy::mut_from_ref)] +unsafe fn seqiter_fields(inst: &PyInstance, rev: bool) -> Option<[&mut Object; 2]> { + let memo = &SEQITER_LAYOUT[usize::from(rev)]; + // SAFETY: the caller's contract. + if let Some(fields) = unsafe { inst.slots.peek_mut() }?.leading_memo_hit_mut(memo) { + return Some(fields); + } + SEQITER_KEYS.with(|keys| { + // SAFETY: the caller's contract (the view above has ended). + unsafe { inst.slots.peek_mut() }?.leading_memo_mut(memo, [&keys[0], &keys[1]]) + }) +} + +/// Whether `e` ends a legacy sequence's iteration: an `IndexError` or a +/// `StopIteration` (CPython's `iter_iternext` clears either). +fn ends_sequence(e: &RuntimeError) -> bool { + let types = crate::builtin_types::builtin_types(); + matches!(e, RuntimeError::PyException(exc) if matches!(&exc.instance, + Object::Instance(i) if i.cls_raw().is_subclass_of(&types.index_error) + || i.cls_raw().is_subclass_of(&types.stop_iteration))) +} + /// Whether `inst.name` is a `__slots__` member of its class (the data /// descriptor the default lookup finds first, under `object`'s own /// `__getattribute__`) that `inst` holds no value for: the member's @@ -77307,11 +90255,16 @@ fn make_agen_await( /// free. #[inline(never)] unsafe fn core_gen_method(code: &CodeObject, name_idx: u32, top: *mut Object) -> bool { - let Some(name) = code - .names - .get(name_idx as usize) - .filter(|n| matches!(n.as_str(), "send" | "throw" | "close" | "__next__")) - else { + // (An async generator's own methods; it has none of a generator's.) + // SAFETY: the caller's contract. + let agen = matches!(unsafe { &*top }, Object::AsyncGenerator(_)); + let Some(name) = code.names.get(name_idx as usize).filter(|n| { + if agen { + matches!(n.as_str(), "asend" | "athrow" | "aclose" | "__anext__") + } else { + matches!(n.as_str(), "send" | "throw" | "close" | "__next__") + } + }) else { return false; }; // `gen.send(v)`: the unbound method and the generator as its self (the @@ -77420,7 +90373,7 @@ fn make_gen_method(name: &str, receiver: &Object) -> Object { thread_local! { /// Lazily-created `coroutine_wrapper` type (CPython's /// `_PyCoroWrapper_Type`) — the iterator `coro.__await__()` returns. - static COROUTINE_WRAPPER_TYPE: RefCell>> = const { RefCell::new(None) }; + static COROUTINE_WRAPPER_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } /// Build the `coroutine_wrapper` iterator for `coro.__await__()`. @@ -77850,96 +90803,187 @@ fn freeze_set_result(o: Object) -> Object { /// [`crate::object::dict_key_is_reentrant`]), and a comparison with a /// stored key that would run Python defers instead. `None` (nothing /// observable done) sends the operation to the snapshot path. -fn set_algebra_fast(a: &Object, b: &Object, op: BinOpKind) -> Option { - // Whether every key of `o` hashes and compares natively. - fn plain(o: &Object) -> bool { - let check = |s: &crate::object::SetData| { - !s.iter().any(|k| crate::object::dict_key_is_reentrant(&k.0)) - }; - match o { - Object::Set(s) => s.try_borrow().is_ok_and(|s| check(&s)), - Object::FrozenSet(s) => check(s), - _ => false, +/// `a | b` of two exact dicts whose keys hash and compare natively: a copy +/// of `a`'s table with `b`'s entries put over it, as `dict.__or__` merges +/// them. `None` (nothing done) for any other case: a key a Python +/// `__eq__`/`__hash__` could answer, an active dict watcher, a cell in use. +pub(crate) fn dict_union_plain(a: &Object, b: &Object) -> Option { + let (Object::Dict(x), Object::Dict(y)) = (a, b) else { + return None; + }; + if crate::capi_watchers::dicts_active() { + return None; + } + let (Ok(x), Ok(y)) = (x.try_borrow(), y.try_borrow()) else { + return None; + }; + let reentrant = |d: &DictData| d.keys().any(|k| crate::object::dict_key_is_reentrant(&k.0)); + if reentrant(&y) || (!y.is_empty() && reentrant(&x)) { + return None; + } + let mut map = x.clone_with_room(y.len()); + for (k, v) in y.iter() { + map.insert(k.clone(), v.clone()); + } + drop((x, y)); + let out = Object::Dict(Rc::new(RefCell::new(DictData::from(map)))); + gc_trace::track_built(&out); + Some(out) +} + +/// One operand of a keys view's set operation: a dict's keys or a set's, +/// each with its stored hash. +enum KeySide<'a> { + Dict(&'a crate::object::DictMap), + Set(&'a crate::object::SetData), +} + +impl KeySide<'_> { + fn len(&self) -> usize { + match self { + KeySide::Dict(d) => d.len(), + KeySide::Set(s) => s.len(), } } - fn len(o: &Object) -> Option { - match o { - Object::Set(s) => s.try_borrow().ok().map(|s| s.len()), - Object::FrozenSet(s) => Some(s.len()), - _ => None, + + fn has(&self, hash: i64, key: &DictKey) -> bool { + match self { + KeySide::Dict(d) => d.contains_hashed(hash, key), + KeySide::Set(s) => s.contains_hashed(hash, key), } } - // Only the keys the operation hashes need checking: those it walks - // (see `set_algebra_plain`). The other operand's keys are only - // compared against, which defers below. - let walked_plain = match op { - BinOpKind::BitOr => plain(b), - BinOpKind::BitAnd => { - if len(b)? > len(a)? { - plain(a) - } else { - plain(b) - } + + fn each(&self, mut f: impl FnMut(i64, &DictKey)) { + match self { + KeySide::Dict(d) => d.hashed_keys().for_each(|(h, k)| f(h, k)), + KeySide::Set(s) => s.as_entries().iter().for_each(|e| f(e.hash, &e.key)), + } + } + + fn all(&self, mut f: impl FnMut(i64, &DictKey) -> bool) -> bool { + match self { + KeySide::Dict(d) => d.hashed_keys().all(|(h, k)| f(h, k)), + KeySide::Set(s) => s.as_entries().iter().all(|e| f(e.hash, &e.key)), } - BinOpKind::Sub => plain(a), - _ => plain(a) && plain(b), - }; - if !walked_plain { - return None; } - let (out, deferred) = crate::object::with_key_eq_deferred(|| set_algebra_plain(a, b, op)); - (!deferred).then_some(out) } -/// `a op b` for `set`/`frozenset` operands that [`set_algebra_fast`] -/// admitted, with CPython's iteration order and element choice: a union -/// copies the left and adds the right; an intersection walks the smaller -/// operand (the right one on a tie) and keeps its elements; a difference -/// walks the left. The result kind follows the left operand. -fn set_algebra_plain(a: &Object, b: &Object, op: BinOpKind) -> Object { - use crate::object::SetData; - fn with(o: &Object, f: impl FnOnce(&SetData) -> R) -> R { - match o { - Object::Set(s) => f(&s.borrow()), - Object::FrozenSet(s) => f(s), - _ => unreachable!("checked by set_algebra_fast"), +/// `f` on the keys of a dict's keys view, a `set` or a `frozenset`, held +/// for the call (a shared borrow: `f` runs no code and changes neither); +/// `None` for anything else, or an operand that is being changed. +fn key_side(o: &Object, f: impl FnOnce(KeySide<'_>) -> Option) -> Option { + match o { + Object::DictView(v) if v.kind == crate::object::DictViewKind::Keys => { + let d = v.dict.try_borrow().ok()?; + f(KeySide::Dict(&d)) + } + Object::Set(s) => { + let s = s.try_borrow().ok()?; + f(KeySide::Set(&s)) } + Object::FrozenSet(s) => f(KeySide::Set(s)), + _ => None, } - let out = with(a, |x| { - with(b, |y| match op { - BinOpKind::BitOr => { - let mut out = x.clone(); - out.reserve(y.len()); - for k in y { - out.insert(k.clone()); - } - out - } - BinOpKind::BitAnd => { - let (small, big) = if y.len() > x.len() { (x, y) } else { (y, x) }; - let mut out = SetData::with_capacity_and_hasher( - small.len().min(big.len()), - crate::fasthash::FxBuildHasher, - ); - for k in small { - if big.contains(k) { - out.insert(k.clone()); +} + +/// Whether a dict's keys view and another, a `set` or a `frozenset` share +/// no key: the smaller side's keys looked up in the larger. `None` when a +/// pair needs a Python comparison, or for other operands. +pub(crate) fn keys_disjoint(a: &Object, b: &Object) -> Option { + key_side(a, |x| { + key_side(b, |y| { + let (small, big) = if x.len() <= y.len() { + (&x, &y) + } else { + (&y, &x) + }; + setalg::pure(|| small.all(|hash, key| !big.has(hash, key))) + }) + }) +} + +/// `a b` where one operand is a dict's keys view and the other a keys +/// view, a `set` or a `frozenset` (CPython's `dictviews_or`, `_and`, +/// `_sub` and `_xor`, which also serve the reflected operators): a `set`, +/// made from the operands' tables with their stored hashes, so no key is +/// hashed and neither side is first copied into a set. `None` (nothing +/// done) when a pair of keys needs a Python comparison, and for the +/// shapes the general path decides. +/// +/// An intersection walks the smaller operand and keeps its elements +/// (`_PyDictView_Intersect`): against a view, the right one on a tie; +/// against a `set`, the view when it is no longer than the set; a +/// `frozenset` is always the one walked. +pub(crate) fn keys_view_algebra(a: &Object, b: &Object, op: BinOpKind) -> Option { + use crate::object::DictViewKind::Keys; + let keys_view = |o: &Object| matches!(o, Object::DictView(v) if v.kind == Keys); + let set_like = |o: &Object| matches!(o, Object::Set(_) | Object::FrozenSet(_)); + if !(keys_view(a) && (keys_view(b) || set_like(b)) || set_like(a) && keys_view(b)) { + return None; + } + let out = key_side(a, |x| { + key_side(b, |y| { + setalg::pure(|| { + let mut out = crate::object::SetData::new(); + // (One operand's keys are distinct, and so are the two + // halves of a symmetric difference: no key taken here is + // compared with those already taken.) + let mut take = |walk: &KeySide<'_>, probe: &KeySide<'_>, keep: bool| { + walk.each(|hash, key| { + if probe.has(hash, key) == keep { + out.insert_unique_hashed(hash, key.clone()); + } + }); + }; + match op { + BinOpKind::BitAnd => { + // Which side is walked (see the function docs). + let walk_left = match (a, b) { + (Object::DictView(_), Object::DictView(_)) => y.len() > x.len(), + (Object::DictView(_), Object::Set(_)) => x.len() <= y.len(), + (Object::Set(_), Object::DictView(_)) => y.len() > x.len(), + (Object::DictView(_), _) => false, + _ => true, + }; + if walk_left { + take(&x, &y, true); + } else { + take(&y, &x, true); + } + } + BinOpKind::Sub => { + take(&x, &y, false); + } + BinOpKind::BitOr => { + out.reserve(x.len()); + x.each(|hash, key| { + out.insert_unique_hashed(hash, key.clone()); + }); + y.each(|hash, key| { + out.insert_hashed(hash, key.clone()); + }); + } + _ => { + take(&x, &y, false); + take(&y, &x, false); } } out - } - BinOpKind::Sub => x.iter().filter(|k| !y.contains(*k)).cloned().collect(), - _ => { - let mut out: SetData = x.iter().filter(|k| !y.contains(*k)).cloned().collect(); - out.extend(y.iter().filter(|k| !x.contains(*k)).cloned()); - out - } + }) }) - }); - match a { + })?; + Some(Object::Set(Rc::new(RefCell::new(out)))) +} + +pub(crate) fn set_algebra_fast(a: &Object, b: &Object, op: BinOpKind) -> Option { + // On the operands' own tables, with their stored hashes (see + // `setalg`): no key is hashed, and a pair that needs a Python + // comparison leaves the operation to the caller's general path. + let out = setalg::with_sets(a, b, |x, y| setalg::pure(|| setalg::algebra(x, y, op)))???; + Some(match a { Object::FrozenSet(_) => Object::FrozenSet(Rc::new(crate::object::FrozenSetObj::new(out))), _ => Object::Set(Rc::new(RefCell::new(out))), - } + }) } fn union_sets(a: &crate::object::SetData, b: &crate::object::SetData) -> Object { @@ -78180,6 +91224,26 @@ pub(crate) fn format_via_spec(value: &Object, spec: &str) -> Result Option> { + let (value, spec) = match args { + [value] => (value, ""), + [value, Object::Str(spec)] => (value, &**spec), + _ => return None, + }; + if !matches!(value, Object::Float(_) | Object::Int(_) | Object::Str(_)) { + return None; + } + if spec.is_empty() { + if let Object::Str(_) = value { + return Some(Ok(value.clone())); + } + } + Some(format_via_spec(value, spec).map(Object::from_str)) +} + /// `format_via_spec` variant used by the printf (`%`) engine, where a /// precision on an integer code means "minimum digits" (CPython's /// `str.format` mini-language forbids it; printf mandates it). @@ -78192,6 +91256,38 @@ fn format_via_spec_impl( spec: &str, allow_int_precision: bool, ) -> Result { + // `.Nf` of a finite float (`f"{x:.2f}"`), the commonest float spec: + // the fixed digits and the sign, which is all the general path adds. + if let Object::Float(f) = value { + if let Some(prec) = plain_fixed_precision(spec).filter(|_| f.is_finite()) { + let core = fixed_core(f.abs(), prec); + return Ok(if f.is_sign_negative() { + format!("-{core}") + } else { + core + }); + } + // `g`, `G` or `.Ng` alone: the general format, with no alignment, + // sign or grouping to apply (and no `str(x)` to compute first). + if let Some((prec, upper)) = plain_general_precision(spec) { + return Ok(format_float_general( + *f, + prec, + upper, + &ParsedSpec::default(), + )); + } + } + // A number with a spec never reads its `str` text (only the string + // presentation does, which numbers reject or route elsewhere). + if !spec.is_empty() + && matches!( + value, + Object::Float(_) | Object::Int(_) | Object::Bool(_) | Object::Long(_) + ) + { + return apply_format_spec_inner(value, spec, "", allow_int_precision); + } // A surrogate-bearing `WStr` bridges its lone surrogates into the PUA // window so the (UTF-8-only) spec engine can pad/slice it; the Object // boundary (`FormatValue`/`str.format` via `str_result`) maps them back. @@ -78208,6 +91304,37 @@ fn format_via_spec_impl( apply_format_spec_inner(value, spec, &plain, allow_int_precision) } +/// The precision of a spec that is exactly `.Nf` (`N` up to two digits), +/// or `None`. +fn plain_fixed_precision(spec: &str) -> Option { + match spec.as_bytes() { + [b'.', d, b'f'] if d.is_ascii_digit() => Some(usize::from(d - b'0')), + [b'.', a, b, b'f'] if a.is_ascii_digit() && b.is_ascii_digit() => { + Some(usize::from(a - b'0') * 10 + usize::from(b - b'0')) + } + _ => None, + } +} + +/// The precision (6 when omitted) and case of a spec that is exactly `g`, +/// `G`, `.Ng` or `.NG` (`N` up to two digits), or `None`. +fn plain_general_precision(spec: &str) -> Option<(usize, bool)> { + let (body, upper) = match spec.as_bytes().split_last()? { + (b'g', body) => (body, false), + (b'G', body) => (body, true), + _ => return None, + }; + let prec = match body { + [] => 6, + [b'.', d] if d.is_ascii_digit() => usize::from(d - b'0'), + [b'.', a, b] if a.is_ascii_digit() && b.is_ascii_digit() => { + usize::from(a - b'0') * 10 + usize::from(b - b'0') + } + _ => return None, + }; + Some((prec.max(1), upper)) +} + /// Public wrapper for `ascii()`. pub(crate) fn ascii_value(value: &Object) -> String { ascii_repr(value) @@ -78678,6 +91805,82 @@ pub(crate) enum PercentMode { /// A `%`-format argument (or argument tuple) of scalars and exact /// strings: its conversions run no Python code. +/// `template % args` for a template of bare `%s` conversions whose `args` +/// hold instances that render with no code run (see +/// `Interpreter::quick_str`), every other item being +/// what [`percent_leaf_args`] takes: each instance is its `str()`, so the +/// text is the payloads'. `None`, having run nothing, for anything else +/// (or an error, which the full handler raises). +fn percent_format_payloads(template: &str, args: &Object) -> Option { + if !percent_only_bare_s(template) { + return None; + } + let sub = |o: &Object| match o { + Object::Instance(i) => Interpreter::quick_str(i), + o => Some(o.clone()), + }; + let args = match args { + Object::Tuple(items) => { + Object::new_tuple(items.iter().map(sub).collect::>>()?) + } + o => sub(o)?, + }; + if !percent_leaf_args(&args) || percent_args_need_bridge(&args) { + return None; + } + percent_format(template, &args).ok() +} + +/// [`percent_format_payloads`] when `args` is the shape it takes (see +/// [`percent_payload_args`]). +#[inline] +pub(crate) fn percent_format_payloads_checked(template: &str, args: &Object) -> Option { + if !percent_payload_args(args) { + return None; + } + percent_format_payloads(template, args) +} + +/// Whether every conversion in `template` is a bare `%s` (or a literal +/// `%%`): no flags, width, precision or mapping key. +fn percent_only_bare_s(template: &str) -> bool { + let b = template.as_bytes(); + let mut i = 0; + while let Some(at) = memchr::memchr(b'%', &b[i..]) { + match b.get(i + at + 1) { + Some(b's' | b'%') => i += at + 2, + _ => return false, + } + } + true +} + +/// Whether `args` (a `%` operator's right operand) holds an instance, +/// every other item being what +/// [`percent_leaf_args`] takes (the instances are checked as they're +/// replaced). Each instance is held elsewhere too, so releasing the +/// operand runs nothing. +fn percent_payload_args(args: &Object) -> bool { + let inst = |o: &Object| matches!(o, Object::Instance(i) if Rc::strong_count(i) > 1); + match args { + Object::Tuple(items) => { + items.iter().any(inst) + && items.iter().all(|o| { + inst(o) + || matches!( + o, + Object::Int(_) + | Object::Float(_) + | Object::Str(_) + | Object::Bool(_) + | Object::None + ) + }) + } + other => inst(other), + } +} + fn percent_leaf_args(args: &Object) -> bool { let leaf = |o: &Object| { matches!( @@ -78842,6 +92045,21 @@ fn percent_render_plain(template: &str, args: PercentArgs<'_>) -> Option } _ => return None, }; + // `%r` of a plain value: its repr in place. + if *bytes.get(k)? == b'r' { + match v { + Object::Int(n) => { + let _ = write!(out, "{n}"); + } + Object::Bool(b) => out.push_str(if *b { "True" } else { "False" }), + Object::None => out.push_str("None"), + Object::Str(_) => out.push_str(&v.repr()), + _ => k = percent_render_spec(&mut out, bytes, k, v)?, + } + i = k + 1; + lit = i; + continue; + } if !matches!(bytes.get(k)?, b's' | b'd' | b'i') { k = percent_render_spec(&mut out, bytes, k, v)?; i = k + 1; @@ -78968,7 +92186,9 @@ fn percent_render_spec(out: &mut String, bytes: &[u8], mut k: usize, v: &Object) if !x.is_finite() { return None; } - let _ = write!(num, "{:.*}", prec.unwrap_or(6), x.abs()); + // (In integer arithmetic for the common shapes, as the `f` + // format spec renders it.) + num.push_str(&fixed_core(x.abs(), prec.unwrap_or(6))); ( if x.is_sign_negative() { "-" } else { "" }, num.as_str(), @@ -79146,6 +92366,51 @@ fn star_arg_int(v: &Object) -> Result { /// `resolve(item, kind)` lets the caller render `%s` / `%r` of user /// instances through `__str__` / `__repr__` (returning `Some(rendered)`), /// falling back to the built-in conversion when it returns `None`. +/// `bytes % args` for the plain conversions (`%d`, `%i`, `%u`, `%x`, `%s` +/// and `%b` without flags, width or precision, and `%%`) over ints and +/// `bytes`, straight into the output; `None` for anything else, which the +/// general engine formats (and raises for). +pub(crate) fn bytes_percent_simple(template: &[u8], value: &Object) -> Option> { + let one; + let args: &[Object] = match value { + Object::Tuple(items) => &items[..], + Object::Int(_) | Object::Bytes(_) => { + one = [value.clone()]; + &one + } + _ => return None, + }; + let mut out = Vec::with_capacity(template.len() + 8 * args.len()); + let mut next = args.iter(); + let mut i = 0; + while i < template.len() { + let Some(k) = memchr::memchr(b'%', &template[i..]) else { + out.extend_from_slice(&template[i..]); + break; + }; + out.extend_from_slice(&template[i..i + k]); + let conv = *template.get(i + k + 1)?; + i += k + 2; + if conv == b'%' { + out.push(b'%'); + continue; + } + match (conv, next.next()?) { + (b'd' | b'i' | b'u', Object::Int(n)) => { + out.extend_from_slice(itoa::Buffer::new().format(*n).as_bytes()); + } + (b'x', Object::Int(n)) if *n >= 0 => { + use std::io::Write; + write!(out, "{n:x}").ok()?; + } + (b's' | b'b', Object::Bytes(b)) => out.extend_from_slice(b), + _ => return None, + } + } + // (Arguments left over raise in the general engine.) + next.next().is_none().then_some(out) +} + pub(crate) fn percent_format_with( template: &str, value: &Object, @@ -80264,8 +93529,7 @@ fn apply_format_spec_inner( Some('%') => { let f = obj_as_float(value, parsed.type_char.unwrap_or('f'))?; let prec = parsed.precision.unwrap_or(6); - let body = format_float_fixed(f * 100.0, prec, false, &parsed); - format!("{body}%") + format_float_percent(f * 100.0, prec, &parsed) } None if matches!(value, Object::Float(_)) => { let Object::Float(f) = value else { @@ -80364,7 +93628,7 @@ fn apply_format_spec_inner( } } } - apply_alignment(&s, &sp, numeric_default) + apply_alignment(s, &sp, numeric_default) } Some('c') => match value { Object::Int(_) | Object::Bool(_) | Object::Long(_) => { @@ -80374,7 +93638,7 @@ fn apply_format_spec_inner( .ok_or_else(|| overflow_error("%c arg not in range(0x110000)"))?; let c = char::from_u32(cp as u32) .ok_or_else(|| value_error("integer is not a valid unicode codepoint"))?; - apply_alignment(&c.to_string(), &parsed, false) + apply_alignment(c.to_string(), &parsed, false) } // `format(1.5, 'c')`: the float/complex formatter has no `c` // (`Unknown format code 'c' for object of type 'float'`). @@ -80462,7 +93726,20 @@ fn accumulate_spec_digit(acc: usize, c: char) -> Result { fn parse_format_spec(spec: &str, type_name: &str) -> Result { let mut p = ParsedSpec::default(); - let chars: Vec = spec.chars().collect(); + // (A short spec's characters on the stack: most are a few long.) + let mut small = ['\0'; 24]; + let heap: Vec; + let chars: &[char] = if spec.len() <= small.len() { + let mut n = 0; + for c in spec.chars() { + small[n] = c; + n += 1; + } + &small[..n] + } else { + heap = spec.chars().collect(); + &heap + }; let mut i = 0; // [[fill]align] if chars.len() >= 2 && matches!(chars[1], '<' | '>' | '^' | '=') { @@ -80596,6 +93873,13 @@ fn obj_as_float(v: &Object, code: char) -> Result { Object::Float(f) => Ok(*f), Object::Int(i) => Ok(*i as f64), Object::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }), + // A big int converts as `float(n)` does (`format(10**20, '.2f')`). + Object::Long(b) => { + use num_traits::ToPrimitive; + b.to_f64() + .filter(|f| f.is_finite()) + .ok_or_else(|| crate::error::overflow_error("int too large to convert to float")) + } // `str.__format__` rejects a numeric code itself, with the same // wording as the integer codes above (CPython // `unicode__format__`); the printf engine's own message for a @@ -80663,7 +93947,7 @@ fn format_int(i: i64, p: &ParsedSpec) -> String { let core = group_int_digits(mag.to_string(), p, 3, int_decor_len(i < 0, p, false)); let core = int_precision_apply(core, p); let body = with_sign(i < 0, &core, p); - apply_alignment(&body, p, true) + apply_alignment(body, p, true) } fn format_int_base(i: i64, base: u32, p: &ParsedSpec) -> String { @@ -80688,7 +93972,7 @@ fn format_int_base(i: i64, base: u32, p: &ParsedSpec) -> String { core }; body = with_sign(i < 0, &body, p); - apply_alignment(&body, p, true) + apply_alignment(body, p, true) } fn format_int_hex(i: i64, upper: bool, p: &ParsedSpec) -> String { @@ -80707,7 +93991,7 @@ fn format_int_hex(i: i64, upper: bool, p: &ParsedSpec) -> String { body_core }; body = with_sign(i < 0, &body, p); - apply_alignment(&body, p, true) + apply_alignment(body, p, true) } /// Group an already-rendered magnitude string into fixed-size runs from @@ -80739,7 +94023,7 @@ fn format_bigint(b: &num_bigint::BigInt, p: &ParsedSpec) -> String { let core = group_int_digits(mag, p, 3, int_decor_len(neg, p, false)); let core = int_precision_apply(core, p); let body = with_sign(neg, &core, p); - apply_alignment(&body, p, true) + apply_alignment(body, p, true) } fn format_bigint_base(b: &num_bigint::BigInt, base: u32, p: &ParsedSpec) -> String { @@ -80764,7 +94048,7 @@ fn format_bigint_base(b: &num_bigint::BigInt, base: u32, p: &ParsedSpec) -> Stri core }; body = with_sign(neg, &body, p); - apply_alignment(&body, p, true) + apply_alignment(body, p, true) } fn format_bigint_hex(b: &num_bigint::BigInt, upper: bool, p: &ParsedSpec) -> String { @@ -80784,7 +94068,7 @@ fn format_bigint_hex(b: &num_bigint::BigInt, upper: bool, p: &ParsedSpec) -> Str core }; body = with_sign(neg, &body, p); - apply_alignment(&body, p, true) + apply_alignment(body, p, true) } /// Unsigned fixed-point magnitude digits (no sign, no padding). A finite @@ -80887,10 +94171,12 @@ fn finish_float(neg: bool, core: String, p: &ParsedSpec) -> String { Some(sep) => group_float_frac(&core, sep), None => core, }; - let grouped = match p.grouping { - Some(sep) => group_float_core(&core, sep), - None => core.clone(), + let Some(sep) = p.grouping else { + // (No grouping: the digits are the body, signed in place.) + let neg = neg && !(p.no_neg_zero && all_digits_zero(&core)); + return apply_alignment(with_sign_owned(neg, core, p), p, true); }; + let grouped = group_float_core(&core, sep); let neg = neg && !(p.no_neg_zero && all_digits_zero(&grouped)); let body = with_sign(neg, &grouped, p); // Zero padding with a thousands separator: the pad zeros join the @@ -80899,14 +94185,14 @@ fn finish_float(neg: bool, core: String, p: &ParsedSpec) -> String { // `_PyUnicode_InsertThousandsGrouping` runs over the padded digit // run, and the result may overshoot the width rather than lead // with a separator). test_types test_float__format__. - if let (Some(sep), Some(width)) = (p.grouping, p.width) { + if let Some(width) = p.width { let zero_fill = p.fill.unwrap_or(if p.zero { '0' } else { ' ' }) == '0' && matches!(p.align, None | Some('=')); if zero_fill && body.chars().count() < width { return zero_pad_grouped(neg, &core, sep, width, p); } } - apply_alignment(&body, p, true) + apply_alignment(body, p, true) } /// Grow the integer-digit run with leading zeros until its *grouped* @@ -80990,7 +94276,7 @@ fn group_float_frac(core: &str, sep: char) -> String { /// matching CPython's `format_float_short` special-value branch. fn finish_special(neg: bool, core: &str, p: &ParsedSpec) -> String { let body = with_sign(neg, core, p); - apply_alignment(&body, p, true) + apply_alignment(body, p, true) } fn format_float_fixed(f: f64, prec: usize, upper: bool, p: &ParsedSpec) -> String { @@ -81009,6 +94295,24 @@ fn format_float_fixed(f: f64, prec: usize, upper: bool, p: &ParsedSpec) -> Strin finish_float(f.is_sign_negative(), core, p) } +/// The `%` type of `f` (already scaled by 100): [`format_float_fixed`] +/// with the sign inside the padding's width, as CPython counts it +/// (`format(0.1, "010.3%")` is `"00010.000%"`). +fn format_float_percent(f: f64, prec: usize, p: &ParsedSpec) -> String { + if f.is_nan() { + return finish_special(false, "nan%", p); + } + if f.is_infinite() { + return finish_special(f < 0.0, "inf%", p); + } + let mut core = fixed_core(f.abs(), prec); + if p.alt { + core = ensure_decimal_point(&core); + } + core.push('%'); + finish_float(f.is_sign_negative(), core, p) +} + /// `#`/alt flag for the float presentation types: force a decimal-point /// character into the mantissa even when no fractional digits follow /// (`"1"` → `"1."`, `"1e+00"` → `"1.e+00"`), matching CPython's @@ -81030,8 +94334,22 @@ fn format_float_scientific(f: f64, prec: usize, upper: bool, p: &ParsedSpec) -> if f.is_infinite() { return finish_special(f < 0.0, if upper { "INF" } else { "inf" }, p); } - // Rust gives e.g. "1.230000e2"; CPython wants "1.230000e+02". - let core = normalize_exponent(&format!("{:.*e}", prec, f.abs()), upper); + // Rust gives e.g. "1.230000e2"; CPython wants "1.230000e+02" (built + // so from the shortest digits where they settle it). + let core = match exp_digits(f.abs(), prec) { + Some((digits, exp)) => { + let mut out = String::with_capacity(prec + 8); + push_exp_mantissa(&mut out, &digits, prec); + out.push(if upper { 'E' } else { 'e' }); + out.push(if exp < 0 { '-' } else { '+' }); + if exp.unsigned_abs() < 10 { + out.push('0'); + } + out.push_str(itoa::Buffer::new().format(exp.unsigned_abs())); + out + } + None => normalize_exponent(&format!("{:.*e}", prec, f.abs()), upper), + }; let core = if p.alt { ensure_decimal_point(&core) } else { @@ -81051,13 +94369,17 @@ fn normalize_exponent(raw: &str, upper: bool) -> String { } else { ('+', exp) }; - let digits = if digits.len() < 2 { - format!("0{digits}") - } else { - digits.to_owned() - }; - let e = if upper { 'E' } else { 'e' }; - format!("{mant}{e}{sign}{digits}") + // (One buffer: the mantissa, the marker, the sign, two digits at + // least.) + let mut out = String::with_capacity(mant.len() + 4 + digits.len()); + out.push_str(mant); + out.push(if upper { 'E' } else { 'e' }); + out.push(sign); + if digits.len() < 2 { + out.push('0'); + } + out.push_str(digits); + out } else { raw.to_owned() } @@ -81079,7 +94401,7 @@ fn format_float_general(f: f64, prec: usize, upper: bool, p: &ParsedSpec) -> Str let core = if p.alt { ensure_decimal_point(&core) } else { - strip_g_zeros(&core) + strip_g_zeros(core) }; finish_float(f.is_sign_negative(), core, p) } @@ -81089,18 +94411,269 @@ fn format_float_general(f: f64, prec: usize, upper: bool, p: &ParsedSpec) -> Str /// CPython, which keys off the rounded exponent rather than `log10`). /// `exp_hi` is the exclusive exponent at which scientific notation kicks in /// (`precision` for `g`, `precision - 1` for the type-omitted format). +/// `format!("{:.*e}", after, mag)`: `mag` (not negative) in scientific +/// form with `after` digits past the point, correctly rounded. For a zero +/// or normal `mag` at no more than 15 significant digits whose shortest +/// round-trip digits fit, those digits padded with zeros are that result +/// (the shortest form is within half an ulp of the value, and an ulp of a +/// normal double is under a unit of its 16th digit, so the padded digits +/// are the nearest), with no exact, big-number formatting. +fn exp_exact(mag: f64, after: usize) -> String { + match exp_digits(mag, after) { + Some((digits, exp)) => { + let mut out = String::with_capacity(after + 8); + push_exp_mantissa(&mut out, &digits, after); + out.push('e'); + out.push_str(itoa::Buffer::new().format(exp)); + out + } + None => format!("{:.*e}", after, mag), + } +} + +/// `d.ddd`, the first `after + 1` of `digits`, the point left out when +/// none follow it. +fn push_exp_mantissa(out: &mut String, digits: &[u8; 18], after: usize) { + out.push(char::from(digits[0])); + if after > 0 { + out.push('.'); + // SAFETY: ASCII digits. + out.push_str(unsafe { std::str::from_utf8_unchecked(&digits[1..=after]) }); + } +} + +/// The digits of `mag` (not negative) to `after` places after the point +/// in exponent form, and the exponent: in integer arithmetic where it +/// fits, else from the shortest form where that settles it; `None` leaves +/// it to the general formatter. +fn exp_digits(mag: f64, after: usize) -> Option<([u8; 18], i32)> { + exp_digits_word(mag, after).or_else(|| exp_shortest_digits(mag, after)) +} + +/// [`exp_digits`] in 128-bit integer arithmetic, for the common shapes +/// (at most 17 significant digits of a normal magnitude from about +/// `1e-20` to `1e38`), as [`fixed_core_word`] formats fixed-point: the +/// float is `m * 2**e` exactly, so `mag * 10**k` is an exact fraction +/// whose floor gives the digits, rounded half to even on the exact +/// remainder. The decimal exponent is estimated from the binary one and +/// settled on that floor having `after + 1` digits. +fn exp_digits_word(mag: f64, after: usize) -> Option<([u8; 18], i32)> { + if after > 16 || !mag.is_normal() { + return None; + } + let bits = mag.to_bits(); + let m = u128::from((bits & ((1u64 << 52) - 1)) | 1 << 52); + let e = ((bits >> 52) & 0x7ff) as i32 - 1075; + let p10 = |n: i32| 10u128.checked_pow(u32::try_from(n).ok()?); + // `floor(mag * 10**k)`, and whether the exact rest rounds it up. + let scaled = |k: i32| -> Option<(u128, bool)> { + let (num, den) = match (k >= 0, e >= 0) { + (true, true) => { + let n = m.checked_mul(p10(k)?)?; + if n.leading_zeros() <= e.unsigned_abs() { + return None; + } + return Some((n << e, false)); + } + (true, false) => { + let n = m.checked_mul(p10(k)?)?; + let sh = e.unsigned_abs(); + if sh >= 128 { + return None; + } + let (q, r, half) = (n >> sh, n & ((1u128 << sh) - 1), 1u128 << (sh - 1)); + return Some((q, r > half || (r == half && q & 1 == 1))); + } + (false, true) => { + if m.leading_zeros() <= e.unsigned_abs() { + return None; + } + (m << e, p10(-k)?) + } + (false, false) => { + let (d, sh) = (p10(-k)?, e.unsigned_abs()); + if d.leading_zeros() <= sh { + return None; + } + (m, d << sh) + } + }; + let (q, r) = (num / den, num % den); + let rest = den - r; + Some((q, r > rest || (r == rest && q & 1 == 1))) + }; + let lo = 10u128.pow(after as u32); + let hi = lo * 10; + // (`78913 / 2**18` is just under log10(2): the estimate is off by one + // at most, either way.) + let mut exp = ((e + 52) * 78913) >> 18; + let mut tries = 0; + let (q, up) = loop { + tries += 1; + if tries > 4 { + return None; + } + let (q, up) = scaled(after as i32 - exp)?; + if q >= hi { + exp += 1; + } else if q < lo { + exp -= 1; + } else { + break (q, up); + } + }; + let mut q = q + u128::from(up); + if q == hi { + // (`9.9996` to `1.000`, a place up.) + q = lo; + exp += 1; + } + // (Below `10**17`: a machine word's digits.) + let mut v = u64::try_from(q).ok()?; + let mut digits = [b'0'; 18]; + for d in digits[..=after].iter_mut().rev() { + *d = b'0' + (v % 10) as u8; + v /= 10; + } + Some((digits, exp)) +} + +/// A float's shortest form (`3.14159e0`), written into a stack buffer. +struct ShortestBuf { + buf: [u8; 32], + len: usize, +} + +impl std::fmt::Write for ShortestBuf { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + let end = self.len + s.len(); + self.buf + .get_mut(self.len..end) + .ok_or(std::fmt::Error)? + .copy_from_slice(s.as_bytes()); + self.len = end; + Ok(()) + } +} + +/// The digits of `mag` (zero, or a normal float) to `after` places after +/// the point in exponent form, and the exponent, from its shortest form +/// (the nearest of the shortest strings that read back as `mag`), which +/// settles the exact rounding in most cases far more cheaply than the +/// exact algorithm, whose fast half fails often (`3.14159` to four digits) +/// and whose bignum half is slow. `None` where they don't settle it: +/// +/// - Shortest digits no more than those asked for are the answer padded +/// with zeros, while `after` is below 15: half a unit in the last digit +/// asked for then exceeds half an ulp, the most `mag` and its shortest +/// digits differ by. +/// - More digits are rounded, unless the dropped ones are exactly `5` (a +/// tie in the digits, which `mag` itself may not be). A rounding +/// boundary strictly between `mag` and its digits would be a string no +/// longer than them, nearer to `mag`, that reads back as `mag`, which +/// the shortest and nearest digits rule out; so rounding the digits +/// rounds `mag`. +fn exp_shortest_digits(mag: f64, after: usize) -> Option<([u8; 18], i32)> { + use std::fmt::Write; + if !(mag == 0.0 || mag.is_normal()) { + return None; + } + let mut short = ShortestBuf { + buf: [0; 32], + len: 0, + }; + write!(short, "{mag:e}").ok()?; + let short = &short.buf[..short.len]; + let k = short.iter().position(|&c| c == b'e')?; + let (neg, exp_digits) = match &short[k + 1..] { + [b'-', rest @ ..] => (true, rest), + rest => (false, rest), + }; + let mut exp: i32 = 0; + for &c in exp_digits { + exp = exp * 10 + i32::from(c.wrapping_sub(b'0')); + } + if neg { + exp = -exp; + } + // (At most 17 shortest digits; the answer has at most 15 when padded, + // and fewer than the shortest when rounded.) + let mut digits = [b'0'; 18]; + let mut n = 0; + for &d in &short[..k] { + if d != b'.' { + *digits.get_mut(n)? = d; + n += 1; + } + } + let want = after + 1; + if n == 0 { + return None; + } + if n <= want { + if after >= 15 { + return None; + } + } else { + let tail = &digits[want..n]; + if tail == b"5" { + return None; + } + if tail[0] >= b'5' { + let mut i = want; + loop { + if i == 0 { + // (`9.99` to `1.00`, a place up.) + digits[0] = b'1'; + exp += 1; + break; + } + i -= 1; + if digits[i] == b'9' { + digits[i] = b'0'; + } else { + digits[i] += 1; + break; + } + } + } + } + Some((digits, exp)) +} + fn general_core(mag: f64, prec: usize, upper: bool, exp_hi: i32) -> String { let prec = prec.max(1); - let sci = format!("{:.*e}", prec - 1, mag); - let exp: i32 = sci - .rfind('e') - .and_then(|k| sci[k + 1..].parse().ok()) - .unwrap_or(0); + let sci = exp_exact(mag, prec - 1); + let Some(k) = sci.rfind('e') else { + return sci; + }; + let exp: i32 = sci[k + 1..].parse().unwrap_or(0); if exp < -4 || exp >= exp_hi { - normalize_exponent(&sci, upper) + return normalize_exponent(&sci, upper); + } + // The fixed form has the same `prec` significant digits, rounded at + // the same place (the exponent is the rounded one): lay them out + // around the point instead of formatting the number again. + // (The mantissa's digits, read in place: ASCII, the point skipped.) + let digits = || sci.as_bytes()[..k].iter().filter(|b| b.is_ascii_digit()); + if digits().count() != prec { + return fixed_core(mag, (prec as i32 - 1 - exp).max(0) as usize); + } + let mut out = String::with_capacity(prec + 6); + if exp >= 0 { + let int_len = exp as usize + 1; + for (i, &d) in digits().enumerate() { + if i == int_len { + out.push('.'); + } + out.push(char::from(d)); + } } else { - fixed_core(mag, (prec as i32 - 1 - exp).max(0) as usize) + out.push_str("0."); + out.extend(std::iter::repeat_n('0', (-exp - 1) as usize)); + out.extend(digits().map(|&d| char::from(d))); } + out } /// `float.__format__` with the presentation type omitted: shortest `repr` @@ -81118,7 +94691,7 @@ fn format_float_no_type(f: f64, p: &ParsedSpec) -> String { None => crate::object::float_repr(f.abs()), // Type omitted: like `g` but scientific kicks in one exponent earlier // (`decpt > precision - 1`), per CPython's `ADD_DOT_0` path. - Some(prec) => strip_g_zeros(&general_core(f.abs(), prec, false, prec.max(1) as i32 - 1)), + Some(prec) => strip_g_zeros(general_core(f.abs(), prec, false, prec.max(1) as i32 - 1)), }; let core = if core.contains(['.', 'e', 'E']) { core @@ -81217,23 +94790,41 @@ fn format_complex(re: f64, im: f64, parsed: &ParsedSpec) -> Result String { - let (mant, exp) = match core.find(['e', 'E']) { - Some(k) => (&core[..k], &core[k..]), - None => (core, ""), - }; - let mant = if mant.contains('.') { - mant.trim_end_matches('0').trim_end_matches('.') +fn strip_g_zeros(mut core: String) -> String { + let k = core.find(['e', 'E']).unwrap_or(core.len()); + let mant = &core[..k]; + if !mant.contains('.') { + return core; + } + let keep = mant.trim_end_matches('0').trim_end_matches('.').len(); + if keep == k { + return core; + } + // (In place: the exponent, if any, moves down over the zeros.) + core.replace_range(keep..k, ""); + core +} + +/// [`with_sign`] of an owned body, which an unsigned result keeps. +fn with_sign_owned(neg: bool, body: String, p: &ParsedSpec) -> String { + let sign = if neg { + '-' } else { - mant + match p.sign { + Some(c @ ('+' | ' ')) => c, + _ => return body, + } }; - format!("{mant}{exp}") + let mut out = String::with_capacity(body.len() + 1); + out.push(sign); + out.push_str(&body); + out } fn with_sign(neg: bool, body: &str, p: &ParsedSpec) -> String { @@ -81248,13 +94839,20 @@ fn with_sign(neg: bool, body: &str, p: &ParsedSpec) -> String { } } -fn apply_alignment(body: &str, p: &ParsedSpec, default_right: bool) -> String { +fn apply_alignment(owned: String, p: &ParsedSpec, default_right: bool) -> String { let width = p.width.unwrap_or(0); - if body.chars().count() >= width { - return body.to_owned(); + // (The common unpadded result is the body itself, not a copy.) + let n = if owned.is_ascii() { + owned.len() + } else { + owned.chars().count() + }; + if n >= width { + return owned; } + let body: &str = &owned; let fill = p.fill.unwrap_or(' '); - let pad = width - body.chars().count(); + let pad = width - n; let align = p.align.unwrap_or(if default_right { '>' } else { '<' }); match align { '<' => { @@ -81311,7 +94909,7 @@ fn apply_alignment(body: &str, p: &ParsedSpec, default_right: bool) -> String { s.push_str(rest); s } - _ => body.to_owned(), + _ => owned, } } @@ -81437,6 +95035,349 @@ fn find_handler(table: &[ExcHandler], pc: u32) -> Option<&ExcHandler> { table.iter().find(|h| pc >= h.start && pc < h.end) } +/// An `except` clause that never looks at the exception it catches (see +/// [`blind_handler`]). +#[derive(Clone, Copy)] +pub(crate) struct BlindHandler { + /// The classes the clause names, each by a `LOAD_GLOBAL`, a + /// `LOAD_DEREF` or a `LOAD_FAST`, from this pc on (none: a bare + /// `except:`). + names: u32, + nnames: u32, + /// The clause's body, up to its `POP_EXCEPT` at `end`. + body: u32, + pub(crate) end: u32, + /// Whether the body does arithmetic (see [`blind_arith`]). + arith: bool, +} + +/// The most instructions a blind clause's body runs. +const BLIND_BODY: usize = 12; + +/// Whether the handler `h` of `code` is a first `except` clause that +/// can't observe the exception it catches: it names its classes by +/// global, closure variable or local (or is bare), doesn't bind the +/// exception, and its body only moves constants, locals and closure +/// variables' values (`pass`, `x = default`, `continue`, `return -1`) and +/// adds, subtracts or multiplies them (`missed += 1`; see +/// [`blind_arith`]). +/// Nothing runs between the raise and the clause's +/// `POP_EXCEPT` that could read the exception, its traceback or +/// `sys.exception()`, so a raise such a clause catches needs none of +/// them (see `Interpreter::blind_catch`). +pub(crate) fn blind_handler(code: &CodeObject, h: &ExcHandler) -> Option { + if h.push_lasti { + return None; + } + let at = |pc: usize| code.instructions.get(pc).copied(); + let mut pc = h.handler as usize; + if at(pc)?.op != OpCode::PushExcInfo { + return None; + } + pc += 1; + let names = pc; + while matches!( + at(pc)?.op, + OpCode::LoadGlobal | OpCode::LoadDeref | OpCode::LoadFast | OpCode::LoadFastBorrow + ) { + pc += 1; + } + let nnames = pc - names; + if nnames > 0 { + if nnames > 1 { + let b = at(pc)?; + if b.op != OpCode::BuildTuple || b.arg as usize != nnames { + return None; + } + pc += 1; + } + if at(pc)?.op != OpCode::CheckExcMatch || at(pc + 1)?.op != OpCode::PopJumpIfFalse { + return None; + } + pc += 2; + if at(pc)?.op == OpCode::NotTaken { + pc += 1; + } + } + if at(pc)?.op != OpCode::PopTop { + return None; + } + pc += 1; + let body = pc; + let mut arith = false; + // The body's stack over the previous exception's slot (`true`). + let mut sim = vec![true]; + loop { + let ins = at(pc)?; + match ins.op { + OpCode::Nop | OpCode::NotTaken => {} + OpCode::LoadConst + | OpCode::LoadSmallInt + | OpCode::LoadFast + | OpCode::LoadFastBorrow + | OpCode::LoadDeref => { + sim.push(false); + } + OpCode::StoreFast | OpCode::PopTop => { + if sim.pop() != Some(false) { + return None; + } + } + OpCode::BinaryOp => { + if !matches!(ins.arg & !weavepy_compiler::BINARY_OP_INPLACE_FLAG, 0..=2) + || sim.pop() != Some(false) + || sim.last() != Some(&false) + { + return None; + } + arith = true; + } + OpCode::Swap => { + let (n, d) = (sim.len(), ins.arg as usize); + if d < 2 || d > n { + return None; + } + sim.swap(n - 1, n - d); + } + OpCode::PopExcept => { + if sim.pop() != Some(true) { + return None; + } + break; + } + _ => return None, + } + pc += 1; + if pc - body > BLIND_BODY { + return None; + } + } + Some(BlindHandler { + names: names as u32, + nnames: nnames as u32, + body: body as u32, + end: pc as u32, + arith, + }) +} + +/// A value a blind clause's body moves, as its run-time check sees it: +/// only numbers take part in arithmetic. +#[derive(Clone, Copy)] +enum BlindVal { + Int(i64), + Float(f64), + Other, +} + +impl BlindVal { + fn of(o: &Object) -> Self { + match o { + Object::Int(i) => Self::Int(*i), + Object::Float(f) => Self::Float(*f), + _ => Self::Other, + } + } + + fn object(self) -> Object { + match self { + Self::Int(i) => Object::Int(i), + Self::Float(f) => Object::Float(f), + Self::Other => Object::None, + } + } +} + +/// A blind clause's `BINARY_OP` (`arg`: `+`, `-` or `*`, in place or not) +/// of two ints that doesn't overflow, or of two floats: what the full +/// operation answers, running no code. `None` for anything else (the +/// clause isn't run blind). +fn blind_arith(arg: u32, a: BlindVal, b: BlindVal) -> Option { + let kind = arg & !weavepy_compiler::BINARY_OP_INPLACE_FLAG; + match (a, b) { + (BlindVal::Int(x), BlindVal::Int(y)) => match kind { + 0 => x.checked_add(y), + 1 => x.checked_sub(y), + 2 => x.checked_mul(y), + _ => None, + } + .map(BlindVal::Int), + (BlindVal::Float(x), BlindVal::Float(y)) => match kind { + 0 => Some(x + y), + 1 => Some(x - y), + 2 => Some(x * y), + _ => None, + } + .map(BlindVal::Float), + _ => None, + } +} + +/// Whether a store into the local `old` is held by can't run a finalizer: +/// an atomic value, or one something else also holds. +#[inline] +fn blind_store_stays(old: &Object) -> bool { + crate::gc_trace::is_atomic(old) + || old.strong_word().is_some_and(|w| { + // SAFETY: the local owns a reference to the live allocation. + unsafe { &*w }.load(std::sync::atomic::Ordering::Relaxed) > 1 + }) +} + +/// `Interpreter::blind_catch`'s run-time check of a body that only moves +/// values: the deepest the body's stack gets over the handler's `depth`, +/// `None` for a body that can't run blind now (an unbound local or cell +/// it reads, a local it overwrites whose value would die). +/// +/// # Safety +/// +/// `locals` are `frame`'s, which `body`'s instructions name. +#[inline] +unsafe fn blind_check_moves( + frame: &Frame, + locals: *const Object, + consts: &[Object], + body: &[weavepy_compiler::Instruction], + depth: usize, +) -> Option { + let mut n = depth + 1; + let mut peak = n; + for ins in body { + match ins.op { + OpCode::LoadFast | OpCode::LoadFastBorrow => { + // SAFETY: the caller's contract. + if matches!(unsafe { &*locals.add(ins.arg as usize) }, Object::Unbound) { + return None; + } + n += 1; + } + OpCode::LoadConst => { + consts.get(ins.arg as usize)?; + n += 1; + } + OpCode::LoadDeref => { + // SAFETY: a read between two instructions. + let v = unsafe { frame.cells.get(ins.arg as usize)?.peek() }?; + if matches!(v, Object::Unbound) { + return None; + } + n += 1; + } + OpCode::LoadSmallInt => n += 1, + OpCode::StoreFast => { + // SAFETY: the caller's contract. + if !blind_store_stays(unsafe { &*locals.add(ins.arg as usize) }) { + return None; + } + n -= 1; + } + OpCode::PopTop => n -= 1, + _ => {} + } + peak = peak.max(n); + } + Some(peak) +} + +/// [`blind_check_moves`] for a body with arithmetic (see [`blind_arith`]): +/// the body's numbers computed as it would compute them, an operand that +/// isn't one (or an overflow) declining. +/// +/// # Safety +/// +/// As [`blind_check_moves`]'s. +#[inline(never)] +unsafe fn blind_check_arith( + frame: &Frame, + locals: *const Object, + consts: &[Object], + body: &[weavepy_compiler::Instruction], + depth: usize, +) -> Option { + // The body's stack as numbers, over the previous exception's slot, and + // what it stores, which later loads in it read (the analysis bounds + // both by the body's length). + let mut vals = [BlindVal::Other; BLIND_BODY + 2]; + let mut k = 1usize; + let mut stored = [(u32::MAX, BlindVal::Other); BLIND_BODY]; + let mut nstored = 0usize; + let mut peak = depth + 1; + for ins in body { + match ins.op { + OpCode::LoadFast | OpCode::LoadFastBorrow => { + vals[k] = match stored[..nstored].iter().rev().find(|s| s.0 == ins.arg) { + Some(&(_, v)) => v, + None => { + // SAFETY: the caller's contract. + let v = unsafe { &*locals.add(ins.arg as usize) }; + if matches!(v, Object::Unbound) { + return None; + } + BlindVal::of(v) + } + }; + k += 1; + } + OpCode::LoadConst => { + vals[k] = BlindVal::of(consts.get(ins.arg as usize)?); + k += 1; + } + OpCode::LoadDeref => { + // SAFETY: a read between two instructions. + let v = unsafe { frame.cells.get(ins.arg as usize)?.peek() }?; + if matches!(v, Object::Unbound) { + return None; + } + vals[k] = BlindVal::Other; + k += 1; + } + OpCode::LoadSmallInt => { + vals[k] = BlindVal::Int(i64::from(ins.arg)); + k += 1; + } + OpCode::BinaryOp => { + k -= 1; + vals[k - 1] = blind_arith(ins.arg, vals[k - 1], vals[k])?; + } + OpCode::StoreFast => { + k -= 1; + // A second store into one local replaces what the first + // stored: only a number of its arithmetic (nothing holds a + // value it moved once the store drops it). + match stored[..nstored].iter().rev().find(|s| s.0 == ins.arg) { + Some((_, BlindVal::Int(_) | BlindVal::Float(_))) => {} + Some(_) => return None, + None => { + // SAFETY: the caller's contract. + if !blind_store_stays(unsafe { &*locals.add(ins.arg as usize) }) { + return None; + } + } + } + stored[nstored] = (ins.arg, vals[k]); + nstored += 1; + } + OpCode::PopTop => k -= 1, + OpCode::Swap => vals.swap(k - 1, k - ins.arg as usize), + _ => {} + } + peak = peak.max(depth + k); + } + Some(peak) +} + +/// [`blind_handler`] of each of `code`'s handlers, decided once (`ext` is +/// `code`'s). +#[inline] +fn blind_handlers<'a>(code: &CodeObject, ext: &'a CodeConstObjects) -> &'a [Option] { + ext.blind.get_or_init(|| { + code.exception_table + .iter() + .map(|h| blind_handler(code, h)) + .collect() + }) +} + /// RFC 0053 WS5 — whether a callable fires CPython's `c_call` / /// `c_return` / `c_exception` profile events: built-in functions and /// bound native methods (`PyCFunction_Check` in `ceval.c`). Classes, @@ -81527,6 +95468,27 @@ fn builtin_needs_interp_uncached(name: &str) -> bool { || matches!( name, ".format" + | "sha256" + | "sha1" + | "md5" + | "crc32" + | "adler32" + | "compress" + | "decompress" + | "audit" + | "_remove_dead_weakref" + | "make_encoder" + | "_acquire_lock" + | "_release_lock" + | "_abc_instancecheck" + | "_abc_subclasscheck" + | "stat" + | "lstat" + | "getcwd" + | "access" + | "listdir" + | "scandir" + | "setlocale" | ".format_map" | ".gc.collect" | ".gc.get_objects" @@ -81633,50 +95595,69 @@ fn exception_init_call(b: &crate::object::BuiltinFn, recv: &Object) -> bool { /// dispatch knows by name. #[inline] fn lane_recv_ok(b: &crate::object::BuiltinFn, recv: &Object, via_call: bool) -> bool { - b.binds_instance - // (A site settled on a plain instance's native `__init__` may see - // a dict payload later, which the dispatch routes.) - && (via_call || b.name != "__init__" || native_init_call(b, recv) || dict_init_call(b, recv)) + if !b.binds_instance { + // A native classmethod's function bound to its class, through the + // full call (see `Interpreter::builtin_lane`). + return via_call && matches!(recv, Object::Type(_)); + } + // (A site settled on a plain instance's native `__init__` may see + // a dict payload later, which the dispatch routes.) + (via_call || b.name != "__init__" || native_init_call(b, recv) || container_init_call(b, recv)) && (!via_call || builtins::method_memo_tag(recv).is_some() + // A builtin subclass's instance (`Counter.items`): the method + // the site loaded from its class, whose body (or the shim + // around it) unwraps the payload itself. + || matches!(recv, Object::Instance(i) if i.native.get().is_some()) + // A native method of a class written in Python on its plain + // instance (`deque.extend`), as `Interpreter::builtin_lane` + // settles it. + || (matches!(recv, Object::Instance(_)) && builtin_method_via_call(b.name)) || exception_init_call(b, recv) || (matches!(b.name, ".object_reduce_ex" | ".object_reduce") && matches!(recv, Object::Instance(_)))) } -/// Whether `b` called on `recv` is `dict.__init__` on a dict or an instance -/// of a `dict` subclass (`super().__init__()` in a subclass's `__init__`): -/// its body (`dict_init_kw`) reads the receiver's payload itself and runs -/// what the dispatch's call of it would, so the core loop's lane runs it. -fn dict_init_call(b: &crate::object::BuiltinFn, recv: &Object) -> bool { +/// Whether `b` called on `recv` is `dict.__init__`, `list.__init__` or +/// `set.__init__` on that container or an instance of a subclass of it +/// (`super().__init__()` in a subclass's `__init__`): its body reads the +/// receiver's payload itself and runs what the dispatch's call of it would +/// (iterating its argument through the interpreter), so the core loop's lane +/// runs it. +fn container_init_call(b: &crate::object::BuiltinFn, recv: &Object) -> bool { thread_local! { - static DICT_INIT: Cell = const { Cell::new(0) }; + /// The three `__init__` bodies, once found: dict's, list's, set's. + static INITS: [Cell; 3] = const { [Cell::new(0), Cell::new(0), Cell::new(0)] }; } - if b.name != "__init__" || b.call_kw.is_none() { + if b.name != "__init__" { return false; } - let dict_payload = match recv { - Object::Dict(_) => true, - Object::Instance(i) => matches!(i.native.get(), Some(Object::Dict(_))), - _ => false, + let payload = match recv { + Object::Instance(i) => match i.native.get() { + Some(p) => p, + None => return false, + }, + other => other, + }; + let (kind, ty) = match payload { + Object::Dict(_) => (0, &builtin_types().dict_), + Object::List(_) => (1, &builtin_types().list_), + Object::Set(_) => (2, &builtin_types().set_), + _ => return false, }; - if !dict_payload { - return false; - } let at = std::ptr::from_ref(b) as usize; - DICT_INIT.with(|c| { - if c.get() == at { + INITS.with(|c| { + if c[kind].get() == at { return true; } - let found = builtin_types() - .dict_ + let found = ty .dict .try_borrow() .ok() .and_then(|d| d.get(&crate::object::StrKey("__init__")).cloned()); let is = matches!(found, Some(Object::Builtin(d)) if std::ptr::eq(Rc::as_ptr(&d), b)); if is { - c.set(at); + c[kind].set(at); } is }) @@ -81786,12 +95767,76 @@ fn builtin_fn_lane_ok_uncached(name: &str) -> bool { // time, heapq, bisect | "time" | "time_ns" | "perf_counter" | "perf_counter_ns" | "monotonic" | "monotonic_ns" | "heappush" | "heappop" | "heapify" | "heapreplace" - | "heappushpop" | "bisect" | "bisect_left" | "bisect_right" | "insort" + | "heappushpop" | "heappush_max" | "heappop_max" | "heapify_max" + | "heapreplace_max" | "heappushpop_max" | "bisect" | "bisect_left" | "bisect_right" | "insort" | "insort_left" | "insort_right" + // os, through the interpreter's call (a path-like argument's + // `__fspath__`), and `locale.setlocale`'s query + | "stat" | "lstat" | "fspath" | "getcwd" | "access" | "listdir" | "scandir" + | "setlocale" | "get_terminal_size" | "isatty" + | "fsdecode" | "fsencode" | "dir" + // hashing and compression, `sys.audit` (whose hooks run through + // the call), `weakref`'s dead-entry callback, `json`'s encoder + // constructor, and the import system's module locks + | "sha256" | "sha1" | "md5" | "crc32" | "adler32" | "compress" | "decompress" + | "audit" | "_remove_dead_weakref" | "make_encoder" | "_acquire_lock" + | "_release_lock" + // `warnings`' filter-version bump, `sys.getsizeof` (a Python + // `__sizeof__` runs through the call), `abc`'s checks (whose + // hooks run through reentrant calls), `time.mktime`, + // `int.from_bytes` (an iterable argument's items likewise), and + // the `datetime` module's pure helpers + | "_filters_mutated_lock_held" | "getsizeof" | "_abc_instancecheck" + | "_abc_subclasscheck" | "mktime" | "from_bytes" | "timedelta_parts" + | "ymd_toordinal" | "ordinal_toymd" | "parse_time_parts" | "date_fields" + | "time_fields" | "format_time_parts" + // files and the `os` calls around them (an opener, a path's + // `__fspath__` or a warning runs through a reentrant call), + // locks' and threads' identities, `pickle`/`json`/`marshal` + // round trips (reducers and hooks likewise), `binascii`, `csv`, + // `re`'s pattern cache and compiler entry, `functools.wraps`' + // copy, and `abc`'s class set-up + | "open" | "text_encoding" | "unlink" | "remove" | "fstat" | "utime" | "chmod" + | "close" | "read" | "write" | "pipe" | "sendfile" | "mkdir" | "makedirs" + | "rmdir" | "rename" | "getpid" | "urandom" | "set_blocking" | "waitpid" + | "WEXITSTATUS" | "WIFSIGNALED" | "WIFEXITED" | "allocate_lock" | "get_ident" + | "get_native_id" | "dumps" | "loads" | "hexlify" | "unhexlify" | "b2a_base64" + | "a2b_base64" | "reader" | "writer" | "_cache_get" | "_cache_put" + | "make_pattern" | "_update_wrapper_plain" | "_abc_init" | "_abc_register" + | "is_frozen" | "_new_mapping" + // `contextvars.copy_context` (the thread's context, not the + // caller's frame), `string.Formatter`'s parsers, the + // `datetime` class methods, `os.path`'s and `re`'s native + // helpers, `os.walk`, `time.strptime`, the tokenizer, the XML + // parser's constructor and `ElementTree`'s serializer (whose + // callbacks run through reentrant calls), and the event loop's + // per-run bookkeeping + | "copy_context" | "formatter_parser" | "formatter_field_name_split" + | "now" | "today" | "fromtimestamp" | "fromisoformat" | "combine" | "fromordinal" + | "_path_normpath" | "_path_splitroot_ex" | "compile_cached" | "exec_match" + | "walk" | "strptime" | "tokens" | "ParserCreate" | "_namespaces" + | "_serialize_xml" | "_set_running_loop" | "get_asyncgen_hooks" + | "set_asyncgen_hooks" + // `decimal.getcontext` (the thread's context), `dict.fromkeys` + // (an iterable's items come through reentrant calls), + // `hmac.compare_digest`, `zlib.decompressobj` and `json`'s + // scanner constructor + | "getcontext" | "fromkeys" | "_compare_digest" | "decompressobj" + | "make_scanner" // sys | "_getframe" | "_getframemodulename" | "getrecursionlimit" | "intern" | "exc_info" // struct | "pack" | "unpack" | "calcsize" + // functools (whose callbacks run through reentrant calls) + | "reduce" + // `itertools.tee`'s native body (a source's `__iter__` runs + // through a reentrant call) + | "tee_native" + // `operator`'s getters' and `methodcaller`'s calls (a Python + // `__getitem__`, getter or method runs through a reentrant call) + | ".itemgetter.__call__" | ".attrgetter.__call__" | ".methodcaller.__call__" + // `str.maketrans`/`bytes.maketrans` (static, pure) + | "maketrans" // warnings (which reads the whole stack, lean activations included) | "warn" // asyncio (`gather` reads the running loop's current task) @@ -81980,6 +96025,10 @@ struct CodeConstObjects { /// value moves into its cell as a call starts, `u32::MAX` for the others /// (a call's cells are made and released by these slots). cell_args: Box<[u32]>, + /// [`Self::cell_args`] inverted: per local slot up to the last + /// argument with a cell, the index of its cell, `u32::MAX` for the + /// others (empty when no argument has a cell). + cell_of_slot: Box<[u32]>, /// RFC 0077 WS4: `py_str_hash` of every `co_names` entry, so the /// attribute-name dict probes the eval loop issues per execution of a /// site (inline-cache shadow guards, generic lookups) hash the @@ -81995,6 +96044,9 @@ struct CodeConstObjects { /// [`site_ranks`]), which index the per-site tables below, or /// [`NO_SITE`]; built with the first of those tables. site_ranks: std::sync::OnceLock>, + /// Which of the code's handlers ignore their exception (see + /// [`blind_handlers`]), by exception-table entry. + blind: std::sync::OnceLock]>>, /// RFC 0077 WS4: the resolved method per `LoadAttrMethod` site (see /// [`MethodSlot`]). Allocated on the first method-shape hit in this /// code object. @@ -82031,6 +96083,22 @@ struct CodeConstObjects { /// Whether the code is a generator body fast steps run (see /// `gen_fast`): 0 not yet scanned, 1 no, 2 yes. gen_fast: std::sync::atomic::AtomicU8, + /// Native generator steps of this body that stopped partway (a call + /// to Python code a step can't make), less those that ran to a yield: + /// past `gen_fast::STALL_LIMIT` the steps are skipped, for the resume + /// a running activation's loop makes (see `gen_native_next`). + pub(crate) gen_stalls: std::sync::atomic::AtomicU32, + /// The pcs (up to four, 16 bits each, `0` none) a suspended generator + /// of this body resumes at by the short path (see + /// `gen_fast::lean_pc`). + pub(crate) gen_lean: std::sync::atomic::AtomicU64, + /// Where the code runs the sequence walk a suspended generator steps + /// without a resume (see `gen_fast::walk_site`): 0 not yet scanned, + /// 1 nowhere, else the walk's first pc plus 2. + pub(crate) gen_walk: std::sync::atomic::AtomicU32, + /// Whether the code's `**kwargs` dict can outlive its call (see + /// [`varkw_stays_local`]): 0 not yet scanned, 1 it can't, 2 it can. + varkw_local: std::sync::atomic::AtomicU8, /// The `RETURN_GENERATOR` a generator-family call of the code starts /// past (see `Interpreter::generator_start`): `0` not yet scanned, /// `u32::MAX` none (the prologue holds something else), else its pc @@ -82060,6 +96128,12 @@ struct CodeConstObjects { /// A leaf body's translation for the frameless evaluator (see /// [`leaf_plan`]), or `None` when the body has none. leaf_plan: std::sync::OnceLock>>, + /// What a one-parameter body reads from its argument and returns, if + /// that is all it does (see [`lambda_part`]). + part_shape: std::sync::OnceLock>, + /// Whether the whole body passes its arguments on to its one free + /// variable (see [`code_forwards`]). + forwards: std::sync::OnceLock, /// Whether every return is `return None` (see /// [`code_returns_only_none`]): `0` not yet decided, `1` no, `2` yes. returns_none: std::sync::atomic::AtomicU8, @@ -82102,6 +96176,11 @@ struct CodeConstObjects { /// [`CodeConstObjects::gen_start`]'s mark of a body with a `SEND`. const GEN_DELEGATES: u32 = 1 << 31; +/// [`CodeConstObjects::gen_start`]'s mark of a body that takes `*args`: +/// only a caller that packs the surplus starts it +/// (`Interpreter::generator_start_spread`). +const GEN_VARARGS: u32 = 1 << 30; + /// The rank [`site_ranks`] gives an instruction that isn't a site (or one /// past the 65,535th): no per-site table has an entry at it. const NO_SITE: u16 = u16::MAX; @@ -82594,6 +96673,12 @@ impl AttrPoly { fn index(&self, ver: u64) -> Option { // SAFETY: see the type docs. let entries = unsafe { &*self.0.get() }; + // (Entries fill from the front and are never cleared: a site that + // isn't polymorphic, a property's or a method's, answers on one + // compare.) + if entries[0].0 == 0 { + return None; + } entries.iter().find(|e| e.0 == ver && ver != 0).map(|e| e.1) } @@ -82923,18 +97008,83 @@ pub(crate) fn inst_builtin_method_site( } /// Whether a method `cls` (an instance's class at the version its site -/// cached) resolved stays the one an attribute read finds: the class reads -/// attributes the default way, and `inst` holds none of its own. +/// cached) resolved as `name` (Python hash `hash`) stays the one an +/// attribute read finds: the class reads attributes the default way, and +/// `inst` holds no attribute of that name. #[cfg(feature = "jit")] #[inline] -pub(crate) fn inst_method_unshadowed( +pub(crate) fn inst_method_unshadowed_by( cls: &crate::types::TypeObject, inst: &crate::types::PyInstance, + name: &str, + hash: i64, ) -> bool { - inst.dict.published().is_none() + Interpreter::default_getattribute(cls) // SAFETY: a read between two instructions (see `GilCell::peek`). - && unsafe { inst.dict.split_cell().peek() }.is_some_and(|s| s.is_empty()) - && Interpreter::default_getattribute(cls) + && unsafe { inst.attr_peek_has(name, hash) } == Some(false) +} + +/// Whether a keyword call of the exact builtin type `ty` with `argc` +/// positional arguments and the keyword `names` (the call's names tuple) +/// is its positional call: the names are, in order, the parameters after +/// the positional ones, each of which may come by keyword (`int(x, +/// base=16)`, `enumerate(xs, start=1)`, `str(b, encoding="utf-8")`). +#[cfg(feature = "jit")] +pub(crate) fn builtin_kw_positional(ty: &Rc, argc: usize, names: &Object) -> bool { + let Some(params) = builtin_kw_params(ty) else { + return false; + }; + let Object::Tuple(names) = names else { + return false; + }; + !names.is_empty() + && argc + names.len() <= params.len() + && names.iter().enumerate().all(|(j, n)| { + let p = params[argc + j]; + !p.starts_with('/') && matches!(n, Object::Str(s) if s.as_ref() == p) + }) +} + +/// The parameters of a builtin type's method on its exact receiver +/// `recv` whose keyword calls [`Interpreter::core_method_kw_positional`] +/// maps to positions (a `/` marks a positional-only one), as CPython's +/// signatures name them. Keyword-only ones (`int.to_bytes`'s `signed`) +/// aren't listed, so a call naming one isn't mapped. +#[inline] +pub(crate) fn builtin_method_kw_params( + recv: &Object, + name: &str, +) -> Option<&'static [&'static str]> { + let text = matches!(recv, Object::Str(_)); + let bytes = matches!(recv, Object::Bytes(_) | Object::ByteArray(_)); + // (`str.split`, `rsplit`, `splitlines`, `encode` and `bytes.decode` + // aren't listed: their registered keyword halves, which + // `Interpreter::core_native_kw_call` binds, serve them as cheaply.) + Some(match name { + "split" | "rsplit" if bytes => &["sep", "maxsplit"], + "expandtabs" if text || bytes => &["tabsize"], + "replace" if text => &["/old", "/new", "count"], + "to_bytes" if matches!(recv, Object::Int(_) | Object::Long(_)) => &["length", "byteorder"], + _ => return None, + }) +} + +/// The parameters of the builtin types whose keyword calls +/// [`builtin_kw_positional`] maps to positions (a `/` marks a +/// positional-only one). +pub(crate) fn builtin_kw_params(ty: &Rc) -> Option<&'static [&'static str]> { + let bt = builtin_types(); + Some(if Rc::ptr_eq(ty, &bt.int_) { + &["/x", "base"] + } else if Rc::ptr_eq(ty, &bt.enumerate_) { + &["iterable", "start"] + } else if Rc::ptr_eq(ty, &bt.str_) { + &["object", "encoding", "errors"] + } else if Rc::ptr_eq(ty, &bt.bytes_) || Rc::ptr_eq(ty, &bt.bytearray_) { + &["source", "encoding", "errors"] + } else { + return None; + }) } /// The leaf builtin's kind the `CALL` at `pc` last settled on. @@ -82975,13 +97125,24 @@ pub(crate) fn call_site_callees( } /// The live Python functions the method load at `pc` has resolved for a -/// receiver it passes as `self`, latest first. +/// receiver it passes as `self`, latest first, each with the number of +/// receiver classes the site recorded it for (the site's two tables each +/// record a class once: the larger count). #[cfg(feature = "jit")] pub(crate) fn method_site_callees( ext: &CodeConstObjects, pc: usize, -) -> Vec> { - let mut out = Vec::new(); +) -> Vec<(Rc, usize)> { + let mut out: Vec<(Rc, [usize; 2])> = Vec::new(); + let mut add = |f: Rc, table: usize| { + if let Some(entry) = out.iter_mut().find(|(g, _)| Rc::ptr_eq(g, &f)) { + entry.1[table] += 1; + } else { + let mut counts = [0; 2]; + counts[table] = 1; + out.push((f, counts)); + } + }; // SAFETY: GIL-serialized; the borrows end here. unsafe { if let Some(site) = ext.leaf_sites.get(pc) { @@ -82992,24 +97153,30 @@ pub(crate) fn method_site_callees( ); for data in entries { if let Some(f) = data.func.upgrade() { - out.push(f); + add(f, 0); } } } if let Some(slot) = ext.method_slot(pc) { if let (_, MethodSlotFn::Py(f)) = &*slot.0.get() { - out.extend(f.upgrade()); + if let Some(f) = f.upgrade() { + add(f, 1); + } } if let Some(poly) = (*slot.1.get()).as_ref() { for (_, f, unbound) in &poly.entries { if !*unbound { - out.extend(f.upgrade()); + if let Some(f) = f.upgrade() { + add(f, 1); + } } } } } } - out + out.into_iter() + .map(|(f, counts)| (f, counts[0].max(counts[1]))) + .collect() } /// Have the JIT's code-generation worker run `hook` whenever it runs out of @@ -83175,7 +97342,34 @@ pub(crate) fn callee_warm(code: &CodeObject, ext: &CodeConstObjects) -> bool { ext.frame_jit.compiled_nlocals().is_some() || code.jit_hint.lean_entries() >= 24 || (code.jit_hint.is_compiled() && !code.jit_hint.is_not_jitable()) - || ext.leaf_tries.load(Relaxed) & u64::from(u32::MAX) >= 24 + || ext.leaf_tries.load(Relaxed) & u64::from(u32::MAX) >= LEAF_WARM_CALLS +} + +/// Finished frameless evaluations after which a callee counts as warm (see +/// [`callee_warm`]). +#[cfg(feature = "jit")] +const LEAF_WARM_CALLS: u64 = 24; + +/// Whether the frameless evaluator has built its plan for the code `ext` +/// extends (it ran there, or tried to). +#[cfg(feature = "jit")] +pub(crate) fn leaf_plan_built(ext: &CodeConstObjects) -> bool { + ext.leaf_plan.get().is_some_and(Option::is_some) +} + +/// Count a nested frameless evaluation of the code `ext` extends toward +/// its warmth (see [`callee_warm`]), as a direct one counts: a helper only +/// ever called from another frameless helper is still worth lowering in +/// line where a compiled caller inlines that helper. (Counts up to the +/// mark only, leaving the bails half alone.) +#[cfg(feature = "jit")] +#[inline(always)] +pub(crate) fn note_leaf_warm(ext: &CodeConstObjects) { + use std::sync::atomic::Ordering::Relaxed; + let tries = ext.leaf_tries.load(Relaxed); + if tries & u64::from(u32::MAX) < LEAF_WARM_CALLS { + ext.leaf_tries.store(tries + 1, Relaxed); + } } /// The `property` getter the `LOAD_ATTR` at `pc` last ran: the function, the @@ -83190,15 +97384,44 @@ pub(crate) fn property_site_getter( // SAFETY: GIL-serialized; the borrows end here. The class holds the // property while its version stands. unsafe { - let (ver, MethodSlotFn::Getter { prop, .. }) = &*slot.0.get() else { + let (ver, MethodSlotFn::Getter(g)) = &*slot.0.get() else { return None; }; let (f, _) = slot.getter(*ver)?; - let cell = (*prop.as_ptr()).fget.as_ptr().cast_const(); + let cell = (*g.prop.as_ptr()).fget.as_ptr().cast_const(); Some((f, *ver, cell)) } } +/// The `property` getter the `LOAD_ATTR` at `pc` keeps for the class at +/// `ver` (the one it last ran, or an earlier one for another class), and +/// where the property holds its getter, if all of it is alive. +#[cfg(feature = "jit")] +pub(crate) fn property_site_getter_at( + ext: &CodeConstObjects, + pc: usize, + ver: u64, +) -> Option<(Rc, *const Object)> { + let slot = ext.method_slot(pc)?; + if ver == 0 { + return None; + } + // SAFETY: GIL-serialized; the borrows end here. The class holds the + // property while its version stands. + unsafe { + let g = match &*slot.0.get() { + (v, MethodSlotFn::Getter(g)) if *v == ver => g, + _ => { + let poly = (*slot.1.get()).as_deref()?; + &poly.getters.iter().find(|(v, _)| *v == ver)?.1 + } + }; + let (f, _) = g.peek()?; + let cell = (*g.prop.as_ptr()).fget.as_ptr().cast_const(); + Some((MethodSlot::held(f), cell)) + } +} + /// Whether the attribute or global site at `pc` has resolved anything /// beyond its inline cache. #[cfg(feature = "jit")] @@ -83421,6 +97644,21 @@ fn slot_field_note( inst: &PyInstance, idx: u32, name_idx: u32, +) { + slot_field_note_with(code, ext, pc, inst, idx, name_idx, true); +} + +/// [`slot_field_note`], with the site tables made whether or not the +/// code has warmed (`warm` false: a frameless setter's store, which runs +/// only from hot callers and never warms its own tables). +fn slot_field_note_with( + code: &CodeObject, + ext: &CodeConstObjects, + pc: usize, + inst: &PyInstance, + idx: u32, + name_idx: u32, + warm: bool, ) { let ninstrs = code.instructions.len(); let cls = inst.cls_raw(); @@ -83439,7 +97677,7 @@ fn slot_field_note( { return; } - if !ext.field_slots.is_allocated() && !site_tables_warm(ext, ninstrs) { + if warm && !ext.field_slots.is_allocated() && !site_tables_warm(ext, ninstrs) { return; } let slots = ext.alloc_sites(code, &ext.field_slots, FieldSlot::empty); @@ -83555,6 +97793,41 @@ pub(crate) fn dunder_note( } } +/// [`DunderSeen::right`] of a `BINARY_SUBSCR`'s `__getitem__`: any key. +#[cfg(feature = "jit")] +pub(crate) const DUNDER_ANY_KEY: u8 = 0xff; + +/// Record that the `BINARY_SUBSCR` at `pc` called `f`, the plain Python +/// `__getitem__` of the plain instance `container`'s class, for the frame +/// JIT to lower in line as it lowers an operator method (any key; the +/// method's `NotImplemented` is a value like any other). +#[cfg(feature = "jit")] +pub(crate) fn getitem_note( + ext: &CodeConstObjects, + pc: usize, + f: &Rc, + container: &Object, +) { + let Object::Instance(inst) = container else { + return; + }; + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 || cls.c_ext_ptr.get() != 0 || inst.native.get().is_some() { + return; + } + let table = ext.dunders.get_or_init(Box::default); + // SAFETY: GIL-serialized; the borrow ends here. + let seen = unsafe { &mut *table.0.get() }; + if seen.iter().all(|d| d.pc != pc) { + seen.push(DunderSeen { + pc, + func: Rc::downgrade(f), + ver: cls.attr_version.get(), + right: Some(DUNDER_ANY_KEY), + }); + } +} + /// Whether the `BINARY_OP` at `pc` has recorded an operator method. #[cfg(feature = "jit")] #[inline] @@ -83688,6 +97961,26 @@ fn bool_hot(b: bool) -> Object { unsafe { std::mem::transmute::<[u64; 2], Object>([BOOL_TAG | (u64::from(b) << 8), 0]) } } +#[cfg(test)] +#[test] +fn lean_pending_exit_leaves_from_where_it_is() { + // Entries stand for activations by address only; nothing reads them. + let mut interp = Interpreter::new(); + interp.lean_pending.clear(); + interp.lean_pending.extend([0x1000, 0x2000, 0x3000]); + // An older activation's entry registered late (0x2000, 0x3000) sits + // above the returning one's (0x1000), which leaves without them. + interp.lean_pending_exit(Some(0x1000)); + assert_eq!(interp.lean_pending, [0x2000, 0x3000]); + interp.lean_pending_exit(Some(0x3000)); + assert_eq!(interp.lean_pending, [0x2000]); + // A flushed (absent) entry is a no-op. + interp.lean_pending_exit(Some(0x9000)); + interp.lean_pending_exit(None); + assert_eq!(interp.lean_pending, [0x2000]); + interp.lean_pending.clear(); +} + #[cfg(test)] #[test] fn scalar_builders_match_the_enum() { @@ -83846,7 +98139,9 @@ pub(crate) unsafe extern "C" fn h_dict_get( /// `BINARY_SUBSCR` of the instance at `cont` of a `dict` subclass that /// keeps `dict.__getitem__` (a `defaultdict`, an `OrderedDict`), by a /// present key that compares natively: as [`h_dict_get`] (a miss, which -/// may run `__missing__`, declines). +/// may run `__missing__`, declines). A `list` or `tuple` subclass's that +/// keeps the builtin `__getitem__` (`email`'s `TokenList`), by an `int` in +/// range: as [`h_seq_get`]. pub(crate) unsafe extern "C" fn h_inst_dict_get( out: *mut Object, cont: *const Object, @@ -83859,8 +98154,32 @@ pub(crate) unsafe extern "C" fn h_inst_dict_get( return 1; }; // (The payload first: most instances have none.) - let Some(Object::Dict(d)) = inst.native.get() else { - return 1; + let d = match inst.native.get() { + Some(Object::Dict(d)) => d, + Some(seq @ (Object::List(_) | Object::Tuple(_))) => { + let Object::Int(i) = *k else { + return 1; + }; + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || !inst + .class_dunder(crate::types::Dunder::GetItem) + .builtin_owner() + { + return 1; + } + let Some(rc) = PlainRelease::of(c, OWNED & 1 != 0) else { + return 1; + }; + let Some(v) = Interpreter::seq_get_hot(seq, i) else { + return 1; + }; + rc.run(); + out.write(v); + return 0; + } + _ => return 1, }; if !inst .class_dunder(crate::types::Dunder::GetItem) @@ -83874,10 +98193,15 @@ pub(crate) unsafe extern "C" fn h_inst_dict_get( ) else { return 1; }; - let Some(v) = Interpreter::dict_get_hot(d, k) else { - return 1; + let v = match Interpreter::dict_get_hot(d, k) { + Some(v) => clone_hot(v), + // A `defaultdict`'s miss whose factory builds natively: the + // new value, stored as its `__missing__` stores it. + None => match crate::stdlib::collections_native::dd_missing_pure(inst, d, k) { + Some(v) => v, + None => return 1, + }, }; - let v = clone_hot(v); rk.run(); rc.run(); out.write(v); @@ -84006,6 +98330,53 @@ pub(crate) unsafe extern "C" fn h_inst_dict_set( } } +/// `STORE_SUBSCR` into an instance whose class resolves `__setitem__` to a +/// built-in base's own with a leaf half (an `OrderedDict`'s; see +/// [`Interpreter::instance_setitem_leaf`]): as [`h_inst_dict_set`], with the +/// owned operands flagged in `owned`, the half storing it. The half only +/// borrows its arguments and runs no code, so it is handed bitwise copies. +pub(crate) unsafe fn inst_leaf_set( + val: *const Object, + cont: *const Object, + key: *const Object, + owned: u32, +) -> u32 { + // SAFETY: as `h_dict_set`'s; the copies are never dropped, and the + // originals outlive the call (no code runs to release them). + unsafe { + let (c, k) = (&*cont, &*key); + let Object::Instance(inst) = c else { + return 1; + }; + let Some(fast) = Interpreter::instance_setitem_leaf(inst) else { + return 1; + }; + let Some(rc) = PlainRelease::of(c, owned & 2 != 0) else { + return 1; + }; + // (A key the store holds alone, `od[(a, b)] = v`, is released in + // full after it: the dict keeps its own reference to a new key.) + let rk = PlainRelease::of(k, owned & 4 != 0); + if rk.is_none() && !Interpreter::core_droppable(k) { + return 1; + } + let args = std::mem::ManuallyDrop::new([cont.read(), key.read(), val.read()]); + // (A half that fails is left to the full path, which reports it.) + let Some(Ok(_)) = fast(&args[..]) else { + return 1; + }; + if owned & 1 != 0 { + crate::drop_hot(val.read()); + } + match rk { + Some(rk) => rk.run(), + None => crate::drop_hot(key.read()), + } + rc.run(); + 0 + } +} + /// `STORE_SUBSCR` of the value at `val` into the exact list at `cont` by /// the `int` at `key` (see [`Interpreter::list_set_hot`]): as /// [`h_dict_set`]. @@ -84494,7 +98865,11 @@ const META_CLASS_ENTRY: u64 = 0x5ca1_a770_0000_000b; /// The metaclass-class attribute the `LOAD_ATTR` site at `pc` remembers /// for `cls` (see [`META_CLASS_ENTRY`]), while both versions stand. #[inline] -fn meta_entry_hit(code: &CodeObject, cls: &crate::types::TypeObject, pc: usize) -> Option { +pub(crate) fn meta_entry_hit( + code: &CodeObject, + cls: &crate::types::TypeObject, + pc: usize, +) -> Option { let slot = code_stamp_slot(code, pc as u32)?; let [ver, tag, bits] = slot.get(); if tag != META_CLASS_ENTRY || ver != cls.attr_version.get() { @@ -84655,10 +99030,63 @@ struct MethodSlot( const POLY_METHODS: usize = 3; /// A [`MethodSlot`]'s earlier plain or static functions, by class -/// version (`0` marks an empty entry), replaced round-robin. +/// version (`0` marks an empty entry), replaced round-robin, and its +/// earlier `property` getters likewise (see [`MethodSlotFn::Getter`]). struct PolyMethods { entries: [(u64, crate::sync::Weak, bool); POLY_METHODS], next: usize, + getters: [(u64, GetterRef); POLY_GETTERS], + getter_next: usize, +} + +/// Earlier `property` getters a polymorphic [`MethodSlot`] keeps (a read +/// of `x.value` over a token tree's two node classes). +const POLY_GETTERS: usize = 2; + +/// A cached `property` getter: the property, its getter function and +/// that function's code when the slot was filled. +#[derive(Clone)] +struct GetterRef { + prop: crate::sync::Weak, + func: crate::sync::Weak, + code: crate::sync::Weak, +} + +impl GetterRef { + const fn empty() -> Self { + Self { + prop: crate::sync::Weak::new(), + func: crate::sync::Weak::new(), + code: crate::sync::Weak::new(), + } + } + + /// The getter, while the property (which the class holds while it + /// reads the entry's version) still holds that function and the + /// function that code. + /// + /// # Safety + /// + /// GIL-serialized; the references must not outlive anything that + /// could rebind the property's getter or the function's code, or + /// change the class. + #[inline] + unsafe fn peek(&self) -> Option<(&crate::object::PyFunction, &Rc)> { + if self.prop.strong_count() == 0 { + return None; + } + // SAFETY: the caller's contract; a raw read of the property's + // getter cell, compared before anything runs. + let Object::Function(f) = (unsafe { &*(*self.prop.as_ptr()).fget.as_ptr() }) else { + return None; + }; + if Rc::as_ptr(f) != self.func.as_ptr() { + return None; + } + // SAFETY: as `PyFunction::code` (the function holds its code). + let c: &Rc = unsafe { &*f.code.as_ptr() }; + (Rc::as_ptr(c) == self.code.as_ptr()).then_some((&**f, c)) + } } /// What a [`MethodSlot`] resolved: a Python function off a class (keyed @@ -84697,11 +99125,7 @@ enum MethodSlotFn { /// A `LOAD_ATTR` site's `property` getter for instances of the class /// at the key's version, and the code it was checked against (see /// `Interpreter::try_inline_property`). - Getter { - prop: crate::sync::Weak, - func: crate::sync::Weak, - code: crate::sync::Weak, - }, + Getter(GetterRef), /// A `LOAD_ATTR` site's plain class value (an enum member, a class's /// function or constant) for the class at the key's version under a /// metaclass at `meta_ver` (`0` for `type`), which reads it as `type` @@ -84770,6 +99194,8 @@ impl MethodSlot { Box::new(PolyMethods { entries: std::array::from_fn(|_| (0, crate::sync::Weak::new(), false)), next: 0, + getters: std::array::from_fn(|_| (0, GetterRef::empty())), + getter_next: 0, }) }); if poly.entries.iter().any(|(v, _, _)| v == old_ver) { @@ -85116,30 +99542,18 @@ impl MethodSlot { /// reads `ver` (see `get_held`), so no upgrade is needed. #[inline] fn getter(&self, ver: u64) -> Option<(Rc, Rc)> { - // SAFETY: GIL-serialized; no `&mut` escapes `set_getter`. - let (v, MethodSlotFn::Getter { prop, func, code }) = (unsafe { &*self.0.get() }) else { - return None; - }; - if *v != ver || prop.strong_count() == 0 { - return None; - } - // SAFETY: the class holds the property (see above); a raw read of - // its getter cell, compared before anything runs. - let Object::Function(f) = (unsafe { &*(*prop.as_ptr()).fget.as_ptr() }) else { - return None; - }; - if Rc::as_ptr(f) != func.as_ptr() { - return None; - } - let c = f.code(); - (Rc::as_ptr(&c) == code.as_ptr()).then(|| (f.clone(), c)) + // SAFETY: the handles are taken before anything runs. + let (f, c) = unsafe { self.getter_peek(ver) }?; + // SAFETY: `f` is a live function (an `Rc` allocation) its property + // holds. + Some((unsafe { Self::held(f) }, c.clone())) } /// Whether the site has cached a `property` getter (for any class). #[cfg(feature = "jit")] - fn holds_getter(&self) -> bool { + pub(crate) fn holds_getter(&self) -> bool { // SAFETY: GIL-serialized; no `&mut` escapes `set_getter`. - matches!(unsafe { &*self.0.get() }, (_, MethodSlotFn::Getter { .. })) + matches!(unsafe { &*self.0.get() }, (_, MethodSlotFn::Getter(_))) } /// [`Self::getter`] borrowed, for a read that runs no Python. @@ -85150,24 +99564,37 @@ impl MethodSlot { /// could rebind the property's getter or the function's code, or /// change the class. #[inline] - unsafe fn getter_peek(&self, ver: u64) -> Option<(&crate::object::PyFunction, &CodeObject)> { - // SAFETY: as `getter`. - let (v, MethodSlotFn::Getter { prop, func, code }) = (unsafe { &*self.0.get() }) else { - return None; - }; - if *v != ver || prop.strong_count() == 0 { - return None; - } - // SAFETY: as `getter`; the forwarded contract keeps both alive. - let Object::Function(f) = (unsafe { &*(*prop.as_ptr()).fget.as_ptr() }) else { - return None; - }; - if Rc::as_ptr(f) != func.as_ptr() { - return None; + unsafe fn getter_peek( + &self, + ver: u64, + ) -> Option<(&crate::object::PyFunction, &Rc)> { + // SAFETY: GIL-serialized; no `&mut` escapes `set_getter`; the + // forwarded contract keeps both alive. + unsafe { + match &*self.0.get() { + (v, MethodSlotFn::Getter(g)) if *v == ver => g.peek(), + _ => self.poly_getter(ver), + } } - // SAFETY: as `PyFunction::code` (the function holds its code). - let c: &Rc = unsafe { &*f.code.as_ptr() }; - (Rc::as_ptr(c) == code.as_ptr()).then_some((&**f, &**c)) + } + + /// An earlier getter the slot keeps for the class at `ver` (see + /// [`PolyMethods::getters`]). + /// + /// # Safety + /// + /// As [`Self::getter_peek`]'s. + #[cold] + #[inline(never)] + unsafe fn poly_getter( + &self, + ver: u64, + ) -> Option<(&crate::object::PyFunction, &Rc)> { + // SAFETY: as `getter_peek`. + let poly = unsafe { &*self.1.get() }.as_deref()?; + let (_, g) = poly.getters.iter().find(|(v, _)| *v == ver && ver != 0)?; + // SAFETY: as above. + unsafe { g.peek() } } #[inline] @@ -85178,15 +99605,35 @@ impl MethodSlot { func: &Rc, code: &Rc, ) { - // SAFETY: as `set`. + // SAFETY: as `set`; the references end before the slot is + // rewritten. unsafe { + // The getter it replaces, for another class, stays among the + // earlier ones. + if let (old_ver, MethodSlotFn::Getter(old)) = &*self.0.get() { + if *old_ver != 0 && *old_ver != ver && old.prop.strong_count() > 0 { + let poly = (*self.1.get()).get_or_insert_with(|| { + Box::new(PolyMethods { + entries: std::array::from_fn(|_| (0, crate::sync::Weak::new(), false)), + next: 0, + getters: std::array::from_fn(|_| (0, GetterRef::empty())), + getter_next: 0, + }) + }); + if !poly.getters.iter().any(|(v, _)| v == old_ver) { + let i = poly.getter_next; + poly.getters[i] = (*old_ver, old.clone()); + poly.getter_next = (i + 1) % POLY_GETTERS; + } + } + } *self.0.get() = ( ver, - MethodSlotFn::Getter { + MethodSlotFn::Getter(GetterRef { prop: Rc::downgrade(prop), func: Rc::downgrade(func), code: Rc::downgrade(code), - }, + }), ); }; } @@ -85229,6 +99676,12 @@ impl MethodSlot { } } +/// The metaclass version under which a `LOAD_ATTR` site's method slot +/// remembers a class's class method entry, native or Python (see +/// `leaf_load_type_attr`): no real version reaches it, so the plain class +/// value reads (`core_class_value`) never see the descriptor. +const NATIVE_CLASSMETHOD_META: u64 = u64::MAX; + /// The method slot for `cache_pc`, allocating the table on first use. #[inline] fn code_method_slot(code: &CodeObject, cache_pc: u32) -> Option<&MethodSlot> { @@ -85353,6 +99806,84 @@ const FAST_ATTR: u8 = 6; const FAST_ATTR_CHAIN: u8 = 7; const FAST_STORE_ATTR: u8 = 8; +/// A Python `__new__`'s code when its whole body is +/// `return object.__new__(cls)`, after an optional +/// `if cls is X: cls = Y`, and it takes positional arguments alone (see +/// [`crate::types::TrivialNew`]): `object`'s and `X`'s name indices, where +/// the reassignment starts and ends, and the positional parameter count a +/// call has to match (`None` for `*args`). +fn trivial_new_shape(code: &CodeObject) -> Option<(u32, Option, (u32, u32), Option)> { + use weavepy_compiler::Instruction; + if code.is_generator + || code.is_coroutine + || code.is_async_generator + || code.arg_count == 0 + || code.kwonly_count != 0 + || (code.has_varargs && code.arg_count != 1) + || !code.cellvars.is_empty() + { + return None; + } + let ins = &code.instructions; + // The next instruction at or past `pc` that does something. + let next = |pc: &mut usize| -> Option { + loop { + let i = *ins.get(*pc)?; + *pc += 1; + if !matches!( + i.op, + OpCode::Resume | OpCode::Nop | OpCode::NotTaken | OpCode::CopyFreeVars + ) { + return Some(i); + } + } + }; + let cls = |i: &Instruction| { + matches!( + i.op, + OpCode::LoadFast | OpCode::LoadFastBorrow | OpCode::LoadFastCheck + ) && i.arg == 0 + }; + let name = |idx: u32| code.names.get(idx as usize).map(|n| n.as_str()); + let mut pc = 0; + let mut first = next(&mut pc)?; + let mut swap = None; + let mut swap_body = (0, 0); + // (`cls is X` jumps past the reassignment when false, the only path + // the lane takes: the branch's body never runs, whatever it is.) + if cls(&first) { + let x = next(&mut pc)?; + let is = next(&mut pc)?; + let jump = next(&mut pc)?; + if x.op != OpCode::LoadGlobal + || is.op != OpCode::IsOp + || is.arg != 0 + || jump.op != OpCode::PopJumpIfFalse + { + return None; + } + let body = pc; + pc += jump.arg as usize; + swap = Some(x.arg); + swap_body = (u32::try_from(body).ok()?, u32::try_from(pc).ok()?); + first = next(&mut pc)?; + } + let method = next(&mut pc)?; + let arg = next(&mut pc)?; + let call = next(&mut pc)?; + let ret = next(&mut pc)?; + let shape = matches!(first.op, OpCode::LoadGlobal | OpCode::LoadGlobalPushNull) + && name(first.arg) == Some("object") + && matches!(method.op, OpCode::LoadMethodAttr | OpCode::LoadAttr) + && name(method.arg) == Some("__new__") + && cls(&arg) + && call.op == OpCode::Call + && call.arg == 1 + && ret.op == OpCode::ReturnValue; + let fixed = (!code.has_varargs).then_some(code.arg_count); + shape.then_some((first.arg, swap, swap_body, fixed)) +} + /// A leaf's parameter count: its positional parameters, its keyword-only /// ones, then its `**kwargs` dictionary when it has one (bound by keyword /// calls only; a leaf has no `*args`). @@ -85491,6 +100022,54 @@ pub(crate) fn body_pcs(code: &CodeObject) -> Vec { out } +/// The most instructions a pure or effect leaf's code has. +const LEAF_BODY_MAX: usize = 64; + +/// [`body_pcs`] of code with at most [`LEAF_BODY_MAX`] instructions, into +/// `out` without allocating: how many pcs. +fn body_pcs_small(code: &CodeObject, out: &mut [u8; LEAF_BODY_MAX]) -> usize { + let ins = &code.instructions; + let n = ins.len(); + debug_assert!(n <= LEAF_BODY_MAX); + let mut seen = 0u64; + // (Each pc pushes at most two successors, and is expanded once; a + // successor past the end, at most `LEAF_BODY_MAX + 255`, is skipped.) + let mut work = [0u16; 2 * LEAF_BODY_MAX + 1]; + let mut top = 1; + let mut k = 0; + while top > 0 { + top -= 1; + let pc = usize::from(work[top]); + if pc >= n || seen & (1 << pc) != 0 { + continue; + } + seen |= 1 << pc; + out[k] = pc as u8; + k += 1; + let i = ins[pc]; + let next = pc + 1; + let mut push = |t: usize| { + work[top] = t.min(usize::from(u16::MAX)) as u16; + top += 1; + }; + match i.op { + OpCode::ReturnValue | OpCode::RaiseVarargs | OpCode::Reraise => {} + OpCode::JumpForward => push(next + i.arg as usize), + OpCode::JumpBackward => push(next.saturating_sub(i.arg as usize)), + OpCode::PopJumpIfFalse + | OpCode::PopJumpIfTrue + | OpCode::PopJumpIfNone + | OpCode::PopJumpIfNotNone + | OpCode::ForIter => { + push(next + i.arg as usize); + push(next); + } + _ => push(next), + } + } + k +} + /// [`code_is_pure_leaf`]'s first answer for `code`, recorded in `ext`. #[cold] #[inline(never)] @@ -85507,16 +100086,41 @@ fn code_pure_leaf_decide(code: &CodeObject, ext: &CodeConstObjects) -> bool { && !code.has_varargs && leaf_arity(code) <= 8 && code.varnames.len() <= 16 - && code.instructions.len() <= 64; + && code.instructions.len() <= LEAF_BODY_MAX; let pure_op = |ins: &weavepy_compiler::Instruction| { // A fresh empty list or dict is unobservable until stored, so // a declined evaluation that made one still did nothing; so is a // fresh tuple (`return (x, 1)`, a key function's pair). - if matches!(ins.op, OpCode::BuildList | OpCode::BuildMap) { - return ins.arg == 0; + // (A list or tuple literal of at most `leaf_plan::SEQ_MAX` items.) + if ins.op == OpCode::BuildList { + return (ins.arg as usize) <= crate::leaf_plan::SEQ_MAX; + } + // (A dict literal of natively hashed keys: see + // `leaf_plan::new_map`.) + if ins.op == OpCode::BuildMap { + return (ins.arg as usize) <= crate::leaf_plan::MAP_MAX; } if ins.op == OpCode::BuildTuple { - return (1..=3).contains(&ins.arg); + return (1..=crate::leaf_plan::SEQ_MAX).contains(&(ins.arg as usize)); + } + if ins.op == OpCode::BuildSlice { + return matches!(ins.arg, 2 | 3); + } + // An f-string's plain conversions and their join (a piece that + // isn't a string, number, bool or `None` declines the evaluation). + if ins.op == OpCode::FormatValue { + return ins.arg == 0; + } + if ins.op == OpCode::BuildString { + return (1..=crate::leaf_plan::JOIN_MAX).contains(&(ins.arg as usize)); + } + // (`!s` and `!r` of a string, number, bool or `None`; `a, b = t` + // of an exact tuple or list of that many items.) + if ins.op == OpCode::ConvertValue { + return matches!(ins.arg, 1 | 2); + } + if ins.op == OpCode::UnpackSequence { + return (1..=crate::leaf_plan::UNPACK_MAX).contains(&(ins.arg as usize)); } matches!( ins.op, @@ -85543,6 +100147,9 @@ fn code_pure_leaf_decide(code: &CodeObject, ext: &CodeConstObjects) -> bool { | OpCode::LoadAttr | OpCode::CompareOp | OpCode::IsOp + // (A membership test over a native container runs no code; + // any other declines the evaluation.) + | OpCode::ContainsOp | OpCode::ToBool | OpCode::UnaryOp | OpCode::PopJumpIfFalse @@ -85552,6 +100159,7 @@ fn code_pure_leaf_decide(code: &CodeObject, ext: &CodeConstObjects) -> bool { | OpCode::JumpForward | OpCode::BinaryOp | OpCode::BinarySubscr + | OpCode::BinarySlice | OpCode::CopyTop | OpCode::Swap | OpCode::PopTop @@ -85565,27 +100173,48 @@ fn code_pure_leaf_decide(code: &CodeObject, ext: &CodeConstObjects) -> bool { // plan can't express, before anything it does is seen, and the // ordinary call then raises: those paths needn't be pure, so a body // guarded by `if bad: raise ...` still evaluates frameless.) - let pcs = if structural { - body_pcs(code) + // (A structural body has at most 64 instructions: its pcs gather on + // the stack, and a body with no raise needs no raise analysis.) + let mut buf = [0u8; LEAF_BODY_MAX]; + let pcs: &[u8] = if structural { + let k = body_pcs_small(code, &mut buf); + &buf[..k] } else { - Vec::new() + &[] }; - let doomed = raise_bound_pcs(code, &pcs); - let body: Vec<&weavepy_compiler::Instruction> = pcs + let raises = pcs .iter() - .filter(|&&pc| !doomed[pc]) - .map(|&pc| &code.instructions[pc]) - .collect(); + .any(|&pc| code.instructions[usize::from(pc)].op == OpCode::RaiseVarargs); + let doomed = if raises { + let wide: Vec = pcs.iter().map(|&pc| usize::from(pc)).collect(); + raise_bound_pcs(code, &wide) + } else { + Vec::new() + }; + let mut kept = [0u8; LEAF_BODY_MAX]; + let mut nkept = 0; + for &pc in pcs { + if !doomed.get(usize::from(pc)).copied().unwrap_or(false) { + kept[nkept] = pc; + nkept += 1; + } + } + let body = || { + kept[..nkept] + .iter() + .map(|&pc| &code.instructions[usize::from(pc)]) + }; // (A body that always raises has nothing to evaluate.) - let structural = structural && !body.is_empty(); - let ok = structural && body.iter().all(|i| pure_op(i)); + let structural = structural && nkept > 0; + let ok = structural && body().all(&pure_op); // An effect leaf: a pure leaf but for attribute stores, which its // evaluation buffers and commits at the return (see - // `Interpreter::pure_leaf_eval`). + // `Interpreter::pure_leaf_eval`), and subscript stores, which land at + // once where nothing after them can decline (`leaf_plan::store_item`). let effect = !ok && structural - && body.iter().all(|i| pure_op(i) || i.op == OpCode::StoreAttr) - && body.iter().any(|i| i.op == OpCode::StoreAttr); + && body().all(|i| pure_op(i) || matches!(i.op, OpCode::StoreAttr | OpCode::StoreSubscr)) + && body().any(|i| matches!(i.op, OpCode::StoreAttr | OpCode::StoreSubscr)); let shape = if ok { let body = code.instructions.as_slice(); let body = if body.first().is_some_and(|i| i.op == OpCode::Resume) { @@ -85684,6 +100313,68 @@ fn effect_setter_shape(code: &CodeObject) -> bool { && ret.op == OpCode::ReturnValue) } +/// The attribute name index of a `__setitem__(self, key, value)` whose +/// body is exactly `self.[key] = value; return None` (a mapping +/// wrapper's, as `UserDict` writes it) or `self.[][key] = value; +/// return None` for a small int `i` (`ChainMap`'s `self.maps[0]`), and +/// that `i`. +pub(crate) fn setitem_delegate_shape(code: &CodeObject) -> Option<(u32, Option)> { + if code.arg_count != 3 + || code.kwonly_count != 0 + || code.has_varargs + || code.has_varkeywords + || !code.cellvars.is_empty() + { + return None; + } + let body = code.instructions.as_slice(); + let body = match body.first() { + Some(i) if i.op == OpCode::Resume => &body[1..], + _ => body, + }; + let local = |i: &weavepy_compiler::Instruction, n: u32| { + matches!( + i.op, + OpCode::LoadFast | OpCode::LoadFastBorrow | OpCode::LoadFastCheck + ) && i.arg == n + }; + let rest = match body { + [pair, rest @ ..] + if matches!( + pair.op, + OpCode::LoadFastLoadFast | OpCode::LoadFastBorrowLoadFastBorrow + ) && pair.arg == 2 << 4 => + { + rest + } + [v, recv, rest @ ..] if local(v, 2) && local(recv, 0) => rest, + _ => return None, + }; + let (attr, index, tail) = match rest { + [attr, small, sub, tail @ ..] + if attr.op == OpCode::LoadAttr + && small.op == OpCode::LoadSmallInt + && sub.op == OpCode::BinarySubscr => + { + (attr, Some(small.arg), tail) + } + [attr, tail @ ..] if attr.op == OpCode::LoadAttr => (attr, None, tail), + _ => return None, + }; + match tail { + [key, store, none, ret] + if local(key, 1) + && store.op == OpCode::StoreSubscr + && none.op == OpCode::LoadConst + && matches!(code.constants.get(none.arg as usize), Some(Constant::None)) + && ret.op == OpCode::ReturnValue => + { + Some((attr.arg, index)) + } + _ => None, + } +} + /// `CONVERT_VALUE` (`arg`'s low bits: `1` for `!s`, `2` for `!r`) of the /// value at `top`, in place, for the exact scalars and strings whose /// conversion runs no Python (an f-string's pieces): `false` touches @@ -85693,6 +100384,35 @@ fn effect_setter_shape(code: &CodeObject) -> bool { /// /// `top` is an initialized slot nothing else reads while this runs. #[inline] +/// The repr of a list (`[`, `]`) or tuple (`(`, `)`) of `items` when each is +/// a plain scalar (`None`, `bool`, `int`, `float`, `str`), whose reprs run no +/// Python: `None` for anything else. +fn scalar_seq_repr(items: &[Object], open: char, close: char) -> Option { + if items.len() > 64 + || !items.iter().all(|x| { + matches!( + x, + Object::None | Object::Bool(_) | Object::Int(_) | Object::Float(_) | Object::Str(_) + ) + }) + { + return None; + } + let mut out = String::with_capacity(2 + items.len() * 4); + out.push(open); + for (i, x) in items.iter().enumerate() { + if i > 0 { + out.push_str(", "); + } + out.push_str(&x.repr()); + } + if close == ')' && items.len() == 1 { + out.push(','); + } + out.push(close); + Some(out) +} + pub(crate) unsafe fn convert_in_place(top: *mut Object, arg: u32) -> bool { // SAFETY: the caller's contract. let v = match (arg & 0x03, unsafe { &*top }) { @@ -85708,10 +100428,36 @@ pub(crate) unsafe fn convert_in_place(top: *mut Object, arg: u32) -> bool { } // SAFETY: as above. (2, Object::Str(_)) => Object::Str(SharedStr::from(unsafe { &*top }.repr().as_str())), + // A list or tuple of plain scalars (a dataclass's `tags=[]` in its + // generated `__repr__`): no item's repr runs Python. + (2, Object::List(l)) => { + // SAFETY: a read with nothing running. + let Some(items) = (unsafe { l.peek() }) else { + return false; + }; + match scalar_seq_repr(items, '[', ']') { + Some(r) => Object::Str(SharedStr::from(r.as_str())), + None => return false, + } + } + (2, Object::Tuple(t)) => match scalar_seq_repr(t, '(', ')') { + Some(r) => Object::Str(SharedStr::from(r.as_str())), + None => return false, + }, + // `!s` of an instance that renders with no code run (a `str` or + // `int` subclass's payload, an enum member's name), held elsewhere + // too. + (1, Object::Instance(inst)) if Rc::strong_count(inst) > 1 => { + match Interpreter::quick_str(inst) { + Some(r) => r, + None => return false, + } + } _ => return false, }; // SAFETY: the replaced value is a scalar, which owes no drop, or a - // string, released here (its repr ran no Python). + // string, or a list or tuple of scalars, or an instance another owner + // holds, released here (no release of theirs runs Python). unsafe { top.replace(v) }; true } @@ -85736,12 +100482,51 @@ pub(crate) unsafe fn format_simple_in_place(top: *mut Object) -> bool { let r = SharedStr::from(crate::object::float_repr(*f).as_str()); top.write(Object::Str(r)); } + // A `str`, `int` or `float` subclass's instance that formats + // and renders as its payload (`f"{SomeIntEnum.A}"`), held + // elsewhere too (its release runs nothing). + Object::Instance(inst) if Rc::strong_count(inst) > 1 => { + let Some(Ok(r)) = Interpreter::quick_format(inst, "") else { + return false; + }; + drop_hot_at(top); + top.write(Object::from_str(r)); + } _ => return false, } } true } +/// `FORMAT_VALUE` with a spec and no conversion of the value at `at` and +/// the spec above it, as the core loop's arm runs it for an exact `int`, +/// `float` or `str` and a `str` spec: the formatted string at `at`, the +/// spec released. `false` touches nothing (another value, or a spec the +/// value rejects, which the full handler raises for). +/// +/// # Safety +/// +/// The two slots from `at` are initialized, and nothing else reads them. +pub(crate) unsafe fn format_spec_in_place(at: *mut Object) -> bool { + // SAFETY: the caller's contract; the replaced value owes a drop only + // for a `str`, which the write below releases. + unsafe { + let (value, spec) = (&*at, &*at.add(1)); + let Object::Str(spec_str) = spec else { + return false; + }; + if !matches!(value, Object::Int(_) | Object::Float(_) | Object::Str(_)) { + return false; + } + let Ok(formatted) = format_via_spec(value, spec_str) else { + return false; + }; + drop(at.add(1).read()); + drop(at.replace(Object::from_str(formatted))); + } + true +} + /// `BUILD_STRING n` of the `n` strings from `at` up (an f-string's join): /// the joined string in `at`'s slot, the parts released; `false` touches /// nothing (a part that isn't a string, more than eight parts, or @@ -85752,12 +100537,12 @@ pub(crate) unsafe fn format_simple_in_place(top: *mut Object) -> bool { /// The `n` slots from `at` are initialized, and nothing else reads them. #[inline] pub(crate) unsafe fn build_string_at(at: *mut Object, n: usize) -> bool { - if n == 0 || n > 8 || crate::stdlib::tracemalloc_real::is_tracking() { + if n == 0 || n > BUILD_STRING_MAX || crate::stdlib::tracemalloc_real::is_tracking() { return false; } // SAFETY: the caller's contract. let parts = unsafe { std::slice::from_raw_parts(at, n) }; - let mut strs: [&str; 8] = [""; 8]; + let mut strs: [&str; BUILD_STRING_MAX] = [""; BUILD_STRING_MAX]; for (k, p) in parts.iter().enumerate() { match p { Object::Str(s) => strs[k] = s, @@ -85774,6 +100559,10 @@ pub(crate) unsafe fn build_string_at(at: *mut Object, n: usize) -> bool { true } +/// The most parts [`build_string_at`] joins (an f-string with four +/// fields and their separators, `UUID.__str__`'s, has nine). +pub(crate) const BUILD_STRING_MAX: usize = 16; + /// Whether every `RETURN_VALUE` in `code` returns the constant `None` /// (what a constructor's `__init__` must return), decided once. fn code_returns_only_none(code: &CodeObject) -> bool { @@ -85964,28 +100753,34 @@ fn forward_call_shape(code: &CodeObject, pc: usize) -> bool { ) } -/// Whether the instructions from `pc` could open a simple call's -/// argument run (see `Interpreter::core_simple_args`): each of the first -/// two is a plain operand load or the `CALL` itself. A cheap filter for -/// the fused pure-call paths, which then scan the whole run. +/// Whether the instructions from `pc` are a simple call's argument run +/// (see `Interpreter::core_simple_args`): at most eight plain operand +/// loads, then the `CALL` that takes exactly them. A filter for the fused +/// pure-call paths, which bind the run (and check its locals) after it: +/// a run that ends otherwise (a `CALL_KW`, an attribute load, an +/// operator) is declined here, in a few instructions, rather than by the +/// fused path's own scan (110 a call). #[inline(always)] fn simple_args_prefix(instrs: &[weavepy_compiler::Instruction], pc: usize) -> bool { - let simple = |i: Option<&weavepy_compiler::Instruction>| { - i.is_some_and(|i| { - matches!( - i.op, - OpCode::LoadFast | OpCode::LoadConst | OpCode::LoadSmallInt | OpCode::Call - ) - }) - }; - let first = instrs.get(pc); - simple(first) && (first.is_some_and(|i| i.op == OpCode::Call) || simple(instrs.get(pc + 1))) + let mut n = 0u32; + for i in instrs.get(pc..).unwrap_or_default().iter().take(9) { + match i.op { + OpCode::LoadFast | OpCode::LoadConst | OpCode::LoadSmallInt => n += 1, + OpCode::Call => return i.arg == n, + _ => return false, + } + } + false } /// Whether a pure leaf's calls may skip the lean activation now: with /// the JIT on, a jittable body's first calls still take it, so the warm /// compile (`LEAN_WARM_COMPILE_THRESHOLD` lean entries) gives compiled -/// callers their direct native lane to it. +/// callers their direct native lane to it. (The core loop's calls of a +/// pure leaf don't ask: their evaluation counts toward the warm compile +/// itself, see `Interpreter::leaf_call_entry`. Gating them cost code that +/// is called a few times each, such as the methods `dataclasses` makes +/// for each class, 6% of `enum` and `dataclass` work.) #[inline(always)] fn pure_leaf_warm(code: &CodeObject) -> bool { #[cfg(feature = "jit")] @@ -86043,8 +100838,8 @@ struct BinderLayout { pub(crate) fn code_gen_names(code: &CodeObject) -> (Object, Object) { let intern = || { ( - crate::stdlib::sys::intern_name(&code.name), - crate::stdlib::sys::intern_name(&code.qualname), + crate::stdlib::sys::intern_code_name(&code.name), + crate::stdlib::sys::intern_code_name(&code.qualname), ) }; match code_vm_ext(code) { @@ -86112,6 +100907,173 @@ fn code_vm_ext_existing(code: &CodeObject) -> Option<&CodeConstObjects> { unsafe { code.vm_ext.get::() } } +/// One part of a value that a function's whole body reads and returns +/// (`lambda kv: kv[1]`, `lambda r: r["age"]`, `lambda p: p.x`). +#[derive(Clone)] +pub(crate) enum PartShape { + /// The item at a constant index. + Index(i64), + /// The value at a constant `str` key. + Key(Object), + /// An attribute. + Attr(Object), +} + +/// The part `f`'s body reads, when `f` is a plain one-parameter function +/// (a lambda) whose whole body returns its argument's item at a constant +/// index or `str` key, or its attribute, decided once per code object. +/// Nothing observes such a function's calls but a trace or profile hook, +/// so none may be active (see [`part_value`]). +pub(crate) fn lambda_part(f: &crate::object::PyFunction) -> Option { + if crate::trace::any_observers_active() { + return None; + } + // SAFETY: GIL-serialized raw read of the function's code cell; the + // caller holds the function, and so its code, for the read. + let code: &CodeObject = unsafe { &*f.code.as_ptr() }; + let ext = code_vm_ext(code)?; + ext.part_shape + .get_or_init(|| part_shape_of(code, ext)) + .clone() +} + +/// Whether `code`'s whole body passes its arguments on to its one free +/// variable, a decorator's wrapper: `def w(*a): return fn(*a)` or `def +/// w(*args, **kwargs): return fn(*args, **kwargs)`. Decided once per code +/// object. +pub(crate) fn code_forwards(code: &CodeObject) -> bool { + code_vm_ext(code).is_some_and(|ext| *ext.forwards.get_or_init(|| forward_shape(code))) +} + +/// Whether `code`'s whole body reads one part of its one argument (see +/// [`lambda_part`]), decided once. +pub(crate) fn code_reads_part(code: &CodeObject) -> bool { + code_vm_ext(code).is_some_and(|ext| { + ext.part_shape + .get_or_init(|| part_shape_of(code, ext)) + .is_some() + }) +} + +/// [`code_forwards`]'s decision for `code`. +fn forward_shape(code: &CodeObject) -> bool { + if code.arg_count != 0 + || code.kwonly_count != 0 + || !code.has_varargs + || code.is_generator + || code.is_coroutine + || code.is_async_generator + || code.freevars.len() != 1 + || !code.cellvars.is_empty() + || code.varnames.len() != 1 + usize::from(code.has_varkeywords) + { + return false; + } + let ins = &code.instructions; + let start = ins + .iter() + .take_while(|i| matches!(i.op, OpCode::CopyFreeVars | OpCode::Resume | OpCode::Nop)) + .count(); + let local = |i: &weavepy_compiler::Instruction, n: u32| { + matches!(i.op, OpCode::LoadFast | OpCode::LoadFastBorrow) && i.arg == n + }; + // (The frame's one cell is the free variable: any `LOAD_DEREF` reads it.) + match ins.get(start..) { + Some([d, null, a, m, k, merge, call, ret]) if code.has_varkeywords => { + d.op == OpCode::LoadDeref + && null.op == OpCode::PushNull + && local(a, 0) + && m.op == OpCode::BuildMap + && m.arg == 0 + && local(k, 1) + && merge.op == OpCode::DictUpdate + && merge.arg == 1 + && call.op == OpCode::CallEx + && ret.op == OpCode::ReturnValue + } + Some([d, null, a, null2, call, ret]) if !code.has_varkeywords => { + d.op == OpCode::LoadDeref + && null.op == OpCode::PushNull + && local(a, 0) + && null2.op == OpCode::PushNull + && call.op == OpCode::CallEx + && ret.op == OpCode::ReturnValue + } + _ => false, + } +} + +/// [`lambda_part`]'s decision for `code`. +fn part_shape_of(code: &CodeObject, ext: &CodeConstObjects) -> Option { + if code.arg_count != 1 + || code.kwonly_count != 0 + || code.has_varargs + || code.has_varkeywords + || code.is_generator + || code.is_coroutine + || code.is_async_generator + { + return None; + } + let ins = &code.instructions; + let start = usize::from(ins.first()?.op == OpCode::Resume); + let load0 = |i: &weavepy_compiler::Instruction| { + matches!(i.op, OpCode::LoadFast | OpCode::LoadFastBorrow) && i.arg == 0 + }; + match ins.get(start..)? { + [l, a, r] if load0(l) && a.op == OpCode::LoadAttr && r.op == OpCode::ReturnValue => { + match ext.name_objs.get(a.arg as usize)? { + n @ Object::Str(_) => Some(PartShape::Attr(n.clone())), + _ => None, + } + } + [l, k, sub, r] + if load0(l) && sub.op == OpCode::BinarySubscr && r.op == OpCode::ReturnValue => + { + match k.op { + OpCode::LoadSmallInt => Some(PartShape::Index(i64::from(k.arg))), + OpCode::LoadConst => match ext.objects.get(k.arg as usize)? { + Object::Int(i) => Some(PartShape::Index(*i)), + v @ Object::Str(_) => Some(PartShape::Key(v.clone())), + _ => None, + }, + _ => None, + } + } + _ => None, + } +} + +/// `item`'s part as `shape` names it, read as the function's body would +/// read it, when that runs no code: a tuple's, list's or string's item, an +/// exact dict's value, or what `getattr` settles natively. `None` for +/// anything else (a miss included), which the full call answers. +pub(crate) fn part_value(shape: &PartShape, item: &Object) -> Option { + let at = |i: i64, len: usize| { + let k = if i < 0 { i + len as i64 } else { i }; + usize::try_from(k).ok().filter(|&k| k < len) + }; + match (shape, item) { + (PartShape::Index(i), Object::Tuple(t)) => t.get(at(*i, t.len())?).cloned(), + (PartShape::Index(i), Object::List(l)) => { + // SAFETY: a read that runs no code. + let xs = unsafe { l.peek() }?; + xs.get(at(*i, xs.len())?).cloned() + } + (PartShape::Index(i), Object::Str(s)) => { + let c = crate::object::str_char_at(s, at(*i, crate::object::str_char_len(s))?)?; + Some(Object::from_char(c)) + } + (PartShape::Key(k), Object::Dict(d)) => { + let probe = crate::object::LeafProbe::new(k)?; + // SAFETY: a read that runs no code. + unsafe { d.peek() }?.get(&probe).cloned() + } + (PartShape::Attr(n), _) => Interpreter::leaf_getattr_value(item, n), + _ => None, + } +} + /// [`code_vm_ext`]'s first call for a code object: build the table. #[cold] #[inline(never)] @@ -86119,61 +101081,91 @@ fn code_vm_ext_build(code: &CodeObject) -> &CodeConstObjects { // SAFETY: as in `code_vm_ext` (this is the slot's one producer; // `marshal` only ever creates the empty default). unsafe { - code.vm_ext.get_or_init(|| CodeConstObjects { - objects: code - .constants - .iter() - .map(constant_to_object_interned) - .collect(), - name_hashes: code + code.vm_ext.get_or_init(|| { + // The names' pooled strings, and their hashes from those + // strings' caches: a name many code objects share (`self`, + // `append`) is hashed once. + let name_objs: Vec = code .names .iter() - .map(|n| crate::object::py_str_hash(n)) - .collect(), - name_objs: code + .map(crate::stdlib::sys::intern_code_name) + .collect(); + let name_hashes = code .names .iter() - .map(|n| crate::stdlib::sys::intern_name(n)) - .collect(), - cell_args: code - .cellvars - .iter() - .map(|c| { - code.varnames - .iter() - .position(|n| n == c) - .map_or(u32::MAX, |i| i as u32) + .zip(&name_objs) + .map(|(n, o)| match o { + Object::Str(s) => SharedStr::hash_cached(s), + _ => crate::object::py_str_hash(n), }) - .collect(), - site_ranks: std::sync::OnceLock::new(), - method_slots: SiteSlots::new(), - stamp_slots: SiteSlots::new(), - attr_poly: SiteSlots::new(), - call_slots: SiteSlots::new(), - pure_leaf: std::sync::atomic::AtomicU8::new(0), - leaf_tries: std::sync::atomic::AtomicU64::new(0), - dunders: std::sync::OnceLock::new(), - fast_pairs: std::sync::OnceLock::new(), - gen_fast: std::sync::atomic::AtomicU8::new(0), - gen_start: std::sync::atomic::AtomicU32::new(0), - field_slots: SiteSlots::new(), - native_sites: std::sync::OnceLock::new(), - instance_sites: std::sync::OnceLock::new(), - heap_sites: std::sync::OnceLock::new(), - leaf_sites: SiteSlots::new(), - leaf_plan: std::sync::OnceLock::new(), - returns_none: std::sync::atomic::AtomicU8::new(0), - store_init: std::sync::OnceLock::new(), - calls: std::sync::atomic::AtomicU8::new(0), - loop_iters: std::sync::atomic::AtomicU8::new(0), - name_memos: std::sync::OnceLock::new(), - gen_names: std::sync::OnceLock::new(), - ident_strs: std::sync::OnceLock::new(), - positions: std::sync::OnceLock::new(), - #[cfg(feature = "jit")] - frame_jit: frame_jit::Slot::default(), - cold_sites: std::sync::atomic::AtomicU32::new(0), - dispatch_len: code_dispatch_len(code), + .collect(); + CodeConstObjects { + objects: code + .constants + .iter() + .map(constant_to_object_interned) + .collect(), + name_hashes, + name_objs: name_objs.into_iter().collect(), + cell_of_slot: { + let mut of_slot: Vec = Vec::new(); + for (i, c) in code.cellvars.iter().enumerate() { + if let Some(s) = code.varnames.iter().position(|n| n == c) { + if of_slot.len() <= s { + of_slot.resize(s + 1, u32::MAX); + } + of_slot[s] = i as u32; + } + } + of_slot.into_boxed_slice() + }, + cell_args: code + .cellvars + .iter() + .map(|c| { + code.varnames + .iter() + .position(|n| n == c) + .map_or(u32::MAX, |i| i as u32) + }) + .collect(), + site_ranks: std::sync::OnceLock::new(), + blind: std::sync::OnceLock::new(), + method_slots: SiteSlots::new(), + stamp_slots: SiteSlots::new(), + attr_poly: SiteSlots::new(), + call_slots: SiteSlots::new(), + pure_leaf: std::sync::atomic::AtomicU8::new(0), + leaf_tries: std::sync::atomic::AtomicU64::new(0), + dunders: std::sync::OnceLock::new(), + fast_pairs: std::sync::OnceLock::new(), + gen_fast: std::sync::atomic::AtomicU8::new(0), + gen_stalls: std::sync::atomic::AtomicU32::new(0), + gen_lean: std::sync::atomic::AtomicU64::new(0), + gen_walk: std::sync::atomic::AtomicU32::new(0), + varkw_local: std::sync::atomic::AtomicU8::new(0), + gen_start: std::sync::atomic::AtomicU32::new(0), + field_slots: SiteSlots::new(), + native_sites: std::sync::OnceLock::new(), + instance_sites: std::sync::OnceLock::new(), + heap_sites: std::sync::OnceLock::new(), + leaf_sites: SiteSlots::new(), + leaf_plan: std::sync::OnceLock::new(), + part_shape: std::sync::OnceLock::new(), + forwards: std::sync::OnceLock::new(), + returns_none: std::sync::atomic::AtomicU8::new(0), + store_init: std::sync::OnceLock::new(), + calls: std::sync::atomic::AtomicU8::new(0), + loop_iters: std::sync::atomic::AtomicU8::new(0), + name_memos: std::sync::OnceLock::new(), + gen_names: std::sync::OnceLock::new(), + ident_strs: std::sync::OnceLock::new(), + positions: std::sync::OnceLock::new(), + #[cfg(feature = "jit")] + frame_jit: frame_jit::Slot::default(), + cold_sites: std::sync::atomic::AtomicU32::new(0), + dispatch_len: code_dispatch_len(code), + } }) } } @@ -86523,7 +101515,7 @@ fn exc_family_flags_slow(cls: &crate::types::TypeObject) -> u16 { /// object's VM extension is populated (it is, after the first /// `LOAD_CONST`/attribute op of any execution). #[inline] -fn code_name_obj(code: &CodeObject, name_idx: u32) -> Option<&Object> { +pub(crate) fn code_name_obj(code: &CodeObject, name_idx: u32) -> Option<&Object> { code_vm_ext(code).and_then(|t| t.name_objs.get(name_idx as usize)) } @@ -86538,6 +101530,53 @@ fn code_name_str(code: &CodeObject, name_idx: u32, name: &str) -> Object { } } +/// A class's native truth method as a compiled `TO_BOOL` site keeps it +/// for the class's version (which keeps the builtin alive: replacing the +/// method moves the version). +#[derive(Clone, Copy)] +pub(crate) struct NativeTruthPlan { + f: *const crate::object::BuiltinFn, + is_len: bool, + op: u8, +} + +impl NativeTruthPlan { + pub(crate) const NONE: Self = Self { + f: std::ptr::null(), + is_len: false, + op: 0, + }; + + /// `v`'s truth through the plan (`v` an instance of the class it was + /// made for), or `None` for the full path. + #[inline] + pub(crate) fn run(self, v: &Object) -> Option { + if self.f.is_null() { + return (self.op == PAYLOAD_TRUTH) + .then(|| payload_truth(v)) + .flatten(); + } + if self.op == crate::stdlib::collections_native::OP_BOOL { + if let Some(Object::Bool(b)) = + crate::stdlib::collections_native::fast_op(self.op, v, None) + { + return Some(b); + } + } + // SAFETY: the class holds the builtin while its version holds. + let b = unsafe { &*self.f }; + let r = match b.call_kw.as_ref() { + Some(ckw) => ckw(std::slice::from_ref(v), &[]), + None => (b.call)(std::slice::from_ref(v)), + }; + match r.ok()? { + Object::Bool(b) => Some(b), + Object::Int(n) if self.is_len && n >= 0 => Some(n != 0), + _ => None, + } + } +} + /// How a class's instances answer a boolean context without running /// Python (see [`Interpreter::leaf_instance_truth`]). #[derive(Clone)] @@ -86554,6 +101593,12 @@ enum NativeTruth { PyLen, /// A Python `__bool__`: its result when it evaluates as a pure leaf. PyBool(Rc), + /// A native `__bool__` with a pure fast half (a `timedelta`'s, a + /// `Decimal`'s): the half's answer, when it gives one. + FastBool(leaf_builtins::Fast), + /// A subclass of a builtin value or container type whose `__bool__` and + /// `__len__` are builtin: its native payload's truth. + Payload, /// Anything else: the full path decides. Decline, } @@ -86562,6 +101607,35 @@ enum NativeTruth { const PY_LEN_TRUTH: u8 = u8::MAX; /// [`NativeTruth::PyBool`]'s. const PY_BOOL_TRUTH: u8 = u8::MAX - 1; +/// [`NativeTruth::Payload`]'s. +const PAYLOAD_TRUTH: u8 = u8::MAX - 2; +/// [`NativeTruth::FastBool`]'s. +const FAST_BOOL_TRUTH: u8 = u8::MAX - 3; + +/// The truth of `v`'s native payload, `v` an instance of a class whose +/// truth is its payload's (see [`NativeTruth::Payload`]): `None` for a +/// payload it doesn't know, or one borrowed now. +fn payload_truth(v: &Object) -> Option { + let Object::Instance(inst) = v else { + return None; + }; + // SAFETY: reads between two instructions (nothing here runs code). + unsafe { + Some(match inst.native.get()? { + Object::Str(s) => !s.is_empty(), + Object::Bytes(b) => !b.is_empty(), + Object::Tuple(t) => !t.is_empty(), + Object::FrozenSet(f) => !f.is_empty(), + Object::Int(i) => *i != 0, + Object::Float(f) => *f != 0.0, + Object::List(l) => !l.peek()?.is_empty(), + Object::Dict(d) => !d.peek()?.is_empty(), + Object::Set(set) => !set.peek()?.is_empty(), + Object::ByteArray(b) => !b.peek()?.is_empty(), + _ => return None, + }) + } +} /// [`inst_may_shadow`] first settled by a leaf site's bound (see /// [`LeafSiteData::limit`]): values laid over the class's names `keys` @@ -86662,6 +101736,39 @@ fn function_stored_attr(f: &crate::object::PyFunction, name: &SharedStr) -> Opti dict.get(&key).cloned() } +/// Whether function `f` stores nothing under `name` (in its slots or its +/// `__dict__`), when that can be told without waiting on a borrow. +fn function_stores_none(f: &crate::object::PyFunction, name: &str) -> bool { + if matches!(name, "__class__" | "__new__") { + return false; + } + if crate::object::is_function_slot(name) { + return f + .slots() + .try_borrow() + .is_ok_and(|d| d.get(&crate::object::StrKey(name)).is_none()); + } + let Ok(attrs) = f.attrs.try_borrow() else { + return false; + }; + attrs.as_ref().is_none_or(|d| { + d.try_borrow() + .is_ok_and(|d| d.get(&crate::object::StrKey(name)).is_none()) + }) +} + +/// The function type, when `obj` is a function storing nothing under +/// `name`: the full read's miss for it then depends on the type alone, and +/// is remembered on the type (see `Verdict::ValueAttrMissing`). +fn function_miss_class(obj: &Object, name: &str) -> Option> { + match obj { + Object::Function(f) if function_stores_none(f, name) => { + Some(crate::builtins::class_of(obj)) + } + _ => None, + } +} + fn code_name_leaf_probe( code: &CodeObject, name_idx: u32, @@ -86842,6 +101949,76 @@ pub fn sequence_concat_native(a: &Object, b: &Object) -> Result) { + let total = unit.len() * times; + out.reserve(total); + let inert = unit.iter().all(|o| { + matches!( + o, + Object::None | Object::Bool(_) | Object::Int(_) | Object::Float(_) + ) + }); + if !inert || total == 0 { + if let [one] = unit { + out.resize(out.len() + times, one.clone()); + } else { + for _ in 0..times { + crate::object::extend_cloned(out, unit); + } + } + return; + } + // SAFETY: the reserved room takes all `total` items; each copied item + // is one of the variants above, which own nothing, so a bitwise copy + // is a clone of it. + unsafe { + let start = out.as_mut_ptr().add(out.len()); + std::ptr::copy_nonoverlapping(unit.as_ptr(), start, unit.len()); + let mut done = unit.len(); + while done < total { + let n = done.min(total - done); + std::ptr::copy_nonoverlapping(start, start.add(done), n); + done += n; + } + out.set_len(out.len() + total); + } +} + +/// `unit * times` as a new `bytes`, built in its own allocation (a fill for +/// one byte, doubling copies otherwise); `None` past a size where the +/// allocation should fail softly (`MemoryError`) instead. +pub(crate) fn bytes_repeat(unit: &[u8], times: usize) -> Option { + let total = unit.len().checked_mul(times)?; + if total > 1 << 30 { + return None; + } + if total == 0 { + return Some(Object::new_bytes(Vec::new())); + } + // SAFETY: every one of the `total` bytes is written: the first copy of + // the unit, then doublings of what's written so far. + Some(Object::Bytes(unsafe { + crate::shared_value::SharedSlice::build_uninit(total, |dst: *mut u8| { + if let [b] = unit { + std::ptr::write_bytes(dst, *b, total); + return; + } + std::ptr::copy_nonoverlapping(unit.as_ptr(), dst, unit.len()); + let mut done = unit.len(); + while done < total { + let n = done.min(total - done); + std::ptr::copy_nonoverlapping(dst, dst.add(done), n); + done += n; + } + }) + })) +} + fn repeat_into(out: &mut Vec, unit: &[T], times: usize) { let total = unit.len() * times; if total == 0 { @@ -87095,6 +102272,9 @@ fn binary_op(a: &Object, b: &Object, op: BinOpKind) -> Result Result = rendered.chars().map(|c| c as u8).collect(); Ok(Object::new_bytearray(out)) } - (O::Bytes(x), O::Bytes(y), B::Add) => { - let mut out = Vec::with_capacity(x.len() + y.len()); - out.extend_from_slice(x); - out.extend_from_slice(y); - Ok(Object::new_bytes(out)) - } + (O::Bytes(x), O::Bytes(y), B::Add) => Ok(Object::bytes_concat(x, y)), // Mixed bytes/bytearray concatenation. CPython allows all four // combinations and the result type follows the *left* operand // (`bytearray + bytes -> bytearray`, `bytes + bytearray -> bytes`). (O::ByteArray(x), O::Bytes(y), B::Add) => { - let mut out = x.borrow().clone(); + let x = x.borrow(); + let mut out = Vec::with_capacity(x.len() + y.len()); + out.extend_from_slice(&x); out.extend_from_slice(y); Ok(Object::new_bytearray(out)) } @@ -87161,15 +102338,21 @@ fn binary_op(a: &Object, b: &Object, op: BinOpKind) -> Result { - let body = x.borrow().clone(); + // (Repeating reads the operand in place: nothing here runs + // code that could resize it.) + let body = x.borrow(); let times = checked_repeat_count(body.len(), *n, "bytearray")?; let mut out = try_alloc_vec(body.len() * times)?; repeat_into(&mut out, &body, times); + drop(body); Ok(Object::new_bytearray(out)) } // Set operators accept any mix of `set`/`frozenset` operands; the @@ -87247,27 +102430,39 @@ fn binary_op(a: &Object, b: &Object, op: BinOpKind) -> Result { - let mut out = x.borrow().clone(); - out.extend(y.borrow().iter().cloned()); - Ok(Object::new_list(out)) + let (x, y) = (x.borrow(), y.borrow()); + let mut out = Vec::with_capacity(x.len() + y.len()); + crate::object::extend_cloned(&mut out, &x); + crate::object::extend_cloned(&mut out, &y); + let out = Object::new_list(out); + gc_trace::track_built(&out); + Ok(out) } (O::List(x), O::Int(n), B::Mult) | (O::Int(n), O::List(x), B::Mult) => { - let body = x.borrow().clone(); + // (Read in place: nothing below runs code.) + let body = x.borrow(); let times = checked_repeat_count(body.len(), *n, "list")?; let mut out = try_alloc_vec(body.len() * times)?; - for _ in 0..times { - out.extend(body.iter().cloned()); - } - Ok(Object::new_list(out)) + repeat_objects(&body, times, &mut out); + drop(body); + let out = Object::new_list(out); + gc_trace::track_built(&out); + Ok(out) } (O::Tuple(x), O::Tuple(y), B::Add) => { - let mut out: Vec = x.iter().cloned().collect(); - out.extend(y.iter().cloned()); - Ok(Object::new_tuple(out)) + if x.is_empty() && y.is_empty() { + return Ok(Object::new_tuple(Vec::new())); + } + Ok(Object::Tuple( + crate::tuple_storage::TupleStorage::from_cloned_pair(x, y), + )) } (O::Tuple(x), O::Int(n), B::Mult) | (O::Int(n), O::Tuple(x), B::Mult) => { // CPython `tuplerepeat`: `t * 1` returns the *same* (exact) tuple @@ -87277,9 +102472,7 @@ fn binary_op(a: &Object, b: &Object, op: BinOpKind) -> Result = try_alloc_vec(x.len() * times)?; - for _ in 0..times { - out.extend(x.iter().cloned()); - } + repeat_objects(x, times, &mut out); Ok(Object::new_tuple(out)) } @@ -87985,6 +103178,47 @@ fn bigint_true_div(x: &num_bigint::BigInt, y: &num_bigint::BigInt) -> f64 { } } +/// [`bignum_op`]'s `+`, `-`, `*`, `//` and `%` of two ints that each fit in +/// 128 bits, when the result does too (`None` otherwise, and for a zero +/// divisor, whose error the slow path raises): CPython's floor semantics, +/// a machine int when the result fits one. +fn i128_op(a: &Object, b: &Object, op: BinOpKind) -> Option { + use BinOpKind as B; + if !matches!(op, B::Add | B::Sub | B::Mult | B::FloorDiv | B::Mod) { + return None; + } + let wide = |o: &Object| match o { + Object::Long(x) => x.to_i128(), + _ => o.as_i64().map(i128::from), + }; + let (x, y) = (wide(a)?, wide(b)?); + let r = match op { + B::Add => x.checked_add(y)?, + B::Sub => x.checked_sub(y)?, + B::Mult => x.checked_mul(y)?, + B::FloorDiv => { + let q = x.checked_div(y)?; + if x % y != 0 && ((x < 0) != (y < 0)) { + q - 1 + } else { + q + } + } + _ => { + let r = x.checked_rem(y)?; + if r != 0 && ((r < 0) != (y < 0)) { + r + y + } else { + r + } + } + }; + Some(match i64::try_from(r) { + Ok(v) => Object::Int(v), + Err(_) => Object::int_from_bigint(num_bigint::BigInt::from(r)), + }) +} + /// Bignum-aware integer arithmetic for `int`-flavoured operands. /// Both inputs are guaranteed `int`/`long`/`bool` by the caller; the /// fast path stays in `i64` until an overflow forces promotion. @@ -88004,6 +103238,44 @@ fn bignum_op(a: &Object, b: &Object, op: BinOpKind) -> Result return Ok(Object::int_from_bigint(&**x + *y)), + (Object::Int(x), Object::Long(y), B::Add) => return Ok(Object::int_from_bigint(&**y + *x)), + (Object::Long(x), Object::Int(y), B::Sub) => return Ok(Object::int_from_bigint(&**x - *y)), + (Object::Long(x), Object::Int(y), B::Mult) => { + return Ok(Object::int_from_bigint(&**x * *y)) + } + (Object::Int(x), Object::Long(y), B::Mult) => { + return Ok(Object::int_from_bigint(&**y * *x)) + } + // (A field cut out of a wide value: `(n >> 64) & 0xffff`.) + (Object::Long(x), Object::Int(y), B::RShift) if *y >= 0 => { + return Ok(Object::int_from_bigint(&**x >> (*y as usize))) + } + (Object::Long(x), Object::Int(y), B::BitAnd) if *y >= 0 && !x.is_negative() => { + let low = x.iter_u64_digits().next().unwrap_or(0); + return Ok(Object::Int((low & *y as u64) as i64)); + } + (Object::Int(y), Object::Long(x), B::BitAnd) if *y >= 0 && !x.is_negative() => { + let low = x.iter_u64_digits().next().unwrap_or(0); + return Ok(Object::Int((low & *y as u64) as i64)); + } + _ => {} + } + + // Both within 128 bits (a machine-int product past 64 bits, and what + // is made of it: `(n * n * n) // d`): the arithmetic in `i128`, the + // result a machine int when it fits, where promoting both sides + // allocated each and grew the result. + if let Some(out) = i128_op(a, b, op) { + return Ok(out); + } + // Slow path: promote both sides to BigInt. let x = a.as_bigint().expect("int-like"); let y = b.as_bigint().expect("int-like"); @@ -88814,6 +104086,38 @@ fn complex_rc_quot(a: f64, br: f64, bi: f64) -> Result<(f64, f64), RuntimeError> Ok((re, im)) } +/// `a OP b` for an exact `complex` and a `complex`, `float` or machine +/// `int` (either side), `OP` one of `+ - * /`, as [`binary_op`]'s complex +/// arm computes it: `None` for anything else, an error included (a +/// division by zero), which the full handler raises. Runs no Python code. +pub(crate) fn complex_binop_fast(a: &Object, b: &Object, op: BinOpKind) -> Option { + use BinOpKind as B; + if !matches!(op, B::Add | B::Sub | B::Mult | B::Div) { + return None; + } + let real = |o: &Object| match *o { + Object::Float(x) => Some(x), + // (An `int` past 2**53 rounds as `int.__float__` does.) + Object::Int(i) => Some(i as f64), + _ => None, + }; + let (ac, bc, mode) = match (a, b) { + (Object::Complex(x), Object::Complex(y)) => { + ((x.real, x.imag), (y.real, y.imag), ComplexMode::Both) + } + (Object::Complex(x), other) => { + ((x.real, x.imag), (real(other)?, 0.0), ComplexMode::LeftOnly) + } + (other, Object::Complex(y)) => ( + (real(other)?, 0.0), + (y.real, y.imag), + ComplexMode::RightOnly, + ), + _ => return None, + }; + complex_arith(ac, bc, op, mode).ok() +} + fn complex_arith( (ar, ai): (f64, f64), (br, bi): (f64, f64), @@ -88900,9 +104204,20 @@ pub(crate) fn coerce_len_result(r: Object) -> Result { )) } } + // An `int` subclass's value (CPython takes any index; a class's + // own `__index__` stays unsupported here). + Object::Instance(inst) => match inst.native.get() { + Some(n @ (Object::Int(_) | Object::Long(_) | Object::Bool(_))) => { + coerce_len_result(n.clone()) + } + _ => Err(type_error(format!( + "'{}' object cannot be interpreted as an integer", + r.type_name_owned() + ))), + }, other => Err(type_error(format!( "'{}' object cannot be interpreted as an integer", - other.type_name() + other.type_name_owned() ))), } } @@ -88938,14 +104253,30 @@ fn native_scalar_compare(a: &Object, b: &Object, op: CompareKind) -> Option bool { - let name = if subclass { - "__subclasscheck__" + use crate::types::{vm_key, AttrKey, LeafAttrKind as K}; + let (name, key) = if subclass { + ("__subclasscheck__", vm_key::TYPE_SUBCLASSCHECK) } else { - "__instancecheck__" + ("__instancecheck__", vm_key::TYPE_INSTANCECHECK) }; - meta.lookup_with_owner(name) - .is_some_and(|(_, owner)| Rc::ptr_eq(&owner, &builtin_types().type_)) + let key = AttrKey::vm(key); + let ver = meta.attr_version.get(); + match meta.leaf_attrs.get(key, ver) { + Some(K::InstanceOnly) => return true, + Some(_) => return false, + None => {} + } + let is_type = meta + .lookup_with_owner(name) + .is_some_and(|(_, owner)| Rc::ptr_eq(&owner, &builtin_types().type_)); + if !crate::object::exotic_str_keys_possible() { + meta.leaf_attrs + .set(key, ver, if is_type { K::InstanceOnly } else { K::Other }); + } + is_type } /// [`plain_compare`] of the operands at `at` and above it, when releasing @@ -88969,9 +104300,33 @@ pub(crate) unsafe fn core_plain_compare(at: *mut Object, op: CompareKind) -> Opt Some(w) => { matches!(o, Object::Str(_) | Object::Bytes(_) | Object::Long(_)) || unsafe { &*w }.load(std::sync::atomic::Ordering::Relaxed) > 1 + || scalar_set(o) } } } + // A small set of strings and numbers (a literal built for the + // comparison) frees only them. + fn scalar_set(o: &Object) -> bool { + let all = |d: &crate::object::SetData| { + d.len() <= 16 + && d.iter().all(|k| { + matches!( + k.0, + Object::Int(_) + | Object::Float(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::Bool(_) + | Object::None + ) + }) + }; + match o { + Object::Set(s) => s.try_borrow().is_ok_and(|d| all(&d)), + Object::FrozenSet(s) => all(s), + _ => false, + } + } if !Interpreter::core_drops_plain() || matches!(a, Object::AsyncGenAwait(_)) || matches!(b, Object::AsyncGenAwait(_)) @@ -88980,7 +104335,17 @@ pub(crate) unsafe fn core_plain_compare(at: *mut Object, op: CompareKind) -> Opt { return None; } - let r = plain_compare(a, b, op)?; + let r = match plain_compare(a, b, op) { + Some(r) => r, + // An `int` or `float` subclass that keeps its base's comparison + // (`IntEnum.A < 2`): the payloads'. + None if matches!(a, Object::Instance(_)) || matches!(b, Object::Instance(_)) => { + let x = Interpreter::compare_number_payload(a, op)?; + let y = Interpreter::compare_number_payload(b, op)?; + plain_compare(&x, &y, op)? + } + None => return None, + }; // SAFETY: the operands leave their slots, each releasing a plain count. unsafe { drop_hot_at(at.add(1)); @@ -89061,6 +104426,31 @@ fn inherited_eq_value(o: &Object) -> Option<&Object> { .then_some(v) } +/// The payload of an instance of a subclass of `list`, `tuple`, `set`, +/// `frozenset` or `dict` whose `__eq__` and `__ne__` are the built-in +/// ones (not an `OrderedDict` or a `Counter`, which define their own). +#[inline] +fn inherited_eq_payload(o: &Object) -> Option<&Object> { + use crate::types::Dunder; + let Object::Instance(i) = o else { + return None; + }; + let v = i.native.get()?; + let cls = i.cls_raw(); + (matches!( + v, + Object::List(_) + | Object::Tuple(_) + | Object::Set(_) + | Object::FrozenSet(_) + | Object::Dict(_) + ) && cls.native_kind.get() == 0 + && cls.c_ext_ptr.get() == 0 + && cls.dunder(Dunder::Eq).builtin_owner() + && cls.dunder(Dunder::Ne).builtin_owner()) + .then_some(v) +} + /// `a b` when the answer runs no Python code and needs no dunder /// dispatch: numbers, strings and bytes by value, the sequences /// [`native_seq_compare`] takes, and equality that comes down to identity @@ -89104,6 +104494,18 @@ pub(crate) fn plain_compare(a: &Object, b: &Object, op: CompareKind) -> Option { return Some(by_ord(Some(long_cmp_int(y, *x).reverse()))); } + (Object::Dict(_), Object::Dict(_)) + if matches!(op, CompareKind::Eq | CompareKind::NotEq) => + { + return native_dict_eq(a, b, 0).map(|eq| eq == (op == CompareKind::Eq)); + } + (Object::Set(_) | Object::FrozenSet(_), Object::Set(_) | Object::FrozenSet(_)) => { + return native_set_compare(a, b, op); + } + (Object::DictView(_), Object::Set(_) | Object::FrozenSet(_) | Object::DictView(_)) + | (Object::Set(_) | Object::FrozenSet(_), Object::DictView(_)) => { + return native_keys_compare(a, b, op); + } _ => {} } if !matches!(op, CompareKind::Eq | CompareKind::NotEq) { @@ -89117,6 +104519,15 @@ pub(crate) fn plain_compare(a: &Object, b: &Object, op: CompareKind) -> Option a.is_same(b), (EqClass::Identity, EqClass::Value(_)) | (EqClass::Value(_), EqClass::Identity) => false, @@ -89130,6 +104541,103 @@ pub(crate) fn plain_compare(a: &Object, b: &Object, op: CompareKind) -> Option Option { + let (Object::Dict(x), Object::Dict(y)) = (a, b) else { + return None; + }; + if depth > 8 { + return None; + } + let (x, y) = (x.try_borrow().ok()?, y.try_borrow().ok()?); + if x.len() != y.len() { + return Some(false); + } + let reentrant = |d: &DictData| d.keys().any(|k| crate::object::dict_key_is_reentrant(&k.0)); + if reentrant(&x) || reentrant(&y) { + return None; + } + let (r, deferred) = crate::object::with_key_eq_deferred(|| { + for (k, v) in x.iter() { + let Some(w) = y.get(k) else { + return Some(false); + }; + if v.is_same(w) { + continue; + } + let eq = match (v, w) { + (Object::Dict(_), Object::Dict(_)) => native_dict_eq(v, w, depth + 1)?, + _ => plain_compare(v, w, CompareKind::Eq)?, + }; + if !eq { + return Some(false); + } + } + Some(true) + }); + if deferred { + None + } else { + r + } +} + +/// `a b` for two exact sets or frozensets whose elements hash and +/// compare natively: equality, subset and superset tests. `None` when an +/// element might run Python. +fn native_set_compare(a: &Object, b: &Object, op: CompareKind) -> Option { + use crate::object::SetData; + fn with(o: &Object, f: impl FnOnce(&SetData) -> Option) -> Option { + match o { + Object::Set(s) => f(&*s.try_borrow().ok()?), + Object::FrozenSet(s) => f(s), + _ => None, + } + } + // (Stored hashes: no key is hashed, so only a comparison could run + // Python, and that defers.) + with(a, |x| { + with(b, |y| setalg::pure(|| setalg::compare(x, y, op))) + }) +} + +/// `a b` for a dict's keys view against a set, a frozenset or another +/// keys view (CPython's `dictview_richcompare`: the lengths, then whether +/// one side's elements are all in the other), when every key hashes and +/// compares natively. `None` for an items or values view, or a key that +/// might run Python. +fn native_keys_compare(a: &Object, b: &Object, op: CompareKind) -> Option { + // (Each side's keys with their stored hashes: nothing is hashed, and + // a comparison that needs Python leaves it undecided.) + key_side(a, |x| { + key_side(b, |y| { + let (m, n) = (x.len(), y.len()); + let len_ok = match op { + CompareKind::Eq | CompareKind::NotEq => m == n, + CompareKind::Lt => m < n, + CompareKind::LtE => m <= n, + CompareKind::Gt => m > n, + CompareKind::GtE => m >= n, + }; + // (`>` and `>=` test that `b`'s elements are all in `a`.) + let (inner, outer) = match op { + CompareKind::Gt | CompareKind::GtE => (&y, &x), + _ => (&x, &y), + }; + let contained = setalg::pure(|| len_ok && inner.all(|hash, key| outer.has(hash, key)))?; + Some(if op == CompareKind::NotEq { + !contained + } else { + contained + }) + }) + }) +} + /// How the big int `x` orders against the machine int `y`, allocating /// nothing. fn long_cmp_int(x: &num_bigint::BigInt, y: i64) -> std::cmp::Ordering { @@ -89165,9 +104673,19 @@ fn native_seq_compare(a: &Object, b: &Object, op: CompareKind, depth: u32) -> Op } _ => return None, }; + // (Sequences of different lengths are unequal whatever they hold, as + // CPython's comparison answers before it looks at an item.) + if xs.len() != ys.len() && matches!(op, CompareKind::Eq | CompareKind::NotEq) { + return Some(op == CompareKind::NotEq); + } for (x, y) in xs.iter().zip(ys) { - // (Identity first, as CPython's element test.) - if x.is_same(y) { + // (Two machine ints, the commonest pair, are settled in line.) + if let (Object::Int(p), Object::Int(q)) = (x, y) { + if p == q { + continue; + } + } else if x.is_same(y) { + // (Identity first, as CPython's element test.) continue; } let eq = match native_scalar_compare(x, y, CompareKind::Eq) { @@ -89206,6 +104724,14 @@ pub(crate) fn compare_op(a: &Object, b: &Object, op: CompareKind) -> Result``, ``>=`` to subset/superset // tests on the set family. They are *not* total orderings, so we // intercept this before falling through to ``Object::cmp``. + let set_like = |o: &Object| matches!(o, Object::Set(_) | Object::FrozenSet(_)); + if set_like(a) && set_like(b) { + // On the sets themselves when no comparison needs Python (the + // lengths settle most unequal pairs at once); else on snapshots. + if let Some(r) = native_set_compare(a, b, op) { + return Ok(r); + } + } if let (Some(lhs), Some(rhs)) = (set_view(a), set_view(b)) { return Ok(compare_sets(&lhs, &rhs, op)); } @@ -89801,16 +105327,18 @@ assert loop(2000) == 1999000 assert!(crate::tier2::code_compiled_for_test(&function.code.borrow()), "{name} must compile during sustained import work"); } crate::tier2::force_enable_for_test(50); - // The lean budget counts warm-up intervals (24 calls, not the - // threshold's 50): 64 of them fall due within 1600 calls, well - // short of 64 thresholds. - let source = "def leaf(x):\n return x + 1\nfor i in range(1600):\n assert leaf(i) == i + 1\n"; + // A pure leaf's calls from module code are frameless: each + // warm-up interval of them is credited to the tier-2 counter + // (`note_frameless_calls`), so during an import it compiles + // after 64 thresholds of calls (64 * 50), where a lean + // activation's warm compile counts 64 intervals of 24. + let source = "def leaf(x):\n return x + 1\nfor i in range(3300):\n assert leaf(i) == i + 1\n"; let module = interp .load_from_source("budget_relative", source, false, "budget_relative.py") .expect("default relative lean budget"); let Object::Module(module) = module else { panic!("module") }; let Object::Function(function) = module.dict.borrow().get(&crate::object::StrKey("leaf")).unwrap().clone() else { panic!("function") }; - assert!(crate::tier2::code_compiled_for_test(&function.code.borrow()), "lean code must retain its earlier relative warm point"); + assert!(crate::tier2::code_compiled_for_test(&function.code.borrow()), "frameless calls must reach the import budget"); }) .expect("spawn import-budget worker") .join() @@ -90374,9 +105902,10 @@ assert loop(2000) == 1999000 assert_eq!(native, 0, "native entry requires JIT"); assert_eq!(attempts, 0, "interpreted calls use their ordinary path"); assert_eq!(armed, 0, "in-line updates require JIT"); - } else if matches!(kind, "parameter" | "constant") { + } else if matches!(kind, "parameter" | "constant" | "slots") { // The helper runs the update until it arms the - // method entry; compiled code runs the rest in line. + // method entry; compiled code runs the rest in line + // (a `__slots__` member's too). assert!( native > 100 || (armed > 0 && native > 0), "compiled {kind} native update coverage: {native} (armed {armed})" @@ -90388,7 +105917,7 @@ assert loop(2000) == 1999000 native == 0 || (armed > 0 && native > 0), "compiled {kind} native update coverage: {native} (armed {armed})" ); - } else if matches!(kind, "default" | "slots" | "alias") { + } else if matches!(kind, "default" | "alias") { assert!( native > 100, "compiled {kind} native update coverage: {native}" @@ -90697,6 +106226,9 @@ assert loop(2000) == 1999000 assert!(status.success(), "borrowed scalar child: {status}"); return; } + // Its loops do little but call a local function, which tier 2 + // otherwise leaves to the frame JIT (`call_bound`). + weavepy_jit::admit_generic_loops(); std::thread::Builder::new() .stack_size(8 * 1024 * 1024) .spawn(|| { diff --git a/crates/weavepy-vm/src/object.rs b/crates/weavepy-vm/src/object.rs index 9f98a2176..9f63b906b 100644 --- a/crates/weavepy-vm/src/object.rs +++ b/crates/weavepy-vm/src/object.rs @@ -42,6 +42,23 @@ const _: () = { assert_sync::(); }; +/// Push `b` as two lowercase hex digits. +#[inline] +pub(crate) fn push_hex_byte(out: &mut String, b: u8) { + const HEX: &[u8; 16] = b"0123456789abcdef"; + out.push(char::from(HEX[usize::from(b >> 4)])); + out.push(char::from(HEX[usize::from(b & 15)])); +} + +/// The lowercase hex text of `bytes` (a digest's `hexdigest()`). +pub(crate) fn hex_lower(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for &b in bytes { + push_hex_byte(&mut out, b); + } + out +} + /// Code-point length of a `str`: O(1) from the count memoised in the /// string itself (see [`SharedStr::char_count`]). WeavePy stores `str` as /// UTF-8, so the first count is a scan; scanners and tokenisers that ask @@ -1235,6 +1252,16 @@ impl FrameSlot { } } + /// The value, when this slot owns it, taken out (a borrowed one is + /// forgotten); the slot is left empty. + pub(crate) fn take_owned(&mut self) -> Option { + let value = self.value.take(); + let owned = std::mem::replace(self.owned.get_mut(), true); + value + .filter(|_| owned) + .map(std::mem::ManuallyDrop::into_inner) + } + pub(crate) fn clear(&mut self) { if let Some(mut value) = self.value.take() { if *self.owned.get_mut() { @@ -1640,7 +1667,9 @@ pub struct PyTraceback { /// The frame this entry records: the frame object, or the live /// activation's spine shell until something asks for the object /// (see [`TbFrame`]). Read through [`Self::frame`]. - frame: RefCell, + /// (Taken by the entry's drop, which may keep a departed activation's + /// shell for reuse: see [`spare_departed_shell`].) + frame: std::mem::ManuallyDrop>, pub lineno: u32, pub lasti: u32, /// `types.TracebackType(…)` stores the caller-supplied `tb_lasti` @@ -1710,7 +1739,7 @@ impl PyTraceback { /// An entry for an existing frame object. pub fn new(frame: Rc, lineno: u32, lasti: u32, raw_lasti: Option) -> Self { Self { - frame: RefCell::new(TbFrame::Ready(frame)), + frame: std::mem::ManuallyDrop::new(RefCell::new(TbFrame::Ready(frame))), lineno, lasti, raw_lasti, @@ -1723,7 +1752,9 @@ impl PyTraceback { /// [`TbFrame`]). pub fn new_lazy(shell: Rc, lineno: u32, lasti: u32) -> Self { Self { - frame: RefCell::new(TbFrame::Lazy(LazyShellRef::new(shell))), + frame: std::mem::ManuallyDrop::new(RefCell::new(TbFrame::Lazy(LazyShellRef::new( + shell, + )))), lineno, lasti, raw_lasti: None, @@ -1825,6 +1856,108 @@ impl Drop for PyTraceback { link = unsafe { (*tb.next.as_ptr()).take() }; drop(tb); } + // SAFETY: taken once, here, and never read again. + let frame = unsafe { std::mem::ManuallyDrop::take(&mut self.frame) }.into_inner(); + if let TbFrame::Lazy(lazy) = frame { + spare_departed_shell(lazy); + } + } +} + +/// Shells of departed activations (see [`FrameShell::depart`]) and their +/// locals storage, emptied when the last traceback entry holding them +/// died, for the next activations' spine shells and locals. An exception +/// unwinding through calls departs every activation it leaves, and the +/// traceback is their shells' last holder: without these, every level of +/// every such unwinding allocated a shell and a locals vector (grown from +/// empty) and freed both again with the traceback. +struct DepartedSpares { + shells: Vec>, + locals: Vec>>>, +} + +const DEPARTED_SPARES_CAP: usize = 32; + +thread_local! { + static DEPARTED_SPARES: std::cell::RefCell = const { + std::cell::RefCell::new(DepartedSpares { + shells: Vec::new(), + locals: Vec::new(), + }) + }; +} + +/// A departed activation's emptied shell (see [`DepartedSpares`]), sole +/// owned, its slots empty and nothing materialized. +pub(crate) fn take_spare_shell() -> Option> { + DEPARTED_SPARES + .try_with(|s| s.borrow_mut().shells.pop()) + .ok() + .flatten() +} + +/// A departed activation's emptied locals vector (see +/// [`DepartedSpares`]), sole owned. +pub(crate) fn take_spare_locals() -> Option>>> { + DEPARTED_SPARES + .try_with(|s| s.borrow_mut().locals.pop()) + .ok() + .flatten() +} + +/// A traceback entry's hold on `lazy`'s shell is ending. When that was the +/// last hold on a departed activation's shell, release what the shell +/// kept, as its drop would (the values first, as the frame object would +/// have released them), and keep the emptied shell and locals vector for +/// reuse (see [`DepartedSpares`]). +fn spare_departed_shell(lazy: LazyShellRef) { + // A departed shell's caller link (see [`FrameShell::depart`]) is + // often the last hold on the caller's departed shell: the chain is + // walked here, not recursively (a `RecursionError`'s is ~1000 deep). + let mut next = Some(lazy); + while let Some(lazy) = next.take() { + let mut shell = lazy.0.clone(); + drop(lazy); + if shell.is_gen || !shell.has_departed() { + return; + } + let Some(m) = Rc::get_mut(&mut shell) else { + return; + }; + if m.materialized.get_mut().is_some() || *m.tb_refs.get_mut() != 0 { + return; + } + m.release_departed_values(); + let locals = m.locals.take_owned(); + m.code.clear(); + m.cells.clear(); + m.globals.clear(); + m.builtins.clear(); + m.builtins_obj = None; + m.class_namespace = None; + m.class_namespace_obj = None; + *m.gen_owner.get_mut() = None; + let back = std::mem::take(m.departed.back.get_mut()); + m.departed = Departed::default(); + *m.has_materialized.get_mut() = false; + // SAFETY: a sole owner's vector: nothing else reaches it. + let locals = + locals.filter(|l| Rc::strong_count(l) == 1 && unsafe { (*l.as_ptr()).is_empty() }); + // What the spares can't take drops outside their borrow. + let mut rejected = (Some(shell), locals); + let _ = DEPARTED_SPARES.try_with(|s| { + let mut s = s.borrow_mut(); + if s.shells.len() < DEPARTED_SPARES_CAP { + s.shells.extend(rejected.0.take()); + } + if s.locals.len() < DEPARTED_SPARES_CAP { + s.locals.extend(rejected.1.take()); + } + }); + drop(rejected); + if let DepartedBack::Lazy(caller) = back { + next = Some(caller); + } } } @@ -1839,11 +1972,11 @@ impl Drop for PyTraceback { static BYTEARRAY_EXPORT_TOTAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -type ExportMap = std::collections::HashMap>>, usize)>; +type ExportMap = crate::fasthash::FxHashMap>>, usize)>; fn bytearray_export_map() -> &'static std::sync::Mutex { static MAP: std::sync::OnceLock> = std::sync::OnceLock::new(); - MAP.get_or_init(|| std::sync::Mutex::new(ExportMap::new())) + MAP.get_or_init(|| std::sync::Mutex::new(ExportMap::default())) } /// Register a live export of `buf`. Pair with @@ -2026,6 +2159,14 @@ impl MemoryViewBuffer { /// views are RFC 0023 future work; the surface is enough for /// `pickle.PickleBuffer`, `socket.recv_into`, and the standard /// `memoryview(b'hello').tobytes()` patterns. +/// The unsigned-byte format `"B"`, one shared string for every view. +fn unsigned_byte_format() -> SharedStr { + match Object::from_static("B") { + Object::Str(s) => s, + _ => SharedStr::from("B"), + } +} + #[derive(Debug)] pub struct PyMemoryView { pub buffer: MemoryViewBuffer, @@ -2038,7 +2179,7 @@ pub struct PyMemoryView { pub len: Cell, pub readonly: Cell, pub released: Cell, - pub format: RefCell, + pub format: RefCell, pub itemsize: Cell, /// Logical dimensions, in *elements*. Empty means "derive a 1-D /// `[len / itemsize]` shape", which keeps every simple constructor a @@ -2097,7 +2238,7 @@ impl PyMemoryView { len: Cell::new(len), readonly: Cell::new(true), released: Cell::new(false), - format: RefCell::new("B".to_owned()), + format: RefCell::new(unsigned_byte_format()), itemsize: Cell::new(1), shape: RefCell::new(Vec::new()), strides: RefCell::new(Vec::new()), @@ -2122,7 +2263,7 @@ impl PyMemoryView { len: Cell::new(len), readonly: Cell::new(readonly), released: Cell::new(false), - format: RefCell::new("B".to_owned()), + format: RefCell::new(unsigned_byte_format()), itemsize: Cell::new(1), shape: RefCell::new(Vec::new()), strides: RefCell::new(Vec::new()), @@ -2148,7 +2289,7 @@ impl PyMemoryView { len: Cell::new(len), readonly: Cell::new(false), released: Cell::new(false), - format: RefCell::new("B".to_owned()), + format: RefCell::new(unsigned_byte_format()), itemsize: Cell::new(1), shape: RefCell::new(Vec::new()), strides: RefCell::new(Vec::new()), @@ -2180,7 +2321,7 @@ impl PyMemoryView { len: Cell::new(len), readonly: Cell::new(readonly), released: Cell::new(false), - format: RefCell::new(format), + format: RefCell::new(SharedStr::from(format)), itemsize: Cell::new(itemsize), shape: RefCell::new(Vec::new()), strides: RefCell::new(Vec::new()), @@ -2207,18 +2348,28 @@ impl PyMemoryView { } MemoryViewBuffer::Shared(s) => MemoryViewBuffer::Shared(s.clone()), }; + // (Guard-free reads where no borrow is live: cloning these runs no + // code. A cell borrowed mutably takes the checked borrow, which + // reports it.) + fn read(cell: &RefCell) -> T { + // SAFETY: the view ends with the clone, which runs no code. + match unsafe { cell.peek() } { + Some(v) => v.clone(), + None => cell.borrow().clone(), + } + } Self { buffer, start: Cell::new(self.start.get()), len: Cell::new(self.len.get()), readonly: Cell::new(self.readonly.get()), released: Cell::new(self.released.get()), - format: RefCell::new(self.format.borrow().clone()), + format: RefCell::new(read(&self.format)), itemsize: Cell::new(self.itemsize.get()), - shape: RefCell::new(self.shape.borrow().clone()), - strides: RefCell::new(self.strides.borrow().clone()), - suboffsets: RefCell::new(self.suboffsets.borrow().clone()), - exporter: RefCell::new(self.exporter.borrow().clone()), + shape: RefCell::new(read(&self.shape)), + strides: RefCell::new(read(&self.strides)), + suboffsets: RefCell::new(read(&self.suboffsets)), + exporter: RefCell::new(read(&self.exporter)), zero_dim: Cell::new(self.zero_dim.get()), // A fresh object: the hash cache and re-entrancy guard are // per-view state, not shared with the source. @@ -2305,6 +2456,14 @@ impl PyMemoryView { /// negative or gapped stride (e.g. `mv[::-1]`, `mv[::2]`) or with /// suboffsets is not. pub fn is_c_contiguous(&self) -> bool { + // (The derived layout, no suboffsets or stored strides, read + // guard-free: the common one-dimensional view.) + // SAFETY: views that end at once; nothing here runs code. + if unsafe { self.suboffsets.peek() }.is_some_and(Vec::is_empty) + && unsafe { self.strides.peek() }.is_some_and(Vec::is_empty) + { + return true; + } if self.has_suboffsets() { return false; } @@ -2446,6 +2605,17 @@ impl PyMemoryView { /// fast `[start..start+nbytes]` path; strided/reversed views are gathered /// element-by-element following `strides`, exactly like CPython's /// `memoryview.tobytes()`. + /// `f` on the view's bytes: where they are for a C-contiguous view, + /// gathered first for any other (see [`Self::to_bytes`]). + pub fn with_bytes(&self, f: impl FnOnce(&[u8]) -> R) -> R { + if self.is_c_contiguous() { + let start = self.start.get(); + let end = start + self.len.get(); + return self.buffer.with_read(|all| f(&all[start..end])); + } + f(&self.to_bytes()) + } + pub fn to_bytes(&self) -> Vec { let itemsize = self.itemsize.get().max(1); if self.is_c_contiguous() { @@ -2454,6 +2624,28 @@ impl PyMemoryView { return self.buffer.with_read(|all| all[start..end].to_vec()); } let shape = self.shape_dims(); + // A one-dimensional strided view: its elements gathered in one + // read of the buffer (any element outside it takes the walk below, + // which skips such elements). + if let ([n], false) = (shape.as_slice(), self.has_suboffsets()) { + let (n, start) = (*n, self.start.get() as isize); + let stride = self + .stride_bytes() + .first() + .copied() + .unwrap_or(itemsize as isize); + let gathered = self.buffer.with_read(|all| { + let mut out = Vec::with_capacity(n * itemsize); + for i in 0..n { + let off = usize::try_from(start + i as isize * stride).ok()?; + out.extend_from_slice(all.get(off..off + itemsize)?); + } + Some(out) + }); + if let Some(out) = gathered { + return out; + } + } let total: usize = shape.iter().product(); let mut out = Vec::with_capacity(total * itemsize); let mut index = vec![0usize; shape.len()]; @@ -2480,7 +2672,8 @@ impl PyMemoryView { /// are also `"B"`. fn norm_format(&self) -> String { let f = self.format.borrow(); - f.strip_prefix('@').unwrap_or(&f).to_owned() + let f: &str = &f; + f.strip_prefix('@').unwrap_or(f).to_owned() } /// `memoryview == memoryview` per CPython's `memory_richcompare`: @@ -3333,6 +3526,19 @@ fn write_drain_fd_intr( pending: &mut Vec, lock: &std::sync::Mutex<()>, ) -> Result<(), RuntimeError> { + let (off, res) = write_slice_fd_intr(fd, pending, lock); + pending.drain(..off.min(pending.len())); + res +} + +/// [`write_drain_fd_intr`] over a slice: how much of it was written, and how +/// the writing ended. +#[cfg(unix)] +fn write_slice_fd_intr( + fd: std::os::unix::io::RawFd, + pending: &[u8], + lock: &std::sync::Mutex<()>, +) -> (usize, Result<(), RuntimeError>) { let mut off = 0usize; let res = loop { if off >= pending.len() { @@ -3379,8 +3585,7 @@ fn write_drain_fd_intr( break Err(e); } }; - pending.drain(..off.min(pending.len())); - res + (off, res) } /// EAGAIN value to default to when a `BlockingIOError` lacks an explicit @@ -3829,6 +4034,17 @@ impl<'a> LeafProbe<'a> { } } + /// A probe for an instance hashed by identity (no native value, and + /// its class keeps `object`'s `__hash__`), or `None`. + #[inline(always)] + pub(crate) fn identity_instance(key: &'a Object) -> Option { + let Object::Instance(i) = key else { + return None; + }; + (i.native.get().is_none() && i.class_dunder(crate::types::Dunder::Hash).object_owner()) + .then(|| Self::with_hash(key, pointer_hash(Rc::as_ptr(i).cast()))) + } + /// [`Self::new`]'s hash for a key other than a `str` or an `int`. #[inline(never)] fn other_hash(key: &Object) -> Option { @@ -3844,6 +4060,11 @@ impl<'a> LeafProbe<'a> { identity_hash(key) } Object::Type(t) if type_hash_is_identity(t) => identity_hash(key), + // A tuple subclass keeping `tuple`'s hash and equality (a named + // tuple): its tuple's, when that is one of the tuples below. + Object::Instance(i) if tuple_like_value(i).is_some() => { + Self::other_hash(i.native.get()?)? + } // A tuple of machine ints, strings and bytes: its (cached) // hash, with no item's `__hash__` to run. (A bytes key too.) Object::Tuple(t) @@ -3856,6 +4077,9 @@ impl<'a> LeafProbe<'a> { // (`re`'s `(LITERAL, 97)` and `(RANGE, (48, 57))`): the same. Object::Tuple(t) if t.iter().all(|x| leaf_tuple_item(x, 0)) => py_hash_value(key)?, Object::Bytes(_) => py_hash_value(key)?, + // `None` and the `bool`s (a key of another kind with an equal + // hash, `1` against `True`, marks the probe foreign). + Object::None | Object::Bool(_) => py_hash_value(key)?, // Kinds that hash and compare by identity alone. Object::Function(_) | Object::Generator(_) @@ -3877,6 +4101,34 @@ impl<'a> LeafProbe<'a> { } } +/// The tuple of an instance of a `tuple` subclass that keeps `tuple`'s +/// `__hash__`, `__eq__` and `__ne__` (a named tuple): it hashes and +/// compares as that tuple, running no Python code of its own. +#[inline] +pub(crate) fn tuple_like_value(i: &crate::types::PyInstance) -> Option<&SharedTuple> { + use crate::types::Dunder; + let Some(Object::Tuple(t)) = i.native.get() else { + return None; + }; + let cls = i.cls_raw(); + (cls.native_kind.get() == 0 + && cls.c_ext_ptr.get() == 0 + && cls.dunder(Dunder::Hash).builtin_owner() + && cls.dunder(Dunder::Eq).builtin_owner() + && cls.dunder(Dunder::Ne).builtin_owner()) + .then_some(t) +} + +/// An exact tuple, or [`tuple_like_value`]'s of an instance. +#[inline] +fn tuple_like(o: &Object) -> Option<&SharedTuple> { + match o { + Object::Tuple(t) => Some(t), + Object::Instance(i) => tuple_like_value(i), + _ => None, + } +} + /// The value of an instance of an `int` subclass that keeps `int`'s /// `__hash__`, `__eq__` and `__ne__` (`re`'s `_NamedIntConstant` opcodes; /// not an `IntEnum` member, whose `Enum` defines `__hash__`): it hashes and @@ -3928,7 +4180,14 @@ pub(crate) fn int_order_value(o: &Object) -> Option { fn leaf_tuple_item(o: &Object, depth: u32) -> bool { match o { Object::Int(_) | Object::Str(_) | Object::Bytes(_) | Object::None => true, - Object::Instance(i) => int_like_value(i).is_some(), + // (A compiled pattern hashes natively, and equals only itself + // here: `re._compile`'s `(type(p), p, flags)` cache key.) + Object::Instance(i) => { + int_like_value(i).is_some() + || identity_instance(i) + || crate::stdlib::sre_objects::native_hash(i).is_some() + } + Object::Type(t) => type_hash_is_identity(t), Object::Tuple(t) => depth < 3 && t.iter().all(|x| leaf_tuple_item(x, depth + 1)), _ => false, } @@ -3947,6 +4206,17 @@ fn leaf_tuples_eq(a: &[Object], b: &[Object], depth: u32) -> Option { (Object::Bytes(p), Object::Bytes(q)) => p[..] == q[..], (Object::None, Object::None) => true, (Object::Instance(p), Object::Instance(q)) if Rc::ptr_eq(p, q) => true, + // Objects that compare by identity alone: only themselves. + (Object::Instance(p), Object::Instance(q)) + if identity_instance(p) && identity_instance(q) => + { + false + } + (Object::Type(p), Object::Type(q)) + if type_hash_is_identity(p) && type_hash_is_identity(q) => + { + Rc::ptr_eq(p, q) + } (Object::Tuple(p), Object::Tuple(q)) if depth < 3 => { p.len() == q.len() && leaf_tuples_eq(p, q, depth + 1)? } @@ -3959,6 +4229,18 @@ fn leaf_tuples_eq(a: &[Object], b: &[Object], depth: u32) -> Option { Some(equal) } +/// Whether `i` hashes and compares by identity alone: a plain instance +/// (no native payload) whose class keeps `object`'s `__hash__`, `__eq__` +/// and `__ne__`. +#[inline] +pub(crate) fn identity_instance(i: &crate::types::PyInstance) -> bool { + use crate::types::Dunder; + i.native.get().is_none() + && i.class_dunder(Dunder::Hash).object_owner() + && i.class_dunder(Dunder::Eq).object_owner() + && i.class_dunder(Dunder::Ne).object_owner() +} + /// A machine `int`'s value, or an [`int_like_value`] instance's. #[inline] fn int_like(o: &Object) -> Option { @@ -4013,6 +4295,8 @@ impl crate::dictmap::Probe for LeafProbe<'_> { (Object::Int(a), Object::Int(b)) => a == b, // The same class (a class probe meets its own entry). (Object::Type(a), Object::Type(b)) if Rc::ptr_eq(a, b) => true, + // The same instance (CPython compares keys with `is` first). + (Object::Instance(a), Object::Instance(b)) if Rc::ptr_eq(a, b) => true, _ => self.other_eq(key), } } @@ -4041,6 +4325,8 @@ impl LeafProbe<'_> { | (Object::AsyncGenerator(a), Object::AsyncGenerator(b)) => Rc::ptr_eq(a, b), (Object::Module(a), Object::Module(b)) => Rc::ptr_eq(a, b), (Object::Bytes(a), Object::Bytes(b)) => a[..] == b[..], + (Object::None, Object::None) => true, + (Object::Bool(a), Object::Bool(b)) => a == b, // Item by item; any item pairing other than int-int or str-str // (an equal `True` or `1.0`, say) may need Python's equality. (Object::Tuple(a), Object::Tuple(b)) if a.len() == b.len() => { @@ -4052,6 +4338,26 @@ impl LeafProbe<'_> { } } } + // `tuple`'s equality, which a tuple subclass that keeps it + // shares (named tuples against each other and against plain + // tuples): the same, on the tuples they hold. + (Object::Instance(_) | Object::Tuple(_), Object::Instance(_) | Object::Tuple(_)) + if tuple_like(self.key).is_some() && tuple_like(&key.0).is_some() => + { + let (Some(a), Some(b)) = (tuple_like(self.key), tuple_like(&key.0)) else { + return false; + }; + if a.len() != b.len() { + return false; + } + match leaf_tuples_eq(a, b, 0) { + Some(equal) => equal, + None => { + self.foreign.set(true); + false + } + } + } _ => { self.foreign.set(true); false @@ -4112,6 +4418,15 @@ fn current_interp_hash(obj: &Object) -> Option { interp.reentrant_py_hash(obj) } +/// [`current_interp_hash`] for an instance whose `__hash__` evaluates as a +/// pure leaf (see `Interpreter::leaf_instance_hash`): no reentrant call, +/// and no code run. `None` when it doesn't apply. +fn current_interp_pure_hash(obj: &Object) -> Option { + let ptr = crate::vm_singletons::current_interpreter_ptr()?; + // SAFETY: see `current_interp_hash`; the evaluation reads only. + unsafe { &*ptr }.leaf_instance_hash(obj) +} + /// Companion to [`current_interp_hash`] for `a == b` via Python `__eq__`. fn current_interp_eq(a: &Object, b: &Object) -> Option { let ptr = crate::vm_singletons::current_interpreter_ptr()?; @@ -4382,21 +4697,23 @@ pub(crate) fn take_repr_error() -> Option { impl PartialEq for DictKey { fn eq(&self, other: &Self) -> bool { - // CPython compares dict/set keys with `a is b or a == b`; the identity - // half makes a stored `nan` findable by itself (`{nan}` contains its - // own nan even though `nan != nan`). - if self.0.is_same(&other.0) { - return true; - } // Two plain strings or machine ints, the common keys, are equal by - // value alone. + // value alone (a string by identity first), before the general + // identity test below. match (&self.0, &other.0) { (Object::Str(a), Object::Str(b)) => { - return crate::dictmap::key_bytes_eq(a.as_bytes(), b.as_bytes()); + return SharedStr::ptr_eq(a, b) + || crate::dictmap::key_bytes_eq(a.as_bytes(), b.as_bytes()); } (Object::Int(a), Object::Int(b)) => return a == b, _ => {} } + // CPython compares dict/set keys with `a is b or a == b`; the identity + // half makes a stored `nan` findable by itself (`{nan}` contains its + // own nan even though `nan != nan`). + if self.0.is_same(&other.0) { + return true; + } // Native fast path also covers instance *identity* (`Rc::ptr_eq`), // which is the `a is b` half of CPython's dict-key comparison. if self.0.eq_value(&other.0) { @@ -4584,6 +4901,7 @@ fn key_eq_defer_active() -> bool { /// exactly once per operation (`test_setdefault_atomic`). Builtin-owned /// overrides (`weakref` comparing by referent) stay on the fast path: they /// cannot re-enter user code. +#[inline] pub(crate) fn dict_key_is_reentrant(key: &Object) -> bool { match key { Object::Instance(inst) => { @@ -4846,7 +5164,7 @@ pub(crate) fn dict_reentrant_remove( let mut m = d.borrow_mut(); match m.find_by_hash(probe.hash, |k| k.0.is_same(&stored)) { Some(i) => { - let (k, v) = m.shift_remove_index(i).expect("found above"); + let (k, v) = m.lazy_remove_index(i).expect("found above"); drop(m); dict_watch_bump(d); dict_mutation_event(d); @@ -4866,9 +5184,10 @@ pub(crate) fn dict_reentrant_remove( // same `ma_used`, so the size trip-wire stays silent — because the delete // leaves a tombstone and the reinsert *appends*: the iterator then finds an // entry beyond the `di->len` elements it expected and raises `RuntimeError: -// dictionary keys changed during iteration`. Our table has no -// tombstones (`shift_remove` compacts in place), so the layout carries no -// trace of the churn. Instead, dict iterators register a *watch* on their +// dictionary keys changed during iteration`. Our table keeps positions +// dense (a removal moves the later keys' positions down, whether or not it +// leaves a tombstone in the entry list), so an iterator's position carries +// no trace of the churn. Instead, dict iterators register a *watch* on their // source dict; the centralized structural mutators (`dict_insert` on a new // key, `dict_remove`, `clear`, `popitem`) bump the watched dict's version, // and the iterator's checked `__next__` raises on a version change. @@ -4880,11 +5199,76 @@ pub(crate) fn dict_reentrant_remove( // thread-local read, keeping `d[k] = v` hot paths unaffected. // --------------------------------------------------------------------------- +/// The live dict watches of a thread (see the section notes): a few in a +/// vector scanned in place (one or two dict loops running at a time is +/// the rule, and each registration through a hash map cost about a +/// hundred instructions), the rest in a map beside it. +#[derive(Default)] +struct DictWatches { + /// dict address, shared structural version, live watcher count. + small: Vec<(usize, Rc>, usize)>, + big: std::collections::HashMap>, usize), crate::fasthash::FxBuildHasher>, +} + +/// How many watched dicts the scanned vector holds before the map takes +/// the rest. +const SMALL_WATCHES: usize = 8; + +impl DictWatches { + /// Count one more watcher of `ptr`, its version shared (a fresh one, + /// `fresh`'s, when the dict had none). + fn enter(&mut self, ptr: usize, fresh: impl FnOnce() -> Rc>) -> Rc> { + if let Some(e) = self.small.iter_mut().find(|e| e.0 == ptr) { + e.2 += 1; + return e.1.clone(); + } + if let Some(e) = self.big.get_mut(&ptr) { + e.1 += 1; + return e.0.clone(); + } + let version = fresh(); + if self.small.len() < SMALL_WATCHES { + self.small.push((ptr, version.clone(), 1)); + } else { + self.big.insert(ptr, (version.clone(), 1)); + } + version + } + + /// Count one watcher of `ptr` fewer, dropping the entry at none. + fn leave(&mut self, ptr: usize) { + if let Some(i) = self.small.iter().position(|e| e.0 == ptr) { + let e = &mut self.small[i]; + e.2 = e.2.saturating_sub(1); + if e.2 == 0 { + self.small.swap_remove(i); + } + return; + } + if let Some(e) = self.big.get_mut(&ptr) { + e.1 = e.1.saturating_sub(1); + if e.1 == 0 { + self.big.remove(&ptr); + } + } + } + + fn version(&self, ptr: usize) -> Option<&Rc>> { + match self.small.iter().find(|e| e.0 == ptr) { + Some(e) => Some(&e.1), + None if self.big.is_empty() => None, + None => self.big.get(&ptr).map(|e| &e.0), + } + } + + fn len(&self) -> usize { + self.small.len() + self.big.len() + } +} + thread_local! { - /// dict address -> (shared structural version, live watcher count). - static DICT_WATCHES: std::cell::RefCell< - std::collections::HashMap>, usize), crate::fasthash::FxBuildHasher>, - > = std::cell::RefCell::new(std::collections::HashMap::default()); + static DICT_WATCHES: crate::gil::ReleaseUnderGil> = + crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(DictWatches::default())); /// Number of entries in `DICT_WATCHES` (fast gate for mutators). static DICT_WATCH_COUNT: std::cell::Cell = const { std::cell::Cell::new(0) }; } @@ -4903,11 +5287,10 @@ impl DictWatch { let ptr = std::ptr::from_ref::>(&**d) as usize; let version = DICT_WATCHES.with(|w| { let mut w = w.borrow_mut(); - let entry = w.entry(ptr).or_insert_with(|| (Rc::new(Cell::new(0)), 0)); - entry.1 += 1; - entry.0.clone() + let v = w.enter(ptr, || Rc::new(Cell::new(0))); + DICT_WATCH_COUNT.with(|c| c.set(w.len())); + v }); - DICT_WATCH_COUNT.with(|c| c.set(DICT_WATCHES.with(|w| w.borrow().len()))); let start = version.get(); DictWatch { ptr, @@ -4930,12 +5313,9 @@ impl Clone for DictWatch { // the watch alive after the original drops). DICT_WATCHES.with(|w| { let mut w = w.borrow_mut(); - let entry = w - .entry(self.ptr) - .or_insert_with(|| (self.version.clone(), 0)); - entry.1 += 1; + w.enter(self.ptr, || self.version.clone()); + DICT_WATCH_COUNT.with(|c| c.set(w.len())); }); - DICT_WATCH_COUNT.with(|c| c.set(DICT_WATCHES.with(|w| w.borrow().len()))); DictWatch { ptr: self.ptr, version: self.version.clone(), @@ -4948,14 +5328,9 @@ impl Drop for DictWatch { fn drop(&mut self) { DICT_WATCHES.with(|w| { let mut w = w.borrow_mut(); - if let Some(entry) = w.get_mut(&self.ptr) { - entry.1 = entry.1.saturating_sub(1); - if entry.1 == 0 { - w.remove(&self.ptr); - } - } + w.leave(self.ptr); + DICT_WATCH_COUNT.with(|c| c.set(w.len())); }); - DICT_WATCH_COUNT.with(|c| c.set(DICT_WATCHES.with(|w| w.borrow().len()))); } } @@ -4967,7 +5342,7 @@ pub(crate) fn dict_watch_bump(d: &RefCell) { } let ptr = std::ptr::from_ref::>(d) as usize; DICT_WATCHES.with(|w| { - if let Some((version, _)) = w.borrow().get(&ptr) { + if let Some(version) = w.borrow().version(ptr) { version.set(version.get() + 1); } }); @@ -5162,6 +5537,12 @@ pub struct DictData { key_filter: std::sync::atomic::AtomicU64, } +impl Drop for DictData { + fn drop(&mut self) { + self.map.clear_entries_inline(); + } +} + impl Clone for DictData { fn clone(&self) -> Self { Self { @@ -5174,6 +5555,11 @@ impl Clone for DictData { } impl DictData { + /// Room for `additional` more entries without growing. + pub(crate) fn reserve(&mut self, additional: usize) { + self.map.reserve(additional); + } + #[inline] pub fn with_capacity_and_hasher(n: usize, h: crate::fasthash::FxBuildHasher) -> Self { Self { @@ -5390,8 +5776,8 @@ impl IntoIterator for DictData { type Item = (DictKey, Object); type IntoIter = crate::dictmap::IntoIter; - fn into_iter(self) -> Self::IntoIter { - self.map.into_iter() + fn into_iter(mut self) -> Self::IntoIter { + std::mem::take(&mut self.map).into_iter() } } @@ -5661,11 +6047,11 @@ impl PyFunction { } map.insert( DictKey(name_key.clone()), - crate::stdlib::sys::intern_name(&code.name), + crate::stdlib::sys::intern_code_name(&code.name), ); map.insert( DictKey(qualname_key.clone()), - crate::stdlib::sys::intern_name(&code.qualname), + crate::stdlib::sys::intern_code_name(&code.qualname), ); let mut slots = self.slots_cell().borrow_mut(); // Every store goes through `slots()`, which plants the seed @@ -5681,8 +6067,8 @@ impl PyFunction { if self.names_seeded() { let code = self.code(); return ( - Some(crate::stdlib::sys::intern_name(&code.name)), - Some(crate::stdlib::sys::intern_name(&code.qualname)), + Some(crate::stdlib::sys::intern_code_name(&code.name)), + Some(crate::stdlib::sys::intern_code_name(&code.qualname)), ); } let Some(slots) = self.slots_raw.get() else { @@ -5754,6 +6140,7 @@ impl PyFunction { self.defaults_override .0 .store(true, std::sync::atomic::Ordering::Relaxed); + crate::rare_events::note_func_edit(); } self.slots() .borrow_mut() @@ -7044,8 +7431,8 @@ fn unpack_text_cookie(cookie: &BigInt) -> (u64, BigInt, u64, bool, u64) { } pub struct PyFile { - pub name: String, - pub mode: String, + pub name: std::borrow::Cow<'static, str>, + pub mode: std::borrow::Cow<'static, str>, pub binary: bool, /// The faithful CPython io layer this stream presents (`type()` and /// `isinstance` identity); see [`IoKind`]. @@ -7114,6 +7501,11 @@ pub struct PyFile { /// `.buffer` access; `None` until then and for streams that are their own /// buffer. pub binary_buffer_cache: RefCell>, + /// The last `BytesIO.getvalue()` result, handed out again while the + /// buffer is unchanged (CPython shares its bytes object the same way). + /// Every write, truncate, re-init, `__setstate__` and `getbuffer()` + /// clears it; see [`Self::mem_changed`]. + pub mem_value: RefCell>>, /// Observed line endings, as CPython's `IncrementalNewlineDecoder` tracks /// them for the text-mode `.newlines` attribute. Bit flags: `1`=`\r`, /// `2`=`\n`, `4`=`\r\n`. Updated on every text-mode read (regardless of the @@ -7188,7 +7580,7 @@ pub struct PyFile { /// (test_io.test_write_readline_races). `Arc` so the dup-ed `.buffer` /// sibling — which shares the OS file description and offset — shares the /// lock too. - pub fd_syscall_lock: std::sync::Arc>, + pub fd_syscall_lock: FdSyscallLock, /// Bytes read ahead of the logical stream position, served back before the /// backend on the next read: line reads fill it a block at a time (see /// [`PyFile::read_line_bytes`]), so the descriptor's offset runs ahead of @@ -7201,8 +7593,34 @@ pub struct PyFile { pub read_ahead: RefCell, } +/// A stream's [`PyFile::fd_syscall_lock`], made at its first use: an +/// in-memory stream (`io.BytesIO()`, `io.StringIO()`) never issues a +/// descriptor syscall, so it never pays for the shared allocation. +#[derive(Default, Debug)] +pub struct FdSyscallLock(std::sync::OnceLock>>); + +impl FdSyscallLock { + /// The same lock, for a sibling stream over the same file description. + pub fn share(&self) -> Self { + let cell = std::sync::OnceLock::new(); + let _ = cell.set(self.0.get_or_init(Default::default).clone()); + Self(cell) + } +} + +impl std::ops::Deref for FdSyscallLock { + type Target = std::sync::Mutex<()>; + fn deref(&self) -> &std::sync::Mutex<()> { + self.0.get_or_init(Default::default) + } +} + impl PyFile { - pub fn new(name: impl Into, mode: impl Into, backend: FileBackend) -> Self { + pub fn new( + name: impl Into>, + mode: impl Into>, + backend: FileBackend, + ) -> Self { let mode_s = mode.into(); let binary = mode_s.contains('b'); let io_kind = IoKind::from_mode(&mode_s); @@ -7225,6 +7643,7 @@ impl PyFile { closefd: crate::sync::Cell::new(true), extra_attrs: RefCell::new(Vec::new()), binary_buffer_cache: RefCell::new(None), + mem_value: RefCell::new(None), seennl: crate::sync::Cell::new(0), write_buf: RefCell::new(Vec::new()), line_buffering: crate::sync::Cell::new(LINE_BUFFER_UNDECIDED), @@ -7237,7 +7656,7 @@ impl PyFile { text_incr: RefCell::new(None), blksize: crate::sync::Cell::new(DEFAULT_BUFFER_SIZE as i64), repr_class: RefCell::new(None), - fd_syscall_lock: std::sync::Arc::new(std::sync::Mutex::new(())), + fd_syscall_lock: FdSyscallLock::default(), read_ahead: RefCell::new(ReadAhead::default()), } } @@ -7491,7 +7910,7 @@ impl PyFile { } } if self.name_is_bytes.get() { - Some(Object::new_bytes(self.name.clone().into_bytes())) + Some(Object::new_bytes(self.name.as_bytes())) } else { Some(Object::from_str(self.name.clone())) } @@ -7552,7 +7971,7 @@ impl PyFile { // The dup-ed descriptor shares the OS file *description* — // and thus the seek offset — with this stream, so raw // syscalls on either object must serialize on one lock. - bf.fd_syscall_lock = self.fd_syscall_lock.clone(); + bf.fd_syscall_lock = self.fd_syscall_lock.share(); if let Some(n) = self.name_override.borrow().as_ref() { *bf.name_override.borrow_mut() = Some(n.clone()); } @@ -7579,7 +7998,7 @@ impl PyFile { /// stream (`TextIOWrapper`) reports the mode string it was opened with. pub fn reported_mode(&self) -> String { if !self.binary { - return self.mode.clone(); + return self.mode.to_string(); } let m = &self.mode; let created = m.contains('x'); @@ -7696,10 +8115,17 @@ impl PyFile { /// do not carry the `mode`/`name` attributes that OS-backed file objects /// do, so callers gate those attributes on this. pub fn is_memory(&self) -> bool { - matches!( - &*self.backend.borrow(), - FileBackend::MemBytes { .. } | FileBackend::MemText { .. } - ) + let memory = |b: &FileBackend| { + matches!( + b, + FileBackend::MemBytes { .. } | FileBackend::MemText { .. } + ) + }; + // SAFETY: the variant is read and the view dropped at once. + if let Some(b) = unsafe { self.backend.peek() } { + return memory(b); + } + memory(&self.backend.borrow()) } /// Whether the stream is attached to a terminal (`f.isatty()`). The @@ -7896,6 +8322,18 @@ impl PyFile { /// translation, or this stream hasn't been through the general path yet. /// Runs no code, so a loop can take it without publishing its frame. pub(crate) fn next_line_pure(&self, limit: Option) -> Option { + self.next_line_pure_with(limit, Some) + } + + /// [`PyFile::next_line_pure`] handed to `take`, the line consumed only + /// when `take` accepts it (the stream is as it was when it declines). + /// `take` runs with the stream's buffer borrowed, so it must not touch + /// the stream. + pub(crate) fn next_line_pure_with( + &self, + limit: Option, + take: impl FnOnce(Object) -> Option, + ) -> Option { // (A zero limit reads nothing, which isn't a line to hand out.) if limit == Some(0) { return None; @@ -7956,7 +8394,7 @@ impl PyFile { // Bytes wait here only on an open stream that has been read. let mut ra = self.read_ahead.try_borrow_mut().ok()?; let n = line_take(ra.rest(), end, cut(ra.rest()))?; - let line = make(&ra.rest()[..n])?; + let line = take(make(&ra.rest()[..n])?)?; ra.consume(n); Some(line) } @@ -7967,7 +8405,7 @@ impl PyFile { let d = data.try_borrow().ok()?; let rest = d.get(*pos..).filter(|r| !r.is_empty())?; let n = line_take(rest, end, cut(rest)).unwrap_or(rest.len()); - let line = make(&rest[..n])?; + let line = take(make(&rest[..n])?)?; *pos += n; Some(line) } @@ -7977,7 +8415,7 @@ impl PyFile { } let rest = data.as_bytes().get(*pos..).filter(|r| !r.is_empty())?; let n = line_take(rest, end, utf8_limit(rest, limit)).unwrap_or(rest.len()); - let line = make(&rest[..n])?; + let line = take(make(&rest[..n])?)?; *pos += n; Some(line) } @@ -8059,6 +8497,121 @@ impl PyFile { true } + /// `BytesIO.write(data)` at the stream's end with nothing exported (a + /// `getbuffer()` view would make it raise): the bytes appended, as + /// the full write appends them. `false`, touching nothing, otherwise. + pub(crate) fn mem_bytes_append(&self, data: &[u8]) -> bool { + if self.io_kind.get() != IoKind::BytesIO || data.is_empty() { + return false; + } + // SAFETY: guard-free views, each dropped at once (nothing here + // runs code). + if unsafe { self.closed.peek() }.is_none_or(|c| *c) { + return false; + } + // SAFETY: as above (the cache's release only frees bytes). + let Some(FileBackend::MemBytes { data: buf, pos }) = (unsafe { self.backend.peek_mut() }) + else { + return false; + }; + if bytearray_is_exported(buf) { + return false; + } + // SAFETY: as above. + let Some(b) = (unsafe { buf.peek_mut() }) else { + return false; + }; + // SAFETY: as above. + if let Some(m) = unsafe { self.mem_value.peek_mut() } { + *m = None; + } else { + return false; + } + // (At the end: appended. Inside the buffer, after a seek: written + // over what is there, the buffer growing if the data runs past its + // end. Past the end is the full method's, which fills the gap.) + let at = *pos; + if at > b.len() { + return false; + } + let over = data.len().min(b.len() - at); + b[at..at + over].copy_from_slice(&data[..over]); + b.extend_from_slice(&data[over..]); + *pos = at + data.len(); + true + } + + /// `StringIO.read(n)` (all with `None`) when the characters to read + /// are ASCII with no `\r` (so no newline translation or surrogate + /// bridge touches them): the `str` copied from the buffer, the position + /// moved past it. `None`, having changed nothing, otherwise. + pub(crate) fn mem_text_read_ascii(&self, n: Option) -> Option { + if self.io_kind.get() != IoKind::StringIO || self.binary { + return None; + } + // SAFETY: guard-free views, each dropped at once (nothing here + // runs code). + if unsafe { self.closed.peek() }.is_none_or(|c| *c) + || unsafe { self.read_ahead.peek() }.is_none_or(|ra| ra.pending() != 0) + { + return None; + } + let mut backend = self.backend.try_borrow_mut().ok()?; + let FileBackend::MemText { data, pos } = &mut *backend else { + return None; + }; + let bytes = data.as_bytes(); + // (At or past the end: nothing, the position kept where a seek + // left it.) + if *pos >= bytes.len() { + return Some(Object::from_static("")); + } + let start = *pos; + let end = n.map_or(bytes.len(), |n| start.saturating_add(n).min(bytes.len())); + let run = &bytes[start..end]; + if !run.is_ascii() || run.contains(&b'\r') { + return None; + } + // SAFETY: an ASCII run of valid UTF-8 is valid UTF-8. + let text = unsafe { std::str::from_utf8_unchecked(run) }; + let out = Object::from_str(text); + *pos = end; + Some(out) + } + + /// The open `BytesIO`'s bytes at its position, where they are: `f` on + /// up to `n` of them (all of them with `None`), the position then moved + /// past the `f`'s count. `None` for any other stream, a closed one, or + /// one with bytes parked ahead of it. + pub(crate) fn mem_bytes_read_with( + &self, + n: Option, + f: impl FnOnce(&[u8]) -> (R, usize), + ) -> Option { + if self.io_kind.get() != IoKind::BytesIO { + return None; + } + // SAFETY: guard-free views, each dropped at once (nothing here + // runs code). + if unsafe { self.closed.peek() }.is_none_or(|c| *c) + || unsafe { self.read_ahead.peek() }.is_none_or(|ra| ra.pending() != 0) + { + return None; + } + let mut backend = self.backend.try_borrow_mut().ok()?; + let FileBackend::MemBytes { data, pos } = &mut *backend else { + return None; + }; + let d = data.try_borrow().ok()?; + let start = (*pos).min(d.len()); + let end = n.map_or(d.len(), |n| start.saturating_add(n).min(d.len())); + let (r, used) = f(&d[start..end]); + if used > 0 { + *pos = start + used; + } + Some(r) + } + /// `sys.stdout.write(s)` when the text's bytes go to the shared sink as /// they are: `None` for any other stream or text, having touched nothing. /// Runs no Python code (a full buffer is written out with the handlers @@ -8125,42 +8678,60 @@ impl PyFile { /// and returns `true`. `false` touches nothing; the general path then /// runs (overwrites, newline translation, an explicit codec). pub fn mem_text_append(&self, s: &str) -> bool { - if self.io_kind.get() != IoKind::StringIO || *self.closed.borrow() { + if self.io_kind.get() != IoKind::StringIO { return false; } - if self.encoding.borrow().is_some() - || self - .errors - .borrow() - .as_deref() - .is_some_and(|e| e != "strict") + // The settings are read through guard-free views, each dropped at + // once (nothing here runs code), and a borrow when one is live. + fn read(c: &RefCell, f: impl FnOnce(&T) -> R) -> R { + // SAFETY: as above. + match unsafe { c.peek() } { + Some(v) => f(v), + None => f(&c.borrow()), + } + } + if read(&self.closed, |c| *c) + || read(&self.encoding, Option::is_some) + || read(&self.errors, |e| { + e.as_deref().is_some_and(|e| e != "strict") + }) { return false; } - let collapse = match self.newline.borrow().as_deref() { - Some("\n" | "") => false, - None if self.io_kind.get() == IoKind::StringIO => true, - _ => return false, + let collapse = match read(&self.newline, |n| match n.as_deref() { + Some("\n" | "") => Some(false), + None => Some(true), + _ => None, + }) { + Some(c) => c, + None => return false, }; if collapse && s.as_bytes().contains(&b'\r') { return false; } - let Ok(mut backend) = self.backend.try_borrow_mut() else { - return false; + let append = |backend: &mut FileBackend| { + let FileBackend::MemText { data, pos } = backend else { + return false; + }; + if *pos != data.len() { + return false; + } + data.push_str(s); + *pos = data.len(); + true }; - let FileBackend::MemText { data, pos } = &mut *backend else { - return false; + // SAFETY: the buffer is extended and the view dropped at once. + let done = match unsafe { self.backend.peek_mut() } { + Some(b) => append(b), + None => match self.backend.try_borrow_mut() { + Ok(mut b) => append(&mut b), + Err(_) => false, + }, }; - if *pos != data.len() { - return false; - } - data.push_str(s); - *pos = data.len(); - drop(backend); - if collapse { + if done && collapse { self.record_seen_newlines(s); } - true + done } fn translate_newlines_write(&self, s: &str) -> String { @@ -8898,7 +9469,7 @@ impl PyFile { while skip_bytes > 0 { pf_call_method(&decoder, "setstate", &[make_state_tuple(&dec_flags_bi)])?; let upto = &next_input[..skip_bytes as usize]; - let dec = pf_call_method(&decoder, "decode", &[Object::new_bytes(upto.to_vec())])?; + let dec = pf_call_method(&decoder, "decode", &[Object::new_bytes(upto)])?; let n = dec.to_str().chars().count(); if n <= chars_to_skip { let st = pf_call_method(&decoder, "getstate", &[])?; @@ -8934,11 +9505,8 @@ impl PyFile { let mut reached = false; for i in (skip_bytes as usize)..next_input.len() { bytes_fed += 1; - let dec = pf_call_method( - &decoder, - "decode", - &[Object::new_bytes(next_input[i..=i].to_vec())], - )?; + let dec = + pf_call_method(&decoder, "decode", &[Object::new_bytes(&next_input[i..=i])])?; chars_decoded += dec.to_str().chars().count(); let st = pf_call_method(&decoder, "getstate", &[])?; let (b, d) = decoder_state_parts(&st)?; @@ -9203,6 +9771,7 @@ impl PyFile { /// the rare read↔write re-init, which CPython itself rejects mid-stream). pub fn reinit_fileio(&self, new_backend: FileBackend, closefd: bool) { self.close(); + self.mem_changed(); *self.backend.borrow_mut() = new_backend; self.closefd.set(closefd); *self.closed.borrow_mut() = false; @@ -9214,29 +9783,393 @@ impl PyFile { *self.binary_buffer_cache.borrow_mut() = None; } - /// Read up to `n` bytes from the backend; `None` reads everything. - /// Returns bytes regardless of mode — the caller decides whether - /// to wrap them as `str` (text mode) or `bytes` (binary mode). - /// Non-blocking-aware variant of [`PyFile::read_bytes`] for the file - /// `read()` method: a would-block on a non-blocking descriptor returns - /// `Ok(None)` (so `BufferedReader.read()` yields `None` instead of raising - /// `OSError(EAGAIN)`), while blocking descriptors and in-memory streams - /// keep the exact `read_bytes` behaviour. Only descriptor-backed streams in - /// `O_NONBLOCK` mode take the special path. - pub fn read_bytes_opt(&self, n: Option) -> Result>, RuntimeError> { - #[cfg(unix)] - { - use std::os::unix::io::AsRawFd; - self.check_open()?; - self.flush_write_buf()?; - self.rewind_read_ahead(); - let parked = self.take_pushback(n); - // A sized read is served by what's parked alone; a read to the - // end goes on to the backend's remainder. - if parked.is_some() && n.is_some() { - return Ok(parked); - } - let raw_fd = match &*self.backend.borrow() { + /// The position of an open `BytesIO` with nothing read ahead or written + /// to flush (its `tell()`), read guard-free; `None` for anything else. + pub(crate) fn mem_bytes_tell(&self) -> Option { + if self.io_kind.get() != IoKind::BytesIO { + return None; + } + // SAFETY: guard-free views, each dropped at once (nothing here runs + // code). + unsafe { + if self.closed.peek().is_none_or(|c| *c) + || self.read_ahead.peek().is_none_or(|r| r.pending() != 0) + || self.write_buf.peek().is_none_or(|w| !w.is_empty()) + { + return None; + } + match self.backend.peek()? { + FileBackend::MemBytes { pos, .. } => Some(*pos), + _ => None, + } + } + } + + /// `seek(at)` (from the start, `at` not negative) of such a stream: the + /// position set as the full method sets it (past the end too), and + /// `tell()` enabled. `None`, nothing touched, for anything else. + pub(crate) fn mem_bytes_seek(&self, at: usize) -> Option<()> { + self.mem_bytes_tell()?; + let mut backend = self.backend.try_borrow_mut().ok()?; + let FileBackend::MemBytes { pos, .. } = &mut *backend else { + return None; + }; + *pos = at; + drop(backend); + self.telling.set(true); + Some(()) + } + + /// `read(want)` of an open, readable, buffered binary disk stream with + /// nothing written to flush and no text sibling, when its read-ahead + /// holds all `want` bytes: those bytes, consumed, with no system call + /// and no code run (a leaf half's read). `None`, nothing touched, for + /// anything else. + pub(crate) fn read_ahead_pure(&self, want: usize) -> Option { + if want == 0 || !self.binary || self.io_kind.get() == IoKind::Raw { + return None; + } + // SAFETY: guard-free views, each dropped at once (nothing here runs + // code). + unsafe { + if self.closed.peek().is_none_or(|c| *c) + || self.write_buf.peek().is_none_or(|w| !w.is_empty()) + || self.binary_buffer_cache.peek().is_none_or(Option::is_some) + || !matches!(self.backend.peek()?, FileBackend::Disk(_)) + { + return None; + } + } + if !self.mode.bytes().any(|b| b == b'r' || b == b'+') { + return None; + } + let mut ra = self.read_ahead.try_borrow_mut().ok()?; + if ra.pending() < want { + return None; + } + let out = SharedSlice::from(&ra.rest()[..want]); + ra.consume(want); + Some(Object::Bytes(out)) + } + + /// `readinto` of `want` bytes into `copy`, when the read-ahead of an + /// open, readable, buffered binary disk stream with nothing written to + /// flush and no text sibling holds them all: `copy` is handed them and + /// they are consumed, with no system call and no code run (a leaf + /// half's read). `None`, nothing touched, for anything else. + pub(crate) fn read_ahead_into(&self, want: usize, copy: impl FnOnce(&[u8])) -> Option<()> { + if want == 0 || !self.binary || self.io_kind.get() == IoKind::Raw { + return None; + } + // SAFETY: guard-free views, each dropped at once (nothing here runs + // code). + unsafe { + if self.closed.peek().is_none_or(|c| *c) + || self.write_buf.peek().is_none_or(|w| !w.is_empty()) + || self.binary_buffer_cache.peek().is_none_or(Option::is_some) + || !matches!(self.backend.peek()?, FileBackend::Disk(_)) + { + return None; + } + } + if !self.mode.bytes().any(|b| b == b'r' || b == b'+') { + return None; + } + let mut ra = self.read_ahead.try_borrow_mut().ok()?; + if ra.pending() < want { + return None; + } + copy(&ra.rest()[..want]); + ra.consume(want); + Some(()) + } + + /// `readinto` of up to `want` bytes from a buffered binary disk file + /// through its read-ahead, as CPython's `BufferedReader` serves a read + /// of less than half its buffer: `copy` is handed each run taken from + /// the read-ahead (which one `read(2)` of a buffer's worth refills, with + /// the GIL released and nothing of the caller's borrowed) and returns + /// how much of it it took, until `want` bytes are taken or the file + /// ends. The count taken, or `None` when another path must serve it + /// (another backend or kind of stream, a larger read, a non-blocking + /// descriptor with nothing taken yet). + #[cfg(unix)] + pub fn readinto_buffered( + &self, + want: usize, + mut copy: impl FnMut(&[u8]) -> usize, + ) -> Option> { + use std::os::unix::io::AsRawFd; + if want == 0 || !self.binary { + return None; + } + let fd = match &*self.backend.borrow() { + FileBackend::Disk(f) if self.io_kind.get() != IoKind::Raw => f.as_raw_fd(), + _ => return None, + }; + let room = self.buf_size.get().clamp(8192, 8192 * 1024); + if want * 2 > room { + return None; + } + if let Err(e) = self.check_open().and_then(|()| self.flush_write_buf()) { + return Some(Err(e)); + } + let lock = &self.fd_syscall_lock; + let mut done = 0; + while done < want { + if self.read_ahead.borrow().pending() == 0 { + if fd_is_nonblocking(fd) { + return (done != 0).then_some(Ok(done)); + } + // (The storage leaves the cell for the read, as in + // `fill_read_ahead`.) + let mut buf = self.read_ahead.borrow_mut().begin_fill(room); + let got = read_fd_into(fd, &mut buf, room, lock); + self.read_ahead.borrow_mut().put_back(buf); + match got { + Err(e) => return Some(Err(e)), + Ok(0) => break, + Ok(_) => {} + } + } + let mut ra = self.read_ahead.borrow_mut(); + let k = (want - done).min(ra.pending()); + let took = copy(&ra.rest()[..k]).min(k); + ra.consume(took); + done += took; + if took < k { + break; + } + } + Some(Ok(done)) + } + + /// A sized binary read of a disk file with nothing parked, read straight + /// into the `bytes` object's own storage: `Ok(Ok(bytes))` when one + /// `read(2)` filled all `want` bytes, `Ok(Err(partial))` with what it + /// read otherwise (end of file or a short read, for the caller to carry + /// on with). `None` when another path must serve the read (another + /// backend, read-ahead waiting, a would-block). The first read of the + /// stream sets `PyFile`'s pre-read state as `read_bytes_opt` does. + #[cfg(unix)] + pub fn read_sized_shared( + &self, + want: usize, + ) -> Option>, RuntimeError>> { + use std::os::unix::io::AsRawFd; + if !(1..=1 << 24).contains(&want) { + return None; + } + let fd = match &*self.backend.borrow() { + FileBackend::Disk(f) if self.io_kind.get() != IoKind::Raw => f.as_raw_fd(), + _ => return None, + }; + if let Err(e) = self.check_open().and_then(|()| self.flush_write_buf()) { + return Some(Err(e)); + } + let lock = &self.fd_syscall_lock; + // A read of less than half a buffer is served from the read-ahead, + // which one `read(2)` of a buffer's worth fills, as CPython's + // `BufferedReader` serves it (line reads share it). + let room = self.buf_size.get().clamp(8192, 8192 * 1024); + if want * 2 <= room { + if self.read_ahead.borrow().pending() == 0 { + if fd_is_nonblocking(fd) { + return None; + } + // (The storage leaves the cell for the read, as in + // `fill_read_ahead`.) + let mut buf = self.read_ahead.borrow_mut().begin_fill(room); + let got = read_fd_into(fd, &mut buf, room, lock); + self.read_ahead.borrow_mut().put_back(buf); + match got { + Err(e) => return Some(Err(e)), + Ok(0) => return Some(Ok(Err(Vec::new()))), + Ok(_) => {} + } + } + let mut ra = self.read_ahead.borrow_mut(); + let k = want.min(ra.pending()); + let out = SharedSlice::from(&ra.rest()[..k]); + ra.consume(k); + return Some(Ok(if k == want { + Ok(Object::Bytes(out)) + } else { + Err(out.to_vec()) + })); + } + if self.read_ahead.borrow().pending() != 0 { + return None; + } + // One `read(2)` (retried on a signal): the count, or `usize::MAX` + // for a would-block. + let read = |dst: *mut u8| -> Result { + loop { + let r = crate::gil::allow_threads_then(|| { + let _serialized = fd_lock(lock); + // SAFETY: `dst` has room for `want` bytes. + unsafe { libc::read(fd, dst.cast(), want) } + }); + if r >= 0 { + return Ok(r as usize); + } + let err = std::io::Error::last_os_error(); + match err.raw_os_error() { + Some(libc::EINTR) => service_pending_signals_io()?, + Some(code) if code == libc::EAGAIN || code == libc::EWOULDBLOCK => { + return Ok(usize::MAX) + } + _ => return Err(crate::error::io_error_to_py(&err)), + } + } + }; + let mut got: Result = Ok(0); + let mut partial = Vec::new(); + // SAFETY: a full read writes all `want` bytes; after anything less + // what came is copied out and the slice zeroed whole before it + // drops unread. + let full = unsafe { + SharedSlice::::build_uninit(want, |dst| { + got = read(dst); + match got { + Ok(k) if k == want => {} + Ok(k) => { + if k < want { + partial = std::slice::from_raw_parts(dst, k).to_vec(); + } + std::ptr::write_bytes(dst, 0, want); + } + Err(_) => std::ptr::write_bytes(dst, 0, want), + } + }) + }; + match got { + Ok(k) if k == want => Some(Ok(Ok(Object::Bytes(full)))), + Ok(usize::MAX) => None, + Ok(_) => Some(Ok(Err(partial))), + Err(e) => Some(Err(e)), + } + } + + /// A binary read to the end of a regular disk file, straight into the + /// `bytes` object's own storage, sized by what `fstat` says is left: the + /// bytes, or `None` when another path must serve it (another backend or + /// kind of file, read-ahead waiting, a non-blocking descriptor, an empty + /// or very large remainder). A file that grew or shrank meanwhile is + /// read on to its end and copied. + #[cfg(unix)] + pub fn read_all_shared(&self) -> Option> { + use std::os::unix::io::AsRawFd; + let fd = match &*self.backend.borrow() { + FileBackend::Disk(f) => f.as_raw_fd(), + _ => return None, + }; + if let Err(e) = self.check_open().and_then(|()| self.flush_write_buf()) { + return Some(Err(e)); + } + self.rewind_read_ahead(); + if self.read_ahead.borrow().pending() != 0 || fd_is_nonblocking(fd) { + return None; + } + // SAFETY: plain queries of our own descriptor. + let est = unsafe { + let mut st: libc::stat = std::mem::zeroed(); + if libc::fstat(fd, &raw mut st) != 0 || (st.st_mode & libc::S_IFMT) != libc::S_IFREG { + return None; + } + let pos = libc::lseek(fd, 0, libc::SEEK_CUR); + if pos < 0 || st.st_size <= pos as libc::off_t { + return None; + } + (st.st_size - pos as libc::off_t) as usize + }; + if est > 1 << 30 { + return None; + } + let lock = &self.fd_syscall_lock; + let read = |dst: *mut u8, room: usize| -> Result { + loop { + let r = crate::gil::allow_threads_then(|| { + let _serialized = fd_lock(lock); + // SAFETY: `dst` has room for `room` bytes. + unsafe { libc::read(fd, dst.cast(), room) } + }); + if r >= 0 { + return Ok(r as usize); + } + let err = std::io::Error::last_os_error(); + if err.raw_os_error() == Some(libc::EINTR) { + service_pending_signals_io()?; + continue; + } + return Err(crate::error::io_error_to_py(&err)); + } + }; + let mut done = 0usize; + let mut failed: Option = None; + // SAFETY: the bytes past `done` are zeroed before the slice can be + // read; when it's kept, `done` is all of it. + let full = unsafe { + SharedSlice::::build_uninit(est, |dst| { + while done < est { + match read(dst.add(done), est - done) { + Ok(0) => break, + Ok(k) => done += k, + Err(e) => { + failed = Some(e); + break; + } + } + } + std::ptr::write_bytes(dst.add(done), 0, est - done); + }) + }; + if let Some(e) = failed { + return Some(Err(e)); + } + // The end of the file, or whatever it has gained since. + let mut more = [0u8; 1]; + let extra = match read(more.as_mut_ptr(), 1) { + Ok(k) => k, + Err(e) => return Some(Err(e)), + }; + if done == est && extra == 0 { + return Some(Ok(Object::Bytes(full))); + } + let mut out = full[..done].to_vec(); + if extra > 0 { + out.push(more[0]); + match read_fd_intr(fd, None, lock) { + Ok(rest) => out.extend_from_slice(&rest), + Err(e) => return Some(Err(e)), + } + } + Some(Ok(Object::new_bytes(out))) + } + + /// Read up to `n` bytes from the backend; `None` reads everything. + /// Returns bytes regardless of mode — the caller decides whether + /// to wrap them as `str` (text mode) or `bytes` (binary mode). + /// Non-blocking-aware variant of [`PyFile::read_bytes`] for the file + /// `read()` method: a would-block on a non-blocking descriptor returns + /// `Ok(None)` (so `BufferedReader.read()` yields `None` instead of raising + /// `OSError(EAGAIN)`), while blocking descriptors and in-memory streams + /// keep the exact `read_bytes` behaviour. Only descriptor-backed streams in + /// `O_NONBLOCK` mode take the special path. + pub fn read_bytes_opt(&self, n: Option) -> Result>, RuntimeError> { + #[cfg(unix)] + { + use std::os::unix::io::AsRawFd; + self.check_open()?; + self.flush_write_buf()?; + self.rewind_read_ahead(); + let parked = self.take_pushback(n); + // A sized read is served by what's parked alone; a read to the + // end goes on to the backend's remainder. + if parked.is_some() && n.is_some() { + return Ok(parked); + } + let raw_fd = match &*self.backend.borrow() { FileBackend::Disk(f) => Some(f.as_raw_fd()), _ => None, }; @@ -9729,6 +10662,37 @@ impl PyFile { // raises only here / at close. if self.is_write_buffered() { let bufsize = self.buf_size.get(); + // A write of at least a buffer's worth with nothing staged goes + // to a blocking descriptor directly, as CPython's + // `BufferedWriter` writes it, instead of through the buffer. + #[cfg(unix)] + if data.len() >= bufsize && self.write_buf.borrow().is_empty() { + use std::os::unix::io::AsRawFd; + let fd = match &*self.backend.borrow() { + FileBackend::Disk(f) => Some(f.as_raw_fd()), + _ => None, + }; + if let Some(fd) = fd.filter(|&fd| !fd_is_nonblocking(fd)) { + // (Settles a text stream's `.buffer` sibling first.) + self.flush_write_buf()?; + if self.write_buf.borrow().is_empty() { + let (off, res) = write_slice_fd_intr(fd, data, &self.fd_syscall_lock); + if res.is_err() && off < data.len() { + // What a raising signal handler cut short waits + // in the buffer, as a flush leaves it. + self.write_buf.borrow_mut().extend_from_slice(&data[off..]); + let addr = std::ptr::from_ref(self) as usize; + if self.write_listed.get() != addr { + self.unlist_writer(); + self.write_listed.set(addr); + pending_writers().push(addr); + } + } + res?; + return Ok(data.len()); + } + } + } // Pre-flush if the buffer is already over size (a prior partial // non-blocking flush left it full). A `BlockingIOError` here means // none of `data` has been accepted yet, so it re-raises with @@ -9799,6 +10763,7 @@ impl PyFile { if data.is_empty() { return Ok(0); } + self.mem_changed(); let mut b = buf.borrow_mut(); if *pos > b.len() { // Seeked past EOF: writing zero-fills the gap (CPython @@ -10128,6 +11093,7 @@ impl PyFile { // live (CPython `bytesio.c` `check_exports`). bytearray_check_resizable(data)?; let n = size.unwrap_or(*pos as u64) as usize; + self.mem_changed(); let mut d = data.borrow_mut(); // `bytesio.c` only ever *shrinks*: a size beyond the end // leaves the buffer untouched, and the requested size is @@ -10162,12 +11128,90 @@ impl PyFile { } } + /// Drop the cached `getvalue()` result: the in-memory buffer changed + /// (or may change through a `getbuffer()` view). + #[inline] + pub(crate) fn mem_changed(&self) { + // SAFETY: a guard-free view, dropped at once. + if unsafe { self.mem_value.peek() }.is_some_and(|v| v.is_some()) { + *self.mem_value.borrow_mut() = None; + } + } + + /// Seed the cached `getvalue()` result with the initial bytes object, + /// so `BytesIO(b).getvalue()` returns `b` itself, as in CPython. + pub(crate) fn mem_seed(&self, v: SharedSlice) { + *self.mem_value.borrow_mut() = Some(v); + } + /// Extract the entire buffer of an in-memory StringIO/BytesIO. /// Used by `StringIO.getvalue()` / `BytesIO.getvalue()`. + /// `getvalue()` of an open `BytesIO` when the value cached at the last + /// call is still the buffer's: shared again, read through guard-free + /// views. `None` otherwise (nothing cached, a buffer changed since or + /// with a live `getbuffer()` view, a closed or other stream). + pub(crate) fn mem_value_cached(&self) -> Option { + // SAFETY: guard-free views, each dropped at once (nothing here runs + // code). + unsafe { + if self.closed.peek().is_none_or(|c| *c) { + return None; + } + let FileBackend::MemBytes { data, .. } = self.backend.peek()? else { + return None; + }; + let v = self.mem_value.peek()?.as_ref()?; + if v.len() != data.peek()?.len() || bytearray_is_exported(data) { + return None; + } + Some(Object::Bytes(v.clone())) + } + } + pub fn getvalue(&self) -> Option { + // (A `BytesIO`'s value read through views: nothing here runs code.) + // SAFETY: the views end with this block; the cache store only + // releases bytes. + unsafe { + if let Some(FileBackend::MemBytes { data, .. }) = self.backend.peek() { + if let Some(d) = data.peek() { + let exported = bytearray_is_exported(data); + if !exported { + if let Some(Some(v)) = self.mem_value.peek() { + if v.len() == d.len() { + return Some(Object::Bytes(v.clone())); + } + } + } + let v = SharedSlice::from(d.as_slice()); + if !exported { + if let Some(m) = self.mem_value.peek_mut() { + *m = Some(v.clone()); + } + } + return Some(Object::Bytes(v)); + } + } + } match &*self.backend.borrow() { FileBackend::MemBytes { data, .. } => { - Some(Object::Bytes(SharedSlice::from(data.borrow().as_slice()))) + let d = data.borrow(); + // A cached value is good while nothing has changed the + // buffer: the mutators clear it, and a live `getbuffer()` + // view (which can write in place) bypasses it. + let exported = bytearray_is_exported(data); + if !exported { + if let Some(v) = self.mem_value.borrow().as_ref() { + if v.len() == d.len() { + return Some(Object::Bytes(v.clone())); + } + } + } + let v = SharedSlice::from(d.as_slice()); + if !exported { + *self.mem_value.borrow_mut() = Some(v.clone()); + } + Some(Object::Bytes(v)) } // The buffer stores lone surrogates as bridged PUA code points // (so a Rust `String` can hold them); map them back to a `str`/ @@ -10189,6 +11233,7 @@ impl PyFile { /// stream, and the export keeps the buffer pinned (a subsequent /// `write`/`truncate` raises `BufferError`) until the view is released. pub fn getbuffer(&self) -> Result { + self.mem_changed(); match &*self.backend.borrow() { FileBackend::MemBytes { data, .. } => Ok(Object::MemoryView(Rc::new( PyMemoryView::from_bytearray(data.clone()), @@ -10207,6 +11252,17 @@ impl fmt::Debug for PyFile { impl Drop for PyFile { fn drop(&mut self) { crate::weakref_registry::on_death(std::ptr::from_ref(self) as usize as u64); + // An in-memory stream with nothing staged and no `.buffer` sibling + // (every `io.BytesIO()`/`io.StringIO()`) has no descriptor to warn + // about or close and nothing to flush. (`&mut self`: no borrow + // bookkeeping needed to look.) + if !matches!(self.backend.get_mut(), FileBackend::Disk(_)) + && self.write_buf.get_mut().is_empty() + && self.binary_buffer_cache.get_mut().is_none() + && self.write_listed.get() == 0 + { + return; + } // CPython's fileio/buffered/textio deallocators emit a // `ResourceWarning("unclosed file %R")` when an *open*, fd-backed // stream is reclaimed without an explicit `close()`/`with` @@ -10467,13 +11523,14 @@ impl PyLazyIter { LazyIterKind::Zip { iters, result, + spare, held, .. } => { for it in iters.iter().chain(held.iter()) { visit(it); } - if let Some(t) = result { + for t in result.iter().chain(spare.iter()) { for v in t.iter() { visit(v); } @@ -10503,6 +11560,12 @@ impl PyLazyIter { visit(&Object::LazyIter(parent.clone())); visit(tgtkey); } + LazyIterKind::CallIter { pair } => { + if let Some((callable, sentinel)) = pair { + visit(callable); + visit(sentinel); + } + } } } @@ -10539,6 +11602,7 @@ impl PyLazyIter { LazyIterKind::Batched { .. } => "batched", LazyIterKind::GroupBy { .. } => "groupby", LazyIterKind::Grouper { .. } => "_grouper", + LazyIterKind::CallIter { .. } => "callable_iterator", } } } @@ -10701,7 +11765,17 @@ pub enum LazyIterKind { iters: Vec, strict: bool, result: Option, + /// The result before `result`, kept to refill once its holder + /// lets go: a loop that binds each tuple (`for t in zip(xs, ys)`) + /// still holds `result` when it asks for the next, so the two + /// take turns and no step allocates. + spare: Option, held: Vec, + /// Whether no source is another's alias (the same iterator passed + /// twice), decided at the first native step: the sources never + /// change, and comparing every pair at every step made + /// `zip(*rows)` quadratic in its rows. + distinct: Option, }, /// The builtin `enumerate(iterable, start)` over a source only the /// interpreter can step (a generator, a user iterator); a native @@ -10730,6 +11804,11 @@ pub enum LazyIterKind { parent: Rc, tgtkey: Object, }, + /// `iter(callable, sentinel)` (CPython's `callable_iterator`): the + /// callable and the sentinel, both let go once a result equals the + /// sentinel or the callable raises `StopIteration` (CPython's + /// `calliter_iternext` clears them). + CallIter { pair: Option<(Object, Object)> }, } /// State of an active iterator. Slim by design — every iterable @@ -10909,6 +11988,20 @@ pub enum PyIterator { }, } +/// The empty store an exhausted list or reverse iterator detaches to: +/// one per thread, shared, so a loop's end allocates nothing (CPython +/// clears `it_seq`). Nothing writes to a detached iterator's store, and +/// `__reduce__` reports a fresh list for an empty one, so no one sees it +/// shared. (Never dropped: its thread's exit runs no destructor.) +#[inline] +pub(crate) fn detached_store() -> Rc>> { + thread_local! { + static EMPTY: std::mem::ManuallyDrop>>> = + std::mem::ManuallyDrop::new(Rc::new(RefCell::new(Vec::new()))); + } + EMPTY.with(|e| Rc::clone(e)) +} + impl PyIterator { /// Pull the next value out of the iterator, or `None` if exhausted. pub fn next_value(&mut self) -> Option { @@ -10932,7 +12025,7 @@ impl PyIterator { // subclass keepalive drops with it, running its // `__del__` here like CPython freeing the list // (test_free_after_iterating). - *items = Rc::new(RefCell::new(Vec::new())); + *items = crate::object::detached_store(); *owner = None; None } @@ -11178,7 +12271,7 @@ impl PyIterator { owner, } => { if *index < 0 { - *items = Rc::new(RefCell::new(Vec::new())); + *items = crate::object::detached_store(); *owner = None; return None; } @@ -11190,7 +12283,7 @@ impl PyIterator { } None => { // Index out of range (list shrank): exhaust + detach. - *items = Rc::new(RefCell::new(Vec::new())); + *items = crate::object::detached_store(); *index = -1; *owner = None; None @@ -11234,6 +12327,22 @@ impl PyIterator { PyIterator::Enumerate { inner, .. } | PyIterator::Shared(inner) => { inner.try_borrow().is_ok_and(|i| i.pure_ready()) } + // A plain dict's forward iterator past its first (checked) step, + // its dict unchanged and an entry left: the step `next_value` + // takes is the checked one's. + PyIterator::DictKeys { + index, + dict: Some(d), + len, + watch: Some(w), + reverse: false, + odict: None, + .. + } => { + !w.changed() + && d.try_borrow() + .is_ok_and(|data| data.len() == *len && data.get_index(*index).is_some()) + } _ => false, } } @@ -11261,6 +12370,10 @@ impl PyIterator { .get(*index..) .and_then(|rest| rest.chars().next()) .map(Object::from_char), + // (A `bytes` object's items are small ints.) + PyIterator::Bytes { data, index } => { + data.get(*index).map(|&b| Object::Int(i64::from(b))) + } PyIterator::Reversed { items, index, @@ -11273,6 +12386,91 @@ impl PyIterator { } } + /// Whether this is a plain cursor (a list's with no owner, a tuple's, + /// a range's, a `str`'s or `bytes`') with no item left: its next step + /// runs no code and reports the end. + pub(crate) fn plain_at_end(&self) -> bool { + match self { + PyIterator::List { + items, + index, + owner: None, + } => { + // SAFETY: a read that runs no code. + unsafe { items.peek() }.is_some_and(|xs| *index >= xs.len()) + } + PyIterator::Tuple { items, index } => *index >= items.len(), + PyIterator::Range { + current, + stop, + step, + } => !((*step > 0 && current < stop) || (*step < 0 && current > stop)), + PyIterator::Str { s, index } => *index >= s.len(), + PyIterator::Bytes { data, index } => *index >= data.len(), + _ => false, + } + } + + /// Whether [`Self::pure_next`] has an item to give. + #[inline(always)] + pub fn pure_has_next(&self) -> bool { + match self { + PyIterator::List { + items, + index, + owner: None, + } => { + // SAFETY: a read that runs no code. + unsafe { items.peek() }.is_some_and(|xs| *index < xs.len()) + } + PyIterator::Tuple { items, index } => *index < items.len(), + PyIterator::Range { + current, + stop, + step, + } => (*step > 0 && current < stop) || (*step < 0 && current > stop), + _ => false, + } + } + + /// [`Self::pure_peek`] and [`Self::pure_skip`] in one, for the plain + /// cursors (a list's with no owner, a tuple's, a range's): the next + /// item, stepped past. `None`, changing nothing, when there is none or + /// for any other iterator. + #[inline(always)] + pub fn pure_next(&mut self) -> Option { + match self { + PyIterator::List { + items, + index, + owner: None, + } => { + // SAFETY: a read that runs no code. + let v = crate::clone_hot(unsafe { items.peek() }?.get(*index)?); + *index += 1; + Some(v) + } + PyIterator::Tuple { items, index } => { + let v = crate::clone_hot(items.get(*index)?); + *index += 1; + Some(v) + } + PyIterator::Range { + current, + stop, + step, + } => { + if !((*step > 0 && current < stop) || (*step < 0 && current > stop)) { + return None; + } + let v = *current; + *current = current.wrapping_add(*step); + Some(Object::Int(v)) + } + _ => None, + } + } + /// Step past the item [`Self::pure_peek`] returned (as `next` steps a /// sequence iterator, whatever the sequence holds now): `false` for /// any other iterator, untouched. @@ -11282,7 +12480,8 @@ impl PyIterator { PyIterator::List { index, owner: None, .. } - | PyIterator::Tuple { index, .. } => *index += 1, + | PyIterator::Tuple { index, .. } + | PyIterator::Bytes { index, .. } => *index += 1, PyIterator::Range { current, step, .. } => *current = current.wrapping_add(*step), PyIterator::Str { s, index } => match s.get(*index..).and_then(|r| r.chars().next()) { Some(ch) => *index += ch.len_utf8(), @@ -11566,6 +12765,43 @@ impl PyIterator { }) } + /// The checked step of a plain dict's forward iterator (not an + /// `OrderedDict`'s) when it can't raise and frees nothing: the dict is + /// as the iterator last saw it, so the step is its next entry, or, + /// with `end_too`, its end while someone else holds the dict too (the + /// reference the end lets go is then not the last). `None`, nothing + /// done, for any other iterator or state: a `yield from`'s or a view + /// generator's native step, which may run no code. + pub fn dict_step_quiet(&mut self, end_too: bool) -> Option> { + let PyIterator::DictKeys { + dict: Some(d), + len, + watch, + index, + reverse: false, + odict: None, + .. + } = &*self + else { + return None; + }; + let left = { + let data = d.try_borrow().ok()?; + if data.len() != *len || watch.as_ref().is_some_and(DictWatch::changed) { + return None; + } + data.get_index(*index).is_some() + }; + if !left && (!end_too || Rc::strong_count(d) < 2) { + return None; + } + match self.next_value_checked() { + Ok(Some(v)) => Some(Some(v)), + Ok(None) if !left => Some(None), + _ => None, + } + } + /// Like [`next_value`], but enforces CPython's "container changed /// size during iteration" invariant before yielding. Used on the /// *user-visible* `__next__` boundaries (`FOR_ITER`, the `next()` @@ -11962,6 +13198,11 @@ impl PyIterator { /// tells them apart from the rest, here and in compiled code. pub(crate) const PLAIN_TAGS: u8 = 5; +/// The variants below this tag (the plain ones, `Long`, `Complex`, `Str` +/// and `WStr`) are all [`Object::is_gc_atomic`]: one compare in compiled +/// code's write barrier. +pub(crate) const ATOMIC_TAGS: u8 = 9; + /// The bytes from a counted variant's pointer to its payload: an `Rc`'s /// `Arc` and a [`ThinArc`] both address the allocation's start, strong /// count first, then the weak count, then the payload (aligned to at most @@ -11972,6 +13213,98 @@ const PAYLOAD_OFFSET: usize = 16; /// collector tracks them by (`Str`, `WStr`, `Bytes`), by tag. const TEXT_TAGS: u64 = 1 << 7 | 1 << 8 | 1 << 27; +/// Clones of `src`'s elements written to the `src.len()` slots at `dst`: +/// the elements copied whole, then their counts taken in a second pass. +/// (A clone moved through an iterator or `Vec::clone` goes by way of the +/// stack in two unaligned halves, about twenty instructions an element.) +/// +/// # Safety +/// +/// `dst` is valid for `src.len()` writes and doesn't overlap `src`; the +/// slots hold nothing that needs dropping. +#[inline] +pub(crate) unsafe fn clone_objects_into(src: &[Object], dst: *mut Object) { + // SAFETY: per the caller; each copied element's count is taken before + // anything can release the copy (nothing here runs code or unwinds, + // and the bias can't change hands meanwhile). + unsafe { + std::ptr::copy_nonoverlapping(src.as_ptr(), dst, src.len()); + if crate::rc::refcounts_biased() { + for item in src { + if let Some(word) = item.strong_word() { + crate::rc::plain_increment(word); + } + } + } else { + for item in src { + if let Some(word) = item.strong_word() { + crate::rc::increment_word(word); + } + } + } + } +} + +/// Clones of the objects `items` yields, written to `dst` one after +/// another: each copied whole and its count taken, as +/// [`clone_objects_into`] does for a slice (a gather by index moves no +/// object through the iterator, only its address). +/// +/// # Safety +/// +/// As [`clone_objects_into`]: `dst` has room for every item `items` yields. +pub(crate) unsafe fn clone_refs_into<'a>( + items: impl Iterator, + dst: *mut Object, +) { + // SAFETY: per the caller; as `clone_objects_into`'s. + unsafe { + let biased = crate::rc::refcounts_biased(); + for (at, item) in items.enumerate() { + std::ptr::copy_nonoverlapping(item, dst.add(at), 1); + if let Some(word) = item.strong_word() { + if biased { + crate::rc::plain_increment(word); + } else { + crate::rc::increment_word(word); + } + } + } + } +} + +/// Clones of `src`'s elements appended to `dst` (see +/// [`clone_objects_into`]). +#[inline] +pub(crate) fn extend_cloned(dst: &mut Vec, src: &[Object]) { + dst.reserve(src.len()); + // SAFETY: the reservation leaves room for `src.len()` more elements, + // all of them written before the length covers them. + unsafe { + clone_objects_into(src, dst.as_mut_ptr().add(dst.len())); + dst.set_len(dst.len() + src.len()); + } +} + +/// A vector of clones of `src`'s elements (see [`clone_objects_into`]). +#[inline] +pub(crate) fn cloned_vec(src: &[Object]) -> Vec { + let mut items = Vec::with_capacity(src.len()); + extend_cloned(&mut items, src); + items +} + +/// Whether two items of sequences being compared are equal: the same +/// object, or equal values. (Two machine ints, the commonest pair, are +/// settled in line, without the two calls.) +#[inline(always)] +fn items_equal(x: &Object, y: &Object) -> bool { + if let (Object::Int(a), Object::Int(b)) = (x, y) { + return a == b; + } + x.is_same(y) || x.eq_value(y) +} + impl Clone for Object { /// A new owner: the strong count (if any) bumped in place and the two /// words copied, with no per-variant dispatch. @@ -12252,6 +13585,19 @@ impl Object { let r = rhs_native.as_ref().unwrap_or(other); return l.eq_value(r); } + // Two sets: on the sets themselves, with their stored hashes and + // any Python comparison deferred (see `setalg`); the arms below + // compare snapshots when that leaves it undecided. + if matches!(self, Object::Set(_) | Object::FrozenSet(_)) + && matches!(other, Object::Set(_) | Object::FrozenSet(_)) + { + let eq = crate::setalg::with_sets(self, other, |x, y| { + crate::setalg::pure(|| crate::setalg::equal(x, y)) + }); + if let Some(Some(eq)) = eq { + return eq; + } + } match (self, other) { (Object::None, Object::None) => true, (Object::Bool(a), Object::Bool(b)) => a == b, @@ -12300,18 +13646,12 @@ impl Object { // Sequence comparison is element-wise `PyObject_RichCompareBool`, // which is identity-first — so `[nan] == [nan]` (same nan) is true. (Object::Tuple(a), Object::Tuple(b)) => { - a.len() == b.len() - && a.iter() - .zip(b.iter()) - .all(|(x, y)| x.is_same(y) || x.eq_value(y)) + a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| items_equal(x, y)) } (Object::List(a), Object::List(b)) => { let a = a.borrow(); let b = b.borrow(); - a.len() == b.len() - && a.iter() - .zip(b.iter()) - .all(|(x, y)| x.is_same(y) || x.eq_value(y)) + a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| items_equal(x, y)) } (Object::Dict(a), Object::Dict(b)) => { let a = a.borrow(); @@ -12685,6 +14025,18 @@ impl Object { } Object::Bytes(haystack) => bytes_membership(haystack, item), Object::ByteArray(haystack) => { + // (A plain needle converts without running code: the + // bytes are searched where they are.) + if matches!( + item, + Object::Int(_) + | Object::Bool(_) + | Object::Long(_) + | Object::Bytes(_) + | Object::ByteArray(_) + ) { + return bytes_membership(&haystack.borrow(), item); + } // Hold a buffer export: converting `item` can reenter // Python (a user `__index__`/`__buffer__`) that tries to // resize this bytearray; the resize then raises @@ -12772,6 +14124,7 @@ impl Object { DictViewKind::Items => { if let Object::Tuple(t) = item { if t.len() == 2 { + crate::builtins::ensure_dict_key(&t[0])?; if let Some(stored) = crate::builtins::dict_lookup(&v.dict, &t[0])? { return member_eq(&stored, &t[1]); } @@ -12918,7 +14271,9 @@ impl Object { }), Object::MemoryView(mv) => { if mv.released.get() { - return Err(value_error("memoryview: released")); + return Err(value_error( + "operation forbidden on released memoryview object", + )); } // CPython's `memoryiter` yields *format-unpacked elements* // (an `int64` exporter iterates as Python ints, `'d'` as @@ -12932,6 +14287,37 @@ impl Object { "multi-dimensional sub-views are not implemented", )); } + // A plain byte view of a `bytes` object: its bytes, which + // can't change, stepped as the `bytes` object's would be + // (no object made for each element first). + if let (Some((start, len)), MemoryViewBuffer::Bytes(all)) = + (crate::mv_plain_bytes(mv), &mv.buffer) + { + // (The whole object shares its storage; a window is + // copied.) + let data = if start == 0 && len == all.len() { + Some(all.clone()) + } else { + all.get(start..start + len).map(SharedSlice::from) + }; + if let Some(data) = data { + return Ok(PyIterator::Bytes { data, index: 0 }); + } + } + // A plain byte view over a whole `bytearray` (which can't + // be resized while the view exports it): the bytearray's + // live iterator, which sees a store made mid-loop, as + // CPython's `memoryiter` does. + if let (Some((0, len)), MemoryViewBuffer::ByteArray(data)) = + (crate::mv_plain_bytes(mv), &mv.buffer) + { + if data.try_borrow().is_ok_and(|d| d.len() == len) { + return Ok(PyIterator::ByteArray { + data: data.clone(), + index: 0, + }); + } + } let items = crate::mv_element_objects(mv)?; Ok(PyIterator::List { items: Rc::new(RefCell::new(items)), @@ -13158,7 +14544,7 @@ impl Object { Object::Unbound => "".to_owned(), Object::Bool(b) => if *b { "True" } else { "False" }.to_owned(), Object::Int(i) => i.to_string(), - Object::Long(b) => b.to_string(), + Object::Long(b) => bigint_decimal(b), Object::Complex(c) => complex_repr(c.real, c.imag), Object::Float(f) => float_repr(*f), Object::Str(s) => { @@ -13197,7 +14583,8 @@ impl Object { c => { let n = c as u32; if n <= 0xff { - out.push_str(&format!("\\x{n:02x}")); + out.push_str("\\x"); + push_hex_byte(&mut out, n as u8); } else if n <= 0xffff { out.push_str(&format!("\\u{n:04x}")); } else { @@ -13235,7 +14622,8 @@ impl Object { // non-printable scalars escape by code-point width. _ => { if n <= 0xff { - out.push_str(&format!("\\x{n:02x}")); + out.push_str("\\x"); + push_hex_byte(&mut out, n as u8); } else if n <= 0xffff { out.push_str(&format!("\\u{n:04x}")); } else { @@ -13252,12 +14640,13 @@ impl Object { if !repr_enter(id) { return "(...)".to_owned(); } - let mut s = String::from("("); + let mut s = String::with_capacity(2 + 4 * items.len()); + s.push('('); for (i, x) in items.iter().enumerate() { if i > 0 { s.push_str(", "); } - s.push_str(&x.repr()); + push_item_repr(&mut s, x); } if items.len() == 1 { s.push(','); @@ -13277,7 +14666,8 @@ impl Object { // (test_list.test_repr_mutate pops it), which CPython's // index-based `list_repr` tolerates — holding the borrow // across the call would instead panic the cell. - let mut s = String::from("["); + let mut s = String::with_capacity(2 + 4 * items.borrow().len()); + s.push('['); let mut i = 0usize; loop { let x = { @@ -13290,7 +14680,7 @@ impl Object { if i > 0 { s.push_str(", "); } - s.push_str(&x.repr()); + push_item_repr(&mut s, &x); i += 1; } s.push(']'); @@ -13311,14 +14701,15 @@ impl Object { .map(|(k, v)| (k.0.clone(), v.clone())) .collect() }; - let mut s = String::from("{"); + let mut s = String::with_capacity(2 + 8 * pairs.len()); + s.push('{'); for (i, (k, v)) in pairs.iter().enumerate() { if i > 0 { s.push_str(", "); } - s.push_str(&k.repr()); + push_item_repr(&mut s, k); s.push_str(": "); - s.push_str(&v.repr()); + push_item_repr(&mut s, v); } s.push('}'); repr_leave(); @@ -13517,6 +14908,23 @@ impl Object { file.repr_with_addr(Rc::as_ptr(file) as usize) } Object::Instance(inst) => { + // A class whose `__repr__` is a Python function: called + // directly through the live interpreter (as below, with the + // same error handling). + if let Some(ptr) = crate::vm_singletons::current_interpreter_ptr() { + // SAFETY: published by an enclosing VM frame still live on + // this thread; the GIL keeps it exclusive. + let interp = unsafe { &mut *ptr }; + if let Some(r) = interp.instance_python_repr(self) { + return match r { + Ok(r) => r.to_str(), + Err(e) => { + stash_repr_error(e); + format!("<{} object>", inst.cls().name) + } + }; + } + } // The `Ellipsis` / `NotImplemented` singletons render as // fixed text — CPython's `ellipsis`/`NotImplementedType` // `tp_repr`. We supply it here, keyed on the registry type @@ -13992,7 +15400,7 @@ impl Object { } Err(type_error(format!( "object of type '{}' has no len()", - self.type_name() + self.type_name_owned() ))) } }, @@ -14005,7 +15413,7 @@ impl Object { Object::Foreign(s) => Ok(crate::foreign::length(s)?.max(0) as usize), _ => Err(type_error(format!( "object of type '{}' has no len()", - self.type_name() + self.type_name_owned() ))), } } @@ -14465,6 +15873,10 @@ pub(crate) fn py_hash_long_i64(n: i64) -> i64 { // the high bits onto the low ones instead of dividing: `|n| < 2**64` // leaves at most one subtraction. const MOD: u64 = (1u64 << PY_HASH_BITS) - 1; + // (A non-negative int below the modulus is its own hash.) + if (n as u64) < MOD { + return n; + } let a = n.unsigned_abs(); let mut r = (a & MOD) + (a >> PY_HASH_BITS); if r >= MOD { @@ -14482,10 +15894,81 @@ pub(crate) fn py_hash_long_i64(n: i64) -> i64 { /// CPython `long_hash` for a big int. `BigInt %` is truncating, so it /// already carries the dividend's sign with magnitude `|n| mod P`. +/// `str(n)` of a big integer: its magnitude's 32-bit limbs folded, most +/// significant first, into base `10**9` digits, as CPython's +/// `long_to_decimal_string` does (a division by the constant `10**9` +/// compiles to a multiply, where num-bigint divides by `10**19` with the +/// 128-by-64-bit hardware division: 7,500 cycles to 2,900 for a 634-bit +/// value). The quadratic fold is kept to values of at most 8,192 bits; +/// larger ones take num-bigint's conversion. +pub(crate) fn bigint_decimal(b: &BigInt) -> String { + const BASE: u64 = 1_000_000_000; + let mag = b.magnitude(); + if mag.bits() > 8192 { + return b.to_string(); + } + let limbs: Vec = mag.iter_u32_digits().collect(); + // (Each 32-bit limb adds at most 1.07 base-10**9 digits.) + let mut out: Vec = Vec::with_capacity(limbs.len() + limbs.len() / 8 + 2); + for &d in limbs.iter().rev() { + let mut carry = u64::from(d); + for o in &mut out { + let z = (u64::from(*o) << 32) + carry; + *o = (z % BASE) as u32; + carry = z / BASE; + } + while carry != 0 { + out.push((carry % BASE) as u32); + carry /= BASE; + } + } + let mut s = String::with_capacity(out.len() * 9 + 1); + if b.sign() == num_bigint::Sign::Minus { + s.push('-'); + } + let Some((&top, rest)) = out.split_last() else { + s.push('0'); + return s; + }; + use std::fmt::Write as _; + let _ = write!(s, "{top}"); + let mut buf = [b'0'; 9]; + for &d in rest.iter().rev() { + let mut v = d; + for slot in buf.iter_mut().rev() { + *slot = b'0' + (v % 10) as u8; + v /= 10; + } + // SAFETY: ASCII digits. + s.push_str(unsafe { std::str::from_utf8_unchecked(&buf) }); + } + s +} + pub(crate) fn py_hash_long_bigint(value: &BigInt) -> i64 { - let modulus = BigInt::from((1u64 << PY_HASH_BITS) - 1); - let rem = value % &modulus; - let mut x = rem.to_i64().unwrap_or(0); + // `|value| mod P` (P = 2**61 - 1) folded over the magnitude's 64-bit + // limbs, most significant first, with shifts and adds instead of a + // big division: 2**64 is 8 (mod P), and a word's residue is its low + // 61 bits plus its top 3. The sign then applies as CPython's + // `long_hash` applies it. + const P: u64 = (1u64 << PY_HASH_BITS) - 1; + #[inline(always)] + fn reduce(v: u64) -> u64 { + let r = (v & P) + (v >> PY_HASH_BITS); + if r >= P { + r - P + } else { + r + } + } + let mut x: u64 = 0; + for d in value.magnitude().iter_u64_digits().rev() { + x = reduce(reduce(x << 3) + reduce(d)); + } + let mut x = x as i64; + if value.sign() == num_bigint::Sign::Minus { + x = -x; + } if x == -1 { x = -2; } @@ -14777,7 +16260,7 @@ fn sip_memo(bytes: &[u8], compute: impl FnOnce(&[u8]) -> i64) -> i64 { h } -fn py_hash_bytes_slice(bytes: &[u8]) -> i64 { +pub(crate) fn py_hash_bytes_slice(bytes: &[u8]) -> i64 { if bytes.is_empty() { return 0; } @@ -15167,18 +16650,21 @@ pub(crate) fn py_hash_value(obj: &Object) -> Option { } // Ints and strings (the usual composite key): their hashes can // neither fail nor run code, so no error scope is needed. - if items - .iter() - .all(|x| matches!(x, Object::Int(_) | Object::Str(_))) - { - let mut hash = TupleHasher::new(); - for item in items.iter() { - hash.push(match item { - Object::Int(i) => py_hash_long_i64(*i), - Object::Str(s) => SharedStr::hash_cached(s), - _ => unreachable!("matched above"), - }); - } + // (One pass: anything else ends it, and the general walk below + // starts over.) + let mut hash = TupleHasher::new(); + let mut plain = true; + for item in items.iter() { + hash.push(match item { + Object::Int(i) => py_hash_long_i64(*i), + Object::Str(s) => SharedStr::hash_cached(s), + _ => { + plain = false; + break; + } + }); + } + if plain { let hash = hash.finish(items.len()); items.store_hash(hash); return Some(hash); @@ -15285,6 +16771,29 @@ pub(crate) fn py_hash_value(obj: &Object) -> Option { { return Some(identity_hash(obj)); } + // An immutable value's subclass instance (a named tuple, a + // `str` or `int` subclass) hashed before: the same hash (its + // own `__hash__`'s, or its payload's, remembered below). + if native_is_immutable(inst.native.get()) { + if let Some(h) = inst.hash_cache.get() { + return Some(h); + } + } + // A Python `__hash__` that evaluates as a pure leaf (an `Enum` + // member's, a frozen dataclass's): in place, ahead of the native + // kinds below, none of which has one. (Recorded as the dispatch + // below records its result.) + if inst.native.get().is_none() { + if let Some(h) = current_interp_pure_hash(obj) { + inst.hash_cache.store(h); + return Some(h); + } + } + // A compiled pattern hashes natively (see + // `stdlib::sre_objects::native_hash`). + if let Some(h) = crate::stdlib::sre_objects::native_hash(inst) { + return Some(h); + } // An exact `decimal.Decimal` hashes natively (see // `stdlib::decimal_native`). if crate::stdlib::decimal_native::is_decimal_instance(inst) { @@ -15332,15 +16841,22 @@ pub(crate) fn py_hash_value(obj: &Object) -> Option { // (`DictKey::eq` / `dict_reentrant_probe`), CPython reads the // entry, never re-invoking `__hash__` — `test_dict`'s // `test_setdefault_atomic` counts exactly one call per key. - let h = current_interp_hash(obj); + // (A `__hash__` that evaluates as a pure leaf, an `Enum` + // member's, in place: the same value with no call.) + let h = current_interp_pure_hash(obj).or_else(|| current_interp_hash(obj)); if let Some(hv) = h { inst.hash_cache.store(hv); } return h; } if let Some(native) = inst.native.get() { - // int/str/… subclass instance hashes as the wrapped value. - return py_hash_value(native); + // int/str/… subclass instance hashes as the wrapped value + // (remembered for one that can't change). + let h = py_hash_value(native); + if let (Some(h), true) = (h, native_is_immutable(Some(native))) { + inst.hash_cache.store(h); + } + return h; } // Custom `__hash__` via the interpreter; `None` (no active // interpreter or only the inherited identity hash) falls through @@ -15637,7 +17153,10 @@ fn bytes_repr_inner(b: &[u8], smartquotes: bool) -> String { b'\r' => out.push_str("\\r"), b'\t' => out.push_str("\\t"), 0x20..=0x7E => out.push(c as char), - _ => out.push_str(&format!("\\x{c:02x}")), + _ => { + out.push_str("\\x"); + push_hex_byte(&mut out, c); + } } } out.push(quote as char); @@ -15805,8 +17324,59 @@ impl Object { Object::Str(rc) } + /// A `str` of a literal's text, shared per thread through a small + /// direct-mapped cache keyed by the literal's address and length: code + /// that builds keys from literals over and over (`os.stat`'s fields, + /// attribute names) gets the same hash-caching string back instead of + /// allocating and rehashing it. A collision just replaces the entry. pub fn from_static(s: &'static str) -> Self { - Object::Str(SharedStr::from(s)) + const SLOTS: usize = 1024; + type Slot = Option<((usize, usize), SharedStr)>; + /// A thread's table, which an exiting thread leaves to the next + /// (a literal's address and text are the process's, so an entry + /// holds on any thread) instead of building and dropping its own. + struct Statics(Option>); + static POOL: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + impl Drop for Statics { + fn drop(&mut self) { + if let (Some(t), Ok(mut pool)) = (self.0.take(), POOL.lock()) { + if pool.len() < 4 { + pool.push(t); + } + } + } + } + thread_local! { + // (Released under the GIL at its thread's exit: a table the + // pool has no room for drops its strings.) + static STATICS: crate::gil::ReleaseUnderGil> = + const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(Statics(None))) }; + } + if s.len() <= 2 { + return Object::Str(SharedStr::from(s)); + } + let key = (s.as_ptr() as usize, s.len()); + let ix = ((key.0 >> 3) ^ (key.0 >> 13) ^ key.1) & (SLOTS - 1); + let hit = STATICS.try_with(|t| { + let Ok(mut t) = t.try_borrow_mut() else { + return SharedStr::from(s); + }; + let table = t.0.get_or_insert_with(|| { + POOL.lock() + .ok() + .and_then(|mut p| p.pop()) + .unwrap_or_else(|| (0..SLOTS).map(|_| None).collect()) + }); + match &table[ix] { + Some((k, v)) if *k == key => v.clone(), + _ => { + let v = SharedStr::from(s); + table[ix] = Some((key, v.clone())); + v + } + } + }); + Object::Str(hit.unwrap_or_else(|_| SharedStr::from(s))) } pub fn new_list(items: Vec) -> Self { @@ -15819,9 +17389,12 @@ impl Object { // `functools.update_wrapper` asserts identity on copied // `__type_params__` and similar empty-tuple attributes. thread_local! { - static EMPTY_TUPLE: crate::object::SharedTuple = TupleStorage::from_array([]); + // (Released under the GIL at its thread's exit, as any + // other reference to it is.) + static EMPTY_TUPLE: crate::gil::ReleaseUnderGil = + crate::gil::ReleaseUnderGil::new(TupleStorage::from_array([])); } - return Object::Tuple(EMPTY_TUPLE.with(Clone::clone)); + return Object::Tuple(EMPTY_TUPLE.with(|t| crate::object::SharedTuple::clone(t))); } Object::Tuple(TupleStorage::from_vec(items)) } @@ -15835,6 +17408,25 @@ impl Object { Object::Tuple(TupleStorage::from_exact_iter(items)) } + /// A tuple of clones of the objects `items` yields (a gather from a + /// pool by index), each copied into its storage whole (the empty + /// tuple is the interned one). `items` yields exactly its length. + pub fn tuple_from_refs<'a>(items: impl ExactSizeIterator) -> Self { + if items.len() == 0 { + return Self::new_tuple(Vec::new()); + } + Object::Tuple(TupleStorage::from_cloned_refs(items)) + } + + /// A tuple of clones of `items`, copied into its storage in one pass + /// (the empty tuple is the interned one). + pub fn tuple_from_slice(items: &[Object]) -> Self { + if items.is_empty() { + return Self::new_tuple(Vec::new()); + } + Object::Tuple(TupleStorage::from_cloned_slice(items)) + } + /// Build a fixed-size tuple directly in reference-counted storage, /// avoiding an intermediate vector allocation. Empty arrays retain /// the ordinary constructor's interned empty tuple. @@ -15891,15 +17483,41 @@ impl Object { Object::FrozenSet(Rc::new(FrozenSetObj::new(s))) } - pub fn new_bytes(data: impl Into>) -> Self { - let v = data.into(); + /// A `bytes` of `data`, copied once into its own allocation (a slice + /// isn't gathered into a vector first). + pub fn new_bytes(data: impl AsRef<[u8]>) -> Self { + let v = data.as_ref(); if v.is_empty() { // CPython caches the empty bytes object (`b"" is b""` across // compiles — test_ast ConstantTests.test_singletons). static EMPTY: std::sync::OnceLock> = std::sync::OnceLock::new(); return Object::Bytes(EMPTY.get_or_init(|| SharedSlice::from(&[][..])).clone()); } - Object::Bytes(SharedSlice::from(v.as_slice())) + if let [b] = v { + // And each one-byte object (CPython's `characters` table: + // `bytes([97]) is b"a"`), made once. + static ONE: std::sync::OnceLock>> = std::sync::OnceLock::new(); + let table = + ONE.get_or_init(|| (0..=255u8).map(|b| SharedSlice::from(&[b][..])).collect()); + return Object::Bytes(table[usize::from(*b)].clone()); + } + Object::Bytes(SharedSlice::from(v)) + } + + /// The `bytes` of `head` followed by `tail`, each copied once into the + /// result's allocation. + pub fn bytes_concat(head: &[u8], tail: &[u8]) -> Self { + let len = head.len() + tail.len(); + if len == 0 { + return Self::new_bytes([]); + } + // SAFETY: the two copies initialize all `len` bytes. + Object::Bytes(unsafe { + SharedSlice::build_uninit(len, |dst| { + std::ptr::copy_nonoverlapping(head.as_ptr(), dst, head.len()); + std::ptr::copy_nonoverlapping(tail.as_ptr(), dst.add(head.len()), tail.len()); + }) + }) } pub fn new_bytearray(data: impl Into>) -> Self { @@ -16007,6 +17625,54 @@ impl Object { } } + /// `f` on this value's bytes where they are (a `bytes`, a `bytearray`, + /// a contiguous `memoryview`; any other view's are gathered first), or + /// `None` for any other type. The buffer is borrowed while `f` runs: + /// it must not run Python code or touch the buffer's owner. (A caller + /// that needs a few bytes of a large buffer shouldn't pay for a copy of + /// all of it, which is what [`Self::as_bytes_view`] makes.) + /// For a `memoryview`, CPython's errors for a buffer taken as one + /// contiguous run (`PyBUF_SIMPLE`, as `zlib` and `hashlib` take one): + /// a released view's `ValueError`, a strided view's `BufferError`. + /// `Ok` for anything else. + pub fn check_simple_buffer(&self) -> Result<(), crate::RuntimeError> { + if let Object::MemoryView(mv) = self { + if mv.released.get() { + return Err(crate::error::value_error( + "operation forbidden on released memoryview object", + )); + } + if !mv.is_c_contiguous() { + return Err(crate::error::buffer_error( + "memoryview: underlying buffer is not C-contiguous", + )); + } + } + Ok(()) + } + + pub fn with_bytes_view(&self, f: impl FnOnce(&[u8]) -> R) -> Option { + match self { + Object::Bytes(b) => Some(f(b)), + Object::ByteArray(b) => Some(f(&b.borrow())), + Object::MemoryView(mv) => Some(mv.with_bytes(f)), + _ => None, + } + } + + /// This value's bytes for a caller that only reads them: a `bytes` + /// object's own, borrowed; a copy of a `bytearray`'s or a + /// `memoryview`'s (which can change, or be borrowed, while the caller + /// works). `None` for any other type. + pub fn bytes_cow(&self) -> Option> { + match self { + Object::Bytes(b) => Some(std::borrow::Cow::Borrowed(&b[..])), + Object::ByteArray(b) => Some(std::borrow::Cow::Owned(b.borrow().clone())), + Object::MemoryView(mv) => Some(std::borrow::Cow::Owned(mv.to_bytes())), + _ => None, + } + } + /// Try to view this value as bytes (works for `bytes`, `bytearray`, /// and contiguous `memoryview`). Returns `None` for any other type. pub fn as_bytes_view(&self) -> Option> { @@ -16023,8 +17689,64 @@ impl Object { const _: () = assert!(std::mem::size_of::() == 16); const _: () = assert!(std::mem::size_of::>() == 16); +/// A container item's repr appended to `out`: an `int`, `bool` or `None` +/// written in place, anything else through its own [`Object::repr`]. +fn push_item_repr(out: &mut String, x: &Object) { + match x { + Object::Int(i) => { + let mut buf = [0u8; 20]; + let mut at = buf.len(); + let mut n = i.unsigned_abs(); + loop { + at -= 1; + buf[at] = b'0' + (n % 10) as u8; + n /= 10; + if n == 0 { + break; + } + } + if *i < 0 { + out.push('-'); + } + // SAFETY: the digits are ASCII. + out.push_str(unsafe { std::str::from_utf8_unchecked(&buf[at..]) }); + } + Object::Bool(b) => out.push_str(if *b { "True" } else { "False" }), + Object::None => out.push_str("None"), + // Printable ASCII with no quote or backslash: single-quoted as is. + Object::Str(t) + if t.as_bytes() + .iter() + .all(|&c| (0x20..0x7f).contains(&c) && c != b'\'' && c != b'\\') => + { + out.push('\''); + out.push_str(t); + out.push('\''); + } + _ => out.push_str(&x.repr()), + } +} + #[cfg(test)] mod tests { + #[test] + fn atomic_tags_are_gc_atomic() { + use super::{Object, ATOMIC_TAGS}; + let below = [ + Object::None, + Object::Bool(true), + Object::Int(1), + Object::Float(1.0), + Object::Long(crate::Rc::new(num_bigint::BigInt::from(1) << 80)), + Object::from_str("s"), + ]; + for o in &below { + assert!(o.tag() < ATOMIC_TAGS && o.is_gc_atomic()); + } + assert_eq!(Object::from_str("s").tag(), ATOMIC_TAGS - 2); + assert_eq!(Object::new_tuple(vec![Object::Int(1)]).tag(), ATOMIC_TAGS); + } + #[test] fn int_hash_folds_like_the_modulus() { let reference = |n: i64| -> i64 { diff --git a/crates/weavepy-vm/src/rare_events.rs b/crates/weavepy-vm/src/rare_events.rs index e4ce80898..5e46632d0 100644 --- a/crates/weavepy-vm/src/rare_events.rs +++ b/crates/weavepy-vm/src/rare_events.rs @@ -56,6 +56,24 @@ static COUNTERS: [AtomicU64; 5] = [ /// mutation targets with one relaxed load. static BUILTINS_DICT_ADDR: AtomicUsize = AtomicUsize::new(0); +/// Every assignment to a function's `__code__`, `__defaults__` or +/// `__kwdefaults__`, counted like `func_modification` but never reset (the +/// test probe's [`reset`] clears the counters above), so a cache can prove +/// that no function changed since it last checked its functions. +static FUNC_EDITS: AtomicU64 = AtomicU64::new(0); + +/// Count a function's code or defaults changing (see [`FUNC_EDITS`]). +#[inline] +pub fn note_func_edit() { + FUNC_EDITS.fetch_add(1, Ordering::Relaxed); +} + +/// How many times any function's code or defaults changed. +#[inline] +pub fn func_edits() -> u64 { + FUNC_EDITS.load(Ordering::Relaxed) +} + #[inline] pub fn bump(event: usize) { COUNTERS[event].fetch_add(1, Ordering::Relaxed); diff --git a/crates/weavepy-vm/src/rc.rs b/crates/weavepy-vm/src/rc.rs index f8957e073..d430e325a 100644 --- a/crates/weavepy-vm/src/rc.rs +++ b/crates/weavepy-vm/src/rc.rs @@ -2,21 +2,28 @@ //! //! [`Rc`] and [`Weak`] wrap [`std::sync::Arc`] and [`std::sync::Weak`] //! with the same API, but a strong-count increment or decrement is a plain -//! load and store instead of a locked read-modify-write while one thread -//! owns every object. That's the common case: a program that never starts a -//! second thread, running under the GIL. A `lock xadd` pair costs about four -//! times a plain pair on x86, and the interpreter performs roughly one pair -//! per bytecode, so atomics were a leading cost of every workload. +//! load and store instead of a locked read-modify-write while nothing +//! updates a count concurrently. That's the common case: a program that +//! never starts a second thread, and one whose threads all run under the +//! GIL. A `lock xadd` pair costs about four times a plain pair on x86, and +//! the interpreter performs roughly one pair per bytecode, so atomics were +//! a leading cost of every workload, and of everything a program did once +//! it had started a thread. //! -//! The bias is the one [`crate::sync`] already maintains for cell borrows: -//! it holds until a second thread registers to run VM code or free-threading -//! starts, and it's never restored. The registering thread revokes the bias -//! while holding the GIL; the previous owner released the GIL before that, -//! and reacquires it before touching another object, so every plain update -//! happens before the revocation and every later update is atomic. Threads -//! that touch objects without the GIL announce themselves with -//! [`crate::sync::mark_cells_shared`] before they begin, and code that -//! spawns a thread which will run VM code revokes the bias first (see +//! With one thread, that thread owns every count. With several, the GIL +//! orders their updates: a thread the VM starts takes the GIL before its +//! first touch of an object and keeps it through its thread-local +//! destructors, a blocking call's GIL-released bracket touches no object, +//! and a hand-off of the GIL is a synchronizing operation. Counts turn +//! atomic, under the GIL, as soon as something will touch one outside it +//! (see `gil_orders_counts` in [`crate::sync`]): free-threading, a thread +//! the VM didn't start, a watcher that reads state without the GIL (it +//! announces itself with [`crate::sync::mark_cells_shared`]), or a thread +//! whose outermost GIL scope ends while others run. The thread that flips +//! the flag holds the GIL, and every other thread acquires it before its +//! next update, so every plain update happens before the flip and every +//! later one is atomic. Code that spawns a thread which touches objects +//! before it takes the GIL makes counts atomic first (see //! [`revoke_refcount_bias`]). //! //! Deallocation always goes through `Arc`'s own drop, so the payload, @@ -239,6 +246,28 @@ pub(crate) unsafe fn try_release_shared(value: *const T) -> bool { unsafe { try_release_word(strong_word(value)) } } +/// Release an owner through the strong count `word` with a locked update, +/// unless it's the last one: `false`, with the count unchanged. The +/// release ordering is `Arc`'s for an owner that isn't the last. +/// +/// # Safety +/// +/// `word` is the strong count of a live `Arc` allocation the caller owns +/// a reference to; on `true` that reference is released. +#[inline] +pub(crate) unsafe fn release_unless_last(word: *const AtomicUsize) -> bool { + // SAFETY: per the caller. + let count = unsafe { &*word }; + let mut n = count.load(Ordering::Relaxed); + while n > 1 { + match count.compare_exchange_weak(n, n - 1, Ordering::Release, Ordering::Relaxed) { + Ok(_) => return true, + Err(now) => n = now, + } + } + false +} + /// Free the `Arc` allocation holding `value` when this is its last owner /// and no weak reference exists, with plain loads instead of `Arc`'s two /// locked decrements (strong, then the implicit weak). Only for payloads @@ -604,6 +633,12 @@ impl Rc { unsafe fn drop_last(&mut self) { // SAFETY: the caller's contract. unsafe { + // Without the bias, an owner that isn't the last gives its + // reference up with one locked update, as `Arc`'s drop would, + // without the last owner's checks below. + if !refcounts_biased() && release_unless_last(strong_word(Arc::as_ptr(&self.0))) { + return; + } // The last reference to an object that owes a finalizer moves // to the finalizer queue instead: the object stays alive, at // its address, until its `__del__` (or generator close) has @@ -614,9 +649,13 @@ impl Rc { return; } if nesting_kind::() { - // A list of scalars releases nothing through its items: - // they're forgotten, not dropped one call at a time, and - // the list frees without the trashcan. + // A list whose items all outlive it (scalars, and values + // other owners hold: a list of shared strings) releases them + // with plain decrements, not one drop call at a time, and + // frees without the trashcan. An item this release would + // free leaves it and the rest to the full release, the items + // released here already gone (none of them died, so the + // order of deaths is the full release's). if std::any::TypeId::of::() == std::any::TypeId::of::>>() && Arc::strong_count(&self.0) == 1 @@ -626,11 +665,28 @@ impl Rc { // The last strong reference: nothing else reads the // items while this release, which runs no code, does. let items = &mut *(*cell).as_ptr(); - if items.iter().all(|o| o.strong_word().is_none()) { - items.set_len(0); + // (Last item first, as CPython's `list_dealloc`, up to + // the first that would die: the usual list has none.) + let biased = refcounts_biased(); + let mut released = 0; + for o in items.iter().rev() { + match o.strong_word() { + None => {} + Some(word) if biased && plain_release(word) => {} + Some(_) => break, + } + released += 1; + } + let kept = items.len() - released; + // (Released: those slots leave the list.) + items.set_len(kept); + if kept == 0 { drop_arc_in(&mut self.0); return; } + // The rest go last first too: the vector's own drop + // releases front to back. + items.reverse(); } release_nested(LastOwner(ManuallyDrop::new(ManuallyDrop::take( &mut self.0, diff --git a/crates/weavepy-vm/src/seqiter.rs b/crates/weavepy-vm/src/seqiter.rs index f5a412d2b..2ebab8889 100644 --- a/crates/weavepy-vm/src/seqiter.rs +++ b/crates/weavepy-vm/src/seqiter.rs @@ -78,6 +78,16 @@ fn lazy(kind: LazyIterKind) -> Object { Object::LazyIter(Rc::new(PyLazyIter::new(kind))) } +/// `map(func, it)` over one iterator already made. +#[cfg(feature = "jit")] +pub(crate) fn lazy_map1(func: Object, it: Object) -> Object { + lazy(LazyIterKind::Map { + func, + iters: vec![it], + strict: false, + }) +} + /// `iter(obj)` for a constructor argument when it needs no interpreter: /// an iterator is its own iterator, and the native containers build /// theirs directly. `None` for anything that might run Python code. @@ -92,6 +102,24 @@ fn pure_iter(obj: &Object) -> Option { | Object::Set(_) | Object::FrozenSet(_) | Object::Bytes(_) => Some(Object::Iter(Rc::new(RefCell::new(obj.make_iter().ok()?)))), + // A list or tuple subclass inheriting `__iter__` (a named tuple's + // `_asdict`, `dict(zip(self._fields, self))`): its value's iterator, + // as `h_get_iter` makes it. + Object::Instance(inst) => { + let native @ (Object::List(_) | Object::Tuple(_)) = inst.native.get()? else { + return None; + }; + let cls = inst.cls_raw(); + if cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || !cls.dunder(crate::types::Dunder::Iter).builtin_owner() + { + return None; + } + Some(Object::Iter(Rc::new(RefCell::new( + native.make_iter().ok()?, + )))) + } _ => None, } } @@ -123,7 +151,18 @@ impl Interpreter { globals: &Rc>, ) -> Result, RuntimeError> { if let Object::Iter(c) = it { - return c.borrow_mut().next_value_checked(); + let mut cur = c.borrow_mut(); + // (A list's, tuple's or range's cursor with an item left: the + // item, in one view; the end and every other cursor, the full + // step.) + if let Some(v) = cur.pure_next() { + return Ok(Some(v)); + } + if let Some(v) = cur.pure_peek() { + cur.pure_skip(); + return Ok(Some(v)); + } + return cur.next_value_checked(); } self.iter_step(it, globals) } @@ -138,15 +177,90 @@ impl Interpreter { v: Object, globals: &Rc>, ) -> Result { - if let Some(r) = self.pure_callback(func, std::slice::from_ref(&v), true) { - self.release(v); - return Ok(r); + // (A Python function that can't run as a pure callback, one whose + // body calls something say, goes straight to its call.) + if pure_callback_maybe(func) { + if let Some(r) = self.pure_callback(func, std::slice::from_ref(&v), true) { + self.release(v); + return Ok(r); + } } + // (The arguments' vector comes from the scratch pool, which the + // bound call returns it to.) match func { - Object::Function(f) => return self.call_python_owned(f, vec![v], Vec::new()), + Object::Function(f) => { + let mut args = self.pooled_scratch(); + args.push(v); + return self.call_python_owned(f, args, Vec::new()); + } Object::BoundMethod(bm) if !bm.redispatch_descriptor => { if let Object::Function(f) = &bm.function { - return self.call_python_owned(f, vec![bm.receiver.clone(), v], Vec::new()); + let mut args = self.pooled_scratch(); + args.push(bm.receiver.clone()); + args.push(v); + return self.call_python_owned(f, args, Vec::new()); + } + } + // A placeholder-free `functools.partial` with no stored + // keywords (`map(partial(add, 3), xs)`): its function over the + // stored positionals and `v`, as its native `__call__` makes + // the call, without the bound `__call__` and its general call. + Object::Instance(inst) if Self::is_plain_partial(inst) => { + let parts = crate::stdlib::functools_mod::with_partial_call(inst, |f, args, kw| { + kw.is_empty().then(|| { + let mut all = Vec::with_capacity(args.len() + 1); + all.extend_from_slice(args); + (f.clone(), all) + }) + }); + if let Some((f, mut all)) = parts { + all.push(v); + if let Some(r) = self.pure_callback(&f, &all, true) { + return Ok(r); + } + return self.call(&f, &all, &[], globals); + } + } + // An `operator.methodcaller` whose method is a Python function + // of `v`'s plain class (`map(methodcaller('area'), shapes)`): + // that function over `v` and the stored arguments, as its + // native `__call__` calls it, frameless when a pure leaf. + Object::Instance(inst) if Self::is_methodcaller(inst) => { + if let Some((f, Object::Tuple(stored))) = + crate::stdlib::operator_accel::methodcaller_target(inst, &v) + { + let mut args = self.pooled_scratch(); + args.push(v); + args.extend(stored.iter().cloned()); + let fo = Object::Function(f.clone()); + if let Some(r) = self.pure_callback(&fo, &args, true) { + // (Released as the full call releases them.) + for a in args.drain(..).rev() { + self.release(a); + } + return Ok(r); + } + return self.call_python_owned(&f, args, Vec::new()); + } + } + // An instance whose class's `__call__` is a plain Python + // function (`map(adder, xs)`): that function over the instance + // and `v`, as a bound method's is called, with no bound + // `__call__` made for the general call. + Object::Instance(inst) => { + if let Some(f) = Self::instance_call_function(inst) { + // (A pure leaf `__call__` evaluates frameless.) + let fo = Object::Function(f.clone()); + let pair = [func.clone(), v]; + if let Some(r) = self.pure_callback(&fo, &pair, true) { + let [recv, v] = pair; + self.release(v); + drop(recv); + return Ok(r); + } + let mut args = self.pooled_scratch(); + args.extend(pair); + return self.call_python_owned(&f, args, Vec::new()); } } _ => {} @@ -158,6 +272,21 @@ impl Interpreter { r } + /// Whether calling `inst` is `operator.methodcaller`'s own native + /// `__call__` (its class is `methodcaller` or a subclass that keeps + /// it). + fn is_methodcaller(inst: &crate::types::PyInstance) -> bool { + // (The class's native `__call__`, remembered per class version.) + Self::instance_call_native(inst).is_some_and(|b| b.name == ".methodcaller.__call__") + } + + /// Whether calling `inst` is `functools.partial`'s own native + /// `__call__` (its class is `partial` or a subclass that keeps it). + fn is_plain_partial(inst: &crate::types::PyInstance) -> bool { + Self::instance_call_native(inst) + .is_some_and(|b| crate::stdlib::functools_mod::is_partial_call(&b)) + } + /// Drain a builtin adapter into `out` (`list(map(f, xs))`, `sorted`, /// `sum`, ...): `false` when `l` is another kind, nothing consumed. /// A `map` or `filter` over one source can't change its callback or @@ -168,9 +297,395 @@ impl Interpreter { out: &mut Vec, globals: &Rc>, ) -> Result { - if chain_drain(l, out) { + // `enumerate` over a generator (`list(enumerate(gen))`): the + // generator's items taken as `list(gen)` takes them (its yields + // folded straight into a vector rather than a resume each), then + // numbered. The count moves past every item taken, a raise + // included, as stepping it item by item moves it. + // SAFETY: a read that runs no code, ending with the match. + let gen_source = match unsafe { l.state.peek() } { + Some(LazyIterKind::Enumerate { + source: Object::Generator(g), + count, + count_big: None, + }) if *count <= i64::MAX >> 1 => Some((g.clone(), *count)), + _ => None, + }; + if let Some((g, start)) = gen_source { + let mut items = Vec::new(); + let r = match self.gen_fast_collect(&g, &mut items) { + Some(v) => { + drop(v); + Ok(()) + } + None => loop { + let sink = crate::FoldSink::Collect(std::ptr::from_mut(&mut items)); + match self.gen_drain_next(&g, Some(sink), false) { + Ok(Some(x)) => items.push(x), + Ok(None) => break Ok(()), + Err(e) => break Err(e), + } + }, + }; + // (A vector's length is below `i64::MAX >> 1`, so the count + // stays a machine int.) + let end = start + items.len() as i64; + // SAFETY: as above; nothing runs code while the count moves. + if let Some(LazyIterKind::Enumerate { count, .. }) = unsafe { l.state.peek_mut() } { + *count = end; + } + out.reserve(items.len()); + for (i, x) in (start..).zip(items) { + out.push(Object::new_tuple_array([Object::Int(i), x])); + } + return r.map(|()| true); + } + // (The adapter's kind read once, each bulk path tried only for its + // own.) + // SAFETY: a read that runs no code, ending with the match. + let (chain, accumulate, zip, grouper) = match unsafe { l.state.peek() } { + Some(LazyIterKind::Chain { .. }) => (true, false, false, false), + Some(LazyIterKind::Accumulate { .. }) => (false, true, false, false), + Some(LazyIterKind::Zip { .. }) => (false, false, true, false), + Some(LazyIterKind::Grouper { .. }) => (false, false, false, true), + _ => (false, false, false, false), + }; + // SAFETY: as above. + let islice = matches!( + unsafe { l.state.peek() }, + Some(LazyIterKind::Islice { + stop: Some(_), + done: false, + .. + }) + ); + if grouper && grouper_drain(l, out) { + return Ok(true); + } + if islice && islice_drain(l, out) { + return Ok(true); + } + // `zip` over generators (`list(zip(gen_a, gen_b))`): each row's + // items stepped from the sources in order, as the general step + // takes them, until the first source's end (the row's earlier items + // dropped, as CPython drops them). The adapter's own state stays as + // the general steps leave it: nothing is held between rows. + // SAFETY: a read that runs no code, ending with the match. + let zip_gens = match unsafe { l.state.peek() } { + Some(LazyIterKind::Zip { + iters, + strict: false, + held, + .. + }) if held.is_empty() + && (2..=8).contains(&iters.len()) + && iters.iter().any(|s| matches!(s, Object::Generator(_))) => + { + Some(iters.clone()) + } + _ => None, + }; + if let Some(srcs) = zip_gens { + loop { + let mut row = Vec::with_capacity(srcs.len()); + for src in &srcs { + match self.iter_step(src, globals) { + Ok(Some(v)) => row.push(v), + Ok(None) => return Ok(true), + Err(e) if is_stop_iteration(&e) => return Ok(true), + Err(e) => return Err(e), + } + } + out.push(Object::Tuple(crate::object::TupleStorage::from_vec(row))); + } + } + // `islice(gen, ...)`: the generator stepped item after item as the + // general step takes them (the skipped items first, then the stop + // bound, then the item), with the adapter's state read once and + // written back once (released source and all) at the end or a raise. + // SAFETY: a read that runs no code, ending with the match. + let islice_gen = match unsafe { l.state.peek() } { + Some(LazyIterKind::Islice { + source: Object::Generator(g), + next_idx, + pos, + stop, + step, + done: false, + }) => Some((g.clone(), *next_idx, *pos, *stop, *step)), + _ => None, + }; + if let Some((g, mut next_idx, mut pos, stop, step)) = islice_gen { + // (The loop ends only once the slice is done.) + let mut err = None; + 'items: loop { + while pos < next_idx { + match self.gen_step(&g) { + Ok(Some(skipped)) => { + drop(skipped); + pos += 1; + } + Ok(None) => break 'items, + Err(e) => { + err = Some(e); + break 'items; + } + } + } + if stop.is_some_and(|s| pos >= s) { + break; + } + match self.gen_step(&g) { + Ok(Some(item)) => { + out.push(item); + pos += 1; + next_idx = next_idx.saturating_add(step); + if let Some(s) = stop { + next_idx = next_idx.min(s); + } + } + Ok(None) => break, + Err(e) => { + err = Some(e); + break; + } + } + } + let released = if let LazyIterKind::Islice { + next_idx: ni, + pos: p, + done: d, + source, + .. + } = &mut *l.state.borrow_mut() + { + (*ni, *p, *d) = (next_idx, pos, true); + // (A finished slice releases its source, as CPython clears + // `lz->it`.) + Some(std::mem::replace(source, Object::None)) + } else { + None + }; + drop(released); + return match err { + Some(e) if !is_stop_iteration(&e) => Err(e), + _ => Ok(true), + }; + } + if chain { + // `chain(gen, ...)`: a generator source drained whole, its + // yields folded straight into `out` as `list(gen)` drains one, + // then the chain moved on as a source's end moves it; plain + // sources in bulk; anything else one general step at a time + // while a generator follows. A raise leaves the generator + // active, as stepping it would. + loop { + // SAFETY: a read that runs no code, ending with the match. + let g = match unsafe { l.state.peek() } { + Some(LazyIterKind::Chain { + active: Some(Object::Generator(g)), + .. + }) => g.clone(), + // `chain(map(f, xs), ...)`: a `map` or `filter` source + // drained whole, as `list(map(f, xs))` drains one, then + // the chain moved on as a source's end moves it. (Only + // those two kinds: their own sources are stepped, never + // drained in turn, so no chain is entered twice.) + Some(LazyIterKind::Chain { + active: Some(Object::LazyIter(inner)), + .. + }) if matches!( + // SAFETY: a read that runs no code. + unsafe { inner.state.peek() }, + Some(LazyIterKind::Map { .. } | LazyIterKind::Filter { .. }) + ) => + { + let inner = inner.clone(); + if !self.seq_drain(&inner, out, globals)? { + return Ok(false); + } + // SAFETY: a step that runs no code; the view ends + // with it. + if let Some(LazyIterKind::Chain { active, .. }) = + unsafe { l.state.peek_mut() } + { + if matches!(active, Some(Object::LazyIter(a)) if Rc::ptr_eq(a, &inner)) + { + let old = active.take(); + drop(old); + continue; + } + } + return Ok(false); + } + _ => { + if chain_drain(l, out) { + return Ok(true); + } + // The next source made active by one step. + match self.lazy_iter_step(l, globals)? { + Some(v) => out.push(v), + None => return Ok(true), + } + // SAFETY: as above. + match unsafe { l.state.peek() } { + Some(LazyIterKind::Chain { + active: Some(Object::Generator(_)), + .. + }) => continue, + // (A `map` or `filter` made active: the lane + // above drains it.) + Some(LazyIterKind::Chain { + active: Some(Object::LazyIter(inner)), + .. + }) if matches!( + // SAFETY: a read that runs no code. + unsafe { inner.state.peek() }, + Some(LazyIterKind::Map { .. } | LazyIterKind::Filter { .. }) + ) => + { + continue + } + _ => return Ok(false), + } + } + }; + match self.gen_fast_collect(&g, out) { + Some(v) => drop(v), + None => loop { + let sink = crate::FoldSink::Collect(std::ptr::from_mut(out)); + match self.gen_drain_next(&g, Some(sink), false)? { + Some(x) => out.push(x), + None => break, + } + }, + } + // SAFETY: a step that runs no code; the view ends with it. + if let Some(LazyIterKind::Chain { active, .. }) = unsafe { l.state.peek_mut() } { + if matches!(active, Some(Object::Generator(a)) if Rc::ptr_eq(a, &g)) { + let old = active.take(); + drop(old); + continue; + } + } + return Ok(false); + } + } + if accumulate { + if let Some(items) = accumulate_collect(l) { + out.extend(items); + return Ok(true); + } + } + if zip && zip_seq_bulk(l, out) { return Ok(true); } + // `map(f, xs, ys)` of a leaf builtin over two plain cursors + // (`map(max, a, b)`): its kind resolved once, each pair through its + // body in place while both cursors hold an item. The end (which + // may consume the first source's item), and a pair the body + // declines or raises on, go on through the general loop. + let pair_leaf = match &*l.state.borrow() { + LazyIterKind::Map { + func: Object::Builtin(b), + iters, + strict, + .. + } => match iters.as_slice() { + [first @ Object::Iter(x), Object::Iter(y)] if !Rc::ptr_eq(x, y) => self + .leaf_call_kind(b) + .map(|k| (b.clone(), k, x.clone(), y.clone(), first.clone(), *strict)), + _ => None, + }, + _ => None, + }; + if let Some((b, kind, x, y, first, strict)) = pair_leaf { + loop { + let args = match cursor_pair_next(&x, &y) { + Some((a, c)) => [a, c], + // (A `str`'s or `bytes`' cursor, peeked then stepped.) + None => match (cursor_peek(&x), cursor_peek(&y)) { + (Some(a), Some(c)) + if cursor_advance(&x).is_some() && cursor_advance(&y).is_some() => + { + [a, c] + } + _ => break, + }, + }; + let r = match self.leaf_builtin_call(kind, &b, &args) { + Some(Ok(r)) => { + let [a, c] = args; + self.release_item(a); + self.release_item(c); + Ok(r) + } + // (Both items are taken: the full call answers them.) + _ => self.call(&Object::Builtin(b.clone()), &args, &[], globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) if is_stop_iteration(&e) => return Ok(true), + Err(e) => return Err(e), + } + } + // (The first source's end, a plain cursor's, ends a map that + // isn't strict, as `zip`'s does: see `lazy_stops_quietly`.) + return Ok(!strict && cursor_at_end(&first)); + } + // `map(f, xs, ys)` of a Python leaf function over two plain cursors + // (`map(lambda a, b: a * b, xs, ys)`), as the builtin's lane above + // runs: each pair through the leaf in place (its native code, once + // warm), a pair it declines through the full call. + let pair_fn = match &*l.state.borrow() { + LazyIterKind::Map { + func: func @ Object::Function(_), + iters, + strict, + .. + } if pure_callback_maybe(func) => match iters.as_slice() { + [first @ Object::Iter(x), Object::Iter(y)] if !Rc::ptr_eq(x, y) => { + Some((func.clone(), x.clone(), y.clone(), first.clone(), *strict)) + } + _ => None, + }, + _ => None, + }; + if let Some((func, x, y, first, strict)) = pair_fn { + if let Some(n) = x.try_borrow().ok().and_then(|c| c.remaining()) { + out.reserve(n); + } + loop { + let args = match cursor_pair_next(&x, &y) { + Some((a, c)) => [a, c], + // (A `str`'s or `bytes`' cursor, peeked then stepped.) + None => match (cursor_peek(&x), cursor_peek(&y)) { + (Some(a), Some(c)) + if cursor_advance(&x).is_some() && cursor_advance(&y).is_some() => + { + [a, c] + } + _ => break, + }, + }; + let r = match self.pure_callback_fn(&func, &args, true) { + Some(r) => { + let [a, c] = args; + self.release_item(a); + self.release_item(c); + Ok(r) + } + // (Both items are taken: the full call answers them.) + None => self.call(&func, &args, &[], globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) if is_stop_iteration(&e) => return Ok(true), + Err(e) => return Err(e), + } + } + return Ok(!strict && cursor_at_end(&first)); + } let (func, source, filter) = match &*l.state.borrow() { LazyIterKind::Map { func, iters, .. } if iters.len() == 1 => { (func.clone(), iters[0].clone(), false) @@ -197,6 +712,50 @@ impl Interpreter { } }; if filter { + if filter_seq_bulk(&func, &source, out) { + return Ok(true); + } + // A leaf builtin predicate (`filter(str.isalpha, words)`), its + // kind resolved once: each item through its body in place, as + // the `map` lane below runs one; an item it declines or raises + // on takes the full call. The item is taken first, so the + // result's full truth test may run code. + let leaf = match &func { + Object::Builtin(b) => self.leaf_call_kind(b).map(|k| (b.clone(), k)), + _ => None, + }; + if let Some((b, kind)) = leaf { + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + let r = match self.leaf_builtin_call(kind, &b, std::slice::from_ref(&v)) { + Some(Ok(r)) => r, + _ => match self.seq_call1(&func, v.clone(), globals) { + Ok(r) => r, + Err(e) => return stop(e), + }, + }; + let keep = match scalar_truth(&r) { + Some(t) => t, + None => { + let t = self.obj_truthy(&r, globals); + self.release(r); + match t { + Ok(t) => t, + Err(e) => return stop(e), + } + } + }; + if keep { + out.push(v); + } else { + self.release(v); + } + } + } loop { match self.filter_next(&func, &source, globals) { Ok(Some(v)) => out.push(v), @@ -205,72 +764,491 @@ impl Interpreter { } } } - loop { - let v = match self.seq_step_source(&source, globals) { - Ok(Some(v)) => v, - Ok(None) => return Ok(true), - Err(e) => return stop(e), - }; - match self.seq_call1(&func, v, globals) { - Ok(r) => out.push(r), - Err(e) => return stop(e), + // `map(d.__getitem__, xs)` of a dict or a dict subclass's + // (`urllib.parse.quote`'s byte quoter): each item found in the + // table by the native probe, as `dict.__getitem__`'s leaf half finds + // it; an item that misses (a subclass's `__missing__` may serve it) + // or that the probe can't key takes the full call. + let table = match &func { + Object::BoundMethod(bm) if !bm.redispatch_descriptor => match &bm.function { + Object::Builtin(b) + if matches!(self.leaf_call_kind(b), Some(LeafKind::Fast(f)) + if f as usize + == crate::builtins::dict_getitem_leaf as crate::leaf_builtins::Fast as usize) => + { + crate::builtins::leaf_dict_of(&bm.receiver).cloned() + } + _ => None, + }, + _ => None, + }; + if let Some(d) = table { + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + let hit = crate::object::LeafProbe::new(&v) + .and_then(|p| d.try_borrow().ok()?.get(&p).cloned()); + match hit { + Some(r) => { + self.release_item(v); + out.push(r); + } + None => match self.seq_call1(&func, v, globals) { + Ok(r) => out.push(r), + Err(e) => return stop(e), + }, + } } } - } - - /// An exact `map`/`filter`/`zip` built from positional arguments - /// without the interpreter (the core loop's `CALL`): `None` when an - /// argument needs `iter()` to run code, or the call would raise. - pub(crate) fn seq_new_pure(ty: SeqType, args: &[Object]) -> Option { - Some(match ty { - SeqType::Map => { - let (func, sources) = args.split_first()?; - if sources.is_empty() { - return None; + // A callback that reads one part of each item + // (`map(itemgetter(1), pairs)`, `map(attrgetter("x"), objs)`, a + // lambda doing either), its shape read once: each item's part, + // read with no call; an item whose part the read doesn't settle + // takes the full call. + let part = part_key(&func); + if let Some(shape @ (crate::PartShape::Index(_) | crate::PartShape::Key(_))) = &part { + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + let r = match crate::part_value(shape, &v) { + Some(r) => { + self.release(v); + Ok(r) + } + None => self.seq_call1(&func, v, globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) => return stop(e), } - let iters = sources.iter().map(pure_iter).collect::>>()?; - lazy(LazyIterKind::Map { - func: func.clone(), - iters, - strict: false, - }) } - SeqType::Filter => { - let [func, source] = args else { - return None; + } + if let Some(shape) = part { + // An attribute's place among the shared names of the last + // item's class, under that class's version (see + // `attr_field_place`): a run of one class's instances reads + // the value there, with no lookup of the name. + let mut place: Option<(Rc, u64, usize)> = None; + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), }; - lazy(LazyIterKind::Filter { - func: func.clone(), - source: pure_iter(source)?, - }) + let placed = match (&v, &place) { + (Object::Instance(i), Some((cls, ver, idx))) + if std::ptr::eq(i.cls_raw(), Rc::as_ptr(cls)) + && cls.attr_version.get() == *ver + && i.native.get().is_none() => + { + // SAFETY: a read that runs no code, the value + // cloned out at once. + unsafe { i.split_field(*idx) }.cloned() + } + _ => None, + }; + let r = match placed.or_else(|| crate::part_value(&shape, &v)) { + Some(r) => { + if placed_miss(place.as_ref(), &v) { + if let crate::PartShape::Attr(Object::Str(name)) = &shape { + place = attr_field_place(&v, name); + } + } + self.release(v); + Ok(r) + } + None => self.seq_call1(&func, v, globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) => return stop(e), + } } - SeqType::Zip => { - let iters = args.iter().map(pure_iter).collect::>>()?; - lazy(LazyIterKind::Zip { - iters, - strict: false, - result: None, - held: Vec::new(), - }) + } + // An `operator.methodcaller` with no stored keywords, its name + // and arguments read once: each plain instance's method, a + // Python function, called with the instance first (frameless + // when a pure leaf), as `seq_call1` calls it. The function is + // remembered for the last item's class and that class's version, + // so a run of one class's instances looks it up once. + let caller = match &func { + Object::Instance(inst) if Self::is_methodcaller(inst) => { + match crate::stdlib::operator_accel::methodcaller_parts(inst) { + Some((Object::Str(name), Object::Tuple(stored))) => Some((name, stored)), + _ => None, + } } - }) - } - - /// The `strict=` keyword of `map`/`zip` (`|$p` in CPython: truth of - /// the value); any other keyword is rejected. - fn seq_strict_kw( - &mut self, - ty: SeqType, - kwargs: &[(String, Object)], - globals: &Rc>, - ) -> Result { - let mut strict = false; - for (k, v) in kwargs { - if k != "strict" { - return Err(type_error(format!( - "{}() got an unexpected keyword argument '{k}'", - ty.name() - ))); + _ => None, + }; + if let Some((name, stored)) = caller { + let mut last: Option<(Rc, u64, Rc)> = None; + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + let method = match &v { + Object::Instance(i) => match &last { + // (The class's checks stand with its version; + // the instance's own are made again.) + Some((cls, ver, f)) + if std::ptr::eq(i.cls_raw(), Rc::as_ptr(cls)) + && cls.attr_version.get() == *ver + && i.native.get().is_none() + && i.c_body.get() == 0 + && i.attr_get_str(&name).is_none() => + { + Some(f.clone()) + } + _ => { + let f = Interpreter::plain_instance_method_named(&v, &name); + if let Some(f) = &f { + let cls = i.cls(); + let ver = cls.attr_version.get(); + last = Some((cls, ver, f.clone())); + } + f + } + }, + _ => None, + }; + let r = match method { + Some(f) => { + let mut args = self.pooled_scratch(); + args.push(v); + args.extend(stored.iter().cloned()); + match self.call_pure_leaf(&f, &args) { + Some(r) => { + // (Released as the full call releases them.) + for a in args.drain(..).rev() { + self.release(a); + } + Ok(r) + } + None => self.call_python_owned(&f, args, Vec::new()), + } + } + None => self.seq_call1(&func, v, globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) => return stop(e), + } + } + } + // A placeholder-free `partial` with no stored keywords, resolved + // once (its function and stored arguments are read-only): each + // item is its function's last argument (see `seq_call1`). + let partial = match &func { + Object::Instance(inst) if Self::is_plain_partial(inst) => { + crate::stdlib::functools_mod::with_partial_call(inst, |f, args, kw| { + kw.is_empty().then(|| (f.clone(), args.to_vec())) + }) + } + _ => None, + }; + if let Some((f, stored)) = partial { + let mut all = stored; + let at = all.len(); + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + all.truncate(at); + all.push(v); + let r = match self.pure_callback(&f, &all, true) { + Some(r) => Ok(r), + None => self.call(&f, &all, &[], globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) => return stop(e), + } + } + } + // A leaf builtin callback (`map(str.upper, words)`, `map(abs, xs)`), + // its kind resolved once: each item through its body in place; one + // it declines or raises on takes the full call (a leaf runs no + // code, so nothing is observed twice). + let leaf = match &func { + Object::Builtin(b) => self.leaf_call_kind(b).map(|k| (b.clone(), k)), + _ => None, + }; + if let Some((b, kind)) = leaf { + // (A list's, tuple's or range's own cursor, `map(len, words)`: + // each item stepped off it in place, with no checked borrow; + // its end, the loop's below.) + if let Object::Iter(c) = &source { + loop { + // SAFETY: a step that runs no code, ending here. + let Some(v) = (unsafe { c.peek_mut() }).and_then(PyIterator::pure_next) else { + break; + }; + let r = match self.leaf_builtin_call(kind, &b, std::slice::from_ref(&v)) { + Some(Ok(r)) => { + self.release(v); + Ok(r) + } + _ => self.seq_call1(&func, v, globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) => return stop(e), + } + } + } + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + let r = match self.leaf_builtin_call(kind, &b, std::slice::from_ref(&v)) { + Some(Ok(r)) => { + self.release(v); + Ok(r) + } + _ => self.seq_call1(&func, v, globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) => return stop(e), + } + } + } + // A leaf method's fast half bound to an instance of a built-in + // subclass (`map(_Quoter(safe).__getitem__, bs)` in + // `urllib.parse.quote`), resolved once: each item through it, on + // views of the receiver and the item; one it declines takes the + // full call. + let bound_fast = match &func { + Object::BoundMethod(bm) + if !bm.redispatch_descriptor && matches!(bm.receiver, Object::Instance(_)) => + { + match &bm.function { + Object::Builtin(b) if b.binds_instance => match self.leaf_call_kind(b) { + Some(LeafKind::Fast(f)) => Some((f, bm.receiver.clone())), + _ => None, + }, + _ => None, + } + } + _ => None, + }; + if let Some((fast, recv)) = bound_fast { + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + // SAFETY: bitwise views of the live receiver and item, never + // dropped (the fast half clones what it keeps). + let views = std::mem::ManuallyDrop::new(unsafe { + [ + std::ptr::read(&raw const recv), + std::ptr::read(&raw const v), + ] + }); + let r = match fast(&views[..]) { + Some(Ok(r)) => { + self.release(v); + Ok(r) + } + _ => self.seq_call1(&func, v, globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) => return stop(e), + } + } + } + // An instance whose class's native `__call__` has a fast half + // (`map(itemgetter(0), pairs)`), resolved once: each item through + // it with the instance first, on views; one it declines takes the + // full call. + let inst_fast = match &func { + Object::Instance(inst) => { + Self::instance_call_native(inst).and_then(|b| match self.leaf_call_kind(&b) { + Some(LeafKind::Fast(f)) => Some(f), + _ => None, + }) + } + _ => None, + }; + if let Some(fast) = inst_fast { + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + // SAFETY: bitwise views of the live instance and item, never + // dropped (the fast half clones what it keeps). + let views = std::mem::ManuallyDrop::new(unsafe { + [ + std::ptr::read(&raw const func), + std::ptr::read(&raw const v), + ] + }); + let r = match fast(&views[..]) { + Some(Ok(r)) => { + self.release(v); + Ok(r) + } + _ => self.seq_call1(&func, v, globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) => return stop(e), + } + } + } + // A Python function (`list(map(f, xs))`): each item straight + // through a warm leaf's native code; an item it declines takes + // the full call, and a function that isn't such a leaf (now, or + // any more) the general callback's lanes. + #[cfg(feature = "jit")] + if let Object::Function(f) = &func { + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + let r = match self.leaf_fast_call(f, None, std::slice::from_ref(&v), true) { + Some(Some(r)) => { + self.release_item(v); + Ok(r) + } + Some(None) => { + let mut args = self.pooled_scratch(); + args.push(v); + self.call_python_owned(f, args, Vec::new()) + } + None => self.seq_call1(&func, v, globals), + }; + match r { + Ok(r) => out.push(r), + Err(e) => return stop(e), + } + } + } + loop { + let v = match self.seq_step_source(&source, globals) { + Ok(Some(v)) => v, + Ok(None) => return Ok(true), + Err(e) => return stop(e), + }; + match self.seq_call1(&func, v, globals) { + Ok(r) => out.push(r), + Err(e) => return stop(e), + } + } + } + + /// An exact `map`/`filter`/`zip` built from positional arguments + /// without the interpreter (the core loop's `CALL`): `None` when an + /// argument needs `iter()` to run code, or the call would raise. + pub(crate) fn seq_new_pure(ty: SeqType, args: &[Object]) -> Option { + Self::seq_new_pure_strict(ty, args, false) + } + + /// `zip(*its, strict=True)` and `map(f, *its, strict=True)` of a plain + /// `bool` flag (compiled `CALL_KW`'s operands: the type, the empty self + /// slot, the positionals, the flag, the names tuple), built as + /// [`Self::seq_new_pure`] builds the positional call. `None` for any + /// other shape. + #[cfg(feature = "jit")] + pub(crate) fn seq_new_strict_kw(ops: &[Object], argc: usize) -> Option { + let bt = builtin_types(); + let (Object::Type(t), Object::Unbound, Some(Object::Tuple(names))) = + (ops.first()?, ops.get(1)?, ops.last()) + else { + return None; + }; + let ty = if Rc::ptr_eq(t, &bt.zip_) { + SeqType::Zip + } else if Rc::ptr_eq(t, &bt.map_) { + SeqType::Map + } else { + return None; + }; + if ops.len() != argc + 4 + || !matches!(&names[..], [Object::Str(n)] if n.as_ref() == "strict") + { + return None; + } + let Object::Bool(strict) = ops[2 + argc] else { + return None; + }; + if !Self::core_all_droppable(ops) { + return None; + } + Self::seq_new_pure_strict(ty, &ops[2..2 + argc], strict) + } + + fn seq_new_pure_strict(ty: SeqType, args: &[Object], strict: bool) -> Option { + Some(match ty { + SeqType::Map => { + let (func, sources) = args.split_first()?; + if sources.is_empty() { + return None; + } + let iters = sources.iter().map(pure_iter).collect::>>()?; + lazy(LazyIterKind::Map { + func: func.clone(), + iters, + strict, + }) + } + SeqType::Filter => { + let [func, source] = args else { + return None; + }; + lazy(LazyIterKind::Filter { + func: func.clone(), + source: pure_iter(source)?, + }) + } + SeqType::Zip => { + let iters = args.iter().map(pure_iter).collect::>>()?; + lazy(LazyIterKind::Zip { + iters, + strict, + result: None, + spare: None, + held: Vec::new(), + distinct: None, + }) + } + }) + } + + /// The `strict=` keyword of `map`/`zip` (`|$p` in CPython: truth of + /// the value); any other keyword is rejected. + fn seq_strict_kw( + &mut self, + ty: SeqType, + kwargs: &[(String, Object)], + globals: &Rc>, + ) -> Result { + let mut strict = false; + for (k, v) in kwargs { + if k != "strict" { + return Err(type_error(format!( + "{}() got an unexpected keyword argument '{k}'", + ty.name() + ))); } strict = self.obj_truthy(v, globals)?; } @@ -339,7 +1317,9 @@ impl Interpreter { iters, strict, result: None, + spare: None, held: Vec::new(), + distinct: None, })) } } @@ -447,6 +1427,41 @@ impl Interpreter { }) } + /// The pairs of a non-strict two-source `zip` (`dict(zip(ks, vs))`), + /// stepped as the zip steps them: the first source, then the second, + /// until either ends (an item the first gave is dropped when the second + /// has none, as the zip drops it). `None`, nothing stepped, for any + /// other iterable. + pub(crate) fn zip2_pairs( + &mut self, + it: &Object, + globals: &Rc>, + ) -> Option, RuntimeError>> { + let Object::LazyIter(l) = it else { + return None; + }; + let (a, b) = match &*l.state.try_borrow().ok()? { + LazyIterKind::Zip { + iters, + strict: false, + held, + .. + } if held.is_empty() && iters.len() == 2 => (iters[0].clone(), iters[1].clone()), + _ => return None, + }; + let mut out = Vec::new(); + Some((|| loop { + let Some(x) = self.seq_step_source(&a, globals)? else { + return Ok(out); + }; + let Some(y) = self.seq_step_source(&b, globals)? else { + self.release(x); + return Ok(out); + }; + out.push((x, y)); + })()) + } + /// The `(index, value)` pair for `v`, advancing a lazy enumerate's /// counter (CPython counts only produced items). fn enumerate_advance(l: &PyLazyIter, v: Object) -> Object { @@ -562,6 +1577,29 @@ impl Interpreter { Object::Type(t) => Rc::ptr_eq(t, &builtin_types().bool_), _ => false, }; + // A plain sequence cursor's items whose truth is plain data, stepped + // in place: anything else (an item whose `__bool__` could run code, + // the end) is the general step's, from where this one stopped. + if check_true { + if let Object::Iter(it) = source { + // SAFETY: nothing below runs code while the view lives (a + // falsy item dropped here is a scalar or a `str`). + if let Some(cursor) = unsafe { it.peek_mut() } { + while let Some(item) = cursor.pure_peek() { + match scalar_truth(&item) { + Some(true) => { + cursor.pure_skip(); + return Ok(Some(item)); + } + Some(false) => { + cursor.pure_skip(); + } + None => break, + } + } + } + } + } loop { let Some(item) = self.seq_step_source(source, globals)? else { return Ok(None); @@ -806,6 +1844,54 @@ pub(crate) fn install(bt: &BuiltinTypes) { ); } } + // `callable_iterator`: no constructor (CPython's has no `tp_new`). + let ci = &bt.callable_iterator_; + put( + ci, + "__new__", + Object::Builtin(Rc::new(BuiltinFn { + name: "__new__", + binds_instance: false, + call: Box::new(|_| Err(type_error("cannot create 'callable_iterator' instances"))), + call_kw: None, + })), + ); + put(ci, "__iter__", method("__iter__", seq_iter)); + put(ci, "__next__", method("__next__", seq_next)); + put(ci, "__reduce__", method("__reduce__", calliter_reduce)); +} + +/// `iter(callable, sentinel)`: a `callable_iterator` (the caller checked +/// that `callable` is one). +pub(crate) fn callable_iter(callable: Object, sentinel: Object) -> Object { + lazy(LazyIterKind::CallIter { + pair: Some((callable, sentinel)), + }) +} + +/// `callable_iterator.__reduce__`: `(iter, (callable, sentinel))`, or +/// `(iter, ((),))` once exhausted (CPython's `calliter_reduce`, which +/// looks `iter` up first: the lookup may run code that exhausts it). +fn calliter_reduce(args: &[Object]) -> Result { + let Some(Object::LazyIter(l)) = args.first() else { + return Err(type_error( + "descriptor '__reduce__' requires a 'callable_iterator'", + )); + }; + let iter = interp()?.reduce_builtin("iter")?; + let pair = match &*l.state.borrow() { + LazyIterKind::CallIter { pair } => pair.clone(), + _ => { + return Err(type_error( + "descriptor '__reduce__' requires a 'callable_iterator'", + )) + } + }; + let args = match pair { + Some((callable, sentinel)) => Object::new_tuple_array([callable, sentinel]), + None => Object::new_tuple_array([Object::new_tuple_array([])]), + }; + Ok(Object::new_tuple_array([iter, args])) } /// `enumerate`'s `(iterable, start=0)` from a call's arguments, with @@ -862,6 +1948,22 @@ fn lazy_enumerate_reduce(args: &[Object]) -> Result { /// The methods a native adapter answers itself, ahead of its type's /// dict: the iterator protocol of a lazy `enumerate` (whose type's /// methods step `Object::Iter`s) and of a classless `itertools` core. +/// Whether every attribute load off `l` resolves through its type (no +/// [`lazy_special_method`] stands in for the type's `__next__`): an exact +/// `itertools` object, or a `map`, `filter` or `zip`. +pub(crate) fn lazy_methods_from_type(l: &PyLazyIter) -> bool { + l.cls.is_some() + || matches!( + l.state.try_borrow().as_deref(), + Ok(LazyIterKind::CallIter { .. }) + ) + || (l.is_builtin_kind() + && !matches!( + l.state.try_borrow().as_deref(), + Ok(LazyIterKind::Enumerate { .. }) + )) +} + pub(crate) fn lazy_special_method(l: &PyLazyIter, name: &str) -> Option { if l.cls.is_some() { return None; @@ -870,7 +1972,9 @@ pub(crate) fn lazy_special_method(l: &PyLazyIter, name: &str) -> Option l.state.try_borrow().as_deref(), Ok(LazyIterKind::Enumerate { .. }) ); - if !is_enumerate && l.is_builtin_kind() { + // (An exact `map`, `filter` or `zip`, and a `callable_iterator`, + // answer through their types.) + if lazy_methods_from_type(l) { return None; } match name { @@ -900,12 +2004,121 @@ fn src_ready(it: &Object, leaf: bool) -> bool { step: Object::Int(b), } => a.checked_add(*b).is_some(), LazyIterKind::Repeat { times, .. } => times.is_none_or(|t| t > 0), + // A `chain` whose current source is a plain cursor with an + // item left (`islice(chain(xs, ys), n)`), for one-source + // adapters only: a `zip` could hold that cursor as another + // source, and the chain's step would exhaust it for that one. + // (A cursor, never another adapter: a chain may come to step + // itself.) + LazyIterKind::Chain { source, active } => { + !leaf && chain_pure_ready(source.as_ref(), active.as_ref()) + } + // A `cycle` over a plain cursor with an item left, or replaying + // the items it saved (`islice(cycle(xs), n)`), for one-source + // adapters only, as for `chain` (a cursor, never another + // adapter, as its source). + LazyIterKind::Cycle { source, saved, .. } => { + !leaf + && match source { + Some(src @ Object::Iter(_)) => src_ready(src, false), + Some(_) => false, + // SAFETY: as above (a distinct cell). + None => unsafe { saved.peek() }.is_some_and(|b| !b.is_empty()), + } + } _ => false, }), _ => false, } } +/// Whether [`chain_pure_next`] has an item for `chain`'s state. +fn chain_pure_ready(source: Option<&Object>, active: Option<&Object>) -> bool { + match active { + Some(a @ Object::Iter(_)) if src_ready(a, false) => true, + // (A cursor, never another adapter: a chain may come to step + // itself.) + Some(a) if !spent_cursor_droppable(a) => false, + _ => chain_next_source(source).is_some(), + } +} + +/// `chain`'s next item where no code runs: the current source's, a plain +/// cursor's; or, that one spent (or none begun), the first item of the +/// next source, an exact list or tuple with items that a plain cursor +/// over the sources holds next. `None`, touching nothing, otherwise. +/// (Releasing a spent cursor frees nothing: its sequence is held +/// elsewhere.) +fn chain_pure_next(source: &mut Option, active: &mut Option) -> Option { + // The common step: the active source a plain cursor with an item. + if let Some(Object::Iter(c)) = active.as_ref() { + // SAFETY: a step that runs no code; the view ends with it. + if let Some(v) = unsafe { c.peek_mut() }.and_then(PyIterator::pure_next) { + return Some(v); + } + } + if let Some(a) = active.as_ref() { + if let Object::Iter(c) = a { + if let Some(v) = cursor_peek(c) { + cursor_advance(c)?; + return Some(v); + } + } + if !spent_cursor_droppable(a) { + return None; + } + } + let (sources, next) = chain_next_source(source.as_ref())?; + let it = Rc::new(RefCell::new(next.make_iter().ok()?)); + let v = cursor_peek(&it)?; + cursor_advance(&it)?; + cursor_advance(sources)?; + let old = active.replace(Object::Iter(it)); + drop(old); + Some(v) +} + +/// The cursor over `chain`'s sources and its next one, where that is an +/// exact list or tuple with items. +fn chain_next_source(source: Option<&Object>) -> Option<(&Rc>, Object)> { + let Some(Object::Iter(sources)) = source else { + return None; + }; + let next = cursor_peek(sources)?; + let nonempty = match &next { + // SAFETY: a read that runs no code. + Object::List(l) => unsafe { l.peek() }.is_some_and(|v| !v.is_empty()), + Object::Tuple(t) => !t.is_empty(), + _ => false, + }; + nonempty.then_some((sources, next)) +} + +/// Whether `a`, `chain`'s current source, is a spent plain cursor whose +/// release frees nothing (its sequence, if any, held elsewhere too). +fn spent_cursor_droppable(a: &Object) -> bool { + let Object::Iter(c) = a else { + return false; + }; + // SAFETY: a read that runs no code. + let Some(cur) = (unsafe { c.peek() }) else { + return false; + }; + if cur.pure_ready() { + return false; + } + match cur { + PyIterator::List { + items, owner: None, .. + } => Rc::strong_count(c) > 1 || Rc::strong_count(items) > 1, + PyIterator::Tuple { items, .. } => { + Rc::strong_count(c) > 1 || crate::object::SharedTuple::strong_count(items) > 1 + } + PyIterator::Range { .. } | PyIterator::Str { .. } => true, + _ => false, + } +} + /// The next item of a source [`src_ready`] admitted. fn src_step(it: &Object) -> Option { match it { @@ -918,30 +2131,47 @@ fn src_step(it: &Object) -> Option { /// Whether every source of a several-source adapter can step purely and /// none is another's alias (which one step could exhaust for the next). -fn srcs_ready(iters: &[Object]) -> bool { +fn srcs_ready(iters: &[Object], distinct: &mut Option) -> bool { iters.iter().all(|it| src_ready(it, true)) - && iters.iter().enumerate().all(|(i, a)| { - iters[..i].iter().all(|b| match (a, b) { - (Object::Iter(a), Object::Iter(b)) => !Rc::ptr_eq(a, b), - (Object::LazyIter(a), Object::LazyIter(b)) => !Rc::ptr_eq(a, b), - _ => true, - }) - }) + && *distinct.get_or_insert_with(|| srcs_distinct(iters)) } -/// One step of a native adapter that runs no code (the core loop's -/// `FOR_ITER`): `None` when the step needs the interpreter, nothing -/// having been consumed. Every source must have an item left, so the -/// step neither stops partway through the sources nor releases a -/// source's container (which could queue a finalizer). +/// Whether no two of `iters` are the same iterator. (Sorted addresses for +/// more than a few: `zip(*rows)` has a source per row.) +fn srcs_distinct(iters: &[Object]) -> bool { + let addr = |it: &Object| match it { + Object::Iter(c) => Some(Rc::as_ptr(c) as usize), + Object::LazyIter(l) => Some(Rc::as_ptr(l) as usize), + _ => None, + }; + if iters.len() <= 8 { + return iters.iter().enumerate().all(|(i, a)| { + let a = addr(a); + a.is_none() || iters[..i].iter().all(|b| addr(b) != a) + }); + } + let mut addrs: Vec = iters.iter().filter_map(addr).collect(); + addrs.sort_unstable(); + addrs.windows(2).all(|w| w[0] != w[1]) +} + +/// One step of a native adapter that runs no code (the core loop's +/// `FOR_ITER`): `None` when the step needs the interpreter, nothing +/// having been consumed. Every source must have an item left, so the +/// step neither stops partway through the sources nor releases a +/// source's container (which could queue a finalizer). (So a strict +/// `zip` steps the same way: its end, where the strictness check is, is +/// the general step's.) pub(crate) fn lazy_pure_next(l: &PyLazyIter) -> Option> { // SAFETY: nothing below runs code; the view ends with this call. let st = unsafe { l.state.peek_mut() }?; let LazyIterKind::Zip { iters, - strict: false, + strict: _, result, + spare, held, + distinct, } = st else { return itertools_pure_next(l); @@ -950,14 +2180,11 @@ pub(crate) fn lazy_pure_next(l: &PyLazyIter) -> Option> { if !held.is_empty() { return None; } + let n = iters.len(); // Two plain sequence cursors (`zip(xs, ys)`), the commonest shape. if let [a, b] = iters.as_slice() { - if let Some((x, y)) = cursor_pair(a, b) { - if let Some(slots) = result - .as_mut() - .and_then(crate::shared_value::ThinArc::get_mut) - .filter(|slots| slots.len() == 2) - { + if let Some((x, y)) = hot_pair(a, b) { + if let Some(slots) = reusable_result(result, spare, 2) { let old = ( std::mem::replace(&mut slots[0], x), std::mem::replace(&mut slots[1], y), @@ -965,28 +2192,54 @@ pub(crate) fn lazy_pure_next(l: &PyLazyIter) -> Option> { drop(old); return Some(Some(Object::Tuple(result.clone()?))); } - let t = crate::object::TupleStorage::from_array([x, y]); - *result = Some(t.clone()); - return Some(Some(Object::Tuple(t))); + return Some(Some(fresh_result( + result, + spare, + crate::object::TupleStorage::from_array([x, y]), + ))); + } + } + // Up to eight plain sequence cursors (`zip(xs, ys, zs)`): their items, + // into the previous result when this adapter holds it alone. + if (3..=CURSORS_MAX).contains(&n) { + // (Tuple and list cursors, straight into the result's slots, in + // one pass over them.) + if let Some(slots) = reusable_result(result, spare, n) { + if seq_cursors_fill(iters, slots) { + return Some(Some(Object::Tuple(result.clone()?))); + } + } else { + let mut items = vec![Object::None; n]; + if seq_cursors_fill(iters, &mut items) { + let t = crate::object::TupleStorage::from_vec(items); + return Some(Some(fresh_result(result, spare, t))); + } + } + if let Some(mut items) = cursors_next(iters) { + if let Some(slots) = reusable_result(result, spare, n) { + // (The old items leave in `items`, released below.) + for (slot, x) in slots.iter_mut().zip(items.iter_mut()) { + std::mem::swap(slot, x); + } + drop(items); + return Some(Some(Object::Tuple(result.clone()?))); + } + let t = crate::object::TupleStorage::from_vec(items[..n].to_vec()); + return Some(Some(fresh_result(result, spare, t))); } } - if !srcs_ready(iters) { + if !srcs_ready(iters, distinct) { return None; } if iters.is_empty() { return Some(None); } // The previous result, refilled when this adapter holds it alone. - if let Some(slots) = result - .as_mut() - .and_then(crate::shared_value::ThinArc::get_mut) - { - if slots.len() == iters.len() { - for (slot, it) in slots.iter_mut().zip(iters.iter()) { - *slot = src_step(it)?; - } - return Some(Some(Object::Tuple(result.clone()?))); + if let Some(slots) = reusable_result(result, spare, n) { + for (slot, it) in slots.iter_mut().zip(iters.iter()) { + *slot = src_step(it)?; } + return Some(Some(Object::Tuple(result.clone()?))); } let t = match iters.as_slice() { [a, b] => crate::object::TupleStorage::from_array([src_step(a)?, src_step(b)?]), @@ -994,22 +2247,173 @@ pub(crate) fn lazy_pure_next(l: &PyLazyIter) -> Option> { iters.iter().map(src_step).collect::>>()?, ), }; - *result = Some(t.clone()); - Some(Some(Object::Tuple(t))) + Some(Some(fresh_result(result, spare, t))) +} + +/// The slots of a `zip`'s result tuple of `n` items that only the adapter +/// holds: `result`'s, or else its spare's (which then becomes `result`). +#[inline] +fn reusable_result<'a>( + result: &'a mut Option, + spare: &mut Option, + n: usize, +) -> Option<&'a mut [Object]> { + let alone = |t: &mut Option| { + t.as_mut() + .and_then(crate::shared_value::ThinArc::get_mut) + .is_some_and(|slots| slots.len() == n) + }; + if !alone(result) { + if !alone(spare) { + return None; + } + std::mem::swap(result, spare); + } + result + .as_mut() + .and_then(crate::shared_value::ThinArc::get_mut) + .map(|slots| &mut slots[..]) +} + +/// A `zip`'s new result `t`, kept as `result` (the old one as the spare). +#[inline] +fn fresh_result( + result: &mut Option, + spare: &mut Option, + t: crate::object::SharedTuple, +) -> Object { + *spare = result.replace(t.clone()); + Object::Tuple(t) +} + +/// [`lazy_pure_next`] for a `zip` of `n` (at most four) distinct plain +/// sequence cursors whose result is unpacked at once: each one's next item +/// written from `out` as the unpacking leaves them (the last lowest), no +/// tuple built, and `true`; `false` (nothing taken) unless every cursor +/// has one. +/// +/// # Safety +/// +/// `out` has `n` free slots. +pub(crate) unsafe fn lazy_pure_cursors_to(l: &PyLazyIter, out: *mut Object, n: usize) -> bool { + // SAFETY: nothing below runs code; the view ends with this call. + let Some(st) = (unsafe { l.state.peek() }) else { + return false; + }; + // (A strict `zip` too: its end is the general step's.) + let LazyIterKind::Zip { iters, held, .. } = st else { + return false; + }; + if !held.is_empty() || iters.len() != n || n > 4 { + return false; + } + let mut runs: [(*const Object, usize, *mut usize); 4] = + [(std::ptr::null(), 0, std::ptr::null_mut()); 4]; + for (k, it) in iters.iter().enumerate() { + let Object::Iter(c) = it else { + return false; + }; + // (Distinct cells, so the views never alias.) + if iters[..k] + .iter() + .any(|d| matches!(d, Object::Iter(d) if Rc::ptr_eq(c, d))) + { + return false; + } + // SAFETY: distinct cells, each viewed once; nothing runs code until + // the views end with this call. + let Some((xs, i)) = (unsafe { c.peek_mut() }).and_then(seq_cursor) else { + return false; + }; + if *i >= xs.len() { + return false; + } + runs[k] = (xs.as_ptr(), *i, std::ptr::from_mut(i)); + } + for (k, &(xs, i, at)) in runs[..n].iter().enumerate() { + // SAFETY: `i` is below its sequence's length (checked above), the + // sequences live while their cursors do, and `out` has `n` slots. + unsafe { + out.add(n - 1 - k).write(crate::clone_hot(&*xs.add(i))); + *at = i + 1; + } + } + true +} + +/// `pairwise`'s first step over a list's or tuple's cursor `c` with two +/// items left: both, the second kept in `old` for the next step. `None` +/// (nothing taken) otherwise; a source with fewer, which the step ends, +/// is the general step's. +/// +/// # Safety +/// +/// `c` is a cell no view borrows; nothing runs code while this one does. +unsafe fn pairwise_first( + c: &Rc>, + old: &mut Option, +) -> Option<(Object, Object)> { + // SAFETY: the caller's contract; the view ends with this call. + let cur = unsafe { c.peek_mut() }?; + let (xs, i) = seq_cursor(cur)?; + let (a, b) = (xs.get(*i)?.clone(), xs.get(*i + 1)?.clone()); + *i += 2; + *old = Some(b.clone()); + Some((a, b)) } /// [`lazy_pure_next`] for a two-source `zip` whose pair is unpacked at /// once: the two items, with no tuple built. pub(crate) fn lazy_pure_pair(l: &PyLazyIter) -> Option<(Object, Object)> { // SAFETY: nothing below runs code; the view ends with this call. - let st = unsafe { l.state.peek() }?; + let st = unsafe { l.state.peek_mut() }?; + // (A strict `zip` too: see `lazy_pure_next`.) let LazyIterKind::Zip { iters, - strict: false, + strict: _, held, .. } = st else { + // `pairwise` past its first step, over a cursor with an item left: + // the previous item and the new one, which replaces it (its first + // step and its end are the general step's). + if let LazyIterKind::Pairwise { + source: Some(Object::Iter(c)), + old, + } = st + { + let Some(old) = old else { + // SAFETY: the source's own cell, under no other view. + return unsafe { pairwise_first(c, old) }; + }; + // SAFETY: the source's own cell; nothing below runs code, and + // the view ends with this block. + let cur = unsafe { c.peek_mut() }?; + // (A list's or tuple's cursor indexed directly.) + let new = match seq_cursor(cur) { + Some((xs, i)) => { + let v = xs.get(*i)?.clone(); + *i += 1; + v + } + None => { + let v = cur.pure_peek()?; + cur.pure_skip(); + v + } + }; + let prev = std::mem::replace(old, new.clone()); + return Some((prev, new)); + } + // A two-source `zip_longest` with an item left in each of two + // plain cursors (its ends, where the fill value comes in, are the + // general step's). + if let LazyIterKind::ZipLongest { iters, .. } = st { + if let [Some(a), Some(b)] = iters.as_slice() { + return cursor_pair(a, b); + } + } return None; }; if !held.is_empty() { @@ -1018,13 +2422,583 @@ pub(crate) fn lazy_pure_pair(l: &PyLazyIter) -> Option<(Object, Object)> { let [a, b] = iters.as_slice() else { return None; }; - if let Some(pair) = cursor_pair(a, b) { + if let Some(pair) = hot_pair(a, b) { return Some(pair); } - if !srcs_ready(iters) { + // (Two sources: compared outright, the state only being read here.) + if !srcs_ready(iters, &mut None) { + return None; + } + Some((src_step(a)?, src_step(b)?)) +} + +/// `next(it[, default])`'s fast half: the next item of a plain sequence +/// cursor or a native adapter that steps without running code. `None` +/// (nothing consumed) for anything else, an exhausted iterator included, +/// which the full call answers. +pub(crate) fn next_fast(args: &[Object]) -> Option> { + let it = match args { + [it] | [it, _] => it, + _ => return None, + }; + let v = match it { + Object::Iter(c) => { + // SAFETY: a view that runs no code and ends with the step. + let cursor = unsafe { c.peek_mut() }?; + match cursor.pure_peek() { + Some(v) => { + cursor.pure_skip(); + v + } + // A dict's or dict view's iterator, stepped as `for` + // steps it (`next(iter(d))`, the first key): any change of + // the dict, and the end, are the full call's to report. + None if matches!(cursor, PyIterator::DictKeys { .. }) => { + crate::Interpreter::core_dict_next_item(cursor)? + } + // A plain cursor at its end: the step the full call takes + // (which runs no code), then the default or the + // `StopIteration` it answers. + None if cursor.plain_at_end() => match cursor.next_value_checked() { + Ok(Some(v)) => v, + Ok(None) => { + return Some(match args { + [_, default] => Ok(default.clone()), + _ => Err(crate::error::stop_iteration()), + }) + } + Err(e) => return Some(Err(e)), + }, + None => return None, + } + } + Object::LazyIter(l) => match lazy_hot_next(l) { + Some(v) => v, + None => lazy_pure_next(l)??, + }, + // An `os.scandir` iterator (`os.walk`'s `next(scandir_it)`): its + // `__next__`'s step, the default or `StopIteration` at the end. + Object::Instance(inst) => match crate::stdlib::os::scandir_step(inst)? { + Some(v) => v, + None => { + return Some(match args { + [_, default] => Ok(default.clone()), + _ => Err(crate::error::stop_iteration()), + }) + } + }, + _ => return None, + }; + Some(Ok(v)) +} + +/// The most sources [`cursors_next`] steps at once. +const CURSORS_MAX: usize = 8; + +/// The next items of distinct tuple and list cursors, in one pass: when +/// every one of the distinct plain sequence cursors `iters` has an item left, +/// each steps, its item written over the matching slot of `out` (the old +/// one released), and `true`; otherwise `false`, nothing touched. +fn seq_cursors_fill(iters: &[Object], out: &mut [Object]) -> bool { + let n = iters.len(); + if n > CURSORS_MAX || out.len() < n { + return false; + } + // (Distinct cells first, so the views below never alias.) + for (k, it) in iters.iter().enumerate() { + let Object::Iter(c) = it else { + return false; + }; + if iters[..k] + .iter() + .any(|d| matches!(d, Object::Iter(d) if Rc::ptr_eq(c, d))) + { + return false; + } + } + let mut runs: [(*const Object, usize, *mut usize); CURSORS_MAX] = + [(std::ptr::null(), 0, std::ptr::null_mut()); CURSORS_MAX]; + for (run, it) in runs.iter_mut().zip(iters) { + let Object::Iter(c) = it else { + return false; + }; + // SAFETY: distinct cells, each viewed once; nothing runs code until + // the views end with this call. + let Some((xs, i)) = (unsafe { c.peek_mut() }).and_then(seq_cursor) else { + return false; + }; + if *i >= xs.len() { + return false; + } + *run = (xs.as_ptr(), *i, std::ptr::from_mut(i)); + } + for (slot, &(xs, i, at)) in out.iter_mut().zip(&runs[..n]) { + // SAFETY: `i` is below its sequence's length (checked above), and + // the sequences live while their cursors do; an item's release only + // queues work for the next safe point. + unsafe { + *slot = (*xs.add(i)).clone(); + *at = i + 1; + } + } + true +} + +/// [`cursor_pair`] for up to [`CURSORS_MAX`] distinct plain sequence +/// cursors: every one's next item, all taken, in the first `iters.len()` +/// slots of the result; `None` (none taken) unless each has one. +fn cursors_next(iters: &[Object]) -> Option<[Object; CURSORS_MAX]> { + let n = iters.len(); + if n > CURSORS_MAX { + return None; + } + let mut cells: [Option<&Rc>>; CURSORS_MAX] = + [None; CURSORS_MAX]; + for (k, it) in iters.iter().enumerate() { + let Object::Iter(c) = it else { return None }; + if cells[..k].iter().flatten().any(|d| Rc::ptr_eq(c, d)) { + return None; + } + cells[k] = Some(c); + } + let mut items = [const { Object::None }; CURSORS_MAX]; + for (slot, c) in items.iter_mut().zip(cells.iter().flatten()) { + // SAFETY: distinct cells, one viewed at a time; nothing here runs + // code, and each view ends with its step. + *slot = unsafe { c.peek_mut()? }.pure_peek()?; + } + for c in cells.iter().flatten() { + // SAFETY: as above; `pure_skip` steps past exactly what + // `pure_peek` found. + unsafe { c.peek_mut()? }.pure_skip(); + } + Some(items) +} + +/// `list(islice(seq, ...))` and its kin: the rest of an `islice` over a +/// tuple or list cursor only it holds, taken at once in CPython's +/// `islice_next` order (the skipped items first, then the stop bound), +/// the adapter left finished with its source released. `None`, nothing +/// consumed, for any other `islice` or iterator. +/// `list(product(...))` and its kin: every row of a combinatoric machine +/// (`product`, `permutations`, `combinations`, `combinations_with_replacement`, +/// a bounded `repeat`) stepped straight to its end, as the items one at a +/// time would leave it (rows are built from the pools it holds, running no +/// code). `None` for any other iterator. +pub(crate) fn machine_collect(l: &PyLazyIter) -> Option> { + // SAFETY: nothing below runs code; the view ends with this call. + let st = unsafe { l.state.peek_mut() }?; + if !matches!( + st, + LazyIterKind::Product { .. } + | LazyIterKind::Permutations { .. } + | LazyIterKind::Combinations { .. } + | LazyIterKind::Cwr { .. } + | LazyIterKind::Repeat { times: Some(_), .. } + ) { + return None; + } + let mut out = Vec::new(); + while let Some(row) = machine_step(st)? { + out.push(row); + } + Some(out) +} + +/// The items a list's or tuple's cursor has left, cloned (which runs no +/// code), the cursor moved past them (the step that finds its end still +/// to come). `None`, touching nothing, for any other source. +fn cursor_take_rest(source: &Object) -> Option> { + use crate::object::PyIterator; + let Object::Iter(c) = source else { + return None; + }; + // SAFETY: reads and an index move that run no code; the view ends here. + match unsafe { c.peek_mut() }? { + PyIterator::Tuple { items, index } => { + let rest = items + .get(*index..) + .map_or_else(Vec::new, <[Object]>::to_vec); + *index += rest.len(); + Some(rest) + } + PyIterator::List { + items, + index, + owner: None, + } => { + let rest = unsafe { items.peek() }? + .get(*index..) + .map_or_else(Vec::new, <[Object]>::to_vec); + *index += rest.len(); + Some(rest) + } + _ => None, + } +} + +/// `pairwise(xs)` or a non-strict (or evenly dividing) `batched(xs, n)` +/// over a list's or tuple's cursor, drained at once: every pair or batch +/// left, the adapter left as its last step leaves it (its source stepped +/// to its end and let go). Only where letting go of the source runs +/// nothing; `None`, nothing consumed, for anything else. +pub(crate) fn window_collect(l: &PyLazyIter) -> Option> { + use crate::object::PyIterator; + // SAFETY: nothing below runs code (clones, tuples, quiet releases); + // the view ends with this call. + let st = unsafe { l.state.peek_mut() }?; + let (source, rest_len) = match st { + LazyIterKind::Pairwise { source, old } if old.as_ref().is_none_or(plain_value) => { + (source, None) + } + LazyIterKind::Batched { source, n, strict } => (source, Some((*n, *strict))), + _ => return None, + }; + if !quiet_source(source.as_ref()?) { return None; } - Some((src_step(a)?, src_step(b)?)) + // (A strict batching whose last batch would be short raises: the + // general step's.) + if let Some((n, true)) = rest_len { + let Some(Object::Iter(c)) = source.as_ref() else { + return None; + }; + // SAFETY: a read that runs no code. + let left = match unsafe { c.peek() }? { + PyIterator::Tuple { items, index } => items.len().saturating_sub(*index), + PyIterator::List { + items, + index, + owner: None, + } => unsafe { items.peek() }?.len().saturating_sub(*index), + _ => return None, + }; + if left % n != 0 { + return None; + } + } + let rest = cursor_take_rest(source.as_ref()?)?; + let src = source.take()?; + exhaust_cursor(&src); + let mut out = Vec::new(); + match st { + LazyIterKind::Pairwise { old, .. } => { + let mut it = rest.into_iter(); + let mut prev = old.take().or_else(|| it.next()); + out.reserve(it.len()); + for x in it { + let p = prev.replace(x.clone()).expect("a previous item"); + out.push(Object::new_tuple_array([p, x])); + } + drop(prev); + } + LazyIterKind::Batched { n, .. } => { + let n = *n; + out.reserve(rest.len().div_ceil(n)); + let mut it = rest.into_iter(); + loop { + let batch: Vec = it.by_ref().take(n).collect(); + if batch.is_empty() { + break; + } + out.push(Object::new_tuple(batch)); + } + } + _ => unreachable!("matched above"), + } + drop(src); + Some(out) +} + +/// `accumulate(xs)` with no function over a plain list or tuple cursor: +/// every remaining running total (the initial value first, when one is +/// still to come), the adapter left as its last step leaves it: its total +/// the last, its cursor at the end (the end itself changes nothing). +/// Totals of machine ints (none overflowing) or floats, the first item +/// any object; `None`, nothing consumed, for anything else. +pub(crate) fn accumulate_collect(l: &PyLazyIter) -> Option> { + // SAFETY: nothing below runs code (clones and native sums); the views + // end with this call. + let st = unsafe { l.state.peek_mut() }?; + let LazyIterKind::Accumulate { + source: Object::Iter(c), + func: None, + total, + initial, + } = st + else { + return None; + }; + // SAFETY: the source's own cell, viewed alone. + let (xs, idx) = unsafe { c.peek_mut() }.and_then(seq_cursor)?; + let rest = xs.get(*idx..)?; + let mut out = Vec::with_capacity(rest.len() + 1); + let mut t = total.clone(); + if let Some(init) = initial.as_ref() { + out.push(init.clone()); + t = Some(init.clone()); + } + for item in rest { + let next = match (&t, item) { + (None, _) => item.clone(), + (Some(Object::Int(a)), Object::Int(b)) => Object::Int(a.checked_add(*b)?), + (Some(Object::Float(a)), Object::Float(b)) => Object::Float(a + b), + _ => return None, + }; + out.push(next.clone()); + t = Some(next); + } + // (Committed: the general steps would have left exactly this.) + *initial = None; + *idx = xs.len(); + let old = std::mem::replace(total, t); + drop(old); + Some(out) +} + +pub(crate) fn islice_collect(l: &PyLazyIter) -> Option> { + // SAFETY: nothing below runs code until the source's release, after + // the views end. + let st = unsafe { l.state.peek_mut() }?; + let LazyIterKind::Islice { + source, + next_idx, + pos, + stop, + step, + done, + } = st + else { + return None; + }; + let Object::Iter(c) = source else { + return None; + }; + if *done || Rc::strong_count(c) != 1 || *step == 0 { + return None; + } + // SAFETY: the source's own cell, viewed alone. + let (xs, idx) = unsafe { c.peek_mut() }.and_then(seq_cursor)?; + let len = xs.len(); + let mut i = *idx; + let mut out = Vec::new(); + loop { + if *pos < *next_idx { + let skip = *next_idx - *pos; + let left = len.saturating_sub(i) as u64; + if skip > left { + *pos += left; + break; + } + i += skip as usize; + *pos += skip; + } + if stop.is_some_and(|s| *pos >= s) || i >= len { + break; + } + out.push(xs[i].clone()); + i += 1; + *pos += 1; + *next_idx = next_idx.saturating_add(*step); + if let Some(s) = *stop { + *next_idx = (*next_idx).min(s); + } + } + *idx = i; + *done = true; + // (CPython clears `lz->it`: the source and what only it holds go.) + let released = std::mem::replace(source, Object::None); + drop(released); + Some(out) +} + +/// Whether a native adapter stops now with nothing consumed and its +/// release, when this is the last reference, frees nothing that could +/// hold a finalizer: the core loop's `FOR_ITER` end, in place. A `zip` +/// whose first source, a tuple or list cursor, is at its end, and an +/// `accumulate` without a function over one (its end changes no state, +/// as CPython's doesn't). +/// Whether `l` is a `chain` at a generator, or a `filter` or `islice` over +/// one: the adapters whose step only +/// [`Interpreter::lazy_gen_one`] takes in place (the steps that run no +/// code can't resume a generator). +#[cfg(feature = "jit")] +#[inline] +pub(crate) fn lazy_steps_generator(l: &Rc) -> bool { + // SAFETY: a read that runs no code, ending with this call. + matches!( + unsafe { l.state.peek() }, + Some( + LazyIterKind::Chain { + active: Some(Object::Generator(_)), + .. + } | LazyIterKind::Filter { + source: Object::Generator(_), + .. + } | LazyIterKind::Islice { + source: Object::Generator(_), + .. + } + ) + ) +} + +pub(crate) fn lazy_stops_quietly(l: &Rc) -> bool { + // SAFETY: reads that run no code, ending with this call. + let Some(st) = (unsafe { l.state.peek() }) else { + return false; + }; + let last = Rc::strong_count(l) == 1; + match st { + LazyIterKind::Zip { + iters, + strict: false, + result, + spare, + held, + distinct: _, + } => { + let Some(first) = iters.first() else { + return false; + }; + if !held.is_empty() || !cursor_at_end(first) { + return false; + } + !last + || (iters.iter().all(quiet_source) + && quiet_tuple(result.as_ref()) + && quiet_tuple(spare.as_ref())) + } + LazyIterKind::Accumulate { + source, + func: None, + total, + initial: None, + } => { + cursor_at_end(source) + && (!last || (quiet_source(source) && total.as_ref().is_none_or(plain_value))) + } + _ => false, + } +} + +/// Whether `it` is a tuple's or an unowned list's cursor at its end. +pub(crate) fn cursor_at_end(it: &Object) -> bool { + use crate::object::PyIterator; + let Object::Iter(c) = it else { + return false; + }; + // SAFETY: reads that run no code, ending with this call. + match unsafe { c.peek() } { + Some(PyIterator::Tuple { items, index }) => *index >= items.len(), + Some(PyIterator::List { + items, + index, + owner: None, + }) => unsafe { items.peek() }.is_some_and(|v| *index >= v.len()), + _ => false, + } +} + +/// The step of a `map`, `filter` or `starmap` whose one source is the +/// plain cursor `src`, at the cursor's end: `Some(None)` (the cursor +/// exhausted, as the general step's own step leaves it) when it is at its +/// end and letting go of its sequence runs nothing; `None` (nothing done) +/// otherwise. +fn cursor_end_quietly(src: &Object) -> Option> { + let Object::Iter(c) = src else { + return None; + }; + // SAFETY: a read that runs no code; the view ends with the test. + if !(unsafe { c.peek() }.is_some_and(|it| it.plain_at_end()) && quiet_source(src)) { + return None; + } + exhaust_cursor(src); + Some(None) +} + +/// The step that finds the end of a cursor [`cursor_at_end`] found at its +/// end, so one someone else holds is exhausted as a general step leaves +/// it (a list's sees no later appends). Runs no code. +fn exhaust_cursor(it: &Object) { + if let Object::Iter(c) = it { + // SAFETY: a step that runs no code at the end; the view ends here. + if let Some(cur) = unsafe { c.peek_mut() } { + let end = cur.next_value(); + debug_assert!(end.is_none()); + drop(end); + } + } +} + +/// A scalar dies quietly. +fn plain_value(v: &Object) -> bool { + matches!( + v, + Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Str(_) + | Object::Bytes(_) + ) +} + +/// A source whose sequence another owner keeps (or that holds only +/// scalars) releases quietly. +fn quiet_source(o: &Object) -> bool { + use crate::object::PyIterator; + let Object::Iter(rc) = o else { + return false; + }; + if Rc::strong_count(rc) > 1 { + return true; + } + // SAFETY: reads that run no code, ending with this call. + match unsafe { rc.peek() } { + Some(PyIterator::Tuple { items, .. }) => { + crate::shared_value::ThinArc::strong_count(items) > 1 || items.iter().all(quiet_item) + } + Some(PyIterator::List { items, .. }) => { + Rc::strong_count(items) > 1 + || unsafe { items.peek() }.is_some_and(|v| v.iter().all(quiet_item)) + } + Some(PyIterator::Range { .. } | PyIterator::Str { .. } | PyIterator::Bytes { .. }) => true, + _ => false, + } +} + +/// A source's item that dies quietly: a scalar, or a tuple of them (the +/// records `starmap` and the unpacking loops walk). +fn quiet_item(v: &Object) -> bool { + match v { + Object::Tuple(t) => t.iter().all(plain_value), + v => plain_value(v), + } +} + +/// A result tuple a `zip` keeps for reuse, released quietly. +fn quiet_tuple(t: Option<&crate::object::SharedTuple>) -> bool { + t.is_none_or(|t| crate::shared_value::ThinArc::strong_count(t) > 1 || t.iter().all(plain_value)) +} + +/// A tuple's or an unowned list's cursor: the items, and the position. +#[inline(always)] +fn seq_cursor(it: &mut crate::object::PyIterator) -> Option<(&[Object], &mut usize)> { + use crate::object::PyIterator; + match it { + PyIterator::Tuple { items, index } => Some((&items[..], index)), + PyIterator::List { + items, + index, + owner: None, + } => { + // SAFETY: a read that runs no code, ending before anything does. + let v = unsafe { items.peek() }?; + Some((&v[..], index)) + } + _ => None, + } } /// The next items of two distinct plain sequence cursors, both taken; `None` @@ -1040,6 +3014,13 @@ fn cursor_pair(a: &Object, b: &Object) -> Option<(Object, Object)> { // SAFETY: two distinct cells; nothing below runs code, and the views // end with this call. let (ia, ib) = unsafe { (ca.peek_mut()?, cb.peek_mut()?) }; + // Two tuple or list cursors (the commonest), indexed directly. + if let (Some((xs, i)), Some((ys, j))) = (seq_cursor(ia), seq_cursor(ib)) { + let pair = (xs.get(*i)?.clone(), ys.get(*j)?.clone()); + *i += 1; + *j += 1; + return Some(pair); + } let x = ia.pure_peek()?; let y = ib.pure_peek()?; // (`pure_skip` steps past exactly what `pure_peek` found.) @@ -1048,6 +3029,46 @@ fn cursor_pair(a: &Object, b: &Object) -> Option<(Object, Object)> { Some((x, y)) } +/// A machine-int `count` and a plain sequence cursor, both stepped: the +/// counter's value and the cursor's item; `None` (neither taken) unless +/// both have one. +#[inline] +fn count_cursor_pair(counter: &Object, cursor: &Object) -> Option<(Object, Object)> { + let (Object::LazyIter(l), Object::Iter(c)) = (counter, cursor) else { + return None; + }; + // SAFETY: two cells of different kinds; nothing below runs code, and + // the views end with this call. + let state = unsafe { l.state.peek_mut() }?; + let LazyIterKind::Count { + current: Object::Int(cur), + step: Object::Int(by), + } = state + else { + return None; + }; + let next = cur.checked_add(*by)?; + // SAFETY: as above. + let item = unsafe { c.peek_mut() }?.pure_next()?; + Some((Object::Int(std::mem::replace(cur, next)), item)) +} + +/// The next items of a two-source `zip`'s commonest sources, both taken: +/// two plain sequence cursors ([`cursor_pair`]), or a machine-int `count` +/// beside one (`zip(count(), xs)`, either way round). `None` (neither +/// taken) otherwise. +#[inline] +fn hot_pair(a: &Object, b: &Object) -> Option<(Object, Object)> { + if let Some(pair) = cursor_pair(a, b) { + return Some(pair); + } + match (a, b) { + (Object::LazyIter(_), Object::Iter(_)) => count_cursor_pair(a, b), + (Object::Iter(_), Object::LazyIter(_)) => count_cursor_pair(b, a).map(|(n, x)| (x, n)), + _ => None, + } +} + /// The `itertools` state machines that touch no other object (`repeat`, /// `product`, `permutations`, `combinations`, /// `combinations_with_replacement`), stepped under one borrow: `None` @@ -1079,8 +3100,7 @@ pub(crate) fn machine_step(st: &mut LazyIterKind) -> Option> { *started = true; indices.clear(); indices.resize(pools.len(), 0); - let t: Vec = pools.iter().map(|p| p[0].clone()).collect(); - return Some(Some(Object::new_tuple(t))); + return Some(Some(Object::tuple_from_refs(pools.iter().map(|p| &p[0])))); } let n = pools.len(); let mut i = n as i64 - 1; @@ -1097,12 +3117,9 @@ pub(crate) fn machine_step(st: &mut LazyIterKind) -> Option> { *stopped = true; return Some(None); } - let t: Vec = pools - .iter() - .zip(indices.iter()) - .map(|(p, &ix)| p[ix].clone()) - .collect(); - Some(Some(Object::new_tuple(t))) + Some(Some(Object::tuple_from_refs( + pools.iter().zip(indices.iter()).map(|(p, &ix)| &p[ix]), + ))) } LazyIterKind::Permutations { pool, @@ -1119,8 +3136,9 @@ pub(crate) fn machine_step(st: &mut LazyIterKind) -> Option> { let r = *r; if !*started { *started = true; - let t: Vec = indices[..r].iter().map(|&ix| pool[ix].clone()).collect(); - return Some(Some(Object::new_tuple(t))); + return Some(Some(Object::tuple_from_refs( + indices[..r].iter().map(|&ix| &pool[ix]), + ))); } if n == 0 { *stopped = true; @@ -1136,8 +3154,9 @@ pub(crate) fn machine_step(st: &mut LazyIterKind) -> Option> { } else { let j = n - cycles[k]; indices.swap(k, j); - let t: Vec = indices[..r].iter().map(|&ix| pool[ix].clone()).collect(); - return Some(Some(Object::new_tuple(t))); + return Some(Some(Object::tuple_from_refs( + indices[..r].iter().map(|&ix| &pool[ix]), + ))); } i -= 1; } @@ -1158,8 +3177,9 @@ pub(crate) fn machine_step(st: &mut LazyIterKind) -> Option> { let r = *r; if !*started { *started = true; - let t: Vec = indices.iter().map(|&ix| pool[ix].clone()).collect(); - return Some(Some(Object::new_tuple(t))); + return Some(Some(Object::tuple_from_refs( + indices.iter().map(|&ix| &pool[ix]), + ))); } let mut i = r as i64 - 1; while i >= 0 && indices[i as usize] == i as usize + n - r { @@ -1174,8 +3194,9 @@ pub(crate) fn machine_step(st: &mut LazyIterKind) -> Option> { for j in k + 1..r { indices[j] = indices[j - 1] + 1; } - let t: Vec = indices.iter().map(|&ix| pool[ix].clone()).collect(); - Some(Some(Object::new_tuple(t))) + Some(Some(Object::tuple_from_refs( + indices.iter().map(|&ix| &pool[ix]), + ))) } LazyIterKind::Cwr { pool, @@ -1191,8 +3212,9 @@ pub(crate) fn machine_step(st: &mut LazyIterKind) -> Option> { let r = *r; if !*started { *started = true; - let t: Vec = indices.iter().map(|&ix| pool[ix].clone()).collect(); - return Some(Some(Object::new_tuple(t))); + return Some(Some(Object::tuple_from_refs( + indices.iter().map(|&ix| &pool[ix]), + ))); } let mut i = r as i64 - 1; while i >= 0 && indices[i as usize] == n - 1 { @@ -1207,13 +3229,214 @@ pub(crate) fn machine_step(st: &mut LazyIterKind) -> Option> { for slot in indices[k..].iter_mut() { *slot = v; } - let t: Vec = indices.iter().map(|&ix| pool[ix].clone()).collect(); - Some(Some(Object::new_tuple(t))) + Some(Some(Object::tuple_from_refs( + indices.iter().map(|&ix| &pool[ix]), + ))) + } + _ => None, + } +} + +/// The commonest steps of `chain`, `count` and `cycle`, which step no +/// other adapter: a chain's current source a plain cursor with an item, a +/// counter of machine ints, a cycle replaying the items it saved. `None`, +/// touching nothing, for any other state. +#[inline(always)] +fn hot_flat_step(st: &mut LazyIterKind) -> Option { + match st { + LazyIterKind::Chain { + active: Some(Object::Iter(c)), + .. + } => { + // SAFETY: a step that runs no code; the view ends with it. + unsafe { c.peek_mut() }?.pure_next() + } + LazyIterKind::Count { + current: Object::Int(a), + step: Object::Int(b), + } => { + let next = a.checked_add(*b)?; + Some(Object::Int(std::mem::replace(a, next))) } + LazyIterKind::Cycle { + source: None, + saved, + index, + .. + } => { + // SAFETY: a read that runs no code (a distinct cell). + let buf = unsafe { saved.peek() }?; + let i = (*index).min(buf.len().checked_sub(1)?); + let item = crate::clone_hot(&buf[i]); + *index = if i + 1 >= buf.len() { 0 } else { i + 1 }; + Some(item) + } + _ => None, + } +} + +/// An `islice` source's next item where taking it is a hot step: a plain +/// cursor's, or a `chain`'s, `count`'s or `cycle`'s own (never another +/// `islice`, so the nesting ends here; its cell is distinct, a source +/// being fixed when the `islice` is made). +#[inline(always)] +fn hot_take(source: &Object) -> Option { + match source { + // SAFETY: a step that runs no code; the view ends with it. + Object::Iter(c) => unsafe { c.peek_mut() }?.pure_next(), + // SAFETY: as above. + Object::LazyIter(inner) => hot_flat_step(unsafe { inner.state.peek_mut() }?), _ => None, } } +/// [`lazy_hot_next`]'s step on an adapter's state, in line (for the frame +/// JIT's `FOR_ITER` helper, which has no other use for a frame). +#[inline(always)] +pub(crate) fn lazy_hot_step_in_line(st: &mut LazyIterKind) -> Option { + let LazyIterKind::Islice { + source, + next_idx, + pos, + stop, + step, + done: false, + } = st + else { + return hot_flat_step(st); + }; + // `islice_next`'s order: the skipped items first (each one something + // its sequence still holds, or an int: dropping it runs nothing), then + // the stop bound. A source that runs out, or stops stepping this way, + // midway leaves the count where the general step picks it up. + while *pos < *next_idx { + hot_take(source)?; + *pos += 1; + } + if stop.is_some_and(|s| *pos >= s) { + return None; + } + let item = hot_take(source)?; + *pos += 1; + let next = next_idx.saturating_add(*step); + *next_idx = match *stop { + Some(s) if next > s => s, + _ => next, + }; + Some(item) +} + +/// `list(islice(src, ..., stop))` over a source whose steps run no code (a +/// plain cursor, `count`, `cycle`, `chain`): every item up to the stop +/// taken as [`lazy_hot_step_in_line`] takes them, in one view, then the +/// end the general step reaches there (the adapter done, its source let +/// go, as CPython's `islice_next` clears it). `false` once a step needs +/// the general loop, the items taken so far in `out` and the state as +/// those steps left it. +fn islice_drain(l: &PyLazyIter, out: &mut Vec) -> bool { + let source = { + // SAFETY: nothing below runs code; the view ends with this block. + let Some(st) = (unsafe { l.state.peek_mut() }) else { + return false; + }; + // (Room for the items the bound leaves, up to a cap: the source + // may end sooner.) + if let LazyIterKind::Islice { + next_idx, + stop: Some(stop), + step, + done: false, + .. + } = st + { + let left = stop.saturating_sub(*next_idx).div_ceil((*step).max(1)); + out.reserve(left.min(1024) as usize); + } + loop { + let LazyIterKind::Islice { + pos, + next_idx, + stop: Some(stop), + done: false, + .. + } = st + else { + return false; + }; + // (The general step's end: nothing left to skip, and the stop + // reached.) + if *pos >= *next_idx && *pos >= *stop { + break; + } + match lazy_hot_step_in_line(st) { + Some(v) => out.push(v), + None => return false, + } + } + let LazyIterKind::Islice { source, done, .. } = st else { + return false; + }; + *done = true; + std::mem::replace(source, Object::None) + }; + // (Released once the view has ended.) + drop(source); + true +} + +/// The sort keys `key=d.__getitem__` (`get` false) or `key=d.get` gives +/// `items` over the exact dict `d`: each item's value, found by the native +/// probe under one view of the table (a `get` miss no stored key could +/// equal is `None`). `None` for an item whose lookup could run code, or a +/// `__getitem__` miss (its `KeyError` is the full call's). +fn dict_value_keys(d: &Rc>, items: &[Object], get: bool) -> Option> { + if crate::trace::any_observers_active() { + return None; + } + // SAFETY: nothing below runs code (the probes compare natively, and a + // decline drops only clones the table also holds); the view ends with + // this call. + let m = unsafe { d.peek() }?; + let mut keys = Vec::with_capacity(items.len()); + for item in items { + let probe = crate::object::LeafProbe::new(item)?; + match m.get(&probe) { + Some(v) => keys.push(crate::clone_hot(v)), + None if get && probe.miss_is_exact() => keys.push(Object::None), + None => return None, + } + } + Some(keys) +} + +/// [`lazy_hot_step_in_line`], out of line. +#[inline(never)] +fn lazy_hot_step(st: &mut LazyIterKind) -> Option { + lazy_hot_step_in_line(st) +} + +/// The commonest steps of `islice`, `chain`, `count` and `cycle` that run +/// no code, ahead of [`Interpreter::lazy_core_next`]'s dispatch (which +/// takes every step this declines, the ends among them): an `islice` +/// over a plain cursor or one of the other three, its skipped items +/// included, and [`hot_flat_step`]'s. Any other adapter costs a tag +/// test. +#[inline] +pub(crate) fn lazy_hot_next(l: &PyLazyIter) -> Option { + // SAFETY: nothing below runs code; the view ends with this call. + let st = unsafe { l.state.peek_mut() }?; + if !matches!( + st, + LazyIterKind::Islice { .. } + | LazyIterKind::Chain { .. } + | LazyIterKind::Count { .. } + | LazyIterKind::Cycle { .. } + ) { + return None; + } + lazy_hot_step(st) +} + /// The next item of a native iterator source when taking it runs no /// code and releases nothing (see [`PyIterator::pure_ready`]). fn ready_next(it: &Object) -> Option { @@ -1233,6 +3456,172 @@ fn ready_next(it: &Object) -> Option { src_step(it) } +/// Whether `l` is a `zip`, `map`, `filter` or `enumerate` with a generator +/// among its sources, whose steps always run code (so its pure step, +/// [`Interpreter::lazy_core_next`], never takes one). +pub(crate) fn lazy_has_generator_source(l: &PyLazyIter) -> bool { + let is_gen = |o: &Object| matches!(o, Object::Generator(_)); + // SAFETY: a read that runs no code, ending with the match. + match unsafe { l.state.peek() } { + Some(LazyIterKind::Zip { iters, .. } | LazyIterKind::Map { iters, .. }) => { + iters.iter().any(is_gen) + } + Some(LazyIterKind::Filter { source, .. } | LazyIterKind::Enumerate { source, .. }) => { + is_gen(source) + } + _ => false, + } +} + +/// `list(g)` of a `groupby` group `l` whose groupby has no key function +/// and steps a plain list or tuple cursor: the group's items in one loop, +/// as `_grouper_next` takes them one at a time (the next group's first +/// item left as the groupby's current value and key). `false` once a step +/// needs the general loop (the source's end, a key that compares only by +/// running code), the items taken so far in `out` and the state as those +/// steps left it. +fn grouper_drain(l: &Rc, out: &mut Vec) -> bool { + // SAFETY: nothing below runs code (keys compare natively, and the + // values released are held in `out`); each view ends before return. + let Some(LazyIterKind::Grouper { parent, tgtkey }) = (unsafe { l.state.peek() }) else { + return false; + }; + let (parent, tgtkey) = (parent.clone(), tgtkey.clone()); + // SAFETY: as above (the parent's distinct cell). + let Some(LazyIterKind::GroupBy { + source: Object::Iter(c), + keyfunc: Object::None, + currkey, + currvalue, + currgrouper, + .. + }) = (unsafe { parent.state.peek_mut() }) + else { + return false; + }; + if !currgrouper + .as_ref() + .is_some_and(|w| std::ptr::eq(w.as_ptr(), Rc::as_ptr(l))) + { + return false; + } + loop { + if currvalue.is_none() { + let Some(v) = cursor_peek(c) else { + return false; + }; + if cursor_advance(c).is_none() { + return false; + } + let old = (currkey.replace(v.clone()), currvalue.replace(v)); + drop(old); + } + let Some(curr) = currkey.as_ref() else { + return false; + }; + match native_key_eq(&tgtkey, curr) { + Some(true) => { + let v = currvalue.take().expect("a current value"); + let old = currkey.take(); + drop(old); + out.push(v); + } + // The group's end: the next group's first item stays current. + Some(false) => return true, + None => return false, + } + } +} + +/// `zip`'s items over sources that are all list or tuple iterators (not +/// `strict`, nothing held back), drained in one pass: as many tuples as +/// the shortest has items left, then the end step CPython's takes, one +/// more item from each source before the first exhausted one (dropped, +/// as it drops them) and that one stepped to its end. Cloning items runs +/// no code. `false`, touching nothing, for any other `zip`. +fn zip_seq_bulk(l: &Rc, out: &mut Vec) -> bool { + use crate::object::PyIterator; + const WIDTH: usize = 8; + // SAFETY: nothing runs code until the end step, which steps clones of + // the cells after every view below has ended. + let Some(LazyIterKind::Zip { + iters, + strict: false, + held, + .. + }) = (unsafe { l.state.peek() }) + else { + return false; + }; + let width = iters.len(); + if !held.is_empty() || !(2..=WIDTH).contains(&width) { + return false; + } + let mut cells: [Option>>; WIDTH] = Default::default(); + // Every source's items and position, read in place. + let mut views: [(&[Object], usize); WIDTH] = [(&[], 0); WIDTH]; + let mut n = usize::MAX; + for (k, src) in iters.iter().enumerate() { + let Object::Iter(c) = src else { + return false; + }; + // (A source given twice steps twice a row: the general steps'.) + if cells[..k].iter().flatten().any(|d| Rc::ptr_eq(c, d)) { + return false; + } + // SAFETY: as above. + let (items, index): (&[Object], usize) = match unsafe { c.peek() } { + Some(PyIterator::List { items, index, .. }) => match unsafe { items.peek() } { + Some(v) => (v.as_slice(), *index), + None => return false, + }, + Some(PyIterator::Tuple { items, index }) => (&items[..], *index), + _ => return false, + }; + let index = index.min(items.len()); + views[k] = (items, index); + n = n.min(items.len() - index); + cells[k] = Some(c.clone()); + } + let cells = &cells[..width]; + out.reserve(n); + for row in 0..n { + let item = |k: usize| views[k].0[views[k].1 + row].clone(); + out.push(match width { + 2 => Object::new_tuple_array([item(0), item(1)]), + 3 => Object::new_tuple_array([item(0), item(1), item(2)]), + // (Straight into the tuple's own allocation.) + _ => Object::Tuple(crate::object::TupleStorage::from_exact_iter( + (0..width).map(item), + )), + }); + } + // The end step: each source before the first exhausted one gives one + // more item, which the step drops. + let ends: [bool; WIDTH] = + std::array::from_fn(|k| k < width && views[k].1 + n >= views[k].0.len()); + for c in cells.iter().flatten() { + // SAFETY: the views above have ended; this runs no code. + match unsafe { c.peek_mut() } { + Some(PyIterator::List { index, .. } | PyIterator::Tuple { index, .. }) => *index += n, + _ => unreachable!("checked above"), + } + } + let mut dropped = Vec::new(); + for (k, c) in cells.iter().flatten().enumerate() { + let mut cur = c.borrow_mut(); + let last = cur.next_value(); + drop(cur); + if ends[k] { + debug_assert!(last.is_none()); + break; + } + dropped.extend(last); + } + drop(dropped); + true +} + /// One step of an `itertools` adapter that runs no code and releases /// nothing (the core loop's `FOR_ITER`, and the interpreter's fast path /// ahead of the general one): `None` when the step needs the general @@ -1253,10 +3642,41 @@ fn chain_drain(l: &PyLazyIter, out: &mut Vec) -> bool { out.extend_from_slice(items.get(from..).unwrap_or(&[])); } Object::Tuple(items) => out.extend_from_slice(items.get(from..).unwrap_or(&[])), + // A `str`'s characters (`chain(xs, "ab")`), from the start. + Object::Str(t) if from == 0 => out.extend(t.chars().map(Object::from_char)), + // A `range` of machine ints (`chain(range(a), range(b))`). + Object::Range(r) if from == 0 && r.big.is_none() => { + let (start, stop, step) = ( + i64::try_from(r.start).ok()?, + i64::try_from(r.stop).ok()?, + i64::try_from(r.step).ok()?, + ); + range_ints(start, stop, step, out)?; + } _ => return None, } Some(()) } + // `start` to `stop` by `step` (non-zero), at most a million of them. + fn range_ints(start: i64, stop: i64, step: i64, out: &mut Vec) -> Option<()> { + let n = if step > 0 && start < stop { + (i128::from(stop) - i128::from(start) + i128::from(step) - 1) / i128::from(step) + } else if step < 0 && start > stop { + (i128::from(start) - i128::from(stop) - i128::from(step) - 1) / -i128::from(step) + } else { + 0 + }; + if n > 1 << 20 { + return None; + } + out.reserve(n as usize); + let mut v = start; + for _ in 0..n { + out.push(Object::Int(v)); + v = v.wrapping_add(step); + } + Some(()) + } // SAFETY: nothing below runs code; the view ends with this call. let Some(LazyIterKind::Chain { source, active }) = (unsafe { l.state.peek_mut() }) else { return false; @@ -1280,7 +3700,7 @@ fn chain_drain(l: &PyLazyIter, out: &mut Vec) -> bool { } // Exhausted: detached from the list, as its own last step // leaves it (see `PyIterator::next_value`). - let old = std::mem::replace(items, Rc::new(RefCell::new(Vec::new()))); + let old = std::mem::replace(items, crate::object::detached_store()); *index = 0; drop(old); } @@ -1288,6 +3708,16 @@ fn chain_drain(l: &PyLazyIter, out: &mut Vec) -> bool { out.extend_from_slice(items.get(*index..).unwrap_or(&[])); *index = items.len(); } + PyIterator::Range { + current, + stop, + step, + } => { + if range_ints(*current, *stop, *step, out).is_none() { + return false; + } + *current = *stop; + } _ => return false, } } else if active.is_some() { @@ -1338,14 +3768,88 @@ fn chain_drain(l: &PyLazyIter, out: &mut Vec) -> bool { pub(crate) fn itertools_pure_next(l: &PyLazyIter) -> Option> { // SAFETY: nothing below runs code; the view ends with this call. let st = unsafe { l.state.peek_mut() }?; - if let Some(r) = machine_step(st) { - return Some(r); + if matches!( + st, + LazyIterKind::Repeat { .. } + | LazyIterKind::Product { .. } + | LazyIterKind::Permutations { .. } + | LazyIterKind::Combinations { .. } + | LazyIterKind::Cwr { .. } + ) { + return machine_step(st); } match st { - LazyIterKind::Chain { - active: Some(active), - .. - } => ready_next(active).map(Some), + LazyIterKind::Chain { source, active } => chain_pure_next(source, active).map(Some), + // `compress` over two distinct plain sequence cursors: the data + // items whose selector is a plain bool, int or `None`, skipped or + // taken in place (a dropped item is the sequence's too). Either + // source's end, and any other selector, take the general step. + LazyIterKind::Compress { data, selectors } => { + let (Object::Iter(dc), Object::Iter(sc)) = (&*data, &*selectors) else { + return None; + }; + if Rc::ptr_eq(dc, sc) { + return None; + } + // Two list or tuple cursors, read in place under one view each. + { + // SAFETY: two distinct cells; nothing below runs code, and + // the views end with this block. + let (id, is) = unsafe { (dc.peek_mut()?, sc.peek_mut()?) }; + if let (Some((ds, i)), Some((ss, j))) = (seq_cursor(id), seq_cursor(is)) { + loop { + let (d, s) = (ds.get(*i)?, ss.get(*j)?); + let keep = match s { + Object::Bool(b) => *b, + Object::Int(n) => *n != 0, + Object::None => false, + _ => return None, + }; + *i += 1; + *j += 1; + if keep { + return Some(Some(crate::clone_hot(d))); + } + } + } + } + loop { + let (d, s) = (cursor_peek(dc)?, cursor_peek(sc)?); + let keep = match s { + Object::Bool(b) => b, + Object::Int(i) => i != 0, + Object::None => false, + _ => return None, + }; + cursor_advance(dc)?; + cursor_advance(sc)?; + if keep { + return Some(Some(d)); + } + } + } + // A tee branch: the shared buffer's next item, or one pulled from + // a source whose step runs no code (its end, and any other + // source, take the general step). + LazyIterKind::TeeBranch { shared, index, .. } => { + // SAFETY: as above (distinct cells). + let sh = unsafe { shared.peek_mut() }?; + if sh.busy { + return None; + } + // SAFETY: as above. + let buf = unsafe { sh.buffer.peek_mut() }?; + let item = match buf.get(*index) { + Some(v) => v.clone(), + None => { + let v = ready_next(sh.source.as_ref()?)?; + buf.push(v.clone()); + v + } + }; + *index += 1; + Some(Some(item)) + } LazyIterKind::Count { current, step } => { let (Object::Int(a), Object::Int(b)) = (&*current, &*step) else { return None; @@ -1414,32 +3918,241 @@ pub(crate) fn itertools_pure_next(l: &PyLazyIter) -> Option> { *total = Some(init.clone()); return Some(Some(init)); } - if !src_ready(source, false) { - return None; + // (A plain cursor's next item, peeked and skipped in one view + // each. At its end this is the end, as the general step's + // would be: nothing changes.) + if cursor_at_end(source) { + return Some(None); } let Object::Iter(c) = source else { return None; }; - // SAFETY: a read that runs no code (a distinct cell). - let item = unsafe { c.peek() }?.pure_peek()?; + let item = cursor_peek(c)?; let next = match (&*total, &item) { (None, _) => item, (Some(Object::Int(a)), Object::Int(b)) => Object::Int(a.checked_add(*b)?), (Some(Object::Float(a)), Object::Float(b)) => Object::Float(a + b), _ => return None, }; - src_step(source)?; + cursor_advance(c)?; *total = Some(next.clone()); Some(Some(next)) } + LazyIterKind::Pairwise { + source: Some(Object::Iter(c)), + old: old @ None, + } => { + // SAFETY: the source's own cell, under no other view. + let (a, b) = unsafe { pairwise_first(c, old) }?; + Some(Some(Object::new_tuple_array([a, b]))) + } LazyIterKind::Pairwise { source: Some(source), old: Some(old), } => { + // At its source's end it lets go of both, as the general step + // does, when releasing them runs nothing. + if cursor_at_end(source) { + if !(plain_value(old) && quiet_source(source)) { + return None; + } + exhaust_cursor(source); + let (src, prev) = (std::mem::replace(source, Object::None), old.clone()); + *st = LazyIterKind::Pairwise { + source: None, + old: None, + }; + drop((src, prev)); + return Some(None); + } let new = ready_next(source)?; let prev = std::mem::replace(old, new.clone()); Some(Some(Object::new_tuple_array([prev, new]))) } + // `batched` over a list's or tuple's cursor: the next `n` items (as + // many as are left, at the end of a non-strict one), with no code + // run. A short last batch, or the end itself, takes the step that + // finds the cursor's end and lets go of the source, as the general + // step does, when releasing it runs nothing; a strict one's short + // batch is the general step's (it raises). + LazyIterKind::Batched { source, n, strict } => { + use crate::object::PyIterator; + let (n, strict) = (*n, *strict); + let Some(Object::Iter(c)) = source.as_ref() else { + return None; + }; + let left = { + // SAFETY: a read that runs no code; the view ends here. + match unsafe { c.peek() }? { + PyIterator::Tuple { items, index } => items.len().saturating_sub(*index), + PyIterator::List { + items, + index, + owner: None, + } => unsafe { items.peek() }?.len().saturating_sub(*index), + _ => return None, + } + }; + let last = left < n; + if last && ((strict && left > 0) || !quiet_source(source.as_ref()?)) { + return None; + } + let mut batch = Vec::with_capacity(left.min(n)); + { + // SAFETY: steps that run no code; the view ends here. + let cur = unsafe { c.peek_mut() }?; + while batch.len() < n { + let Some(v) = cur.pure_peek() else { + break; + }; + cur.pure_skip(); + batch.push(v); + } + if last { + let end = cur.next_value(); + debug_assert!(end.is_none()); + drop(end); + } + // (A full batch that ends the cursor leaves the end for the + // next step, as the general step does.) + } + if last { + drop(source.take()); + if batch.is_empty() { + return Some(None); + } + } + Some(Some(Object::new_tuple(batch))) + } + // `zip_longest` over plain sequence cursors: each active source's + // next item, or the fill value for one finished before or now (a + // source finishing now is let go, as the general step lets it go, + // when releasing it runs nothing); the step that finishes the last + // one ends it, as the general step does. + LazyIterKind::ZipLongest { + iters, + fillvalue, + numactive, + } => { + if iters.is_empty() || *numactive == 0 { + return Some(None); + } + // Two plain cursors with an item left in each, the commonest + // step. + if let [Some(a), Some(b)] = iters.as_slice() { + if let Some((x, y)) = cursor_pair(a, b) { + return Some(Some(Object::new_tuple_array([x, y]))); + } + } + // (A source passed twice, `zip_longest(it, it)`, steps twice: + // the general step's.) + for (i, a) in iters.iter().enumerate() { + if let Some(Object::Iter(a)) = a { + if iters[..i] + .iter() + .any(|b| matches!(b, Some(Object::Iter(b)) if Rc::ptr_eq(a, b))) + { + return None; + } + } + } + // (Up to four sources in arrays, the row built in place.) + if iters.len() <= 4 { + let n = iters.len(); + let mut items: [Option; 4] = [None, None, None, None]; + let mut ending = 0usize; + for (k, slot) in iters.iter().enumerate() { + items[k] = match slot { + None => None, + Some(src) if cursor_at_end(src) => { + if !quiet_source(src) { + return None; + } + exhaust_cursor(src); + ending += 1; + None + } + Some(Object::Iter(c)) => Some(cursor_peek(c)?), + Some(_) => return None, + }; + } + if ending >= *numactive { + *numactive = 0; + return Some(None); + } + let mut row = [Object::None, Object::None, Object::None, Object::None]; + let mut done: [Option; 4] = [None, None, None, None]; + for (k, (slot, item)) in iters.iter_mut().zip(items).enumerate() { + row[k] = match item { + Some(v) => { + if let Some(Object::Iter(c)) = slot { + cursor_advance(c)?; + } + v + } + None => { + if let Some(src) = slot.take() { + done[k] = Some(src); + *numactive -= 1; + } + fillvalue.clone() + } + }; + } + drop(done); + let [a, b, c, d] = row; + return Some(Some(match n { + 1 => Object::new_tuple_array([a]), + 2 => Object::new_tuple_array([a, b]), + 3 => Object::new_tuple_array([a, b, c]), + _ => Object::new_tuple_array([a, b, c, d]), + })); + } + let mut items: Vec> = Vec::with_capacity(iters.len()); + let mut ending = 0usize; + for slot in iters.iter() { + items.push(match slot { + None => None, + Some(src) if cursor_at_end(src) => { + if !quiet_source(src) { + return None; + } + exhaust_cursor(src); + ending += 1; + None + } + Some(Object::Iter(c)) => Some(cursor_peek(c)?), + Some(_) => return None, + }); + } + // The end: the general step keeps its sources and counts none + // active. + if ending >= *numactive { + *numactive = 0; + return Some(None); + } + let mut result = Vec::with_capacity(iters.len()); + let mut done = Vec::new(); + for (slot, item) in iters.iter_mut().zip(items) { + match item { + Some(v) => { + if let Some(Object::Iter(c)) = slot { + cursor_advance(c)?; + } + result.push(v); + } + None => { + if let Some(src) = slot.take() { + done.push(src); + *numactive -= 1; + } + result.push(fillvalue.clone()); + } + } + } + drop(done); + Some(Some(Object::new_tuple(result))) + } _ => None, } } @@ -1449,10 +4162,65 @@ pub(crate) fn itertools_pure_next(l: &PyLazyIter) -> Option> { /// empty container, built without running any code (the core loop's /// `CALL`): `None` for every shape that might. pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option { - if let Some(ty) = SeqType::of_exact(cls) { - return Interpreter::seq_new_pure(ty, args); + // The type's pure constructor (see `TypeObject::pure_new`): one of the + // arms below for the builtin types they serve, or one of its own + // (`io.BytesIO()`, `threading.Lock()`, `object()`). + cls.pure_new.get()?(cls, args) +} + +/// `map(...)`, `filter(...)` and `zip(...)` of the exact adapter types +/// (see [`Interpreter::seq_new_pure`]). +pub(crate) fn seq_ctor_pure(cls: &Rc, args: &[Object]) -> Option { + Interpreter::seq_new_pure(SeqType::of_exact(cls)?, args) +} + +/// The value of an `int` subclass's instance whose class keeps `int`'s own +/// `__int__`, as `int(x)` returns it: an exact `int`. `None` for any other +/// instance. +fn int_subclass_value( + inst: &crate::types::PyInstance, + bt: &crate::builtin_types::BuiltinTypes, +) -> Option { + let v @ (Object::Int(_) | Object::Long(_)) = inst.native.get()? else { + return None; + }; + let own = bt + .int_ + .dict + .try_borrow() + .ok()? + .get(&crate::object::StrKey("__int__")) + .cloned()?; + match inst.cls_raw().lookup("__int__") { + Some(g) if g.is_same(&own) => Some(v.clone()), + _ => None, } +} + +/// [`builtin_ctor_pure`]'s arms for the builtin types `builtin_types` +/// registers it on. +pub(crate) fn builtin_ctor_arms(cls: &Rc, args: &[Object]) -> Option { let bt = builtin_types(); + // `bool(x)` of a plain value or exact container, ahead of the other + // classes' arms. + if let ([x], true) = (args, Rc::ptr_eq(cls, &bt.bool_)) { + return match x { + Object::Int(i) => Some(Object::Bool(*i != 0)), + Object::Float(f) => Some(Object::Bool(*f != 0.0)), + Object::Bool(b) => Some(Object::Bool(*b)), + Object::None => Some(Object::Bool(false)), + Object::Str(s) => Some(Object::Bool(!s.is_empty())), + // An exact container is true when it holds anything + // (`bool(items)`, as `if items:` reads it). + Object::Bytes(b) => Some(Object::Bool(!b.is_empty())), + Object::Tuple(t) => Some(Object::Bool(!t.is_empty())), + Object::List(l) => Some(Object::Bool(!l.try_borrow().ok()?.is_empty())), + Object::Dict(d) => Some(Object::Bool(!d.try_borrow().ok()?.is_empty())), + Object::Set(s) => Some(Object::Bool(!s.try_borrow().ok()?.is_empty())), + Object::FrozenSet(s) => Some(Object::Bool(s.iter().next().is_some())), + _ => None, + }; + } // `float(x)` and `int(x)` of a plain number or a well-formed `str` // (a malformed one raises through the full constructor). if Rc::ptr_eq(cls, &bt.float_) { @@ -1469,10 +4237,67 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option return match args { [] => Some(Object::Int(0)), [Object::Int(i)] => Some(Object::Int(*i)), + // An `int` subclass's instance whose class keeps `int`'s own + // `__int__` (`re`'s named opcode constants): its value, exact. + [Object::Instance(inst)] => int_subclass_value(inst, bt), [Object::Bool(b)] => Some(Object::Int(i64::from(*b))), // Truncated toward zero, inside the machine range. [Object::Float(f)] if f.is_finite() && f.abs() < 9.0e18 => Some(Object::Int(*f as i64)), - [Object::Str(text)] => decimal_i64(text).map(Object::Int), + [Object::Str(text)] => decimal_i64(text) + .map(Object::Int) + .or_else(|| big_from_digits(text, 10)), + // `int('ff', 16)`: plain digits of the base, an optional sign + // and surrounding ASCII whitespace, inside the machine range + // (a prefix, an underscore or anything malformed is the full + // constructor's). + [Object::Str(text), Object::Int(base)] if (2..=36).contains(base) => { + // (Hex digits and nothing else, of any width: read once.) + if *base == 16 { + if let Some(v) = crate::builtins::int_from_plain_hex(text.as_bytes()) { + return Some(v); + } + } + let t = text.trim_matches(|c: char| c.is_ascii_whitespace()); + let digits = t.strip_prefix(['+', '-']).unwrap_or(t); + if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_alphanumeric()) { + return None; + } + // (Digits enough to pass 64 bits skip the machine parse, + // which would read them all to find that out.) + let radix = *base as u32; + let machine = if digits.len() as u32 * radix.ilog2() > 64 { + None + } else { + i64::from_str_radix(t, radix).ok() + }; + machine + .map(Object::Int) + .or_else(|| big_from_digits(text, radix)) + } + _ => None, + }; + } + // `super(C, obj)` whose receiver passes the plain check (a failing + // one, or a duck-typed `__class__`, goes the full way). + if Rc::ptr_eq(cls, &bt.super_) { + let [Object::Type(class), receiver] = args else { + return None; + }; + let receiver_class = crate::builtins::supercheck(class, receiver).ok()?; + return Some(crate::builtins::build_super_proxy( + cls.clone(), + class.clone(), + receiver.clone(), + receiver_class, + )); + } + // `str(x)` of an instance that renders with no code run (a `str`, + // `int` or `float` subclass's payload, an enum member's name), as + // `Interpreter::do_str_call` answers. + if Rc::ptr_eq(cls, &bt.str_) { + return match args { + [Object::Str(_)] => Some(args[0].clone()), + [Object::Instance(inst)] => Interpreter::quick_str(inst), _ => None, }; } @@ -1483,6 +4308,69 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option _ => None, }; } + // `weakref.ref(x)` and `weakref.ref(x, callback)`. + if let [target, callback @ ..] = args { + if callback.len() <= 1 && crate::stdlib::weakref_real::is_ref_type(cls) { + return crate::stdlib::weakref_real::ref_pure(target, callback.first()); + } + } + // `dict(d)` of an exact dict, and `dict(zip(xs, ys))` of plain + // sequences with simple keys. + if let [src] = args { + if Rc::ptr_eq(cls, &bt.dict_) { + if crate::stdlib::tracemalloc_real::is_tracking() || crate::gc_trace::auto_collect_due() + { + return None; + } + let data = match src { + // SAFETY: a read between two instructions (cloning runs no + // code). + Object::Dict(d) => unsafe { d.peek() }?.clone(), + Object::LazyIter(l) => dict_from_zip_pure(l)?, + _ => return None, + }; + let obj = Object::Dict(Rc::new(crate::sync::RefCell::new(data))); + crate::gc_trace::track(&obj); + return Some(obj); + } + } + // `bytes(n)`, `bytes(b)`, `bytearray(n)` and `bytearray(b)` of a small + // count or an exact `bytes` or `bytearray` (a copy that runs no code). + let bytes = Rc::ptr_eq(cls, &bt.bytes_); + if bytes || Rc::ptr_eq(cls, &bt.bytearray_) { + let data = match args { + [] => Vec::new(), + [Object::Int(n)] if (0..=1 << 16).contains(n) => vec![0; *n as usize], + // (An exact `bytes` is its own copy.) + [Object::Bytes(_)] if bytes => return Some(args[0].clone()), + // (A `bytearray`'s bytes go straight into the new `bytes`.) + [Object::ByteArray(b)] if bytes => { + return Some(Object::new_bytes(&b.try_borrow().ok()?[..])); + } + // (Likewise a live contiguous view's.) + [Object::MemoryView(mv)] if bytes && !mv.released.get() && mv.is_c_contiguous() => { + return Some(mv.with_bytes(|run| Object::new_bytes(run))); + } + [Object::Bytes(b)] => b.to_vec(), + [Object::ByteArray(b)] => b.try_borrow().ok()?.clone(), + // `bytes(text, "utf-8")`: `text.encode(...)`'s plain codecs, + // every character encodable (anything else, the full + // constructor's). + [Object::Str(_), Object::Str(_)] | [Object::Str(_), Object::Str(_), Object::Str(_)] => { + match crate::builtins::str_encode_leaf(args)?.ok()? { + v @ Object::Bytes(_) if bytes => return Some(v), + Object::Bytes(b) => b.to_vec(), + _ => return None, + } + } + _ => return None, + }; + return Some(if bytes { + Object::new_bytes(data) + } else { + Object::new_bytearray(data) + }); + } // `types.MethodType(func, obj)`: `func` bound to `obj`, as the full // constructor binds it. if Rc::ptr_eq(cls, &bt.method_) { @@ -1522,7 +4410,7 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option Object::Tuple(_) => Some(src.clone()), // SAFETY: a read between two instructions (cloning runs no // code). - Object::List(l) => Some(Object::new_tuple(unsafe { l.peek() }?.clone())), + Object::List(l) => Some(Object::tuple_from_slice(unsafe { l.peek() }?)), _ => None, }; } @@ -1532,9 +4420,9 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option return None; } let items = match src { - Object::Tuple(t) => t.to_vec(), + Object::Tuple(t) => crate::object::cloned_vec(t), // SAFETY: as above. - Object::List(l) => unsafe { l.peek() }?.clone(), + Object::List(l) => crate::object::cloned_vec(unsafe { l.peek() }?), _ => return None, }; let obj = Object::new_list(items); @@ -1553,24 +4441,6 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option _ => None, }; } - if Rc::ptr_eq(cls, &bt.bool_) { - return match x { - Object::Int(i) => Some(Object::Bool(*i != 0)), - Object::Float(f) => Some(Object::Bool(*f != 0.0)), - Object::Bool(b) => Some(Object::Bool(*b)), - Object::None => Some(Object::Bool(false)), - Object::Str(s) => Some(Object::Bool(!s.is_empty())), - // An exact container is true when it holds anything - // (`bool(items)`, as `if items:` reads it). - Object::Bytes(b) => Some(Object::Bool(!b.is_empty())), - Object::Tuple(t) => Some(Object::Bool(!t.is_empty())), - Object::List(l) => Some(Object::Bool(!l.try_borrow().ok()?.is_empty())), - Object::Dict(d) => Some(Object::Bool(!d.try_borrow().ok()?.is_empty())), - Object::Set(s) => Some(Object::Bool(!s.try_borrow().ok()?.is_empty())), - Object::FrozenSet(s) => Some(Object::Bool(s.iter().next().is_some())), - _ => None, - }; - } if Rc::ptr_eq(cls, &bt.str_) { return match x { Object::Int(i) => Some(Object::from_str(i.to_string())), @@ -1599,9 +4469,34 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option step, }))); } + // `set(s)` and `frozenset(s)` of an exact set or frozenset: its table + // copied, hashes and all (no key is hashed or compared); an exact + // frozenset's `frozenset(f)` is `f` itself, as CPython's. + if let [src @ (Object::Set(_) | Object::FrozenSet(_))] = args { + let frozen = Rc::ptr_eq(cls, &bt.frozenset_); + if frozen || Rc::ptr_eq(cls, &bt.set_) { + if frozen && matches!(src, Object::FrozenSet(_)) { + return Some(src.clone()); + } + if crate::stdlib::tracemalloc_real::is_tracking() || crate::gc_trace::auto_collect_due() + { + return None; + } + let data = crate::setalg::with_set(src, crate::object::SetData::clone)?; + let obj = if !frozen { + Object::Set(Rc::new(crate::sync::RefCell::new(data))) + } else if data.is_empty() { + Object::new_frozenset_from(std::iter::empty()) + } else { + Object::FrozenSet(Rc::new(crate::object::FrozenSetObj::new(data))) + }; + crate::gc_trace::track(&obj); + return Some(obj); + } + } // `set(xs)` and `frozenset(xs)` of an exact list or tuple of plain // hashable values: no element's hash or comparison runs any code. - if let [src @ (Object::List(_) | Object::Tuple(_))] = args { + if let [src @ (Object::List(_) | Object::Tuple(_) | Object::Str(_))] = args { let frozen = Rc::ptr_eq(cls, &bt.frozenset_); if frozen || Rc::ptr_eq(cls, &bt.set_) { if crate::stdlib::tracemalloc_real::is_tracking() || crate::gc_trace::auto_collect_due() @@ -1609,12 +4504,18 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option return None; } let borrowed; + let chars: Vec; let items: &[Object] = match src { Object::Tuple(t) => t, Object::List(l) => { borrowed = l.try_borrow().ok()?; &borrowed } + // (A short `str`'s characters: `set(word)`.) + Object::Str(t) if t.len() <= 64 => { + chars = t.chars().map(Object::from_char).collect(); + &chars + } _ => return None, }; // (What this saves is the general call around the build, which @@ -1671,10 +4572,8 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option // names for base 0 (where a decimal literal can't have a leading // zero). Underscores, spaces, and anything that would raise or not fit // a machine word take the full path. - if let [Object::Str(text), Object::Int(base)] = args { - if !Rc::ptr_eq(cls, &bt.int_) { - return None; - } + // (Another class's pair, `enumerate(text, 1)` say, goes on below.) + if let ([Object::Str(text), Object::Int(base)], true) = (args, Rc::ptr_eq(cls, &bt.int_)) { let t: &str = text.as_ref(); let (neg, body) = match t.as_bytes().first() { Some(b'-') => (true, &t[1..]), @@ -1752,9 +4651,12 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option } if Rc::ptr_eq(cls, &bt.reversed_) { return match args { - [Object::List(_) | Object::Tuple(_) | Object::Range(_) | Object::Dict(_)] => { - crate::builtins::b_reversed(args).ok() - } + [Object::List(_) + | Object::Tuple(_) + | Object::Range(_) + | Object::Dict(_) + | Object::Str(_) + | Object::Bytes(_)] => crate::builtins::b_reversed(args).ok(), _ => None, }; } @@ -1768,8 +4670,13 @@ pub(crate) fn builtin_ctor_pure(cls: &Rc, args: &[Object]) -> Option // takes the builtin's full path untouched. // --------------------------------------------------------------------------- -/// `iter(x)` of a native container or an iterator. +/// `iter(x)` of a native container or an iterator, and `iter(f, sentinel)` +/// of a callable (a `callable_iterator`; testing `f` runs no code). pub(crate) fn iter_fast(args: &[Object]) -> Option> { + if let [f, sentinel] = args { + return crate::builtins::object_is_callable(f) + .then(|| Ok(callable_iter(f.clone(), sentinel.clone()))); + } let [x] = args else { return None; }; @@ -1780,6 +4687,8 @@ pub(crate) fn iter_fast(args: &[Object]) -> Option> | Object::Str(_) | Object::Range(_) | Object::Dict(_) + | Object::DictView(_) + | Object::MappingProxy(_) | Object::Set(_) | Object::FrozenSet(_) | Object::Bytes(_) => Object::Iter(Rc::new(RefCell::new(x.make_iter().ok()?))), @@ -1789,12 +4698,14 @@ pub(crate) fn iter_fast(args: &[Object]) -> Option> /// The items `min`/`max`/`sum`/`any`/`all` scan: the positional /// arguments, or a single list or tuple argument's items. -fn scan_items(args: &[Object], multi: bool) -> Option> { +fn scan_items(args: &[Object], multi: bool) -> Option> { + use std::borrow::Cow; match args { - [Object::Tuple(t)] => Some(t.to_vec()), - [Object::List(l)] => Some(l.try_borrow().ok()?.clone()), + [Object::Tuple(t)] => Some(Cow::Owned(crate::object::cloned_vec(t))), + [Object::List(l)] => Some(Cow::Owned(crate::object::cloned_vec(&l.try_borrow().ok()?))), [_] => None, - _ if multi && args.len() > 1 => Some(args.to_vec()), + // (The arguments themselves, read where they are.) + _ if multi && args.len() > 1 => Some(Cow::Borrowed(args)), _ => None, } } @@ -1803,6 +4714,32 @@ fn scan_items(args: &[Object], multi: bool) -> Option> { /// (CPython's rich-comparison loop: a strict comparison keeps the first /// extremum). fn min_max_fast(args: &[Object], want_max: bool) -> Option> { + // (A non-empty byte string's or buffer's extreme byte; an empty one + // raises on the full path.) + let extreme = |b: &[u8]| { + let x = if want_max { + b.iter().max() + } else { + b.iter().min() + }; + x.map(|&x| Ok(Object::Int(i64::from(x)))) + }; + match args { + // `max(a, b)` of two ints or two floats (NaNs ordered as the scan + // below orders them: the first wins unless the second compares + // greater), with no list of items gathered. + [x @ Object::Int(a), y @ Object::Int(b)] => { + let second = if want_max { b > a } else { b < a }; + return Some(Ok(if second { y.clone() } else { x.clone() })); + } + [x @ Object::Float(a), y @ Object::Float(b)] => { + let second = if want_max { b > a } else { b < a }; + return Some(Ok(if second { y.clone() } else { x.clone() })); + } + [Object::Bytes(b)] => return extreme(b), + [Object::ByteArray(b)] => return extreme(&b.try_borrow().ok()?), + _ => {} + } let items = scan_items(args, true)?; let (first, rest) = items.split_first()?; // Ints, big ints and `int` subclasses that keep `int`'s ordering @@ -1824,99 +4761,583 @@ fn min_max_fast(args: &[Object], want_max: bool) -> Option b) || (!want_max && a < b) { best = x; } - } + } + } + // Ints and floats mixed (see the float arm). + Object::Int(_) => { + for x in rest { + let (Some(a), Some(b)) = (exact_f64(x), exact_f64(best)) else { + return None; + }; + if (want_max && a > b) || (!want_max && a < b) { + best = x; + } + } + } + Object::Float(_) => { + for x in rest { + // An int among floats compares by its exact value: as a + // float only while that's exact. + let (Some(a), Some(b)) = (exact_f64(x), exact_f64(best)) else { + return None; + }; + if (want_max && a > b) || (!want_max && a < b) { + best = x; + } + } + } + Object::Str(_) => { + for x in rest { + let (Object::Str(a), Object::Str(b)) = (x, best) else { + return None; + }; + let (a, b): (&str, &str) = (a, b); + if (want_max && a > b) || (!want_max && a < b) { + best = x; + } + } + } + _ => return None, + } + Some(Ok(best.clone())) +} + +/// [`min_max_fast`] over integers: machine ints, big ints, and instances +/// of `int` subclasses that keep `int`'s ordering (see +/// `object::int_order_value`). `None` if any item is anything else. +fn min_max_integers(items: &[Object], want_max: bool) -> Option { + use std::cmp::Ordering; + enum Key<'a> { + Small(i64), + Big(&'a num_bigint::BigInt), + } + fn key(o: &Object) -> Option> { + match o { + Object::Long(b) => Some(Key::Big(b)), + _ => crate::object::int_order_value(o).map(Key::Small), + } + } + let cmp = |a: &Key<'_>, b: &Key<'_>| match (a, b) { + (Key::Small(x), Key::Small(y)) => x.cmp(y), + (Key::Small(x), Key::Big(y)) => num_bigint::BigInt::from(*x).cmp(y), + (Key::Big(x), Key::Small(y)) => (*x).cmp(&num_bigint::BigInt::from(*y)), + (Key::Big(x), Key::Big(y)) => x.cmp(y), + }; + let (first, rest) = items.split_first()?; + let mut best = (first, key(first)?); + for x in rest { + let k = key(x)?; + let ord = cmp(&k, &best.1); + if (want_max && ord == Ordering::Greater) || (!want_max && ord == Ordering::Less) { + best = (x, k); + } + } + Some(best.0.clone()) +} + +/// `int(text, radix)` for plain digits of the radix (an optional sign, +/// surrounding ASCII whitespace) whose value is past a machine int: the +/// big value, built here once. The full constructor, which the arms above +/// otherwise leave such text to, tries the machine parse again at each of +/// its layers before it builds the same value (a UUID's 32 hex digits +/// cost 7,300 instructions that way). `None` for anything malformed, and +/// for decimal-like text past the conversion limit, which the full +/// constructor reports. +fn big_from_digits(text: &str, radix: u32) -> Option { + let t = text.trim_matches(|c: char| c.is_ascii_whitespace()); + let (negative, digits) = match t.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, t.strip_prefix('+').unwrap_or(t)), + }; + // (Digits of the radix, or the text is the full constructor's to + // reject: `int("x12")` in a `try` is an everyday test, and it is tried + // at each layer that reaches these arms.) + if digits.is_empty() || !digits.bytes().all(|b| (b as char).is_digit(radix)) { + return None; + } + if !radix.is_power_of_two() { + let max = crate::stdlib::sys::int_max_str_digits(); + if max > 0 && digits.len() > max as usize { + return None; + } + } + if radix == 16 && !negative { + if let Some(v) = crate::builtins::int_from_plain_hex(digits.as_bytes()) { + return Some(v); + } + } + let big = num_bigint::BigInt::parse_bytes(digits.as_bytes(), radix)?; + Some(Object::int_from_bigint(if negative { -big } else { big })) +} + +/// `int(text)` for plain decimal text (ASCII digits, an optional sign, +/// surrounding ASCII whitespace) that fits a machine int; `None` for +/// anything else, which the full constructor parses (or rejects). +fn decimal_i64(text: &str) -> Option { + let t = text.trim_matches(|c: char| c.is_ascii_whitespace()); + let digits = t.strip_prefix(['+', '-']).unwrap_or(t); + if digits.is_empty() || digits.len() > 18 || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + t.parse().ok() +} + +/// A float's value, or a machine int's when a float holds it exactly +/// (so comparing the two is comparing the numbers). +fn exact_f64(x: &Object) -> Option { + match x { + Object::Float(f) => Some(*f), + Object::Int(i) if i.unsigned_abs() <= 1 << 53 => Some(*i as f64), + _ => None, + } +} + +/// `round(x[, n])` of a plain number with a plain `int` (or no) digit +/// count: the builtin's own arithmetic, which runs no code for these. +pub(crate) fn round_fast(args: &[Object]) -> Option> { + let num = |o: &Object| matches!(o, Object::Int(_) | Object::Float(_) | Object::Bool(_)); + match args { + [x] | [x, Object::None] if num(x) => Some(crate::builtins::b_round(args)), + [x, Object::Int(_)] if num(x) => Some(crate::builtins::b_round(args)), + // A natively served value's own `__round__` (a `Decimal`'s), + // where it runs no Python code. + [Object::Instance(i)] | [Object::Instance(i), Object::Int(_)] => { + crate::Interpreter::native_num_leaf(i, 3, "__round__")?(args) + } + _ => None, + } +} + +/// `repr(x)` of a value whose repr runs no code: a native scalar or a +/// `str`. +pub(crate) fn repr_fast(args: &[Object]) -> Option> { + match args { + [x @ (Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Str(_))] => Some(Ok(Object::from_str(x.repr()))), + _ => None, + } +} + +/// `list.sort()` with no arguments of a list whose comparisons run no +/// code (see [`sort_plain`]): sorted in place. +pub(crate) fn list_sort_fast(args: &[Object]) -> Option> { + let [Object::List(l)] = args else { + return None; + }; + let mut v = l.try_borrow_mut().ok()?; + Some(sort_plain(&mut v, false)?.map(|()| Object::None)) +} + +/// `list.sort(*, key=None, reverse=...)`'s keyword half (see +/// `leaf_builtins::register_fast_kw`): the receiver, then `key` and +/// `reverse`, each `Unbound` when the call left it out. Only no key, and a +/// `bool` or `int` flag, of a list `list_sort_fast` sorts. +pub(crate) fn list_sort_kw_fast(args: &[Object]) -> Option> { + let [Object::List(l), key, reverse] = args else { + return None; + }; + let reverse = plain_sort_flag(reverse)?; + let mut v = l.try_borrow_mut().ok()?; + Some(sort_maybe_keyed(&mut v, key, reverse)?.map(|()| Object::None)) +} + +/// `sorted(iterable, /, *, key=None, reverse=...)`'s keyword half, as +/// [`list_sort_kw_fast`] for a list's or tuple's items: a new list. +pub(crate) fn sorted_kw_fast(args: &[Object]) -> Option> { + let [iterable, key, reverse] = args else { + return None; + }; + let reverse = plain_sort_flag(reverse)?; + let mut v = match iterable { + Object::List(l) => l.try_borrow().ok()?.clone(), + Object::Tuple(t) => crate::object::cloned_vec(t), + // A dict's keys, or a view's keys, values or `(key, value)` items, + // in the dict's order (cloning them runs no code). + Object::Dict(d) => d.try_borrow().ok()?.keys().map(|k| k.0.clone()).collect(), + Object::DictView(view) => { + let d = view.dict.try_borrow().ok()?; + match view.kind { + crate::object::DictViewKind::Keys => d.keys().map(|k| k.0.clone()).collect(), + crate::object::DictViewKind::Values => d.values().cloned().collect(), + crate::object::DictViewKind::Items => d + .iter() + .map(|(k, v)| Object::new_tuple_array([k.0.clone(), v.clone()])) + .collect(), + } + } + _ => return None, + }; + Some(sort_maybe_keyed(&mut v, key, reverse)?.map(|()| { + let obj = Object::new_list(v); + crate::gc_trace::track(&obj); + obj + })) +} + +/// The direction a keyword sort runs in (`None` for a flag whose truth +/// could run code). +fn plain_sort_flag(reverse: &Object) -> Option { + match *reverse { + Object::Unbound => Some(false), + Object::Bool(b) => Some(b), + Object::Int(i) => Some(i != 0), + _ => None, + } +} + +/// [`sort_plain`] of `v`, or with `key` (not `None`) a key function whose +/// keys compute without running code (see [`native_sort_keys`]), the items +/// sorted by those keys as CPython's `list.sort` decorates them. `None`, `v` +/// untouched, for anything else. +fn sort_maybe_keyed( + v: &mut [Object], + key: &Object, + reverse: bool, +) -> Option> { + if matches!(key, Object::Unbound | Object::None) { + return sort_plain(v, reverse); + } + let keys = native_sort_keys(v, key)?; + let kind = plain_kind(&keys)?; + // Each item moves beside its key (its slot left `None`) and back after. + let mut pairs: Vec<(Object, Object)> = Vec::with_capacity(v.len()); + for (k, item) in keys.into_iter().zip(v.iter_mut()) { + pairs.push((k, std::mem::replace(item, Object::None))); + } + if reverse { + pairs.reverse(); + } + let sorted = sort_by_kind(&mut pairs, kind, |p| &p.0); + if reverse { + pairs.reverse(); + } + // (The keys are plain values, and the slots hold `None`: what drops here + // runs no code.) + for (slot, (_, item)) in v.iter_mut().zip(pairs) { + *slot = item; + } + Some(sorted) +} + +/// Each item's key under `key` when computing it runs no code: `len` of a +/// string or built-in container, or an instance whose native `__call__` +/// has a leaf half (`itemgetter(1)`, `attrgetter("x")`). `None` for any +/// other key function, or an item it declines. +/// What a sort key reads from each item: the native getters' part, or a +/// lambda's (see [`crate::lambda_part`]). +fn part_key(key: &Object) -> Option { + if let Some(i) = crate::stdlib::operator_accel::itemgetter_single_index(key) { + return Some(crate::PartShape::Index(i)); + } + if let Some(k) = crate::stdlib::operator_accel::itemgetter_single_key(key) { + return Some(crate::PartShape::Key(k)); + } + if let Some(n) = crate::stdlib::operator_accel::attrgetter_single_name(key) { + return Some(crate::PartShape::Attr(n)); + } + match key { + Object::Function(f) => crate::lambda_part(f), + _ => None, + } +} + +/// Whether `place` (see [`attr_field_place`]) is not `v`'s class's. +#[inline] +fn placed_miss(place: Option<&(Rc, u64, usize)>, v: &Object) -> bool { + match (place, v) { + (Some((cls, ver, _)), Object::Instance(i)) => { + !std::ptr::eq(i.cls_raw(), Rc::as_ptr(cls)) || cls.attr_version.get() != *ver + } + (None, Object::Instance(_)) => true, + _ => false, + } +} + +/// Where the plain instance `v` keeps the attribute `name` among its +/// class's shared names, when `getattr(v, name)` is that instance value +/// (the class supplies nothing for the name, as +/// `Interpreter::leaf_getattr_value` noted under the class's version): +/// the class, its version, and the position, at which every instance of +/// the class whose attributes are still split over those names holds the +/// attribute (see `PyInstance::split_field`). +fn attr_field_place(v: &Object, name: &str) -> Option<(Rc, u64, usize)> { + let Object::Instance(i) = v else { return None }; + let cls = i.cls_raw(); + if i.native.get().is_some() + || cls.native_kind.get() != 0 + || !matches!( + crate::instance_getattr_memo(cls, name), + Some(crate::InstGetattrClass::Nothing | crate::InstGetattrClass::Shadowed) + ) + { + return None; + } + let idx = i.attr_position_str(name)? as usize; + // SAFETY: a read that runs no code. + unsafe { i.split_field(idx) }?; + let cls = i.cls(); + let ver = cls.attr_version.get(); + Some((cls, ver, idx)) +} + +fn native_sort_keys(items: &[Object], key: &Object) -> Option> { + let ptr = crate::vm_singletons::current_interpreter_ptr()?; + // SAFETY: published by the enclosing VM frame on this thread; only its + // tables are read. + let interp = unsafe { &*ptr }; + let part = part_key(key); + // `itemgetter(i)` or `lambda x: x[i]` of tuples or lists: each item's + // `i`th element. + if let Some(crate::PartShape::Index(i)) = part { + let at = |len: usize| { + let k = if i < 0 { i + len as i64 } else { i }; + usize::try_from(k).ok().filter(|&k| k < len) + }; + let mut keys = Vec::with_capacity(items.len()); + for item in items { + keys.push(match item { + Object::Tuple(t) => t.get(at(t.len())?)?.clone(), + // SAFETY: a read that runs no code. + Object::List(l) => { + let xs = unsafe { l.peek() }?; + xs.get(at(xs.len())?)?.clone() + } + _ => return None, + }); } - // Ints and floats mixed (see the float arm). - Object::Int(_) => { - for x in rest { - let (Some(a), Some(b)) = (exact_f64(x), exact_f64(best)) else { - return None; - }; - if (want_max && a > b) || (!want_max && a < b) { - best = x; + return Some(keys); + } + // `lambda r: r["name"]` of exact dicts: each one's value for the key (a + // miss is the full call's `KeyError`). + if let Some(crate::PartShape::Key(k)) = &part { + let probe = crate::object::LeafProbe::new(k)?; + let mut keys = Vec::with_capacity(items.len()); + for item in items { + let Object::Dict(d) = item else { + return None; + }; + // SAFETY: a read that runs no code. + keys.push(unsafe { d.peek() }?.get(&probe)?.clone()); + } + return Some(keys); + } + // `attrgetter(name)`: each item's attribute, as `getattr` reads it + // natively; a `__slots__` member's straight from its laid-out place + // once the class's first item has found it there. + if let Some(crate::PartShape::Attr(name)) = part { + let Object::Str(s) = &name else { + return None; + }; + let s: &str = s; + let mut keys = Vec::with_capacity(items.len()); + let mut slot: Option<(*const crate::types::TypeObject, usize)> = None; + for item in items { + if let (Object::Instance(inst), Some((cls, ix))) = (item, slot) { + if std::ptr::eq(inst.cls_raw(), cls) { + // SAFETY: a read that runs no code. + let v = unsafe { inst.slots.peek() } + .and_then(|sl| sl.get_index(ix)) + .filter(|(k, v)| { + matches!(&k.0, Object::Str(n) if { let n: &str = n; n == s }) + && !matches!(v, Object::Unbound) + }); + if let Some((_, v)) = v { + keys.push(v.clone()); + continue; + } } } + keys.push(crate::Interpreter::leaf_getattr_value(item, &name)?); + if let Object::Instance(inst) = item { + slot = crate::Interpreter::slot_member_position(inst, s) + .map(|ix| (std::ptr::from_ref(inst.cls_raw()), ix)); + } } - Object::Float(_) => { - for x in rest { - // An int among floats compares by its exact value: as a - // float only while that's exact. - let (Some(a), Some(b)) = (exact_f64(x), exact_f64(best)) else { - return None; - }; - if (want_max && a > b) || (!want_max && a < b) { - best = x; + return Some(keys); + } + let is_len = + matches!(key, Object::Builtin(b) if Rc::as_ptr(b) as usize == interp.leaf_fns().len_ptr); + // A builtin the leaf registry vouches runs no code (`abs`), or a bound + // one over its receiver (`d.get`): its leaf half on each item. + let leaf = match key { + _ if is_len => None, + Object::Builtin(b) => Some((b, None)), + Object::BoundMethod(bm) if !bm.redispatch_descriptor => match &bm.function { + Object::Builtin(b) => Some((b, Some(&bm.receiver))), + _ => None, + }, + _ => None, + }; + if let Some((b, recv)) = leaf { + if let Some(kind) = interp.leaf_call_kind(b) { + // `key=d.__getitem__` or `key=d.get` of an exact dict + // (`sorted(d, key=d.get)`): one view of its table, each item's + // value found by the native probe. + if let Some(Object::Dict(d)) = recv { + let get = matches!(kind, LeafKind::DictGet); + if get + || matches!(kind, LeafKind::Fast(f) + if f as usize == crate::builtins::dict_getitem_leaf as crate::leaf_builtins::Fast as usize) + { + return dict_value_keys(d, items, get); } } - } - Object::Str(_) => { - for x in rest { - let (Object::Str(a), Object::Str(b)) = (x, best) else { - return None; + let mut keys = Vec::with_capacity(items.len()); + for item in items { + let k = match recv { + Some(r) => interp.leaf_builtin_call(kind, b, &[r.clone(), item.clone()]), + None => interp.leaf_builtin_call(kind, b, std::slice::from_ref(item)), }; - let (a, b): (&str, &str) = (a, b); - if (want_max && a > b) || (!want_max && a < b) { - best = x; - } + keys.push(k?.ok()?); } + return Some(keys); } - _ => return None, } - Some(Ok(best.clone())) + let call_fast = if is_len { + None + } else { + Some(interp.instance_call_fast(key)?) + }; + let mut keys = Vec::with_capacity(items.len()); + for item in items { + let k = match call_fast { + None => match item { + Object::Str(_) + | Object::List(_) + | Object::Tuple(_) + | Object::Dict(_) + | Object::Set(_) + | Object::FrozenSet(_) + | Object::Bytes(_) => Object::Int(i64::try_from(item.len().ok()?).ok()?), + _ => return None, + }, + Some(fast) => { + // SAFETY: bitwise views of the live key function and item, + // never dropped (the half clones what it keeps). + let views = std::mem::ManuallyDrop::new(unsafe { + [std::ptr::read(key), std::ptr::read(item)] + }); + fast(&views[..])?.ok()? + } + }; + keys.push(k); + } + Some(keys) } -/// [`min_max_fast`] over integers: machine ints, big ints, and instances -/// of `int` subclasses that keep `int`'s ordering (see -/// `object::int_order_value`). `None` if any item is anything else. -fn min_max_integers(items: &[Object], want_max: bool) -> Option { - use std::cmp::Ordering; - enum Key<'a> { - Small(i64), - Big(&'a num_bigint::BigInt), - } - fn key(o: &Object) -> Option> { - match o { - Object::Long(b) => Some(Key::Big(b)), - _ => crate::object::int_order_value(o).map(Key::Small), - } +/// Sort `v` in place, as the interpreter's sort does, when its items are +/// strings only, plain numbers only, or tuples of ints and strings +/// (comparisons that run no code); +/// `None`, `v` untouched, for any other items. A reverse sort reverses, +/// sorts and reverses again, as CPython's does, so equal items keep their +/// order. +fn sort_plain(v: &mut [Object], reverse: bool) -> Option> { + let kind = plain_kind(v)?; + if reverse { + v.reverse(); } - let cmp = |a: &Key<'_>, b: &Key<'_>| match (a, b) { - (Key::Small(x), Key::Small(y)) => x.cmp(y), - (Key::Small(x), Key::Big(y)) => num_bigint::BigInt::from(*x).cmp(y), - (Key::Big(x), Key::Small(y)) => (*x).cmp(&num_bigint::BigInt::from(*y)), - (Key::Big(x), Key::Big(y)) => x.cmp(y), - }; - let (first, rest) = items.split_first()?; - let mut best = (first, key(first)?); - for x in rest { - let k = key(x)?; - let ord = cmp(&k, &best.1); - if (want_max && ord == Ordering::Greater) || (!want_max && ord == Ordering::Less) { - best = (x, k); - } + let sorted = sort_by_kind(v, kind, |o| o); + if reverse { + v.reverse(); } - Some(best.0.clone()) + Some(sorted) } -/// `int(text)` for plain decimal text (ASCII digits, an optional sign, -/// surrounding ASCII whitespace) that fits a machine int; `None` for -/// anything else, which the full constructor parses (or rejects). -fn decimal_i64(text: &str) -> Option { - let t = text.trim_matches(|c: char| c.is_ascii_whitespace()); - let digits = t.strip_prefix(['+', '-']).unwrap_or(t); - if digits.is_empty() || digits.len() > 18 || !digits.bytes().all(|b| b.is_ascii_digit()) { +/// Which plain kind every item of `v` is, for [`sort_by_kind`]: strings only +/// (0), ints only (1), floats only (4), plain numbers only (2), or tuples +/// of ints and strings (3); `None` for anything else. +fn plain_kind(v: &[Object]) -> Option { + Some(if v.iter().all(|x| matches!(x, Object::Str(_))) { + 0 + } else if v.iter().all(|x| matches!(x, Object::Int(_))) { + 1 + } else if v.iter().all(|x| matches!(x, Object::Float(_))) { + 4 + } else if v + .iter() + .all(|x| matches!(x, Object::Int(_) | Object::Float(_) | Object::Bool(_))) + { + 2 + } else if v.iter().all(|x| { + matches!(x, Object::Tuple(t) if t.iter().all(|e| matches!(e, Object::Int(_) | Object::Bool(_) | Object::Str(_)))) + }) { + 3 + } else { return None; + }) +} + +/// Sort `v` stably by the values `value` gives, all of [`plain_kind`] +/// `kind`, as the interpreter's sort compares them, running no code: +/// code-point order for strings (which their UTF-8 bytes sort in), and +/// CPython's tuple order, the first unequal place deciding (an int against +/// a string raises as the interpreter's comparison does). Each kind's +/// comparison is its own closure. +fn sort_by_kind( + v: &mut [T], + kind: u8, + value: impl Fn(&T) -> &Object, +) -> Result<(), RuntimeError> { + use weavepy_compiler::CompareKind as C; + match kind { + 0 => crate::timsort::sort(v, |a, b| { + Ok(match (value(a), value(b)) { + (Object::Str(a), Object::Str(b)) => a.as_bytes() < b.as_bytes(), + _ => false, + }) + }), + 1 => crate::timsort::sort(v, |a, b| { + Ok(match (value(a), value(b)) { + (Object::Int(a), Object::Int(b)) => a < b, + _ => false, + }) + }), + 2 => crate::timsort::sort(v, |a, b| crate::compare_op(value(a), value(b), C::Lt)), + // (`<` of two floats, a NaN on either side false, as the + // interpreter's comparison gives it.) + 4 => crate::timsort::sort(v, |a, b| { + Ok(match (value(a), value(b)) { + (Object::Float(a), Object::Float(b)) => a < b, + _ => false, + }) + }), + _ => crate::timsort::sort(v, |a, b| { + let (Object::Tuple(a), Object::Tuple(b)) = (value(a), value(b)) else { + return Ok(false); + }; + for (x, y) in a.iter().zip(b.iter()) { + match plain_elem_order(x, y) { + Some(std::cmp::Ordering::Equal) => {} + Some(o) => return Ok(o == std::cmp::Ordering::Less), + None => { + if !x.eq_value(y) { + return crate::compare_op(x, y, C::Lt); + } + } + } + } + Ok(a.len() < b.len()) + }), } - t.parse().ok() } -/// A float's value, or a machine int's when a float holds it exactly -/// (so comparing the two is comparing the numbers). -fn exact_f64(x: &Object) -> Option { - match x { - Object::Float(f) => Some(*f), - Object::Int(i) if i.unsigned_abs() <= 1 << 53 => Some(*i as f64), +/// How two of [`plain_kind`]'s tuple elements order when they're of one +/// kind: two ints or bools by value, two strings in code-point order +/// (their UTF-8 bytes'). `None` for a string beside a number, which the +/// interpreter's comparison settles (it raises). +#[inline] +fn plain_elem_order(x: &Object, y: &Object) -> Option { + let int = |o: &Object| match o { + Object::Int(i) => Some(*i), + Object::Bool(b) => Some(i64::from(*b)), _ => None, + }; + match (x, y) { + (Object::Str(a), Object::Str(b)) => Some(a.as_bytes().cmp(b.as_bytes())), + _ => Some(int(x)?.cmp(&int(y)?)), } } @@ -1926,6 +5347,11 @@ pub(crate) fn abs_fast(args: &[Object]) -> Option> [Object::Int(i)] => Object::Int(i.checked_abs()?), [Object::Float(f)] => Object::Float(f.abs()), [Object::Bool(b)] => Object::Int(i64::from(*b)), + // A natively served value's own `__abs__` (a `Decimal`'s, a + // `timedelta`'s), where it runs no Python code. + [Object::Instance(i)] => { + return crate::Interpreter::native_num_leaf(i, 2, "__abs__")?(args) + } _ => return None, })) } @@ -1937,11 +5363,168 @@ pub(crate) fn plain_hashable(x: &Object, depth: u32) -> bool { match x { Object::Int(_) | Object::Bool(_) | Object::None | Object::Str(_) | Object::Bytes(_) => true, Object::Float(f) => !f.is_nan(), - Object::Tuple(t) => depth < 4 && t.iter().all(|e| plain_hashable(e, depth + 1)), + // (An element that's a scalar or a string is settled here: only a + // nested tuple or a float costs a call.) + Object::Tuple(t) => { + depth < 4 + && t.iter().all(|e| { + matches!( + e, + Object::Int(_) + | Object::Bool(_) + | Object::None + | Object::Str(_) + | Object::Bytes(_) + ) || plain_hashable(e, depth + 1) + }) + } _ => false, } } +/// `dict(zip(xs, ys))` over two plain list or tuple cursors whose keys +/// hash and compare without running code ([`plain_hashable`]): the dict, +/// with both cursors left as the general `zip` step leaves them (the first +/// source one past the pairs when the second ran out first, and the source +/// that ran out finished). `None`, nothing consumed, for anything else, or +/// when finishing a source would free its list (which could run code). +pub(crate) fn dict_from_zip_pure(l: &PyLazyIter) -> Option { + use crate::object::PyIterator; + // (No more pairs than CPython's own loop would take without a look at + // anything else in a few tens of milliseconds.) + const MAX_PAIRS: usize = 1 << 20; + // SAFETY: nothing below runs code; the views end with this call. + let st = unsafe { l.state.peek_mut() }?; + let LazyIterKind::Zip { + iters, + strict: false, + held, + .. + } = st + else { + return None; + }; + if !held.is_empty() { + return None; + } + let [Object::Iter(ca), Object::Iter(cb)] = iters.as_slice() else { + return None; + }; + if Rc::ptr_eq(ca, cb) { + return None; + } + // SAFETY: two distinct cells, as above. + let (ia, ib) = unsafe { (ca.peek_mut()?, cb.peek_mut()?) }; + // What a cursor has left: items, or a string's characters. + #[derive(Clone, Copy)] + enum Src<'a> { + Items(&'a [Object]), + Text(&'a str), + } + // A cursor's items from its position, and whether finishing it frees + // nothing. + fn rest(it: &PyIterator) -> Option<(Src<'_>, bool)> { + match it { + PyIterator::List { + items, + index, + owner: None, + } => { + // SAFETY: a read that runs no code. + let v = unsafe { items.peek() }?; + Some(( + Src::Items(v.get(*index..).unwrap_or(&[])), + Rc::strong_count(items) > 1, + )) + } + PyIterator::Tuple { items, index } => { + Some((Src::Items(items.get(*index..).unwrap_or(&[])), true)) + } + // (`zip("abc", values)`: each character a one-character + // string; finishing it frees only text.) + PyIterator::Str { s, index } => Some((Src::Text(s.get(*index..)?), true)), + _ => None, + } + } + // The items of a source, its characters made strings. + enum Items<'a> { + Slice(std::slice::Iter<'a, Object>), + Chars(std::str::Chars<'a>), + } + impl Iterator for Items<'_> { + type Item = Object; + #[inline] + fn next(&mut self) -> Option { + match self { + Items::Slice(it) => it.next().cloned(), + Items::Chars(it) => it.next().map(Object::from_char), + } + } + } + fn items(s: Src<'_>) -> Items<'_> { + match s { + Src::Items(v) => Items::Slice(v.iter()), + Src::Text(t) => Items::Chars(t.chars()), + } + } + let ((xs, a_free), (ys, b_free)) = (rest(ia)?, rest(ib)?); + // (A string's characters counted only as far as the other source + // reaches, and one past it.) + let bound = match (xs, ys) { + (Src::Items(v), Src::Items(w)) => v.len().min(w.len()), + (Src::Items(v), _) | (_, Src::Items(v)) => v.len(), + _ => MAX_PAIRS, + } + .min(MAX_PAIRS); + let len = |s: Src<'_>| match s { + Src::Items(v) => v.len(), + Src::Text(t) => t.chars().take(bound + 1).count(), + }; + let (la, lb) = (len(xs), len(ys)); + let n = la.min(lb); + let first_ends = la <= lb; + if n > MAX_PAIRS || !(if first_ends { a_free } else { b_free }) { + return None; + } + if let Src::Items(v) = xs { + if !v[..n].iter().all(|k| plain_hashable(k, 0)) { + return None; + } + } + let mut data = crate::object::DictData::default(); + data.reserve(n); + for (k, v) in items(xs).zip(items(ys)).take(n) { + data.insert(crate::object::DictKey(k), v); + } + // (Keys that mostly repeated leave most of the room unused.) + if n > 64 && data.len() * 4 < n { + data.shrink_to_fit(); + } + // (The general step takes the first source's next item before it + // finds the second finished.) + let advance = |it: &mut PyIterator, by: usize| match it { + PyIterator::List { index, .. } | PyIterator::Tuple { index, .. } => *index += by, + PyIterator::Str { s, index } => { + *index += s[*index..] + .chars() + .take(by) + .map(char::len_utf8) + .sum::(); + } + _ => {} + }; + if first_ends { + advance(ia, n); + advance(ib, n); + let _ = ia.next_value(); + } else { + advance(ia, n + 1); + advance(ib, n); + let _ = ib.next_value(); + } + Some(data) +} + /// `hash(x)` of a value whose hash runs no Python code and can't fail /// ([`plain_hashable`]), or an instance's where that holds. pub(crate) fn hash_fast(args: &[Object]) -> Option> { @@ -1955,6 +5538,16 @@ pub(crate) fn hash_fast(args: &[Object]) -> Option> return Some(Ok(Object::Int(crate::object::identity_hash(x)))); } } + // A tuple subclass that keeps `tuple`'s `__hash__` (a named tuple) over + // plain items: its tuple's hash. + if let Object::Instance(i) = x { + if crate::object::tuple_like_value(i).is_some() { + let payload = i.native.get()?; + return plain_hashable(payload, 0) + .then(|| crate::object::py_hash_value(payload).map(|h| Ok(Object::Int(h)))) + .flatten(); + } + } // An instance whose Python `__hash__` evaluates as a pure leaf (a frozen // dataclass's `hash((self.a, self.b))`). if let Object::Instance(_) = x { @@ -2076,6 +5669,12 @@ pub(crate) fn chr_fast(args: &[Object]) -> Option> /// `divmod(a, b)` of plain ints, floored as Python's (a zero divisor /// raises on the full path). pub(crate) fn divmod_fast(args: &[Object]) -> Option> { + // A natively served value's own `__divmod__` (a `Decimal`'s), where + // it settles the pair without running Python code (an operand it + // doesn't take, a subclass's among them, is left to the full call). + if let [Object::Instance(i), _] = args { + return crate::Interpreter::native_num_leaf(i, 4, "__divmod__")?(args); + } let [Object::Int(a), Object::Int(b)] = args else { return None; }; @@ -2101,6 +5700,102 @@ pub(crate) fn max_fast(args: &[Object]) -> Option> min_max_fast(args, true) } +/// `min(iterable, *, key=None, default=...)`'s keyword half (see +/// `leaf_builtins::register_fast_kw`): the iterable, then `key` and +/// `default`, each `Unbound` when the call left it out. No key: the +/// positional half's answer, or the default for an empty list or tuple. +pub(crate) fn min_kw_fast(args: &[Object]) -> Option> { + min_max_kw_fast(args, false) +} + +/// [`min_kw_fast`] for `max`. +pub(crate) fn max_kw_fast(args: &[Object]) -> Option> { + min_max_kw_fast(args, true) +} + +fn min_max_kw_fast(args: &[Object], want_max: bool) -> Option> { + let [iterable, key, default] = args else { + return None; + }; + if !matches!(key, Object::Unbound | Object::None) { + return min_max_keyed(iterable, key, default, want_max); + } + let empty = match iterable { + Object::List(l) => l.try_borrow().ok()?.is_empty(), + Object::Tuple(t) => t.is_empty(), + _ => false, + }; + if empty { + return match default { + Object::Unbound => None, + d => Some(Ok(d.clone())), + }; + } + min_max_fast(std::slice::from_ref(iterable), want_max) +} + +/// [`min_max_kw_fast`] with a key function [`native_sort_keys`] computes +/// without running code (`max(d, key=d.get)`), over a list's, a tuple's or +/// a dict's items whose keys are all ints, all floats or all strings: the +/// first item with the least (or greatest) key, as CPython keeps it. +fn min_max_keyed( + iterable: &Object, + key: &Object, + default: &Object, + want_max: bool, +) -> Option> { + let items: Vec = match iterable { + Object::List(l) => l.try_borrow().ok()?.clone(), + Object::Tuple(t) => crate::object::cloned_vec(t), + Object::Dict(d) => d.try_borrow().ok()?.keys().map(|k| k.0.clone()).collect(), + _ => return None, + }; + if items.is_empty() { + return match default { + Object::Unbound => None, + d => Some(Ok(d.clone())), + }; + } + let keys = native_sort_keys(&items, key)?; + // (Whether `a` replaces the best so far `b`: strictly beyond it.) + let beyond = |a: &Object, b: &Object| -> Option { + Some(match (a, b) { + (Object::Int(x), Object::Int(y)) => { + if want_max { + x > y + } else { + x < y + } + } + (Object::Float(x), Object::Float(y)) => { + if want_max { + x > y + } else { + x < y + } + } + (Object::Str(x), Object::Str(y)) => { + let (x, y): (&str, &str) = (x, y); + if want_max { + x > y + } else { + x < y + } + } + _ => return None, + }) + }; + let mut best = 0; + for i in 1..keys.len() { + if beyond(&keys[i], &keys[best])? { + best = i; + } + } + // (A lone item's key still has to be one of the plain kinds.) + beyond(&keys[0], &keys[0])?; + Some(Ok(items[best].clone())) +} + /// `sum(xs)` of plain ints that stays a machine int. pub(crate) fn sum_fast(args: &[Object]) -> Option> { let mut total: i64 = 0; @@ -2111,9 +5806,24 @@ pub(crate) fn sum_fast(args: &[Object]) -> Option> total = total.checked_add(*i)?; Some(()) }; + // (A byte string's or buffer's bytes: their total can't overflow.) + let bytes_total = |b: &[u8]| b.iter().map(|&x| u64::from(x)).sum::() as i64; + // (A list or tuple with floats, or past a machine int: the numeric + // sum's int-then-float loops, which run no code either.) + let numeric = || crate::builtins::sum_numeric_sequence(&args[0], &Object::Int(0)); match args { - [Object::Tuple(t)] => t.iter().try_for_each(&mut add)?, - [Object::List(l)] => l.try_borrow().ok()?.iter().try_for_each(&mut add)?, + [Object::Tuple(t)] => { + if t.iter().try_for_each(&mut add).is_none() { + return numeric(); + } + } + [Object::List(l)] => { + if l.try_borrow().ok()?.iter().try_for_each(&mut add).is_none() { + return numeric(); + } + } + [Object::Bytes(b)] => return Some(Ok(Object::Int(bytes_total(b)))), + [Object::ByteArray(b)] => return Some(Ok(Object::Int(bytes_total(&b.try_borrow().ok()?)))), _ => return None, } Some(Ok(Object::Int(total))) @@ -2153,6 +5863,57 @@ pub(crate) fn all_fast(args: &[Object]) -> Option> any_all_fast(args, false) } +/// `list(enumerate(xs))` over a list or tuple iterator: the pairs of the +/// rest of the source at once, both cursors advanced past them and the +/// source detached as its end leaves it. `None`, nothing stepped, for any +/// other iterator or a count that would overflow. +pub(crate) fn enumerate_seq_collect(it: &Object) -> Option> { + let Object::Iter(c) = it else { + return None; + }; + let mut e = c.try_borrow_mut().ok()?; + let PyIterator::Enumerate { + inner, + count, + count_big: None, + } = &mut *e + else { + return None; + }; + let mut src = inner.try_borrow_mut().ok()?; + let rest: Vec = match &*src { + PyIterator::List { + items, + index, + owner: None, + } => items + .try_borrow() + .ok()? + .get(*index..) + .unwrap_or(&[]) + .to_vec(), + PyIterator::Tuple { items, index } => items.get(*index..).unwrap_or(&[]).to_vec(), + _ => return None, + }; + let start = *count; + *count = count.checked_add(i64::try_from(rest.len()).ok()?)?; + match &mut *src { + PyIterator::List { index, .. } | PyIterator::Tuple { index, .. } => *index += rest.len(), + _ => unreachable!("checked above"), + } + // (The step past the end detaches the source, as the last one does.) + let detached = src.next_value(); + drop(src); + drop(e); + drop(detached); + Some( + rest.into_iter() + .zip(start..) + .map(|(x, k)| Object::new_tuple_array([Object::Int(k), x])) + .collect(), + ) +} + /// The `(index, item)` step of an `enumerate` over a native iterator /// whose step runs no code, without the tuple (a loop that unpacks it): /// `None` for any other iterator or step. @@ -2172,6 +5933,26 @@ pub(crate) fn enumerate_pure_pair(it: &Object) -> Option<(Object, Object)> { let next = count.checked_add(1)?; // SAFETY: as above; `inner` is a cell of its own. let src = unsafe { inner.peek_mut() }?; + // A list's or tuple's next item, read in place (their end goes through + // `next_value`, which detaches the source). + let item = match src { + PyIterator::List { + items, + index, + owner: None, + } => unsafe { items.peek() } + .and_then(|xs| xs.get(*index)) + .map(crate::clone_hot), + PyIterator::Tuple { items, index } => items.get(*index).map(crate::clone_hot), + _ => None, + }; + if let Some(v) = item { + if let PyIterator::List { index, .. } | PyIterator::Tuple { index, .. } = src { + *index += 1; + } + let i = std::mem::replace(count, next); + return Some((Object::Int(i), v)); + } if !src.pure_ready() { return None; } @@ -2180,8 +5961,75 @@ pub(crate) fn enumerate_pure_pair(it: &Object) -> Option<(Object, Object)> { Some((Object::Int(i), v)) } +/// The rest of `filter(None, xs)` or `filter(bool, xs)` over a plain list +/// or tuple cursor whose items' truth runs no code, taken at once (see +/// [`filter_seq_bulk`]): `None`, nothing consumed, for anything else. +pub(crate) fn filter_collect(l: &PyLazyIter) -> Option> { + // SAFETY: nothing below runs code; the view ends with this call. + let st = unsafe { l.state.peek() }?; + let LazyIterKind::Filter { func, source } = st else { + return None; + }; + let mut out = Vec::new(); + filter_seq_bulk(func, source, &mut out).then_some(out) +} + /// The truth of a value whose truth is plain data (`None` for anything /// whose `__bool__`/`__len__` could run code). +/// `filter(None, xs)` or `filter(bool, xs)` drained over a plain list or +/// tuple cursor whose items left all have a truth that runs no code (see +/// [`scalar_truth`]): the items kept appended to `out` at once, and the +/// cursor stepped to its end and then past it, as stepping it item by item +/// leaves it. `false`, nothing consumed, for anything else. +fn filter_seq_bulk(func: &Object, source: &Object, out: &mut Vec) -> bool { + let plain = match func { + Object::None => true, + Object::Type(t) => Rc::ptr_eq(t, &builtin_types().bool_), + _ => false, + }; + let Object::Iter(c) = source else { + return false; + }; + if !plain { + return false; + } + { + // SAFETY: a view that runs no code (cloning a scalar or a string + // runs none) and ends in this block. + let Some((xs, idx)) = (unsafe { c.peek_mut() }).and_then(seq_cursor) else { + return false; + }; + let Some(rest) = xs.get(*idx..) else { + return false; + }; + if rest.is_empty() { + return false; + } + let mut kept = 0; + for x in rest { + match scalar_truth(x) { + Some(keep) => kept += usize::from(keep), + None => return false, + } + } + out.reserve(kept); + for x in rest { + if scalar_truth(x) == Some(true) { + out.push(x.clone()); + } + } + *idx = xs.len(); + } + // (The step that finds the end, so the cursor records its exhaustion; + // what that releases holds only scalars and strings.) + if let Ok(mut cursor) = c.try_borrow_mut() { + let end = cursor.next_value(); + drop(cursor); + drop(end); + } + true +} + fn scalar_truth(v: &Object) -> Option { Some(match v { Object::Bool(b) => *b, @@ -2225,6 +6073,26 @@ fn cursor_peek(c: &Rc>) -> Option { unsafe { c.peek() }?.pure_peek() } +/// The next items of two distinct plain cursors (a list's, a tuple's or a +/// range's each), both stepped past: `None`, neither touched, unless both +/// have one. +#[inline] +fn cursor_pair_next( + x: &Rc>, + y: &Rc>, +) -> Option<(Object, Object)> { + // SAFETY: reads and steps that run no code, on two distinct cells (the + // callers' check); the views end with this call. + let (cx, cy) = unsafe { (x.peek_mut()?, y.peek_mut()?) }; + if !cy.pure_has_next() { + return None; + } + let a = cx.pure_next()?; + // (Promised just above.) + let c = cy.pure_next().unwrap_or(Object::None); + Some((a, c)) +} + /// Step past the item [`cursor_peek`] found. #[inline] fn cursor_advance(c: &Rc>) -> Option<()> { @@ -2247,10 +6115,72 @@ pub(crate) fn pure_callback_maybe(func: &Object) -> bool { }; // SAFETY: a function's code is only replaced under the GIL, and the // reference ends here. - crate::code_is_pure_leaf(unsafe { &*f.code.as_ptr() }) + let code = unsafe { &*f.code.as_ptr() }; + crate::code_is_pure_leaf(code) || crate::code_forwards(code) || crate::code_reads_part(code) } impl Interpreter { + /// [`Self::pure_callback`] of a forwarding wrapper `f` (see + /// [`crate::code_forwards`]: a decorator's `def w(*args, **kwargs): + /// return fn(*args, **kwargs)`) called positionally: its target's + /// pure call over the same arguments, with no frame for the wrapper. + /// Nothing observes the elided frame: the target's evaluation runs no + /// code and declines anything that would raise (the full call then + /// raises it, through the wrapper), and no hook may be set. The + /// target is a pure leaf or another pure callback, never a further + /// wrapper. + pub(crate) fn forward_pure_call( + &self, + f: &crate::object::PyFunction, + args: &[Object], + effects: bool, + ) -> Option { + // SAFETY: a function's code is only replaced under the GIL, and + // nothing here runs code that could replace it. + let code = unsafe { &*f.code.as_ptr() }; + if !crate::code_forwards(code) + || crate::trace::any_observers_active() + || crate::recursion::current_depth() + 1 >= crate::recursion::recursion_limit() + { + return None; + } + let Some(Object::Cell(cell)) = f.closure.first() else { + return None; + }; + // SAFETY: a read; the calls below run no code that could rebind + // the cell. + match unsafe { cell.peek() }? { + Object::Function(g) => self.call_pure_leaf_with(g, None, args), + Object::Unbound => None, + target => self.pure_callback(target, args, effects), + } + } + + /// [`Self::release`] for an adapter's item: a scalar's is nothing, + /// with no call. + #[inline(always)] + fn release_item(&self, v: Object) { + if v.strong_word().is_none() { + std::mem::forget(v); + } else { + self.release(v); + } + } + + /// [`Self::pure_callback`] for an adapter's step, a Python function's + /// warm leaf entered first and directly (see + /// [`Self::leaf_fast_call`]). + #[inline(always)] + fn pure_callback_fn(&self, func: &Object, args: &[Object], effects: bool) -> Option { + #[cfg(feature = "jit")] + if let Object::Function(f) = func { + if let Some(r) = self.leaf_fast_call(f, None, args, args.len() == 1) { + return r; + } + } + self.pure_callback(func, args, effects) + } + /// `func(*args)` for an adapter's callback when the call runs no Python /// code: a warm pure-leaf function or a bound method over one (evaluated /// in place, as the core loop calls one), a registered leaf builtin or a @@ -2287,10 +6217,32 @@ impl Interpreter { (effects || !effect).then_some(kind) }; match func { - Object::Function(f) => self.call_pure_leaf(f, args), + // (A lambda that reads one part of its argument, read here.) + Object::Function(f) => match args { + [x] => { + // (A warm leaf that reads no part: its native code.) + #[cfg(feature = "jit")] + if let Some(r) = self.leaf_fast_call(f, None, args, true) { + return r; + } + match crate::lambda_part(f) { + Some(shape) => { + crate::part_value(&shape, x).or_else(|| self.call_pure_leaf(f, args)) + } + None => self + .call_pure_leaf(f, args) + .or_else(|| self.forward_pure_call(f, args, effects)), + } + } + _ => self + .call_pure_leaf(f, args) + .or_else(|| self.forward_pure_call(f, args, effects)), + }, // (As the core loop's leaf builtin lane admits them: a function, // or a method bound to its exact builtin receiver.) - Object::Builtin(b) if !b.binds_instance => { + // (A method read off its type, `map(str.upper, xs)`, takes its + // receiver first, as its kind expects.) + Object::Builtin(b) if !b.binds_instance || !args.is_empty() => { let kind = admit(self.leaf_call_kind(b)?)?; self.leaf_builtin_call(kind, b, args)?.ok() } @@ -2308,6 +6260,21 @@ impl Interpreter { }; self.leaf_builtin_call(kind, b, &call)?.ok() } + // `d.get` of a dict subclass's instance that reads as its + // payload does (`max(counts, key=counts.get)`): the + // payload's own. + Object::Builtin(b) if b.binds_instance => { + let payload = Interpreter::plain_dict_payload(&bm.receiver)?; + let kind = match self.leaf_call_kind(b)? { + kind @ LeafKind::DictGet => kind, + _ => return None, + }; + let call = match args { + [a] => [Object::Dict(payload.clone()), a.clone()], + _ => return None, + }; + self.leaf_builtin_call(kind, b, &call)?.ok() + } // A leaf method's fast half bound to an instance of a // built-in subclass (`map(_Quoter(dict).__getitem__, bs)` in // `urllib.parse.quote`), which settles what it can natively. @@ -2327,37 +6294,147 @@ impl Interpreter { }, // An instance whose class's `__call__` is a registered leaf // half (`key=attrgetter("x")`, `map(itemgetter(0), ...)`). - Object::Instance(i) if !crate::gil::free_threading_enabled() => { - let Object::Builtin(b) = i.cls_raw().lookup("__call__")? else { - return None; + // (Its half found once per class version; a half counts as an + // effect, as `admit` counts one.) + // An `operator` getter of one index, key or attribute name: + // the item's part, a plain read (so a caller that allows no + // effects takes it too: `filter(attrgetter("ok"), rows)`). + Object::Instance(inst) => { + let [a] = args else { + // (A `partial` takes any number: `reduce`'s pair.) + return if Self::is_plain_partial(inst) { + self.call_partial_leaf(inst, args) + } else { + None + }; }; - let LeafKind::Fast(f) = admit(self.leaf_call_kind(&b)?)? else { + if let Some(v) = + Self::getter_part(inst).and_then(|shape| crate::part_value(&shape, a)) + { + return Some(v); + } + // A placeholder-free `functools.partial` of a pure-leaf + // Python function: evaluated in place over its stored + // arguments, its stored keywords and the item. + if Self::is_plain_partial(inst) { + return self.call_partial_leaf(inst, args); + } + // An `operator.methodcaller` whose method is a pure-leaf + // Python function of the item's plain class: evaluated in + // place with the item first, then the stored arguments. + if Self::is_methodcaller(inst) { + let (f, stored) = crate::stdlib::operator_accel::methodcaller_target(inst, a)?; + let Object::Tuple(stored) = &stored else { + return None; + }; + return self.call_pure_leaf_with(&f, Some(a), stored); + } + // An instance whose class's `__call__` is a registered leaf + // half: its half found once per class version (a half + // counts as an effect, as `admit` counts one). + if !effects { return None; - }; - let call = match args { - [a] => [func.clone(), a.clone()], - _ => return None, - }; - f(&call)?.ok() + } + let f = self.instance_call_fast(func)?; + // SAFETY: bitwise views of the live callable and argument, + // never dropped (the half clones what it keeps). + let views = std::mem::ManuallyDrop::new(unsafe { + [std::ptr::read(func), std::ptr::read(a)] + }); + f(&views[..])?.ok() } _ => None, } } + /// The part an `operator.itemgetter` of one int index or `str` key, + /// or an `operator.attrgetter` of one dotless name, reads from its + /// argument (the class's native `__call__` remembered per class + /// version). + fn getter_part(inst: &PyInstance) -> Option { + let call = Self::instance_call_native(inst)?; + // SAFETY: a read that runs no code, what it finds cloned out. + let slots = unsafe { inst.slots.peek() }?; + match call.name { + ".itemgetter.__call__" => match slots.get_hinted(0, "_items")? { + Object::Tuple(items) => match &items[..] { + [Object::Int(i)] => Some(crate::PartShape::Index(*i)), + [key @ Object::Str(_)] => Some(crate::PartShape::Key(key.clone())), + _ => None, + }, + _ => None, + }, + ".attrgetter.__call__" => match slots.get_hinted(0, "_attrs")? { + Object::Tuple(attrs) => match &attrs[..] { + [name @ Object::Str(s)] if !s.as_bytes().contains(&b'.') => { + Some(crate::PartShape::Attr(name.clone())) + } + _ => None, + }, + _ => None, + }, + _ => None, + } + } + + /// The fast half of an instance's class's native `__call__` + /// (`attrgetter("x")`, `itemgetter(0)`), for a caller that calls it per + /// item (a sort's key) to resolve once; it takes the instance first. + pub(crate) fn instance_call_fast(&self, func: &Object) -> Option { + use crate::types::LeafAttrKind as K; + let Object::Instance(i) = func else { + return None; + }; + if crate::gil::free_threading_enabled() { + return None; + } + // (Found once per class version: a callback calls one key function + // for every item.) + let cls = i.cls_raw(); + let ver = cls.attr_version.get(); + let key = crate::types::AttrKey::vm(crate::types::vm_key::CALL_LEAF); + match cls.leaf_attrs.get(key, ver) { + Some(K::LeafFast(f)) => return Some(*f), + Some(_) => return None, + None => {} + } + if crate::object::exotic_str_keys_possible() { + return None; + } + let fast = match cls.lookup("__call__") { + Some(Object::Builtin(b)) => match self.leaf_call_kind(&b) { + Some(LeafKind::Fast(f)) => Some(f), + _ => None, + }, + _ => None, + }; + cls.leaf_attrs + .set(key, ver, fast.map_or(K::Other, K::LeafFast)); + fast + } + /// `groupby_step` when taking the next value and computing its key - /// run no code: the value and its key, the value taken. `None` (nothing - /// consumed) otherwise. - fn groupby_step_pure(&self, source: &Object, keyfunc: &Object) -> Option<(Object, Object)> { + /// run no code: the value and its key, the value taken, or `Some(None)` + /// at a plain cursor's end that lets go of nothing loud. `None` + /// (nothing consumed) otherwise. + fn groupby_step_pure( + &self, + source: &Object, + keyfunc: &Object, + ) -> Option> { let Object::Iter(c) = source else { return None; }; - let value = cursor_peek(c)?; + let Some(value) = cursor_peek(c) else { + // The source's end, which leaves the state as it is. + return cursor_end_quietly(source).map(|_| None); + }; let key = match keyfunc { Object::None => value.clone(), f => self.pure_callback(f, std::slice::from_ref(&value), true)?, }; cursor_advance(c)?; - Some((value, key)) + Some(Some((value, key))) } /// One item of `source` for [`Self::lazy_gen_pair`]: a generator's @@ -2497,6 +6574,18 @@ impl Interpreter { active: Some(g @ Object::Generator(_)), .. } => (g.clone(), None), + LazyIterKind::Filter { + func, + source: Object::Generator(g), + } if match func { + Object::None => true, + Object::Type(t) => Rc::ptr_eq(t, &builtin_types().bool_), + _ => false, + } => + { + let g = g.clone(); + return self.lazy_gen_filter(l, &g, snap_gen, dead, depth_cell); + } LazyIterKind::Islice { source: g @ Object::Generator(_), next_idx, @@ -2537,6 +6626,176 @@ impl Interpreter { Some(item) } + /// One step of `filter(None, gen)` (or `filter(bool, gen)`) from a + /// running activation (see [`Self::lazy_gen_one`]): the generator's + /// items stepped by its native code where it stands until one tests + /// true. An item whose truth would run code (a `__bool__` that doesn't + /// evaluate frameless, a foreign object's) is put back ahead of the + /// generator, the adapter's source becoming a `chain` of the two, for + /// the general step to test. `None` when the generator doesn't yield: + /// the general step finds it as it stands. + #[cfg(feature = "jit")] + fn lazy_gen_filter( + &mut self, + l: &Rc, + g: &Rc, + snap_gen: u64, + dead: *const std::cell::Cell, + depth_cell: *const std::cell::Cell, + ) -> Option { + loop { + let v = match self.gen_native_next(g, snap_gen, dead, depth_cell, 0) { + crate::gen_fast::GenNext::Yielded(v) => v, + _ => return None, + }; + let truth = match &v { + Object::Instance(_) if !v.is_same(&crate::vm_singletons::not_implemented()) => { + self.leaf_instance_truth(&v) + } + Object::Instance(_) | Object::Foreign(_) | Object::MappingProxyObj(_) => None, + o if o.truth_dispatches() => None, + o => Some(o.is_truthy()), + }; + match truth { + Some(true) => return Some(v), + Some(false) => drop(v), + None => { + Self::filter_put_back(l, v); + return None; + } + } + } + } + + /// Put `item`, taken from a `filter`'s generator source, back ahead of + /// it (see [`Self::lazy_gen_filter`]). + #[cfg(feature = "jit")] + #[cold] + fn filter_put_back(l: &Rc, item: Object) { + let one = |o: Object| -> Object { + let Object::Tuple(items) = Object::new_tuple_array([o]) else { + unreachable!("a tuple") + }; + Object::Iter(Rc::new(RefCell::new(PyIterator::Tuple { items, index: 0 }))) + }; + let mut st = l.state.borrow_mut(); + let LazyIterKind::Filter { source, .. } = &mut *st else { + // (The generator's body replaced the adapter's state: the + // item goes where a general step's would, nowhere.) + drop(st); + drop(item); + return; + }; + let rest = std::mem::replace(source, Object::None); + *source = lazy(LazyIterKind::Chain { + source: Some(one(rest)), + active: Some(one(item)), + }); + } + + /// [`Self::lazy_core_next`] of an `enumerate` over a native adapter + /// whose pair is unpacked at once (`for i, (x, y) in enumerate(zip(xs, + /// ys))`): the index and the source's item, with no pair built. `None` + /// for any other adapter, and at the source's end (which the general + /// step finds as this one left it). + pub(crate) fn lazy_enumerate_pair(&self, l: &Rc) -> Option<(Object, Object)> { + // SAFETY: as `lazy_core_next`'s; the source is another adapter. + let st = unsafe { l.state.peek_mut() }?; + let LazyIterKind::Enumerate { + source: Object::LazyIter(src), + count, + count_big: None, + } = st + else { + return None; + }; + if *count == i64::MAX { + return None; + } + // A two-cursor `zip` (`enumerate(zip(xs, ys))`): its pair in a + // tuple only the caller holds, which the unpacking after it takes + // apart in place, rather than the result the `zip` keeps for reuse + // (whose items the unpacking would copy). + let zipped = { + // SAFETY: a distinct cell (an adapter can't be its own source); + // nothing below runs code, and the view ends with this block. + match unsafe { src.state.peek() } { + Some(LazyIterKind::Zip { iters, held, .. }) if held.is_empty() => { + match iters.as_slice() { + [a, b] => cursor_pair(a, b), + _ => None, + } + } + _ => None, + } + }; + if let Some((x, y)) = zipped { + let i = *count; + *count += 1; + return Some((Object::Int(i), self.alloc_tuple_array([x, y]))); + } + let v = self.lazy_core_next(src)??; + let i = *count; + *count += 1; + Some((Object::Int(i), v)) + } + + /// `any(it)` (`want_any`) or `all(it)` of a native adapter, stepped as + /// [`Self::lazy_core_next`] steps it with each item's truth read + /// natively: `Ok` with the answer once an item decides it or the + /// adapter ends, `Err` with an item already taken whose truth needs + /// the full test (the caller tests it, then may call again), `None` + /// at the first step these can't take (nothing of it consumed). A + /// `map` of a leaf builtin over one plain sequence (`map(str.isupper, + /// words)`) settles the builtin's kind once, not per item. + pub(crate) fn lazy_any_all( + &self, + l: &Rc, + want_any: bool, + ) -> Option> { + // SAFETY: a read that runs no code; the view ends here. + let hoisted = match unsafe { l.state.peek() }? { + LazyIterKind::Map { + func: Object::Builtin(b), + iters, + .. + } => match iters.as_slice() { + [Object::Iter(c)] => Some((b.clone(), c.clone())), + _ => None, + }, + _ => None, + }; + if let Some((b, c)) = hoisted { + // (As `pure_callback` calls it for `map`, which admits every + // kind; the end, or an item the call declines, is the general + // step's below.) + if let Some(kind) = self.leaf_call_kind(&b) { + while let Some(v) = cursor_peek(&c) { + let Some(Ok(r)) = self.leaf_builtin_call(kind, &b, std::slice::from_ref(&v)) + else { + break; + }; + cursor_advance(&c)?; + match scalar_truth(&r) { + Some(t) if t == want_any => return Some(Ok(want_any)), + Some(_) => {} + None => return Some(Err(r)), + } + } + } + } + loop { + match self.lazy_core_next(l)? { + Some(r) => match scalar_truth(&r) { + Some(t) if t == want_any => return Some(Ok(want_any)), + Some(_) => {} + None => return Some(Err(r)), + }, + None => return Some(Ok(!want_any)), + } + } + } + /// One step of a native adapter that runs no Python code, for every /// `FOR_ITER` (the core loop's, the frame JIT's, tier 2's) and ahead of /// the interpreter's general step: [`lazy_pure_next`]'s state machines, @@ -2546,7 +6805,41 @@ impl Interpreter { /// and a `groupby` or grouper whose key function and key comparisons /// are native. `None` (nothing consumed, or only whole steps the /// general path would have taken the same way) for every other step. + #[inline(always)] pub(crate) fn lazy_core_next(&self, l: &Rc) -> Option> { + // Each kind straight to the step that takes it (one tag test here, + // not one in each of them in turn). + // SAFETY: the hot step runs no code, and the view ends before any + // other step takes its own. + let st = unsafe { l.state.peek_mut() }?; + match st { + LazyIterKind::Islice { .. } + | LazyIterKind::Chain { .. } + | LazyIterKind::Count { .. } + | LazyIterKind::Cycle { .. } => match lazy_hot_step(st) { + Some(v) => Some(Some(v)), + None => itertools_pure_next(l), + }, + LazyIterKind::Zip { .. } => lazy_pure_next(l), + LazyIterKind::Map { .. } + | LazyIterKind::Filter { .. } + | LazyIterKind::StarMap { .. } + | LazyIterKind::TakeWhile { .. } + | LazyIterKind::DropWhile { .. } + | LazyIterKind::FilterFalse { .. } + | LazyIterKind::Enumerate { .. } + | LazyIterKind::GroupBy { .. } + | LazyIterKind::Grouper { .. } + | LazyIterKind::Accumulate { func: Some(_), .. } => self.lazy_core_next_rest(l), + // (Every step calls the callable: see `calliter_step`.) + LazyIterKind::CallIter { .. } => None, + _ => itertools_pure_next(l), + } + } + + /// [`Self::lazy_core_next`]'s steps that may call a callback or step + /// another adapter (`map`, `filter`, `enumerate`, `groupby`, ...). + fn lazy_core_next_rest(&self, l: &Rc) -> Option> { // SAFETY: nothing below runs code that could reach the adapter // (pure callbacks call nothing); the view ends with this call. let st = unsafe { l.state.peek_mut() }?; @@ -2559,37 +6852,144 @@ impl Interpreter { None } LazyIterKind::Map { func, iters, .. } => match iters.as_slice() { - [Object::Iter(c)] => { - let v = cursor_peek(c)?; - let r = self.pure_callback(func, std::slice::from_ref(&v), true)?; + [src @ Object::Iter(c)] => { + let Some(v) = cursor_peek(c) else { + return cursor_end_quietly(src); + }; + let r = self.pure_callback_fn(func, std::slice::from_ref(&v), true)?; cursor_advance(c)?; Some(Some(r)) } [Object::Iter(a), Object::Iter(b)] if !Rc::ptr_eq(a, b) => { let args = [cursor_peek(a)?, cursor_peek(b)?]; - let r = self.pure_callback(func, &args, true)?; + let r = self.pure_callback_fn(func, &args, true)?; cursor_advance(a)?; cursor_advance(b)?; Some(Some(r)) } _ => None, }, - LazyIterKind::Filter { + LazyIterKind::Filter { func, source } if matches!(source, Object::Iter(_)) => loop { + let Object::Iter(c) = &*source else { + return None; + }; + let Some(v) = cursor_peek(c) else { + return cursor_end_quietly(source); + }; + let keep = match &*func { + Object::None => scalar_truth(&v)?, + Object::Type(t) if Rc::ptr_eq(t, &builtin_types().bool_) => scalar_truth(&v)?, + // (The truth test may yet decline: no effects.) + f => { + scalar_truth(&self.pure_callback_fn(f, std::slice::from_ref(&v), false)?)? + } + }; + cursor_advance(c)?; + if keep { + return Some(Some(v)); + } + }, + // `starmap(f, pairs)` over a list or tuple of tuples, as `map` + // over one source steps (the item's fields the arguments). + LazyIterKind::StarMap { func, source } + if matches!(source, Object::Iter(_)) && pure_callback_maybe(func) => + { + let Object::Iter(c) = &*source else { + return None; + }; + let Some(v) = cursor_peek(c) else { + return cursor_end_quietly(source); + }; + let Object::Tuple(t) = &v else { + return None; + }; + let r = self.pure_callback_fn(func, t, true)?; + cursor_advance(c)?; + Some(Some(r)) + } + // `takewhile(pred, xs)` over a plain cursor: the item while the + // predicate holds, the end (stopped) at the first that fails, + // as the general step consumes it. + LazyIterKind::TakeWhile { + func, + source: Object::Iter(c), + stopped: stopped @ false, + } if pure_callback_maybe(func) => { + let v = cursor_peek(c)?; + let keep = + scalar_truth(&self.pure_callback(func, std::slice::from_ref(&v), false)?)?; + cursor_advance(c)?; + if keep { + Some(Some(v)) + } else { + *stopped = true; + Some(None) + } + } + // `dropwhile(pred, xs)` over a plain cursor: the items the + // predicate holds for skipped (each a whole step), then the + // rest as they are. + LazyIterKind::DropWhile { func, source: Object::Iter(c), + started, } => loop { let v = cursor_peek(c)?; - let keep = match &*func { + if !*started { + if !pure_callback_maybe(func) { + return None; + } + let skip = scalar_truth(&self.pure_callback( + func, + std::slice::from_ref(&v), + false, + )?)?; + cursor_advance(c)?; + if skip { + continue; + } + *started = true; + return Some(Some(v)); + } + cursor_advance(c)?; + return Some(Some(v)); + }, + // `filterfalse(pred, xs)` over a plain cursor, as `filter`'s + // step with the verdict inverted. + LazyIterKind::FilterFalse { + func, + source: Object::Iter(c), + } if matches!(func, Object::None) || pure_callback_maybe(func) => loop { + let v = cursor_peek(c)?; + let truthy = match &*func { Object::None => scalar_truth(&v)?, - Object::Type(t) if Rc::ptr_eq(t, &builtin_types().bool_) => scalar_truth(&v)?, - // (The truth test may yet decline: no effects.) f => scalar_truth(&self.pure_callback(f, std::slice::from_ref(&v), false)?)?, }; cursor_advance(c)?; - if keep { + if !truthy { return Some(Some(v)); } }, + // `accumulate(xs, f)` over a plain cursor with a pure callback + // (`operator.add`, `max`, a leaf lambda): the running value + // through the callback, the item taken once it has succeeded. + // (A running value that isn't a plain scalar may die with the + // step, which the general one lets it do.) + LazyIterKind::Accumulate { + source: Object::Iter(c), + func: Some(f), + total, + initial: None, + } if pure_callback_maybe(f) && total.as_ref().is_none_or(plain_value) => { + let item = cursor_peek(c)?; + let next = match &*total { + None => item, + Some(t) => self.pure_callback(f, &[t.clone(), item], true)?, + }; + cursor_advance(c)?; + *total = Some(next.clone()); + Some(Some(next)) + } // `enumerate(map(...))` and the like: the source's own pure step. LazyIterKind::Enumerate { source: Object::LazyIter(src), @@ -2626,7 +7026,9 @@ impl Interpreter { } } } - let (value, key) = self.groupby_step_pure(source, keyfunc)?; + let Some((value, key)) = self.groupby_step_pure(source, keyfunc)? else { + return Some(None); + }; let old = (currkey.replace(key), currvalue.replace(value)); drop(old); } @@ -2667,7 +7069,9 @@ impl Interpreter { return Some(None); } if currvalue.is_none() { - let (value, key) = self.groupby_step_pure(source, keyfunc)?; + let Some((value, key)) = self.groupby_step_pure(source, keyfunc)? else { + return Some(None); + }; let old = (currkey.replace(key), currvalue.replace(value)); drop(old); } @@ -2685,6 +7089,9 @@ impl Interpreter { // A `filter` or `enumerate` over a source only the // interpreter can step. LazyIterKind::Filter { .. } | LazyIterKind::Enumerate { .. } => None, + // `chain(xs, ys)`: its active source's next item, a plain + // cursor's read and stepped in one. + LazyIterKind::Chain { source, active } => chain_pure_next(source, active).map(Some), _ => lazy_pure_next(l), } } @@ -2872,3 +7279,70 @@ impl Interpreter { Ok(Some(value)) } } + +impl Interpreter { + /// One step of a `callable_iterator` (CPython's `calliter_iternext`), + /// `None` for any other adapter: the callable called (a pure leaf in + /// place, else in full), its result compared with the sentinel + /// (`sentinel == result`, identity first). A result equal to the + /// sentinel, or a `StopIteration` the callable raises, ends the + /// iteration and lets both go; a step re-entered while the call ran + /// that ended it makes this result end it too (gh-101892). + pub(crate) fn calliter_step( + &mut self, + l: &Rc, + globals: &Rc>, + ) -> Option, RuntimeError>> { + let callable = match &*l.state.borrow() { + LazyIterKind::CallIter { pair } => pair.as_ref().map(|(c, _)| c.clone()), + _ => return None, + }; + let Some(callable) = callable else { + return Some(Ok(None)); + }; + let end = |l: &PyLazyIter| { + let old = match &mut *l.state.borrow_mut() { + LazyIterKind::CallIter { pair } => pair.take(), + _ => None, + }; + drop(old); + }; + let v = match self.pure_callback_fn(&callable, &[], true) { + Some(v) => v, + None => match self.call(&callable, &[], &[], globals) { + Ok(v) => v, + Err(e) if is_stop_iteration(&e) => { + end(l); + return Some(Ok(None)); + } + Err(e) => return Some(Err(e)), + }, + }; + drop(callable); + let sentinel = match &*l.state.borrow() { + LazyIterKind::CallIter { pair } => pair.as_ref().map(|(_, s)| s.clone()), + _ => None, + }; + let Some(sentinel) = sentinel else { + return Some(Ok(None)); + }; + let equal = if v.is_same(&sentinel) { + true + } else { + match self.dispatch_compare_op( + &sentinel, + &v, + weavepy_compiler::CompareKind::Eq, + globals, + ) { + Ok(b) => b, + Err(e) => return Some(Err(e)), + } + }; + if equal { + end(l); + return Some(Ok(None)); + } + Some(Ok(Some(v))) + } +} diff --git a/crates/weavepy-vm/src/setalg.rs b/crates/weavepy-vm/src/setalg.rs new file mode 100644 index 000000000..f056f5e97 --- /dev/null +++ b/crates/weavepy-vm/src/setalg.rs @@ -0,0 +1,371 @@ +//! Set algebra on the tables themselves. +//! +//! A `set` operation compares one operand's keys with the other's. Every +//! stored key carries its Python hash, so nothing here hashes a key again +//! (no `__hash__` runs), and a pair of keys with equal hashes compares +//! natively or by identity; only a pair that needs a Python `__eq__` is +//! left over, and inside [`pure`] that comparison is deferred: it answers +//! "not equal" and marks the result undecided. So each function below +//! runs no Python code under [`pure`], reads its operands in place (no +//! snapshot of either), and walks only the side the operation has to +//! walk: the smaller one for an intersection, a subset test or a +//! disjointness test, the right one for an in-place difference. A caller +//! takes the answer when [`pure`] decides it and runs its general path, +//! which snapshots the operands and lets comparisons run Python, +//! otherwise. +//! +//! Which elements a result holds, and in what order, follows CPython's +//! `setobject.c`: an intersection keeps the walked (smaller) operand's +//! elements, the right one's on a tie; a union and a difference keep the +//! left operand's. + +use crate::dictmap::{Bucket, SetMap}; +use crate::object::{DictKey, Object}; +use weavepy_compiler::{BinOpKind, CompareKind}; + +/// Run `f` with Python key comparisons deferred: its result, or `None` +/// when some comparison needed Python (the result is then meaningless, +/// and `f` must have changed nothing). +#[inline] +pub(crate) fn pure(f: impl FnOnce() -> R) -> Option { + let (out, deferred) = crate::object::with_key_eq_deferred(f); + (!deferred).then_some(out) +} + +/// `f` on the table of an exact `set` (if nothing is changing it) or +/// `frozenset`; `None` for anything else. +#[inline] +pub(crate) fn with_set(o: &Object, f: impl FnOnce(&SetMap) -> R) -> Option { + match o { + Object::Set(s) => Some(f(&*s.try_borrow().ok()?)), + Object::FrozenSet(s) => Some(f(s)), + _ => None, + } +} + +/// [`with_set`] for two operands at once (the same set twice is fine). +#[inline] +pub(crate) fn with_sets( + a: &Object, + b: &Object, + f: impl FnOnce(&SetMap, &SetMap) -> R, +) -> Option { + with_set(a, |x| with_set(b, |y| f(x, y)))? +} + +#[inline(always)] +fn has(s: &SetMap, e: &Bucket<()>) -> bool { + s.contains_hashed(e.hash, &e.key) +} + +/// Whether every key of `a` is in `b`. +pub(crate) fn subset(a: &SetMap, b: &SetMap) -> bool { + a.len() <= b.len() && a.as_entries().iter().all(|e| has(b, e)) +} + +/// Whether the two hold the same keys. +pub(crate) fn equal(a: &SetMap, b: &SetMap) -> bool { + a.len() == b.len() && subset(a, b) +} + +/// Whether no key is in both. +pub(crate) fn disjoint(a: &SetMap, b: &SetMap) -> bool { + let (small, big) = if a.len() <= b.len() { (a, b) } else { (b, a) }; + !small.as_entries().iter().any(|e| has(big, e)) +} + +/// `a b` as CPython's `set_richcompare` answers it. +pub(crate) fn compare(a: &SetMap, b: &SetMap, op: CompareKind) -> bool { + match op { + CompareKind::Eq => equal(a, b), + CompareKind::NotEq => !equal(a, b), + CompareKind::LtE => subset(a, b), + CompareKind::Lt => a.len() < b.len() && subset(a, b), + CompareKind::GtE => subset(b, a), + CompareKind::Gt => a.len() > b.len() && subset(b, a), + } +} + +/// `a | b`: `a`'s keys, then `b`'s that `a` lacks. +pub(crate) fn union(a: &SetMap, b: &SetMap) -> SetMap { + let mut out = a.clone(); + if !b.is_empty() { + out.reserve(b.len().div_ceil(2)); + for e in b.as_entries() { + out.insert_hashed(e.hash, e.key.clone()); + } + } + out +} + +/// `a | b | c ...` of exact sets and frozensets: the first's keys, then +/// each other's that the result still lacks, in turn. `None` when one +/// isn't a set or frozenset, or is being changed. +pub(crate) fn union_many(sets: &[crate::object::Object]) -> Option { + let (first, rest) = sets.split_first()?; + let mut out = with_set(first, SetMap::clone)?; + for o in rest { + with_set(o, |b| { + if !b.is_empty() { + out.reserve(b.len().div_ceil(2)); + for e in b.as_entries() { + out.insert_hashed(e.hash, e.key.clone()); + } + } + })?; + } + Some(out) +} + +/// `a & b`: the smaller operand's keys that the other holds (`b`'s on a +/// tie), in the smaller one's order. +pub(crate) fn intersection(a: &SetMap, b: &SetMap) -> SetMap { + let (small, big) = if b.len() > a.len() { (a, b) } else { (b, a) }; + let mut out = SetMap::new(); + for e in small.as_entries() { + if has(big, e) { + out.insert_unique_hashed(e.hash, e.key.clone()); + } + } + out +} + +/// `a - b`: `a`'s keys that `b` lacks, in order. A `b` much smaller than +/// `a` is looked up in a copy of `a` (whose table is copied whole, with no +/// key probed) and its hits taken out, as CPython's +/// `set_copy_and_difference` does. +pub(crate) fn difference(a: &SetMap, b: &SetMap) -> SetMap { + if b.len() * 4 < a.len() { + let mut hits: Vec = b + .as_entries() + .iter() + .filter_map(|e| a.index_hashed(e.hash, &e.key)) + .collect(); + let mut out = a.clone(); + if hits.len() <= 8 { + hits.sort_unstable_by(|x, y| y.cmp(x)); + for at in hits { + out.shift_remove_index(at); + } + } else { + hits.sort_unstable(); + let (mut at, mut next) = (0, 0); + out.retain(|_| { + let gone = hits.get(next) == Some(&at); + at += 1; + next += usize::from(gone); + !gone + }); + } + return out; + } + let mut out = SetMap::new(); + for e in a.as_entries() { + if !has(b, e) { + out.insert_unique_hashed(e.hash, e.key.clone()); + } + } + out +} + +/// `a ^ b`: `a`'s keys that `b` lacks, then `b`'s that `a` lacks. +pub(crate) fn symmetric_difference(a: &SetMap, b: &SetMap) -> SetMap { + let mut out = difference(a, b); + for e in b.as_entries() { + if !has(a, e) { + out.insert_unique_hashed(e.hash, e.key.clone()); + } + } + out +} + +/// `a b` for the four set operators; `None` for any other operator. +pub(crate) fn algebra(a: &SetMap, b: &SetMap, op: BinOpKind) -> Option { + Some(match op { + BinOpKind::BitOr => union(a, b), + BinOpKind::BitAnd => intersection(a, b), + BinOpKind::Sub => difference(a, b), + BinOpKind::BitXor => symmetric_difference(a, b), + _ => return None, + }) +} + +/// What an in-place operation will do to its left operand, decided with +/// both operands only read (see [`plan`]) and applied by [`Plan::apply`] +/// once that is known to have run no Python. +pub(crate) enum Plan { + /// Nothing changes. + Keep, + /// Every key goes. + Clear, + /// The keys at these positions go. + Remove(Vec), + /// The keys at these positions go and these arrive. + Toggle(Vec, Vec<(i64, DictKey)>), + /// These keys arrive (none is present). + Add(Vec<(i64, DictKey)>), + /// The table becomes this one. + Replace(SetMap), +} + +/// The change `a = b` makes to `a`: `None` for an operator that isn't +/// a set's. Walks `b`, except where `a` is the smaller side of a +/// difference; an intersection is the one `a & b` makes, elements and +/// all, as CPython's `set_intersection_update` swaps it in. +pub(crate) fn plan(a: &SetMap, b: &SetMap, op: BinOpKind) -> Option { + Some(match op { + BinOpKind::BitOr => { + let add: Vec<(i64, DictKey)> = b + .as_entries() + .iter() + .filter(|e| !has(a, e)) + .map(|e| (e.hash, e.key.clone())) + .collect(); + if add.is_empty() { + Plan::Keep + } else { + Plan::Add(add) + } + } + BinOpKind::Sub => { + let gone: Vec = if b.len() <= a.len() { + b.as_entries() + .iter() + .filter_map(|e| a.index_hashed(e.hash, &e.key)) + .collect() + } else { + a.as_entries() + .iter() + .enumerate() + .filter(|(_, e)| has(b, e)) + .map(|(i, _)| i) + .collect() + }; + if gone.is_empty() { + Plan::Keep + } else if gone.len() == a.len() { + Plan::Clear + } else { + Plan::Remove(gone) + } + } + BinOpKind::BitAnd => { + let both = intersection(a, b); + if both.is_empty() { + Plan::Clear + } else { + Plan::Replace(both) + } + } + BinOpKind::BitXor => { + let mut gone = Vec::new(); + let mut add = Vec::new(); + for e in b.as_entries() { + match a.index_hashed(e.hash, &e.key) { + Some(at) => gone.push(at), + None => add.push((e.hash, e.key.clone())), + } + } + if gone.is_empty() && add.is_empty() { + Plan::Keep + } else { + Plan::Toggle(gone, add) + } + } + _ => return None, + }) +} + +impl Plan { + /// Make the planned change to `a`, the table the plan was made for + /// and unchanged since. Compares no keys: positions name what goes, + /// and what arrives is known to be absent. Returns the keys taken + /// out, for the caller to release once `a` is no longer borrowed. + pub(crate) fn apply(self, a: &mut SetMap) -> Gone { + // (A replaced table goes out whole, its keys never gathered.) + if let Plan::Replace(new) = self { + return Gone::Table(std::mem::replace(a, new)); + } + Gone::Keys(self.apply_keys(a)) + } + + fn apply_keys(self, a: &mut SetMap) -> Vec { + let take = |a: &mut SetMap, mut gone: Vec| -> Vec { + // (From the highest position down: each removal moves the + // last key into the freed place, never one still to go.) + gone.sort_unstable_by(|x, y| y.cmp(x)); + // (An iterable may name one key twice.) + gone.dedup(); + gone.into_iter() + .filter_map(|at| a.swap_remove_index(at)) + .collect() + }; + match self { + Plan::Keep => Vec::new(), + Plan::Clear => a.drain(..).collect(), + Plan::Remove(gone) => take(a, gone), + Plan::Toggle(gone, add) => { + let out = take(a, gone); + a.reserve(add.len()); + for (hash, key) in add { + a.insert_unique_hashed(hash, key); + } + out + } + Plan::Add(add) => { + a.reserve(add.len()); + for (hash, key) in add { + a.insert_unique_hashed(hash, key); + } + Vec::new() + } + Plan::Replace(new) => std::mem::replace(a, new).into_iter().collect(), + } + } +} + +/// What [`Plan::apply`] took out of a table: its keys, or the old table +/// itself. +pub(crate) enum Gone { + Keys(#[allow(dead_code)] Vec), + Table(#[allow(dead_code)] SetMap), +} + +/// `dst = src` in place, for a `set` and a `set` or `frozenset` whose +/// keys compare without Python: `true` when done, `false` (nothing +/// touched) for the caller's general path. An operand with itself is +/// settled by the operator alone. +pub(crate) fn update(dst: &Object, src: &Object, op: BinOpKind) -> bool { + let Object::Set(cell) = dst else { + return false; + }; + if crate::builtins::set_ops_pending() { + return false; + } + let same = matches!(src, Object::Set(other) if crate::sync::Rc::ptr_eq(cell, other)); + let planned = if same { + match op { + // (`a &= a` keeps `a`'s own elements, as `a & a` does.) + BinOpKind::BitOr | BinOpKind::BitAnd => Some(Plan::Keep), + BinOpKind::Sub | BinOpKind::BitXor => Some(Plan::Clear), + _ => None, + } + } else { + with_sets(dst, src, |a, b| pure(|| plan(a, b, op))) + .flatten() + .flatten() + }; + let Some(planned) = planned else { + return false; + }; + if matches!(planned, Plan::Keep) { + return true; + } + let Ok(mut a) = cell.try_borrow_mut() else { + return false; + }; + let gone = planned.apply(&mut a); + drop(a); + drop(gone); + true +} diff --git a/crates/weavepy-vm/src/shared_value.rs b/crates/weavepy-vm/src/shared_value.rs index 27585506b..da2defc28 100644 --- a/crates/weavepy-vm/src/shared_value.rs +++ b/crates/weavepy-vm/src/shared_value.rs @@ -146,6 +146,17 @@ impl ThinArc { } } + /// The payload of a handle that is its allocation's only owner. + /// + /// # Safety + /// + /// No other strong or weak owner of the allocation exists. + #[inline] + pub(crate) unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { + // SAFETY: the caller's contract; this owner keeps it alive. + unsafe { &mut *this.raw().cast_mut() } + } + pub fn get_mut(this: &mut Self) -> Option<&mut T> { if crate::rc::refcounts_biased() { // `Arc::get_mut` locks the weak count against another thread's @@ -396,8 +407,17 @@ impl SharedSlice { ptr::addr_of_mut!((*raw).len).write(len); ptr::addr_of_mut!((*raw).hash).write(AtomicI64::new(-1)); let dst = ptr::addr_of_mut!((*raw).items).cast::(); - for (i, value) in items.into_iter().enumerate() { - dst.add(i).write(value); + if std::mem::needs_drop::() { + for (i, value) in items.into_iter().enumerate() { + dst.add(i).write(value); + } + } else { + // (Elements with no drop glue move as one bulk copy: the + // `Vec` then frees only its buffer.) + let mut items = std::mem::ManuallyDrop::new(items); + ptr::copy_nonoverlapping(items.as_ptr(), dst, len); + items.set_len(0); + std::mem::ManuallyDrop::drop(&mut items); } Self::from_arc(Arc::from_raw(raw)) } @@ -436,6 +456,42 @@ impl SharedSlice { } } } +impl SharedSlice { + /// A slice of `len` elements that `fill` writes in place through the + /// pointer to its first element: one allocation, no copy. + /// + /// # Safety + /// + /// `fill` must initialize all `len` elements. + pub unsafe fn build_uninit(len: usize, fill: impl FnOnce(*mut T)) -> Self { + let layout = Self::layout(len); + macro_rules! allocate { + ($($word:ty),*) => { $(if layout.align() == align_of::<$word>() && layout.size() % size_of::<$word>() == 0 { + // SAFETY: the caller's contract. + return unsafe { Self::fill_aligned::<$word>(len, layout, fill) }; + })* }; + } + allocate!(u8, u16, u32, usize, u64, AtomicU64, u128); + panic!("unsupported shared slice alignment: {}", layout.align()); + } + + /// # Safety + /// + /// As [`Self::build_uninit`]'s. + unsafe fn fill_aligned(len: usize, layout: Layout, fill: impl FnOnce(*mut T)) -> Self { + let storage = Arc::<[Word]>::new_uninit_slice(layout.size() / size_of::()); + let data = Arc::into_raw(storage).cast::().cast_mut(); + let raw = ptr::slice_from_raw_parts_mut(data, len) as *mut SliceStorage; + // SAFETY: as in `from_copy_aligned`; `fill` initializes the + // elements (the caller's word) before any Arc can read them. + unsafe { + ptr::addr_of_mut!((*raw).len).write(len); + ptr::addr_of_mut!((*raw).hash).write(AtomicI64::new(-1)); + fill(ptr::addr_of_mut!((*raw).items).cast::()); + Self::from_arc(Arc::from_raw(raw)) + } + } +} impl From> for SharedSlice { fn from(items: Vec) -> Self { Self::from_vec_owned(items) @@ -635,6 +691,11 @@ pub struct SharedStr(ThinArc); #[derive(Debug)] pub struct WeakStr(ThinWeak); impl SharedStr { + /// The text, as a `&str`. + #[inline] + pub fn as_str(&self) -> &str { + self + } /// The allocation's address: equal for every strong and weak owner of /// the same string, and never reused while one exists. pub fn addr(this: &Self) -> usize { @@ -660,6 +721,14 @@ impl SharedStr { storage.hash.store(h, Ordering::Relaxed); h } + /// Record `h`, which must be `py_str_hash` of this text, as its + /// memoised `hash(s)` (a builder that hashed the text before making + /// the string, so the first dict insert doesn't hash it again). + #[inline] + pub fn prime_hash(this: &Self, h: i64) { + debug_assert_eq!(h, crate::object::py_str_hash(this)); + this.0.storage().hash.store(h, Ordering::Relaxed); + } /// The memoised `hash(s)` if it has been computed. #[inline] pub fn known_hash(this: &Self) -> Option { diff --git a/crates/weavepy-vm/src/stdlib/ast_mod.rs b/crates/weavepy-vm/src/stdlib/ast_mod.rs index 51bf6271b..11e8cd612 100644 --- a/crates/weavepy-vm/src/stdlib/ast_mod.rs +++ b/crates/weavepy-vm/src/stdlib/ast_mod.rs @@ -471,7 +471,8 @@ pub(crate) struct Direct { struct CheckedClasses(FxHashMap); thread_local! { - static CHECKED: std::cell::RefCell = std::cell::RefCell::default(); + static CHECKED: crate::gil::ReleaseUnderGil> = + crate::gil::ReleaseUnderGil::new(std::cell::RefCell::default()); } struct Checked { diff --git a/crates/weavepy-vm/src/stdlib/asyncio_events.rs b/crates/weavepy-vm/src/stdlib/asyncio_events.rs index 1219917cc..2044a7202 100644 --- a/crates/weavepy-vm/src/stdlib/asyncio_events.rs +++ b/crates/weavepy-vm/src/stdlib/asyncio_events.rs @@ -186,9 +186,9 @@ fn new_handle(hs: &HandleState, cb: Object, args: Object, loop_: Object, ctx: Ob obj } -/// `install_handle(Handle, run_failed)`. +/// `install_handle(Handle, run_failed[, TimerHandle])`. fn install_handle(args: &[Object]) -> Result { - let [Object::Type(cls), run_failed] = args else { + let [Object::Type(cls), run_failed, timer @ ..] = args else { return Err(type_error("install_handle(Handle, run_failed)")); }; let run_py = cls @@ -213,6 +213,30 @@ fn install_handle(args: &[Object]) -> Result { std::sync::atomic::Ordering::Relaxed, ); } + // A timer's instances likewise: the handle's members where a handle + // keeps them, then the timer's own (`_scheduled`, `_when`), so that + // `timer._cancelled` and `timer._scheduled` read through the slot + // caches too (the native bodies read a handle's members by position + // with the name to fall back on, whichever class laid them out). + if let [Object::Type(timer)] = timer { + let mut names: Vec = HANDLE_SLOTS + .iter() + .map(|n| crate::types::slot_key(n)) + .collect(); + for name in timer.slot_names.borrow().iter() { + if name != "__dict__" && name != "__weakref__" && !HANDLE_SLOTS.contains(&name.as_str()) + { + names.push(crate::types::slot_key(name)); + } + } + let timer_layout: SharedSlice = names.into(); + if timer.slot_layout.set(Some(timer_layout.clone())).is_ok() { + timer.slot_layout_word.store( + SharedSlice::word(&timer_layout), + std::sync::atomic::Ordering::Relaxed, + ); + } + } let st = Rc::new(HandleState { cls: cls.clone(), layout, @@ -423,7 +447,7 @@ fn fast_call_soon( let handle = new_handle( &hs, cb.clone(), - Object::new_tuple(cb_args.to_vec()), + Object::tuple_from_slice(cb_args), loop_.clone(), ctx, ); diff --git a/crates/weavepy-vm/src/stdlib/asyncio_mod.rs b/crates/weavepy-vm/src/stdlib/asyncio_mod.rs index 450797ec6..7a2557354 100644 --- a/crates/weavepy-vm/src/stdlib/asyncio_mod.rs +++ b/crates/weavepy-vm/src/stdlib/asyncio_mod.rs @@ -872,7 +872,7 @@ fn register_gc_hooks() { // ---- running-loop slot (per OS thread) ---- thread_local! { - static RUNNING_LOOP: RefCell = const { RefCell::new(Object::None) }; + static RUNNING_LOOP: crate::gil::ReleaseUnderGil> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(Object::None)) }; } fn running_loop() -> Object { diff --git a/crates/weavepy-vm/src/stdlib/binascii_mod.rs b/crates/weavepy-vm/src/stdlib/binascii_mod.rs index bfb3b3bae..38d03f032 100644 --- a/crates/weavepy-vm/src/stdlib/binascii_mod.rs +++ b/crates/weavepy-vm/src/stdlib/binascii_mod.rs @@ -71,11 +71,46 @@ pub fn build(_cache: &ModuleCache) -> Rc { // quoted-printable pair, etc. register_kw(&mut d, "b2a_hex", b2a_hex_kw); register_kw(&mut d, "hexlify", b2a_hex_kw); + // `hexlify(data)`/`b2a_hex(data)` of a `bytes` or `bytearray`: the + // full body, which then runs no code. + for name in ["hexlify", "b2a_hex"] { + if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static(name))) { + crate::leaf_builtins::register_fast(b, hex_fast); + } + } register_kw(&mut d, "b2a_base64", b2a_base64_kw); register_kw(&mut d, "a2b_base64", a2b_base64_kw); register_kw(&mut d, "b2a_uu", b2a_uu_kw); register_kw(&mut d, "a2b_qp", a2b_qp_kw); register_kw(&mut d, "b2a_qp", b2a_qp_kw); + // The bodies over a `bytes`, `bytearray` or (for the decoders) `str` + // argument run no code (only another object's buffer hook could): + // their positional calls run in place. + for (name, fast) in [ + ("b2a_base64", b2a_base64_fast as crate::leaf_builtins::Fast), + ("a2b_base64", a2b_base64_fast), + ("a2b_hex", a2b_hex_fast), + ("unhexlify", a2b_hex_fast), + ("crc32", crc32_fast), + ] { + if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static(name))) { + crate::leaf_builtins::register_fast(b, fast); + } + } + // (And their keyword calls, `b2a_base64(s, newline=False)` as + // `base64.b64encode` makes it.) + for (name, names, fast) in [ + ( + "b2a_base64", + &["/data", "*newline"] as crate::leaf_builtins::KwNames, + b2a_base64_kw_fast as crate::leaf_builtins::Fast, + ), + ("a2b_base64", &["/data", "*strict_mode"], a2b_base64_kw_fast), + ] { + if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static(name))) { + crate::leaf_builtins::register_fast_kw(b, names, fast); + } + } } Rc::new(PyModule { name: "binascii".to_owned(), @@ -192,6 +227,96 @@ fn truthy_kw(kwargs: &[(String, Object)], key: &str) -> Option { // ---- hex ---- +fn hex_fast(args: &[Object]) -> Option> { + match args { + [Object::Bytes(_) | Object::ByteArray(_)] => Some(b2a_hex_kw(args, &[])), + _ => None, + } +} + +/// Whether `o` is a `bytes` or `bytearray`, whose bytes the bodies read +/// with no code run. +fn plain_bytes(o: &Object) -> bool { + matches!(o, Object::Bytes(_) | Object::ByteArray(_)) +} + +/// `b2a_base64(data)` of plain bytes. +fn b2a_base64_fast(args: &[Object]) -> Option> { + match args { + [d] if plain_bytes(d) => Some(b2a_base64_kw(args, &[])), + _ => None, + } +} + +/// `a2b_base64(data)` of plain bytes or a `str`. +fn a2b_base64_fast(args: &[Object]) -> Option> { + match args { + [d] if plain_bytes(d) || matches!(d, Object::Str(_)) => Some(a2b_base64_kw(args, &[])), + _ => None, + } +} + +/// The keyword half's call of `body` on `data` and its one keyword-only +/// flag (`Unbound` when the call left it out). +fn with_flag( + data: &Object, + flag: &Object, + name: &str, + body: fn(&[Object], &[(String, Object)]) -> Result, +) -> Result { + let args = std::slice::from_ref(data); + match flag { + Object::Unbound => body(args, &[]), + f => body(args, &[(name.to_owned(), f.clone())]), + } +} + +/// `b2a_base64(data, *, newline)`'s keyword half, as [`b2a_base64_fast`]. +fn b2a_base64_kw_fast(args: &[Object]) -> Option> { + match args { + [d, nl] if plain_bytes(d) => Some(with_flag(d, nl, "newline", b2a_base64_kw)), + _ => None, + } +} + +/// `a2b_base64(data, *, strict_mode)`'s keyword half, as +/// [`a2b_base64_fast`]. +fn a2b_base64_kw_fast(args: &[Object]) -> Option> { + match args { + [d, strict] if plain_bytes(d) || matches!(d, Object::Str(_)) => { + Some(with_flag(d, strict, "strict_mode", a2b_base64_kw)) + } + _ => None, + } +} + +/// `unhexlify(data)` of plain bytes or a `str`. +fn a2b_hex_fast(args: &[Object]) -> Option> { + match args { + [d] if plain_bytes(d) || matches!(d, Object::Str(_)) => Some(a2b_hex(args)), + _ => None, + } +} + +/// `crc32(data[, value])` of plain bytes and an `int`. +fn crc32_fast(args: &[Object]) -> Option> { + match args { + [d] | [d, Object::Int(_)] if plain_bytes(d) => Some(crc32(args)), + _ => None, + } +} + +/// `data` as lowercase hex digits, two a byte, through a table. +fn hex_encode(data: &[u8]) -> Vec { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut out = vec![0u8; data.len() * 2]; + for (pair, &b) in out.as_chunks_mut::<2>().0.iter_mut().zip(data) { + pair[0] = DIGITS[usize::from(b >> 4)]; + pair[1] = DIGITS[usize::from(b & 0x0f)]; + } + out +} + fn b2a_hex_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result { let data = buffer_bytes(args.first())?; // sep / bytes_per_sep, positional or keyword. CPython: @@ -214,14 +339,7 @@ fn b2a_hex_kw(args: &[Object], kwargs: &[(String, Object)]) -> Result = { - let mut out = Vec::with_capacity(data.len() * 2); - for &b in &data { - out.push(hex_digit(b >> 4)); - out.push(hex_digit(b & 0x0f)); - } - out - }; + let hex = hex_encode(&data); let sep = match sep_obj { None | Some(Object::None) => None, @@ -279,13 +397,6 @@ fn insert_sep(data: &[u8], hex: &[u8], sep: u8, bytes_per_sep: i64) -> Vec { out } -fn hex_digit(nibble: u8) -> u8 { - match nibble { - 0..=9 => b'0' + nibble, - _ => b'a' + (nibble - 10), - } -} - fn a2b_hex(args: &[Object]) -> Result { let data = input_bytes(args.first())?; if !data.len().is_multiple_of(2) { diff --git a/crates/weavepy-vm/src/stdlib/bisect_accel.rs b/crates/weavepy-vm/src/stdlib/bisect_accel.rs index 58252dade..935a0ea8c 100644 --- a/crates/weavepy-vm/src/stdlib/bisect_accel.rs +++ b/crates/weavepy-vm/src/stdlib/bisect_accel.rs @@ -201,6 +201,39 @@ fn less(interp: &mut crate::Interpreter, a: &Object, b: &Object) -> Result (i64, i64) { + let Object::List(l) = a else { + return (lo, hi); + }; + // SAFETY: nothing below runs code while the view lives. + let Some(items) = (unsafe { l.peek() }) else { + return (lo, hi); + }; + while lo < hi { + let mid = lo + (hi - lo) / 2; + let Some(litem) = usize::try_from(mid).ok().and_then(|m| items.get(m)) else { + break; + }; + let go_left = if right { + crate::native_scalar_compare(item, litem, CompareKind::Lt) + } else { + crate::native_scalar_compare(litem, item, CompareKind::Lt).map(|lt| !lt) + }; + match go_left { + Some(true) => hi = mid, + Some(false) => lo = mid + 1, + None => break, + } + } + (lo, hi) +} + /// `internal_bisect_right`: leftmost index where `item` could be inserted to /// keep `a` sorted, with everything `<= item` to its left. fn internal_bisect_right( @@ -211,6 +244,9 @@ fn internal_bisect_right( mut hi: i64, key: Option<&Object>, ) -> Result { + if key.is_none() { + (lo, hi) = native_steps(a, item, lo, hi, true); + } while lo < hi { // `lo + (hi - lo) / 2` rather than `(lo + hi) / 2`: identical result // for `0 <= lo <= hi`, but can't overflow when `hi` is near @@ -219,7 +255,7 @@ fn internal_bisect_right( let mid = lo + (hi - lo) / 2; let mut litem = item_at(interp, a, mid)?; if let Some(k) = key { - litem = interp.call_object(k.clone(), &[litem], &[])?; + litem = key_of(interp, k, litem)?; } // `item < litem` → search left half. if less(interp, item, &litem)? { @@ -231,6 +267,19 @@ fn internal_bisect_right( Ok(lo) } +/// `key(item)` for a probe: in place when the call runs no Python code (an +/// `itemgetter`, a pure-leaf function), else through the full call. +fn key_of( + interp: &mut crate::Interpreter, + key: &Object, + item: Object, +) -> Result { + if let Some(v) = interp.pure_callback(key, std::slice::from_ref(&item), true) { + return Ok(v); + } + interp.call_object(key.clone(), &[item], &[]) +} + /// `internal_bisect_left`: leftmost index keeping everything `< item` to its /// left (so an equal element sorts to the right of the insertion point). fn internal_bisect_left( @@ -241,12 +290,15 @@ fn internal_bisect_left( mut hi: i64, key: Option<&Object>, ) -> Result { + if key.is_none() { + (lo, hi) = native_steps(a, item, lo, hi, false); + } while lo < hi { // See `internal_bisect_right`: overflow-safe midpoint for huge `hi`. let mid = lo + (hi - lo) / 2; let mut litem = item_at(interp, a, mid)?; if let Some(k) = key { - litem = interp.call_object(k.clone(), &[litem], &[])?; + litem = key_of(interp, k, litem)?; } // `litem < item` → search right half. if less(interp, &litem, item)? { diff --git a/crates/weavepy-vm/src/stdlib/bz2_mod.rs b/crates/weavepy-vm/src/stdlib/bz2_mod.rs index 544aa983f..45907daf5 100644 --- a/crates/weavepy-vm/src/stdlib/bz2_mod.rs +++ b/crates/weavepy-vm/src/stdlib/bz2_mod.rs @@ -7,7 +7,6 @@ use crate::sync::Rc; use crate::sync::RefCell; -use std::collections::HashMap; use std::io::{Read, Write}; use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::{Mutex, OnceLock}; @@ -140,17 +139,35 @@ unsafe impl Send for BzDecompState {} /// Process-global registries keyed by the integer handle stored on each /// Python instance. Global (not thread-local) so a compressor/decompressor /// created on one thread is reachable from any other (see `testThreading`). -type CompReg = Mutex>>>; -type DecompReg = Mutex>>>; +type CompReg = Mutex>; +type DecompReg = Mutex>; fn comp_reg() -> &'static CompReg { static REG: OnceLock = OnceLock::new(); - REG.get_or_init(|| Mutex::new(HashMap::new())) + REG.get_or_init(Mutex::default) +} + +/// A compressor's state goes with it (see `handle_table`). +fn comp_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + if let Ok(mut reg) = comp_reg().try_lock() { + reg.remove(id); + } + } +} + +/// A decompressor's state goes with it (see `handle_table`). +fn decomp_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + if let Ok(mut reg) = decomp_reg().try_lock() { + reg.remove(id); + } + } } fn decomp_reg() -> &'static DecompReg { static REG: OnceLock = OnceLock::new(); - REG.get_or_init(|| Mutex::new(HashMap::new())) + REG.get_or_init(Mutex::default) } fn bz_next_id() -> i64 { @@ -159,11 +176,11 @@ fn bz_next_id() -> i64 { } fn comp_state(id: i64) -> Option>> { - comp_reg().lock().ok()?.get(&id).cloned() + comp_reg().lock().ok()?.get(id) } fn decomp_state(id: i64) -> Option>> { - decomp_reg().lock().ok()?.get(&id).cloned() + decomp_reg().lock().ok()?.get(id) } fn eof_error(msg: &str) -> RuntimeError { @@ -329,6 +346,7 @@ fn compressor_class() -> Rc { is_builtin: true, }, ) + .inspect(|cls| super::handle_table::watch_owner_class(cls, comp_died)) .expect("BZ2Compressor must linearise") }) .clone() @@ -353,6 +371,7 @@ fn decompressor_class() -> Rc { is_builtin: true, }, ) + .inspect(|cls| super::handle_table::watch_owner_class(cls, decomp_died)) .expect("BZ2Decompressor must linearise") }) .clone() @@ -395,10 +414,11 @@ fn compressor_init(args: &[Object], kwargs: &[(String, Object)]) -> Result Result Result<(Object, usize), RuntimeError> { + // Well-formed input, the usual case, is the text itself: no handler + // has anything to do, and nothing is left over. (The loop below builds + // code points and encodes them again, several times the work.) + if let Some(text) = well_formed_text(data) { + return Ok((text, data.len())); + } let mut ctx = DecCtx::new(name, errors, data); let mut out: Vec = Vec::with_capacity(data.len()); let mut i = 0usize; @@ -756,6 +762,88 @@ fn utf8_decode_named( // UTF-16 / UTF-32 decoders // --------------------------------------------------------------------------- +/// The text of whole UTF-16 units whose surrogates all pair up, its UTF-8 +/// written straight into a buffer sized for the worst case (three bytes a +/// unit; a pair's four bytes are its two units'). `None` at a lone +/// surrogate, for the handler's path. +fn utf16_well_formed(pairs: &[[u8; 2]], big: bool) -> Option { + let unit = |pair: [u8; 2]| { + u32::from(if big { + u16::from_be_bytes(pair) + } else { + u16::from_le_bytes(pair) + }) + }; + let mut out: Vec = Vec::with_capacity(pairs.len() * 3); + // (A unit is ASCII when its high byte is zero and its low byte is.) + let (mask, at) = if big { + (0x80FF_80FF_80FF_80FF_u64, 1) + } else { + (0xFF80_FF80_FF80_FF80_u64, 0) + }; + let dst = out.as_mut_ptr(); + let (mut k, mut o) = (0, 0); + // SAFETY: no unit writes more than three bytes (a pair's four are its + // two units'), so every write lands inside the reserved capacity; the + // length then covers exactly what was written. + unsafe { + let put = |o: &mut usize, bytes: &[u8]| { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), dst.add(*o), bytes.len()); + *o += bytes.len(); + }; + while k < pairs.len() { + // Four ASCII units at a time. + if let Some(block) = pairs.get(k..k + 4) { + let b: &[u8; 8] = block.as_flattened().try_into().expect("eight bytes"); + if u64::from_le_bytes(*b) & mask == 0 { + put(&mut o, &[b[at], b[at + 2], b[at + 4], b[at + 6]]); + k += 4; + continue; + } + } + let u = unit(pairs[k]); + k += 1; + if u < 0x80 { + *dst.add(o) = u as u8; + o += 1; + } else if u < 0x800 { + put(&mut o, &[0xC0 | (u >> 6) as u8, 0x80 | (u & 0x3F) as u8]); + } else if (0xD800..0xDC00).contains(&u) { + let low = unit(*pairs.get(k)?); + if !(0xDC00..0xE000).contains(&low) { + return None; + } + k += 1; + let cp = 0x1_0000 + ((u - 0xD800) << 10) + (low - 0xDC00); + put( + &mut o, + &[ + 0xF0 | (cp >> 18) as u8, + 0x80 | ((cp >> 12) & 0x3F) as u8, + 0x80 | ((cp >> 6) & 0x3F) as u8, + 0x80 | (cp & 0x3F) as u8, + ], + ); + } else if (0xDC00..0xE000).contains(&u) { + return None; + } else { + put( + &mut o, + &[ + 0xE0 | (u >> 12) as u8, + 0x80 | ((u >> 6) & 0x3F) as u8, + 0x80 | (u & 0x3F) as u8, + ], + ); + } + } + out.set_len(o); + // (Every sequence written is a whole, valid UTF-8 encoding of a + // scalar value, surrogates excluded.) + Some(String::from_utf8_unchecked(out)) + } +} + /// CPython's `PyUnicode_DecodeUTF16Stateful`: `byteorder` < 0 is LE, > 0 is /// BE, 0 sniffs a BOM (defaulting to native/LE). Returns the decoded text, /// bytes consumed, and the (possibly BOM-updated) byte order. @@ -777,6 +865,20 @@ pub fn utf16_decode( } } let big = byteorder > 0; + // Well-formed input (whole units, every surrogate paired), the usual + // case, is decoded straight to text: no handler has anything to do + // and nothing is left over. + if (data.len() - start).is_multiple_of(2) { + // (ASCII text, the commonest: each unit's low byte is its + // character.) + let body = &data[start..]; + if let Some(text) = utf16_ascii(body, big) { + return Ok((text, data.len(), byteorder)); + } + if let Some(text) = utf16_well_formed(body.as_chunks::<2>().0, big) { + return Ok((Object::from_str(text), data.len(), byteorder)); + } + } let encoding = if big { "utf-16-be" } else { "utf-16-le" }; let mut ctx = DecCtx::new(encoding, errors, data); let mut out: Vec = Vec::with_capacity(data.len() / 2); @@ -851,6 +953,22 @@ pub fn utf32_decode( } } let big = byteorder > 0; + // Well-formed input (whole units, each a scalar value) is decoded + // straight to text. + if (data.len() - start).is_multiple_of(4) { + let mut text = String::with_capacity((data.len() - start) / 4); + let whole = data[start..].as_chunks::<4>().0.iter().all(|unit| { + let v = if big { + u32::from_be_bytes(*unit) + } else { + u32::from_le_bytes(*unit) + }; + char::from_u32(v).map(|c| text.push(c)).is_some() + }); + if whole { + return Ok((Object::from_str(text), data.len(), byteorder)); + } + } let encoding = if big { "utf-32-be" } else { "utf-32-le" }; let mut ctx = DecCtx::new(encoding, errors, data); let mut out: Vec = Vec::with_capacity(data.len() / 4); @@ -896,6 +1014,11 @@ pub fn utf32_decode( // --------------------------------------------------------------------------- pub fn ascii_decode(data: &[u8], errors: &str) -> Result<(Object, usize), RuntimeError> { + if data.is_ascii() { + if let Some(text) = well_formed_text(data) { + return Ok((text, data.len())); + } + } let mut ctx = DecCtx::new("ascii", errors, data); let mut out: Vec = Vec::with_capacity(data.len()); let mut i = 0usize; @@ -912,7 +1035,84 @@ pub fn ascii_decode(data: &[u8], errors: &str) -> Result<(Object, usize), Runtim Ok((Object::str_from_codepoints(out), consumed)) } +/// The `str` of bytes that are well-formed UTF-8 (ASCII text is born +/// knowing its length in characters); `None` for any other bytes. +/// UTF-16 `body` (whole units, little-endian unless `big`) that is all +/// ASCII, as the `str` of its low bytes: checked eight bytes at a time +/// (every high byte and every low byte's top bit clear), then each word's +/// four low bytes packed straight into the string. `None` for any other +/// text. +fn utf16_ascii(body: &[u8], big: bool) -> Option { + use crate::shared_value::SharedStr; + let (words, tail) = body.as_chunks::<8>(); + // (A unit's high byte, and its low byte's top bit, in a word read + // little-endian.) + let mask: u64 = if big { + 0x80FF_80FF_80FF_80FF + } else { + 0xFF80_FF80_FF80_FF80 + }; + let stray = words + .iter() + .fold(0u64, |acc, w| acc | (u64::from_le_bytes(*w) & mask)); + let tail_units = tail.as_chunks::<2>().0; + let (lo, hi) = if big { (1, 0) } else { (0, 1) }; + let tail_stray = tail_units + .iter() + .fold(0u8, |acc, pair| acc | pair[hi] | (pair[lo] & 0x80)); + if stray != 0 || tail_stray != 0 { + return None; + } + let len = body.len() / 2; + if len <= 2 { + let text: Vec = body + .as_chunks::<2>() + .0 + .iter() + .map(|pair| pair[lo]) + .collect(); + return well_formed_text(&text); + } + let shift = if big { 8 } else { 0 }; + // SAFETY: every byte written is ASCII (checked above), `len` of them, + // one code point each. + let text = unsafe { + SharedStr::build_unchecked(len, Some(len), |out| { + for w in words { + let mut x = (u64::from_le_bytes(*w) >> shift) & 0x00FF_00FF_00FF_00FF; + x = (x | (x >> 8)) & 0x0000_FFFF_0000_FFFF; + x = (x | (x >> 16)) & 0x0000_0000_FFFF_FFFF; + out.push(&(x as u32).to_le_bytes()); + } + for pair in tail_units { + out.push_byte(pair[lo]); + } + }) + }; + Some(Object::Str(text)) +} + +fn well_formed_text(data: &[u8]) -> Option { + use crate::shared_value::SharedStr; + if data.is_ascii() { + // SAFETY: ASCII is UTF-8. + let text = unsafe { std::str::from_utf8_unchecked(data) }; + return Some(Object::Str(if text.len() <= 2 { + SharedStr::from(text) + } else { + SharedStr::from_ascii(text) + })); + } + let text = std::str::from_utf8(data).ok()?; + Some(Object::Str(SharedStr::from(text))) +} + pub fn latin1_decode(data: &[u8], _errors: &str) -> Result<(Object, usize), RuntimeError> { + if data.is_ascii() { + if let Some(text) = well_formed_text(data) { + return Ok((text, data.len())); + } + } // Latin-1 decode can never fail: bytes are ordinals. let s: String = data.iter().map(|&b| b as char).collect(); Ok((Object::from_str(s), data.len())) @@ -1425,7 +1625,6 @@ pub fn utf16_encode(cps: &[u32], errors: &str, byteorder: i32) -> Result } else { "utf-16-le" }; - let mut ctx = EncCtx::new(name, errors, cps); let push16 = move |out: &mut Vec, u: u16| { if big { out.extend_from_slice(&u.to_be_bytes()); @@ -1433,6 +1632,25 @@ pub fn utf16_encode(cps: &[u32], errors: &str, byteorder: i32) -> Result out.extend_from_slice(&u.to_le_bytes()); } }; + // Text with no lone surrogate, the usual case, has nothing for a + // handler: its units are written in one pass. + if !cps.iter().any(|cp| (0xD800..=0xDFFF).contains(cp)) { + let mut out = Vec::with_capacity(cps.len() * 2 + 2); + if byteorder == 0 { + out.extend_from_slice(&[0xFF, 0xFE]); // native (LE) BOM + } + for &cp in cps { + if cp <= 0xFFFF { + push16(&mut out, cp as u16); + } else { + let v = cp - 0x1_0000; + push16(&mut out, 0xD800 + (v >> 10) as u16); + push16(&mut out, 0xDC00 + (v & 0x3FF) as u16); + } + } + return Ok(out); + } + let mut ctx = EncCtx::new(name, errors, cps); let mut body = encode_loop_units(&mut ctx, "surrogates not allowed", 2, true, |cp, out| { if (0xD800..=0xDFFF).contains(&cp) { false @@ -1455,6 +1673,161 @@ pub fn utf16_encode(cps: &[u32], errors: &str, byteorder: i32) -> Result Ok(body) } +/// How many of `bytes` satisfy `test`, counted in lanes of bytes (a run +/// of up to 255 at a time), which the compiler vectorizes. +fn count_bytes(bytes: &[u8], test: impl Fn(u8) -> bool) -> usize { + bytes + .chunks(255) + .map(|run| usize::from(run.iter().fold(0u8, |c, &b| c + u8::from(test(b))))) + .sum() +} + +/// [`utf16_encode`] of text with no lone surrogate (a `str`'s own): its +/// units written straight from the text, an ASCII character as its byte +/// and a zero. +pub fn utf16_encode_str(text: &str, byteorder: i32) -> Vec { + let big = byteorder > 0; + let bom = if byteorder == 0 { 2 } else { 0 }; + if text.is_ascii() { + let mut out = vec![0u8; bom + text.len() * 2]; + if bom != 0 { + out[..2].copy_from_slice(&[0xFF, 0xFE]); // native (LE) BOM + } + let at = usize::from(big); + for (pair, &b) in out[bom..] + .as_chunks_mut::<2>() + .0 + .iter_mut() + .zip(text.as_bytes()) + { + pair[at] = b; + } + return out; + } + // The output sized exactly (a character is a unit, and one of four + // UTF-8 bytes a second), and zeroed: an ASCII character then writes + // one byte. + let bytes = text.as_bytes(); + let units = count_bytes(bytes, |b| (b as i8) >= -0x40) + count_bytes(bytes, |b| b >= 0xF0); + let mut out = vec![0u8; bom + units * 2]; + if bom != 0 { + out[..2].copy_from_slice(&[0xFF, 0xFE]); // native (LE) BOM + } + let (lo, hi) = if big { (1, 0) } else { (0, 1) }; + // Four bytes spread into the low bytes of four 16-bit lanes. + let spread = |v: u32| { + let v = u64::from(v); + let v = (v | (v << 16)) & 0x0000_FFFF_0000_FFFF; + (v | (v << 8)) & 0x00FF_00FF_00FF_00FF + }; + let n = bytes.len(); + let (src, dst) = (bytes.as_ptr(), out.as_mut_ptr()); + let (mut i, mut o) = (0, bom); + // SAFETY: `out` holds exactly the units the text's characters make, so + // every write lands inside it; every read is inside the text, whose + // lead bytes all have their continuation bytes (it is valid UTF-8). + unsafe { + while i < n { + let b = *src.add(i); + if b < 0x80 { + // Eight bytes at a time while they are ASCII; the ASCII + // bytes before the first that isn't go one at a time. + if i + 8 <= n { + let x = u64::from_le_bytes(src.add(i).cast::<[u8; 8]>().read_unaligned()); + let high = x & 0x8080_8080_8080_8080; + if high == 0 { + let shift = if big { 8 } else { 0 }; + let at = dst.add(o).cast::<[u8; 8]>(); + at.write_unaligned((spread(x as u32) << shift).to_le_bytes()); + at.add(1) + .write_unaligned((spread((x >> 32) as u32) << shift).to_le_bytes()); + i += 8; + o += 16; + continue; + } + for _ in 0..high.trailing_zeros() / 8 { + *dst.add(o + lo) = *src.add(i); + o += 2; + i += 1; + } + continue; + } + *dst.add(o + lo) = b; + o += 2; + i += 1; + continue; + } + let tail = |k: usize| u32::from(*src.add(i + k) & 0x3F); + let (cp, width) = if b < 0xE0 { + ((u32::from(b & 0x1F) << 6) | tail(1), 2) + } else if b < 0xF0 { + ((u32::from(b & 0x0F) << 12) | (tail(1) << 6) | tail(2), 3) + } else { + let cp = (u32::from(b & 0x07) << 18) | (tail(1) << 12) | (tail(2) << 6) | tail(3); + (cp, 4) + }; + i += width; + if cp < 0x1_0000 { + *dst.add(o + lo) = cp as u8; + *dst.add(o + hi) = (cp >> 8) as u8; + o += 2; + } else { + let v = cp - 0x1_0000; + let (h, l) = (0xD800 + (v >> 10), 0xDC00 + (v & 0x3FF)); + *dst.add(o + lo) = h as u8; + *dst.add(o + hi) = (h >> 8) as u8; + *dst.add(o + 2 + lo) = l as u8; + *dst.add(o + 2 + hi) = (l >> 8) as u8; + o += 4; + } + } + } + debug_assert_eq!(o, out.len()); + out +} + +/// [`utf32_encode`] of text with no lone surrogate (a `str`'s own). +pub fn utf32_encode_str(text: &str, byteorder: i32) -> Vec { + let big = byteorder > 0; + if text.is_ascii() { + // (An ASCII character is its byte and three zeros.) + let bom = if byteorder == 0 { 4 } else { 0 }; + let mut out = vec![0u8; bom + text.len() * 4]; + if bom != 0 { + out[..2].copy_from_slice(&[0xFF, 0xFE]); // native (LE) BOM + } + let at = if big { 3 } else { 0 }; + for (unit, &b) in out[bom..] + .as_chunks_mut::<4>() + .0 + .iter_mut() + .zip(text.as_bytes()) + { + unit[at] = b; + } + return out; + } + // (Sized once: a unit per character, each written whole.) + let bom = if byteorder == 0 { 4 } else { 0 }; + let mut out = vec![0u8; bom + text.chars().count() * 4]; + if bom != 0 { + out[..4].copy_from_slice(&[0xFF, 0xFE, 0x00, 0x00]); // native (LE) BOM + } + for (unit, c) in out[bom..] + .as_chunks_mut::<4>() + .0 + .iter_mut() + .zip(text.chars()) + { + *unit = if big { + (c as u32).to_be_bytes() + } else { + (c as u32).to_le_bytes() + }; + } + out +} + /// UTF-32 encode (same byteorder protocol). pub fn utf32_encode(cps: &[u32], errors: &str, byteorder: i32) -> Result, RuntimeError> { let big = byteorder > 0; diff --git a/crates/weavepy-vm/src/stdlib/codecs_mod.rs b/crates/weavepy-vm/src/stdlib/codecs_mod.rs index 1036309dd..8a971fde8 100644 --- a/crates/weavepy-vm/src/stdlib/codecs_mod.rs +++ b/crates/weavepy-vm/src/stdlib/codecs_mod.rs @@ -199,12 +199,17 @@ fn arg_codec_name(args: &[Object], idx: usize, name: &str) -> Result Result, RuntimeError> { +fn arg_bytes<'a>( + args: &'a [Object], + idx: usize, + name: &str, +) -> Result, RuntimeError> { let _ = name; match args.get(idx) { // Argument-clinic `Py_buffer` converter wording (`codecs.utf_8_decode("x")` // → "a bytes-like object is required, not 'str'"). - Some(o) => o.as_bytes_view().ok_or_else(|| { + // (A `bytes` object's bytes are read where they are.) + Some(o) => o.bytes_cow().ok_or_else(|| { type_error(format!( "a bytes-like object is required, not '{}'", o.type_name() @@ -219,7 +224,7 @@ fn arg_bytes(args: &[Object], idx: usize, name: &str) -> Result, Runtime fn arg_bytes_or_str_utf8(args: &[Object], idx: usize, name: &str) -> Result, RuntimeError> { match args.get(idx) { Some(Object::Str(s)) => Ok(s.as_bytes().to_vec()), - _ => arg_bytes(args, idx, name), + _ => arg_bytes(args, idx, name).map(std::borrow::Cow::into_owned), } } @@ -972,7 +977,7 @@ fn decode_via_registry( let res = with_interp(|interp| { interp.call_object( codec, - &[Object::new_bytes(bytes.to_vec()), Object::from_str(errors)], + &[Object::new_bytes(bytes), Object::from_str(errors)], &[], ) }); @@ -1212,36 +1217,14 @@ fn encode_special(s: &str, encoding: &str, errors: &str) -> Result Some(crate::stdlib::codecs_engine::ascii_encode(&cps(), errors)?), "latin1" | "iso88591" => Some(crate::stdlib::codecs_engine::latin1_encode(&cps(), errors)?), - "utf16" => Some(crate::stdlib::codecs_engine::utf16_encode( - &cps(), - errors, - 0, - )?), - "utf16le" => Some(crate::stdlib::codecs_engine::utf16_encode( - &cps(), - errors, - -1, - )?), - "utf16be" => Some(crate::stdlib::codecs_engine::utf16_encode( - &cps(), - errors, - 1, - )?), - "utf32" => Some(crate::stdlib::codecs_engine::utf32_encode( - &cps(), - errors, - 0, - )?), - "utf32le" => Some(crate::stdlib::codecs_engine::utf32_encode( - &cps(), - errors, - -1, - )?), - "utf32be" => Some(crate::stdlib::codecs_engine::utf32_encode( - &cps(), - errors, - 1, - )?), + // (A `str` has no lone surrogate, so nothing for a handler: its + // units are written straight from the text.) + "utf16" => Some(crate::stdlib::codecs_engine::utf16_encode_str(s, 0)), + "utf16le" => Some(crate::stdlib::codecs_engine::utf16_encode_str(s, -1)), + "utf16be" => Some(crate::stdlib::codecs_engine::utf16_encode_str(s, 1)), + "utf32" => Some(crate::stdlib::codecs_engine::utf32_encode_str(s, 0)), + "utf32le" => Some(crate::stdlib::codecs_engine::utf32_encode_str(s, -1)), + "utf32be" => Some(crate::stdlib::codecs_engine::utf32_encode_str(s, 1)), "rawunicodeescape" => Some(encode_raw_unicode_escape(s)), "unicodeescape" => Some(encode_unicode_escape(s)), "utf7" => Some(crate::stdlib::codecs_engine::utf7_encode(&cps(), errors)?), diff --git a/crates/weavepy-vm/src/stdlib/collections_native.rs b/crates/weavepy-vm/src/stdlib/collections_native.rs index be4f4c2d3..aa198f09a 100644 --- a/crates/weavepy-vm/src/stdlib/collections_native.rs +++ b/crates/weavepy-vm/src/stdlib/collections_native.rs @@ -268,6 +268,112 @@ pub(crate) fn op_returns_element(op: u8) -> bool { matches!(op, OP_POP | OP_POPLEFT | OP_GETITEM | OP_NEXT | OP_RNEXT) } +thread_local! { + /// This thread's `deque.__len__` builtin (see [`is_deque_len`]). + static DEQUE_LEN: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether `b` is this thread's `deque.__len__`, whose length +/// [`fast_op`]'s `OP_LEN` reads straight off a deque receiver. +#[inline] +pub(crate) fn is_deque_len(b: &Rc) -> bool { + DEQUE_LEN.with(std::cell::Cell::get) == Rc::as_ptr(b) as usize +} + +thread_local! { + /// This thread's `deque.__iter__` builtin (see [`iterates_natively`]). + static DEQUE_ITER: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The version token of the class last found to keep the native +/// `__iter__` and `__len__` (a token names one state of one class, and +/// none is zero). +static NATIVE_ITER_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether `iter()` and `len()` of `inst` are the native deque ones: a +/// deque, or a subclass that overrides neither. Remembered for the class +/// last asked about. +#[inline] +fn iterates_natively(inst: &crate::types::PyInstance) -> bool { + use std::sync::atomic::Ordering::Relaxed; + if crate::gil::free_threading_enabled() { + return false; + } + let cls = inst.cls_raw(); + let ver = cls.attr_version.get(); + if ver == NATIVE_ITER_VER.load(Relaxed) { + return true; + } + if ver != 0 && ver == FOREIGN_ITER_VER.load(Relaxed) { + return false; + } + iterates_natively_slow(cls, ver) +} + +/// The version token of the class last found NOT to keep the deque's +/// `__iter__` and `__len__` (`list(od)` asks of an `OrderedDict` first). +static FOREIGN_ITER_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +#[cold] +#[inline(never)] +fn iterates_natively_slow(cls: &crate::types::TypeObject, ver: u64) -> bool { + let is = |name: &str, p: usize| { + p != 0 + && matches!(cls.lookup(name), Some(Object::Builtin(b)) if Rc::as_ptr(&b) as usize == p) + }; + let ok = is("__iter__", DEQUE_ITER.with(std::cell::Cell::get)) + && is("__len__", DEQUE_LEN.with(std::cell::Cell::get)); + if ok { + NATIVE_ITER_VER.store(ver, std::sync::atomic::Ordering::Relaxed); + } else { + FOREIGN_ITER_VER.store(ver, std::sync::atomic::Ordering::Relaxed); + } + ok +} + +/// The items of a deque whose class keeps the native `__iter__` and +/// `__len__`, in order, as iterating it would collect them (`list(d)`, +/// `tuple(d)`, `sorted(d)`): copied off its backing list with no iterator +/// made. `None` for anything else. +pub(crate) fn deque_items(v: &Object) -> Option> { + let Object::Instance(inst) = v else { + return None; + }; + if !iterates_natively(inst) { + return None; + } + // SAFETY: no guard is live on the cells (`peek` checks), and nothing + // runs code before the views end with this call. + let ds = unsafe { inst.slots.peek() }?; + let n = names(); + let [data, head, _, _] = + ds.leading_memo(&DEQUE_LAYOUT, [&n.data, &n.head, &n.maxlen, &n.state])?; + let Object::List(data) = data else { + return None; + }; + let h = match *head { + Object::Int(h) if h >= 0 => h as usize, + _ => 0, + }; + // SAFETY: as above. + let d = unsafe { data.peek() }?; + Some(d[h.min(d.len())..].to_vec()) +} + +/// `iter(d)` of a deque whose class keeps the native `__iter__`, for a +/// `for` loop's `GET_ITER` in compiled code: the iterator +/// [`deque_make_iter`] builds, which runs no Python code. `None` for +/// anything else. +pub(crate) fn deque_iter_lane(v: &Object) -> Option { + let Object::Instance(inst) = v else { + return None; + }; + if !iterates_natively(inst) { + return None; + } + deque_make_iter(std::slice::from_ref(v), false).ok() +} + /// One deque operation's common case on `recv` (and its one argument), /// over the unguarded views [`fast_parts`] takes: the whole operation, /// or `None` with nothing touched when it needs the full body (a guarded @@ -302,7 +408,7 @@ pub(crate) fn fast_op(op: u8, recv: &Object, arg: Option<&Object>) -> Option, d: &mut Vec) -> Result, slack: usize) { + let mut grown = Vec::with_capacity(slack + d.len()); + grown.resize(slack, Object::None); + grown.append(d); + *d = grown; +} + +/// `_extend_items(d, items, left)`: `d.extend(items)` (or `extendleft`) +/// for a list or tuple of items, all at once, with the trimming `maxlen` +/// calls for; `False`, having done nothing, for any other source (the +/// Python method iterates it). +fn deque_extend_items(args: &[Object]) -> Result { + let [_, src, left] = args else { + return Err(type_error( + "_extend_items() takes a deque, items and a side", + )); + }; + let left = left.is_truthy(); + let mut st = receiver(&args[..1], "extend")?; + // Items that `maxlen` would trim as soon as they went in (all but the + // last `maxlen` of the source, which every item already held goes out + // before) are left out: the source still holds them, so trimming them + // would release nothing. + let skip = |n: usize| st.maxlen().map_or(0, |m| n.saturating_sub(m)); + let items: Vec = match src { + Object::List(l) => { + let l = l.borrow(); + crate::object::cloned_vec(&l[skip(l.len())..]) + } + Object::Tuple(t) => crate::object::cloned_vec(&t[skip(t.len())..]), + _ => return Ok(Object::Bool(false)), + }; + let data = st.data.clone(); + let mut trimmed = Vec::new(); + { + let mut d = data.borrow_mut(); + st.bump_state(); + let mut h = st.head().min(d.len()); + if left { + let need = items.len(); + if h < need { + let slack = need.max((d.len() - h) / 2).max(8) - h; + grow_front(&mut d, slack); + h += slack; + } + for item in items { + h -= 1; + trimmed.push(std::mem::replace(&mut d[h], item)); + } + st.set_head(h); + if let Some(m) = st.maxlen() { + while d.len() - h > m { + trimmed.extend(d.pop()); + } + } + } else { + d.extend(items); + if let Some(m) = st.maxlen() { + // The oldest items out in one cut, in the order `popleft` + // takes them (the free prefix before the head holds only + // placeholders). + let live = d.len() - h; + if live > m { + trimmed.extend(d.drain(..h + live - m).skip(h)); + st.set_head(0); + } + } + } + } + drop(st); + drop(trimmed); + Ok(Object::Bool(true)) +} + +/// Whether `item == x` is settled without Python code: `Some(eq)` when +/// both are plain values (`int`, `float`, `bool`, `None`, `str`, `bytes`) +/// or the same object, `None` when an `__eq__` might run. +fn plain_eq(item: &Object, x: &Object) -> Option { + fn plain(o: &Object) -> bool { + matches!( + o, + Object::Int(_) + | Object::Float(_) + | Object::Bool(_) + | Object::None + | Object::Str(_) + | Object::Bytes(_) + ) + } + if item.is_same(x) { + return Some(true); + } + (plain(item) && plain(x)).then(|| item.eq_value(x)) +} + +/// `_plain_find(items, x, start, stop)`: the first index in +/// `items[start:stop]` of an item equal to `x`, `-1` for none, when every +/// comparison is settled natively ([`plain_eq`]); `None` (the Python +/// loop's to answer) otherwise. +fn deque_plain_find(args: &[Object]) -> Result { + let [Object::List(items), x, Object::Int(start), Object::Int(stop)] = args else { + return Ok(Object::None); + }; + let items = items.borrow(); + let stop = usize::try_from(*stop).unwrap_or(0).min(items.len()); + let start = usize::try_from(*start).unwrap_or(0).min(stop); + for (i, item) in items[start..stop].iter().enumerate() { + match plain_eq(item, x) { + Some(true) => return Ok(Object::Int((start + i) as i64)), + Some(false) => {} + None => return Ok(Object::None), + } + } + Ok(Object::Int(-1)) +} + +/// `_plain_count(items, x)`: how many items equal `x`, when every +/// comparison is settled natively; `None` otherwise. +fn deque_plain_count(args: &[Object]) -> Result { + let [Object::List(items), x] = args else { + return Ok(Object::None); + }; + let mut n = 0; + for item in items.borrow().iter() { + match plain_eq(item, x) { + Some(hit) => n += i64::from(hit), + None => return Ok(Object::None), + } + } + Ok(Object::Int(n)) +} + +thread_local! { + /// This thread's `deque.__contains__` (see [`deque_contains_method`]). + static DEQUE_CONTAINS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The version token of the class last found to keep the native +/// `__contains__` (see [`NATIVE_ITER_VER`]). +static NATIVE_CONTAINS_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// `x in d` for a deque (`inst`) whose items and `x` compare natively +/// ([`plain_eq`]): searched in place, with no Python code run. `None` +/// (nothing decided) when a comparison might run an `__eq__`, or the +/// cells are guarded. +fn deque_plain_contains(inst: &crate::types::PyInstance, x: &Object) -> Option { + // SAFETY: no guard is live on the cells (`peek` checks), and nothing + // runs code before the views end with this call. + let ds = unsafe { inst.slots.peek() }?; + let n = names(); + let [data, head, _, _] = + ds.leading_memo(&DEQUE_LAYOUT, [&n.data, &n.head, &n.maxlen, &n.state])?; + let Object::List(data) = data else { + return None; + }; + let h = match *head { + Object::Int(h) if h >= 0 => h as usize, + _ => 0, + }; + // SAFETY: as above. + let d = unsafe { data.peek() }?; + for item in &d[h.min(d.len())..] { + if plain_eq(item, x)? { + return Some(true); + } + } + Some(false) +} + +/// `x in d` for an instance whose class keeps the deque's native +/// `__contains__` (remembered for the class last asked about), where +/// [`deque_plain_contains`] settles it. `None` for anything else. +pub(crate) fn deque_contains_fast(inst: &crate::types::PyInstance, x: &Object) -> Option { + use std::sync::atomic::Ordering::Relaxed; + if crate::gil::free_threading_enabled() { + return None; + } + let cls = inst.cls_raw(); + let ver = cls.attr_version.get(); + if ver != NATIVE_CONTAINS_VER.load(Relaxed) { + let want = DEQUE_CONTAINS.with(std::cell::Cell::get); + match cls.lookup("__contains__") { + Some(Object::Builtin(b)) if want != 0 && Rc::as_ptr(&b) as usize == want => {} + _ => return None, + } + NATIVE_CONTAINS_VER.store(ver, Relaxed); + } + deque_plain_contains(inst, x) +} + +/// `_contains_method(fallback)`: a deque's `__contains__`, which searches +/// plain items natively (see [`deque_plain_contains`]) and calls the +/// Python function `fallback` with the same arguments for anything else. +fn deque_contains_method(args: &[Object]) -> Result { + let [fallback] = args else { + return Err(type_error("_contains_method() takes a fallback")); + }; + let fallback = fallback.clone(); + let method = Rc::new(BuiltinFn { + name: "__contains__", + binds_instance: true, + call: Box::new(move |a: &[Object]| { + if let [Object::Instance(recv), x] = a { + if let Some(hit) = deque_plain_contains(recv, x) { + return Ok(Object::Bool(hit)); + } + } + let interp = crate::builtins::reentrant_interp()?; + let globals = interp.builtins_dict(); + interp.call(&fallback, a, &[], &globals) + }), + call_kw: None, + }); + DEQUE_CONTAINS.with(|c| c.set(Rc::as_ptr(&method) as usize)); + Ok(Object::Builtin(method)) +} + +/// `_extend_method(fallback, left)`: a deque's `extend` (or +/// `extendleft`), which takes a list or tuple in at once (see +/// [`deque_extend_items`]) and calls the Python function `fallback` with +/// the same arguments for anything else. +fn deque_extend_method(args: &[Object]) -> Result { + let [fallback, left] = args else { + return Err(type_error("_extend_method() takes a fallback and a side")); + }; + let (fallback, left) = (fallback.clone(), left.is_truthy()); + let name = if left { "extendleft" } else { "extend" }; + Ok(Object::Builtin(Rc::new(BuiltinFn { + name, + binds_instance: true, + call: Box::new(move |a: &[Object]| { + if let [recv, src @ (Object::List(_) | Object::Tuple(_))] = a { + let side = Object::Bool(left); + if let Object::Bool(true) = deque_extend_items(&[recv.clone(), src.clone(), side])? + { + return Ok(Object::None); + } + } + let interp = crate::builtins::reentrant_interp()?; + let globals = interp.builtins_dict(); + // Any other iterable (a generator, a range, a dict's keys): + // stepped here, each item appended as the deque's own `append` + // takes it, so an error midway leaves the items before it in + // place. (A deque extending itself iterates a snapshot, which + // the Python method takes.) + if let [recv @ Object::Instance(_), src] = a { + if !src.is_same(recv) { + let step = if left { deque_appendleft } else { deque_append }; + // (The receiver's own check first, before the source + // is asked for an iterator.) + drop(receiver(std::slice::from_ref(recv), name)?); + let it = interp.make_iter(src, &globals)?; + while let Some(item) = interp.iter_next(&it, &globals)? { + step(&[recv.clone(), item])?; + } + return Ok(Object::None); + } + } + interp.call(&fallback, a, &[], &globals) + }), + call_kw: None, + }))) +} + pub(crate) fn deque_append(args: &[Object]) -> Result { if let [recv, x] = args { if let Some(v) = fast_op(OP_APPEND, recv, Some(x)) { @@ -446,7 +819,7 @@ fn deque_appendleft(args: &[Object]) -> Result { let mut h = st.head(); if h == 0 { h = std::cmp::max(8, d.len() / 2); - d.splice(0..0, std::iter::repeat_n(Object::None, h)); + grow_front(&mut d, h); } h -= 1; d[h] = x; @@ -570,46 +943,72 @@ fn deque_rotate(args: &[Object]) -> Result { return Err(type_error("deque.rotate() takes at most one argument")); } }; + // The unguarded parts, found in one pass over the slots (see + // `fast_parts`); the guarded ones otherwise. + if let Some(mut f) = fast_parts(args) { + let h = f.head(); + if let Some(h) = rotate_in(f.d, h, n) { + f.bump_state(); + f.set_head(h); + } + return Ok(Object::None); + } let mut st = receiver(args, "rotate")?; let data = st.data.clone(); let mut d = data.borrow_mut(); - let mut h = st.head().min(d.len()); + let h = st.head(); + if let Some(h) = rotate_in(&mut d, h, n) { + st.bump_state(); + st.set_head(h); + } + Ok(Object::None) +} + +/// Rotate the deque whose items are `d[h..]` right by `n`: the new head, +/// or `None` when there was nothing to move (fewer than two items; the +/// state counter moves only otherwise, though a whole turn changes +/// nothing). +fn rotate_in(d: &mut Vec, h: usize, n: i64) -> Option { + let mut h = h.min(d.len()); let len = d.len() - h; if len <= 1 { - return Ok(Object::None); + return None; } - st.bump_state(); let right = n.rem_euclid(len as i64) as usize; if right == 0 { - return Ok(Object::None); + return Some(h); } if right <= len / 2 { if h < right { - let slack = right.max(len / 2).max(8); - d.splice(0..0, std::iter::repeat_n(Object::None, slack)); + // (Room for as many items again as the deque holds, so the + // next rotations find it there: a gap the size of one rotation + // moved the whole deque on every other call.) + let slack = right.max(len).max(8); + grow_front(d, slack); h += slack; } let end = d.len(); - for i in 0..right { - d.swap(h - right + i, end - right + i); - } + // (The last `right` items trade places, as one block, with the + // free slots just before the head.) + let (front, back) = d.split_at_mut(end - right); + front[h - right..h].swap_with_slice(back); d.truncate(end - right); - st.set_head(h - right); + Some(h - right) } else { let left = len - right; - d.reserve(left); - for i in 0..left { - let value = std::mem::replace(&mut d[h + i], Object::None); - d.push(value); - } + // (The first `left` items trade places, as one block, with free + // slots added at the end.) + let end = d.len(); + d.resize(end + left, Object::None); + let (front, back) = d.split_at_mut(end); + front[h..h + left].swap_with_slice(back); h += left; if h >= 32 && h * 2 >= d.len() { d.drain(..h); h = 0; } - st.set_head(h); + Some(h) } - Ok(Object::None) } /// `iter(d)` / `reversed(d)`: a fresh `_deque_iterator` (or reverse @@ -633,21 +1032,60 @@ fn deque_make_iter(args: &[Object], reverse: bool) -> Result match types.get(usize::from(reverse)) { - Some(Object::Type(cls)) => cls.clone(), + // (The class's iterator types, remembered for the class version last + // asked about: its `_iter_types` pair.) + let ver = inst.cls_raw().attr_version.get(); + let memo = ITER_TYPES.with(|m| match &*m.borrow() { + Some((v, types)) if *v == ver => Some(types[usize::from(reverse)].clone()), + _ => None, + }); + let it_cls = match memo { + Some(cls) => cls, + None => match inst.cls().lookup("_iter_types") { + Some(Object::Tuple(types)) => match (types.first(), types.get(1)) { + (Some(Object::Type(f)), Some(Object::Type(r))) => { + let pair = [f.clone(), r.clone()]; + let cls = pair[usize::from(reverse)].clone(); + ITER_TYPES.with(|m| *m.borrow_mut() = Some((ver, pair))); + cls + } + _ => return Err(type_error("deque iterator types are not set")), + }, _ => return Err(type_error("deque iterator types are not set")), }, - _ => return Err(type_error("deque iterator types are not set")), }; + // The iterator classes' slot order (see `deque_next_fast`): written + // whole where the class lays exactly those slots out, by name + // otherwise. + const SLOTS: [&str; 3] = ["_deq", "_index", "_deq_state"]; + if let Some(layout) = it_cls.own_slot_layout().filter(|layout| { + layout.len() == SLOTS.len() + && layout + .iter() + .zip(SLOTS) + .all(|(k, n)| matches!(&k.0, Object::Str(s) if s.as_ref() == n)) + }) { + let values = [recv.clone(), Object::Int(0), state]; + let slots = crate::types::SlotStorage::from_layout_array(layout.clone(), values); + let obj = Object::Instance(Rc::new(crate::types::PyInstance::with_slots(it_cls, slots))); + crate::gc_trace::track(&obj); + return Ok(obj); + } let it = crate::types::PyInstance::new_deferred(it_cls); - // The iterator classes' slot order (see `deque_next_fast`). it.slot_set("_deq", recv.clone()); it.slot_set("_index", Object::Int(0)); it.slot_set("_deq_state", state); Ok(Object::Instance(it)) } +thread_local! { + /// The deque class version last asked for its iterator types, and + /// that class's `_iter_types` pair (forward, reverse). + #[allow(clippy::type_complexity)] + static ITER_TYPES: std::cell::RefCell; 2])>> = + const { std::cell::RefCell::new(None) }; +} + fn deque_iter(args: &[Object]) -> Result { deque_make_iter(args, false) } @@ -737,6 +1175,189 @@ fn deque_next_fast(iterator: &crate::types::PyInstance, reverse: bool) -> Option Some(v) } +/// The deque iterators' native `__next__` builtins (their addresses), for +/// [`deque_iter_rest`]'s check. +static ITER_NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static RITER_NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The version tokens of the classes last found to keep the forward +/// deque iterator's native `__next__`, and not to (see +/// [`NATIVE_ITER_VER`]). +static NATIVE_NEXT_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static FOREIGN_NEXT_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +#[cold] +#[inline(never)] +fn steps_natively_slow(cls: &crate::types::TypeObject, ver: u64) -> bool { + use std::sync::atomic::Ordering::Relaxed; + let want = ITER_NEXT.load(Relaxed); + let ok = want != 0 + && matches!(cls.lookup("__next__"), Some(Object::Builtin(b)) if Rc::as_ptr(&b) as usize == want); + (if ok { + &NATIVE_NEXT_VER + } else { + &FOREIGN_NEXT_VER + }) + .store(ver, Relaxed); + ok +} + +/// One step of a `for` loop over an instance iterator, where it is a +/// deque's. +pub(crate) enum DequeStep { + /// The next item, the iterator stepped past it. + Item(Object), + /// The end of an unchanged deque (nothing touched: the loop lets the + /// iterator go). + End, + /// Not a deque's forward iterator, or a step for its full `__next__` + /// (a deque changed since the iterator was made, a guarded cell). + Other, +} + +/// A `for` loop's step over `it` in compiled code: a deque iterator's +/// next item or its end, read in place (see [`deque_next_fast`]), when its +/// class keeps the native `__next__` (remembered for the class last asked +/// about). +#[inline] +pub(crate) fn deque_for_step(it: &crate::types::PyInstance) -> DequeStep { + use std::sync::atomic::Ordering::Relaxed; + let cls = it.cls_raw(); + let ver = cls.attr_version.get(); + if ver != NATIVE_NEXT_VER.load(Relaxed) + && (ver == FOREIGN_NEXT_VER.load(Relaxed) + || crate::gil::free_threading_enabled() + || !steps_natively_slow(cls, ver)) + { + return DequeStep::Other; + } + match deque_next_fast(it, false) { + Some(v) => DequeStep::Item(v), + None if deque_iter_at_end(it) => DequeStep::End, + None => DequeStep::Other, + } +} + +/// Whether the forward deque iterator `it` is at the end of a deque +/// unchanged since it was made (its next step raises `StopIteration`). +#[inline(never)] +fn deque_iter_at_end(it: &crate::types::PyInstance) -> bool { + let at_end = || -> Option { + // SAFETY: as in `deque_next_fast`: no guard is live on the cells, + // and nothing runs code before the views end with this call. + let its = unsafe { it.slots.peek() }?; + let n = names(); + let [deque, index, it_state] = + its.leading_memo(&ITER_LAYOUT, [&n.deq, &n.index, &n.deq_state])?; + let (Object::Instance(deque), Object::Int(i)) = (deque, index) else { + return None; + }; + // SAFETY: as above. + let ds = unsafe { deque.slots.peek() }?; + let [data, head, _, state] = + ds.leading_memo(&DEQUE_LAYOUT, [&n.data, &n.head, &n.maxlen, &n.state])?; + let Object::List(data) = data else { + return None; + }; + match (state, it_state) { + (Object::Int(a), Object::Int(b)) if a == b => {} + _ => return None, + } + let h = match *head { + Object::Int(h) if h >= 0 => h as usize, + _ => 0, + }; + // SAFETY: as above. + let d = unsafe { data.peek() }?; + let left = d.len() - h.min(d.len()); + Some(*i >= 0 && *i as usize >= left) + }; + at_end() == Some(true) +} + +/// The rest of a deque iterator's items at once (`list(dq)`), when its +/// class keeps the native `__next__` and the deque is unchanged since the +/// iterator was made: the items in order (reversed for `reversed(dq)`'s), +/// the iterator moved to its end as stepping it would leave it. `None`, +/// nothing changed, for anything else. +pub(crate) fn deque_iter_rest(iterator: &crate::types::PyInstance) -> Option> { + use std::sync::atomic::Ordering; + let reverse = match iterator.cls_raw().lookup("__next__") { + Some(Object::Builtin(b)) => { + let p = Rc::as_ptr(&b) as usize; + if p == ITER_NEXT.load(Ordering::Relaxed) { + false + } else if p == RITER_NEXT.load(Ordering::Relaxed) { + true + } else { + return None; + } + } + _ => return None, + }; + // SAFETY: as in `deque_next_fast`: no guard is live on the cells, no + // Python runs before the last use, and the two objects are distinct. + let its = unsafe { iterator.slots.peek_mut() }?; + let n = names(); + let [deque, index, it_state] = + its.leading_memo_mut(&ITER_LAYOUT, [&n.deq, &n.index, &n.deq_state])?; + let Object::Instance(deque) = deque else { + return None; + }; + let deque: *const crate::types::PyInstance = Rc::as_ptr(deque); + let Object::Int(i) = index else { + return None; + }; + // SAFETY: as above. + let ds = unsafe { (*deque).slots.peek() }?; + let [data, head, _, state] = + ds.leading_memo(&DEQUE_LAYOUT, [&n.data, &n.head, &n.maxlen, &n.state])?; + let Object::List(data) = data else { + return None; + }; + match (state, &*it_state) { + (Object::Int(a), Object::Int(b)) if a == b => {} + _ => return None, + } + let h = match *head { + Object::Int(h) if h >= 0 => h as usize, + _ => 0, + }; + // SAFETY: as above. + let d = unsafe { data.peek() }?; + let h = h.min(d.len()); + let total = d.len() - h; + let at = usize::try_from(*i).ok()?; + if at > total { + return None; + } + let out = if reverse { + (at..total).map(|k| d[d.len() - 1 - k].clone()).collect() + } else { + d[h + at..].to_vec() + }; + *i = total as i64; + Some(out) +} + +/// A deque iterator's `__next__` leaf half: the next item read in place +/// while the deque is unchanged (see [`deque_next_fast`]). `None` (the +/// end, a change, or anything unusual) for the full body. +fn deque_iterator_next_leaf(args: &[Object]) -> Option> { + let [Object::Instance(it)] = args else { + return None; + }; + deque_next_fast(it, false).map(Ok) +} + +/// [`deque_iterator_next_leaf`] for `reversed(deque)`'s iterator. +fn deque_reverse_iterator_next_leaf(args: &[Object]) -> Option> { + let [Object::Instance(it)] = args else { + return None; + }; + deque_next_fast(it, true).map(Ok) +} + fn deque_next(args: &[Object], reverse: bool) -> Result { let [Object::Instance(iterator)] = args else { return Err(type_error("deque iterator __next__ requires one iterator")); @@ -1215,6 +1836,50 @@ fn chainmap_maps_of(inst: &crate::types::PyInstance) -> Option Option { + let want = CHAINMAP_CONTAINS.load(std::sync::atomic::Ordering::Relaxed); + if want == 0 { + return None; + } + let cls = inst.cls_raw(); + match cls.lookup("__contains__") { + Some(Object::Builtin(b)) if Rc::as_ptr(&b) as usize == want => {} + _ => return None, + } + if cls.lookup("maps").is_some() { + return None; + } + let maps = chainmap_maps_of(inst)?; + let probe = crate::object::LeafProbe::new(key)?; + // SAFETY: views that run no code (native probes), ending with this call. + let ms = unsafe { maps.peek() }?; + for m in ms.iter() { + let Object::Dict(d) = m else { + return None; + }; + // SAFETY: as above. + let dd = unsafe { d.peek() }?; + if dd.get_index_of(&probe).is_some() { + return Some(true); + } + if !probe.miss_is_exact() { + return None; + } + } + Some(false) +} + /// [`chainmap_getitem`]'s leaf half (see `leaf_builtins::Fast`): a plain /// key found by exact native equality in a list of exact dicts held in /// the instance's own `maps` attribute. A key no map holds (the @@ -1335,9 +2000,133 @@ fn install_defaultdict(args: &[Object]) -> Result { d.shift_remove(&DictKey(Object::from_static("__slots__"))); } cls.bump_attr_version(); + // (The exact class's plain calls build in place; a subclass has its + // own, empty, constructor hook.) + cls.pure_new.set(Some(dd_pure_new)); Ok(Object::None) } +/// `install_deque(deque)`: the class's plain constructions build in place +/// (see [`deque_pure_new`]). +fn install_deque(args: &[Object]) -> Result { + let [Object::Type(cls)] = args else { + return Err(type_error("install_deque() expects a class")); + }; + cls.pure_new.set(Some(deque_pure_new)); + static PARAMS: &[&str] = &["iterable", "maxlen"]; + cls.pure_new_kw.set(Some(&PARAMS)); + Ok(Object::None) +} + +/// The version token of the deque class last found by [`deque_pure_new`] +/// to keep `_collections`' `__init__` and slot layout. +static PURE_NEW_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// `deque()`, `deque(xs)` or `deque(xs, maxlen)` of a list or tuple (a +/// range or str too, without a bound), of the exact class while its +/// `__init__` is `_collections`' own and its slots are laid out as that +/// `__init__` stores them: the instance over a copy of the items (the +/// last `maxlen` of them), as `__init__` leaves it. `None` for any other +/// call. +fn deque_pure_new(cls: &Rc, args: &[Object]) -> Option { + const SLOTS: [&str; 4] = ["_data", "_head", "_maxlen", "_state"]; + // (A positional `maxlen`, `None` or a non-negative `int`: `d.copy()`'s + // `type(self)(items, maxlen)`. Any other is `__init__`'s to reject.) + let (source, maxlen) = match args { + [] => (None, &Object::None), + [src] => (Some(src), &Object::None), + [src, m @ Object::None] => (Some(src), m), + [src, m @ Object::Int(n)] if *n >= 0 => (Some(src), m), + _ => return None, + }; + // The items a bound keeps: the last `maxlen` of them, as appending + // each in turn leaves the deque. + let kept = |xs: &[Object]| match maxlen { + Object::Int(m) => xs[xs.len().saturating_sub(*m as usize)..].to_vec(), + _ => xs.to_vec(), + }; + let items: Vec = match source { + None => Vec::new(), + Some(Object::List(l)) => kept(&l.try_borrow().ok()?), + Some(Object::Tuple(t)) => kept(t), + // An unbounded deque of a range's ints or a string's characters, + // as iterating them yields them (a range too long to hold is + // `__init__`'s to report). + Some(r @ Object::Range(_)) if matches!(maxlen, Object::None) => { + crate::object::collect_small_int_range(r)?.ok()? + } + Some(Object::Str(s)) if matches!(maxlen, Object::None) => { + s.chars().map(Object::from_char).collect() + } + _ => return None, + }; + let layout = cls.own_slot_layout()?; + // (Both checks remembered for the class version last found to pass.) + let ver = cls.attr_version.get(); + if ver == 0 || ver != PURE_NEW_VER.load(std::sync::atomic::Ordering::Relaxed) { + match cls.lookup("__init__") { + Some(Object::Function(f)) if f.code().qualname == "deque.__init__" => {} + _ => return None, + } + if layout.len() != SLOTS.len() + || !layout + .iter() + .zip(SLOTS) + .all(|(k, n)| matches!(&k.0, Object::Str(s) if s.as_ref() == n)) + { + return None; + } + PURE_NEW_VER.store(ver, std::sync::atomic::Ordering::Relaxed); + } + let data = Object::new_list(items); + crate::gc_trace::track_built(&data); + let values = [data, Object::Int(0), maxlen.clone(), Object::Int(0)]; + let inst = crate::types::PyInstance::with_slots( + cls.clone(), + crate::types::SlotStorage::from_layout_array(layout.clone(), values), + ); + let obj = Object::Instance(Rc::new(inst)); + crate::gc_trace::track(&obj); + Some(obj) +} + +/// `defaultdict()`, `defaultdict(factory)` or `defaultdict(factory, +/// mapping)` of the exact class, with the factory `None`, a class, a +/// builtin or a function (callable, as `defdict_init` requires): the +/// instance over an empty dict (or a copy of the mapping's), its +/// `default_factory` set, as `__new__` and `__init__` leave it. `None` +/// for any other call. +fn dd_pure_new(cls: &Rc, args: &[Object]) -> Option { + let (factory, source) = match args { + [] => (Object::None, None), + [f @ (Object::None | Object::Type(_) | Object::Builtin(_) | Object::Function(_))] => { + (f.clone(), None) + } + // `defaultdict(factory, mapping)` (`d.copy()`'s own call) of an + // exact dict or a dict subclass's instance that reads as its + // payload does: the table copied whole, hashes and all. + [f @ (Object::None | Object::Type(_) | Object::Builtin(_) | Object::Function(_)), src] => { + let d = match src { + Object::Dict(d) => d, + other => crate::Interpreter::plain_dict_payload(other)?, + }; + (f.clone(), Some(d)) + } + _ => return None, + }; + let payload = Object::new_dict(); + if let (Some(src), Object::Dict(new)) = (source, &payload) { + // SAFETY: a read that runs no code; the view ends with the copy. + let table = crate::object::DictMap::clone(unsafe { src.peek() }?); + **new.try_borrow_mut().ok()? = table; + } + let inst = Rc::new(crate::types::PyInstance::with_native(cls.clone(), payload)); + inst.slot_set("default_factory", factory); + let obj = Object::Instance(inst); + crate::gc_trace::track(&obj); + Some(obj) +} + /// `defaultdict.__init__(self, default_factory=None, /, *args, **kwds)`, /// as CPython's `defdict_init`: the factory (callable or `None`) is set /// first, then the rest initializes the dict. @@ -1426,6 +2215,63 @@ fn dd_missing(args: &[Object]) -> Result { crate::builtins::dict_setdefault(&[recv.clone(), key.clone(), value]) } +/// The native `defaultdict.__missing__` the module installs, by address +/// (the class's entry is it while the class keeps it). +static DD_MISSING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// `d[key]` of a `defaultdict` (`inst`, over its payload `d`) missing +/// `key`, where the class keeps the native `__missing__` and the factory +/// is one whose value builds natively (`list`, `int`, `dict`, ...): the +/// new value, stored under the key as `__missing__` stores it. `None`, +/// touching nothing, for anything else (a key only Python code compares, +/// any other factory). +pub(crate) fn dd_missing_pure( + inst: &crate::types::PyInstance, + d: &Rc>, + key: &Object, +) -> Option { + let ours = DD_MISSING.load(std::sync::atomic::Ordering::Relaxed); + // (The class's `__missing__` is the native one, remembered per class + // version.) + let cls = inst.cls_raw(); + if ours == 0 + || !cls.memo_verdict(crate::types::Verdict::DefaultDictMissing, "", || { + matches!( + cls.lookup("__missing__"), + Some(Object::Builtin(b)) if Rc::as_ptr(&b) as usize == ours + ) + }) + { + return None; + } + if crate::capi_watchers::dicts_active() { + return None; + } + let factory = inst + .slots + .try_borrow() + .ok()? + .get("default_factory") + .cloned()?; + let value = builtin_factory_value(&factory)?; + let probe = crate::object::LeafProbe::new(key)?; + { + let mut m = d.try_borrow_mut().ok()?; + match m.probe_entry(&probe) { + crate::dictmap::ProbeEntry::Vacant(e) if probe.miss_is_exact() => { + e.insert(DictKey(key.clone()), value.clone()); + } + _ => return None, + } + } + if matches!(value, Object::List(_) | Object::Dict(_) | Object::Set(_)) { + crate::gc_trace::track(&value); + } + crate::object::dict_watch_bump(d); + crate::object::dict_mutation_event(d); + Some(value) +} + // --------------------------------------------------------------------- // `_count_elements`. @@ -1459,6 +2305,46 @@ fn tally_dict(mapping: &Object) -> Option>> { } } +/// Count the leading run of `items` whose keys probe natively and whose +/// counts are machine ints into `d`, under one view of it (nothing runs +/// code, so one change notice covers the run): how many were counted. +/// The first item it can't take, and the rest, are the caller's. +fn tally_run(d: &Rc>, items: &[Object]) -> usize { + if crate::capi_watchers::dicts_active() { + return 0; + } + // SAFETY: native probes and int counts run no code; the view ends + // before the notices below. + let Some(m) = (unsafe { d.peek_mut() }) else { + return 0; + }; + let (mut done, mut added) = (0, false); + for key in items { + let Some(probe) = crate::object::LeafProbe::new(key) else { + break; + }; + match m.probe_entry(&probe) { + crate::dictmap::ProbeEntry::Occupied(e) => match e.into_mut() { + Object::Int(n) if *n < i64::MAX => *n += 1, + _ => break, + }, + crate::dictmap::ProbeEntry::Vacant(e) if probe.miss_is_exact() => { + e.insert(DictKey(key.clone()), Object::Int(1)); + added = true; + } + crate::dictmap::ProbeEntry::Vacant(_) => break, + } + done += 1; + } + if done > 0 { + if added { + crate::object::dict_watch_bump(d); + } + crate::object::dict_mutation_event(d); + } + done +} + /// Count one element into `d` (`d[key] = d.get(key, 0) + 1`). fn tally_one( interp: &mut crate::Interpreter, @@ -1524,8 +2410,10 @@ fn count_elements(args: &[Object]) -> Result { } } Object::List(items) => { + // (The leading plain keys under one view: see `tally_run`.) + // SAFETY: a view that runs no code, ending with the statement. + let mut i = unsafe { items.peek() }.map_or(0, |xs| tally_run(&d, xs)); // Snapshot-free: the list may change under a key's `__eq__`. - let mut i = 0; loop { let item = items.borrow().get(i).cloned(); let Some(item) = item else { break }; @@ -1534,7 +2422,8 @@ fn count_elements(args: &[Object]) -> Result { } } Object::Tuple(items) => { - for item in items.iter() { + let done = tally_run(&d, items); + for item in items.iter().skip(done) { tally_one(interp, &d, item)?; } } @@ -1549,6 +2438,406 @@ fn count_elements(args: &[Object]) -> Result { Ok(Object::Bool(true)) } +/// `_deepcopy_plain(x)`: `copy.deepcopy(x)` (no memo given) for a tree of +/// exact dicts, lists and tuples over `None`, bools, ints, floats, strings +/// and bytes, which `copy`'s own table copies the same way: what the +/// original shares, the copy shares (by identity, cycles included), and a +/// tuple whose items all copy to themselves is itself. `None` for anything +/// else, a tree deeper than the native walk goes, or any call a trace or +/// profile hook watches, which the Python function then copies. +fn deepcopy_plain(args: &[Object]) -> Result { + let [x] = args else { + return Err(type_error("_deepcopy_plain() takes one argument")); + }; + // (A trace or profile hook sees `copy`'s Python frames, as CPython's.) + if crate::trace::any_observers_active() { + return Ok(Object::None); + } + let mut memo = crate::fasthash::FxHashMap::default(); + Ok(deep_plain(x, &mut memo, 0).unwrap_or(Object::None)) +} + +/// `_asdict_plain(obj, field_marker)`: `dataclasses.asdict(obj)` with the +/// default `dict` factory, for a tree of plain dataclass instances, exact +/// lists, tuples and dicts, and `None`, bools, numbers, strings and bytes: +/// the copy `_asdict_inner` makes, read with no code run. `field_marker` +/// is `dataclasses._FIELD` (the kind of field `fields()` keeps). `None` +/// for anything else (another value, a field read through a descriptor, +/// a tree too deep), which the Python path copies, or while a trace or +/// profile hook watches. +fn asdict_plain(args: &[Object]) -> Result { + let [obj @ Object::Instance(_), Object::Instance(marker)] = args else { + return Ok(Object::None); + }; + if crate::trace::any_observers_active() || crate::object::exotic_str_keys_possible() { + return Ok(Object::None); + } + Ok(asdict_value(obj, marker, 0).unwrap_or(Object::None)) +} + +/// [`asdict_plain`]'s copy of `x`, `depth` levels down. +fn asdict_value(x: &Object, marker: &Rc, depth: u32) -> Option { + if depth >= DEEPCOPY_DEPTH { + return None; + } + match x { + Object::None + | Object::Bool(_) + | Object::Int(_) + | Object::Long(_) + | Object::Float(_) + | Object::Complex(_) + | Object::Str(_) + | Object::Bytes(_) => Some(x.clone()), + Object::List(l) => { + let items = l.try_borrow().ok()?.clone(); + let out = items + .iter() + .map(|v| asdict_value(v, marker, depth + 1)) + .collect::>>()?; + let y = Object::new_list(out); + crate::gc_trace::track(&y); + Some(y) + } + Object::Tuple(t) => { + let out = t + .iter() + .map(|v| asdict_value(v, marker, depth + 1)) + .collect::>>()?; + Some(Object::new_tuple(out)) + } + Object::Dict(d) => { + let entries: Vec<(Object, Object)> = d + .try_borrow() + .ok()? + .iter() + .map(|(k, v)| (k.0.clone(), v.clone())) + .collect(); + let mut out = + DictData::with_capacity_and_hasher(entries.len(), crate::fasthash::FxBuildHasher); + for (k, v) in &entries { + let (k, v) = ( + asdict_value(k, marker, depth + 1)?, + asdict_value(v, marker, depth + 1)?, + ); + // (Keys of these kinds hash natively.) + out.insert(DictKey(k), v); + } + let y = Object::Dict(Rc::new(RefCell::new(out))); + crate::gc_trace::track(&y); + Some(y) + } + Object::Instance(inst) => asdict_instance(inst, marker, depth), + _ => None, + } +} + +/// [`asdict_value`] of a plain dataclass instance: its fields (the +/// `__dataclass_fields__` entries whose `_field_type` is `marker`), in +/// order, each read from its dict under the default attribute access with +/// no descriptor of the name on the class. +fn asdict_instance( + inst: &Rc, + marker: &Rc, + depth: u32, +) -> Option { + let cls = inst.cls_raw(); + if inst.native.get().is_some() + || cls.native_kind.get() != 0 + || cls.c_ext_ptr.get() != 0 + || !cls + .dunder(crate::types::Dunder::GetAttribute) + .object_owner() + { + return None; + } + let Some(Object::Dict(fields)) = cls.lookup("__dataclass_fields__") else { + return None; + }; + let fields: Vec = fields.try_borrow().ok()?.values().cloned().collect(); + let mut out = DictData::with_capacity_and_hasher(fields.len(), crate::fasthash::FxBuildHasher); + for f in &fields { + let Object::Instance(fi) = f else { + return None; + }; + let (name, kind) = { + let slots = fi.slots.try_borrow().ok()?; + ( + slots.get("name")?.clone(), + slots.get("_field_type")?.clone(), + ) + }; + // (A class variable or init-only pseudo-field: not a field.) + match &kind { + Object::Instance(k) if Rc::ptr_eq(k, marker) => {} + Object::Instance(_) => continue, + _ => return None, + } + let Object::Str(name) = name else { + return None; + }; + // (A class attribute of the name may only be a plain default.) + match cls.lookup(&name) { + None + | Some( + Object::None + | Object::Bool(_) + | Object::Int(_) + | Object::Float(_) + | Object::Str(_) + | Object::Bytes(_), + ) => {} + Some(_) => return None, + } + let v = match inst.dict.published() { + Some(d) => d + .try_borrow() + .ok()? + .get(&crate::object::StrKey(&name)) + .cloned(), + None => inst + .dict + .split_cell() + .try_borrow() + .ok()? + .get_str(&name) + .cloned(), + }?; + let v = asdict_value(&v, marker, depth + 1)?; + out.insert(DictKey(Object::Str(name)), v); + } + let y = Object::Dict(Rc::new(RefCell::new(out))); + crate::gc_trace::track(&y); + Some(y) +} + +/// `_most_common_plain(counter, n)`: `Counter.most_common(n)` of an exact +/// `Counter` (the caller checks) whose counts are all plain ints: the `n` +/// largest `(key, count)` pairs, ties in insertion order, as +/// `heapq.nlargest(n, self.items(), key=itemgetter(1))` gives them. `None` +/// for anything else, or while a trace or profile hook watches. +fn most_common_plain(args: &[Object]) -> Result { + let [Object::Instance(inst), Object::Int(n)] = args else { + return Ok(Object::None); + }; + if crate::trace::any_observers_active() { + return Ok(Object::None); + } + let Some(Object::Dict(d)) = inst.native.get() else { + return Ok(Object::None); + }; + let Ok(d) = d.try_borrow() else { + return Ok(Object::None); + }; + let mut items = Vec::with_capacity(d.len()); + for (k, v) in d.iter() { + let count = match *v { + Object::Int(i) => i, + Object::Bool(b) => i64::from(b), + _ => return Ok(Object::None), + }; + items.push((count, k, v)); + } + // (A stable sort: equal counts keep insertion order, as `nlargest`'s + // decreasing tie-break index keeps it.) + items.sort_by_key(|item| std::cmp::Reverse(item.0)); + let take = usize::try_from(*n).unwrap_or(0).min(items.len()); + let out: Vec = items[..take] + .iter() + .map(|(_, k, v)| Object::new_tuple_array([k.0.clone(), (*v).clone()])) + .collect(); + drop(d); + let list = Object::new_list(out); + crate::gc_trace::track(&list); + Ok(list) +} + +/// The original `Logger.isEnabledFor` the native log methods require of a +/// logger's class (see [`log_methods`]). +static LOG_IS_ENABLED_FOR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// `_log_methods(Logger)`: native `debug`, `info`, `warning`, `error` and +/// `critical` for `logging.Logger`, as `(name, method)` pairs for the +/// module to assign. A call on a logger that is disabled for the level, as +/// its class's own `isEnabledFor` would find it (`disabled`, or `False` +/// cached for the level), with no keywords and no trace or profile hook +/// set, returns `None` at once; anything else calls the Python method. +fn log_methods(args: &[Object]) -> Result { + let [Object::Type(cls)] = args else { + return Err(type_error("_log_methods() expects the Logger class")); + }; + let dict = cls.dict.borrow(); + let Some(Object::Function(enabled)) = dict.get(&crate::object::StrKey("isEnabledFor")) else { + return Err(type_error("_log_methods(): no isEnabledFor")); + }; + LOG_IS_ENABLED_FOR.store( + Rc::as_ptr(enabled) as usize, + std::sync::atomic::Ordering::Relaxed, + ); + let table: [(&'static str, crate::stdlib::struct_mod::Fast); 5] = [ + ("debug", |a| log_disabled(a, 10)), + ("info", |a| log_disabled(a, 20)), + ("warning", |a| log_disabled(a, 30)), + ("error", |a| log_disabled(a, 40)), + ("critical", |a| log_disabled(a, 50)), + ]; + let mut out = Vec::with_capacity(table.len()); + for (name, fast) in table { + let orig = dict + .get(&crate::object::StrKey(name)) + .cloned() + .ok_or_else(|| type_error(format!("_log_methods(): no {name} to replace")))?; + out.push(Object::new_tuple(vec![ + Object::from_static(name), + crate::stdlib::struct_mod::fast_method(cls, name, fast, orig, true), + ])); + } + Ok(Object::new_list(out)) +} + +/// A log method's leaf half: `None` for a call at `level` on a logger the +/// level is disabled for (see [`log_methods`]); `None`, the call left to +/// the Python method, for anything else. +fn log_disabled(args: &[Object], level: i64) -> Option> { + let [Object::Instance(inst), _msg, ..] = args else { + return None; + }; + if crate::trace::any_observers_active() { + return None; + } + let enabled = crate::Interpreter::instance_dunder_function( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::LOG_ENABLED_FOR), + "isEnabledFor", + )?; + if Rc::as_ptr(&enabled) as usize + != LOG_IS_ENABLED_FOR.load(std::sync::atomic::Ordering::Relaxed) + { + return None; + } + // (The two names' hashes, once per process.) + static HASHES: std::sync::OnceLock<(i64, i64)> = std::sync::OnceLock::new(); + let &(disabled, cache) = HASHES.get_or_init(|| { + ( + crate::object::py_str_hash("disabled"), + crate::object::py_str_hash("_cache"), + ) + }); + match inst.attr_get_hashed("disabled", disabled)? { + Object::Bool(true) => return Some(Ok(Object::None)), + Object::Bool(false) => {} + _ => return None, + } + let Object::Dict(cache) = inst.attr_get_hashed("_cache", cache)? else { + return None; + }; + let cached = cache + .try_borrow() + .ok()? + .get(&crate::object::LeafProbe::new(&Object::Int(level))?) + .cloned(); + matches!(cached, Some(Object::Bool(false))).then_some(Ok(Object::None)) +} + +/// How deep [`deep_plain`] nests before leaving the copy to Python. +const DEEPCOPY_DEPTH: u32 = 200; + +fn deep_plain( + x: &Object, + memo: &mut crate::fasthash::FxHashMap, + depth: u32, +) -> Option { + let id = |o: &Object| o.strong_word().map(|w| w as usize); + match x { + Object::None + | Object::Bool(_) + | Object::Int(_) + | Object::Long(_) + | Object::Float(_) + | Object::Str(_) + | Object::Bytes(_) => Some(x.clone()), + Object::List(l) => { + let key = id(x)?; + if let Some(y) = memo.get(&key) { + return Some(y.clone()); + } + if depth >= DEEPCOPY_DEPTH { + return None; + } + // (A snapshot: copying the items runs no code.) + let items = l.try_borrow().ok()?.clone(); + let y = Object::new_list(Vec::with_capacity(items.len())); + crate::gc_trace::track(&y); + memo.insert(key, y.clone()); + let Object::List(out) = &y else { + unreachable!("made a list") + }; + for item in &items { + let c = deep_plain(item, memo, depth + 1)?; + out.try_borrow_mut().ok()?.push(c); + } + Some(y) + } + Object::Dict(d) => { + let key = id(x)?; + if let Some(y) = memo.get(&key) { + return Some(y.clone()); + } + if depth >= DEEPCOPY_DEPTH { + return None; + } + let entries: Vec<(Object, Object)> = d + .try_borrow() + .ok()? + .iter() + .map(|(k, v)| (k.0.clone(), v.clone())) + .collect(); + let out = Rc::new(RefCell::new(DictData::with_capacity_and_hasher( + entries.len(), + crate::fasthash::FxBuildHasher, + ))); + let y = Object::Dict(out.clone()); + crate::gc_trace::track(&y); + memo.insert(key, y.clone()); + for (k, v) in &entries { + let (k, v) = ( + deep_plain(k, memo, depth + 1)?, + deep_plain(v, memo, depth + 1)?, + ); + // (Keys of these kinds hash natively.) + out.try_borrow_mut().ok()?.insert(DictKey(k), v); + } + Some(y) + } + Object::Tuple(t) => { + let key = id(x)?; + if let Some(y) = memo.get(&key) { + return Some(y.clone()); + } + if depth >= DEEPCOPY_DEPTH { + return None; + } + let mut ys = Vec::with_capacity(t.len()); + for item in t.iter() { + ys.push(deep_plain(item, memo, depth + 1)?); + } + // (A tuple reached again through its own items is the copy + // made there, as `_deepcopy_tuple` finds it.) + if let Some(y) = memo.get(&key) { + return Some(y.clone()); + } + let y = if ys.iter().zip(t.iter()).all(|(a, b)| a.is_same(b)) { + x.clone() + } else { + Object::new_tuple(ys) + }; + memo.insert(key, y.clone()); + Some(y) + } + _ => None, + } +} + pub fn build(_cache: &ModuleCache) -> Rc { let dict = Rc::new(RefCell::new(DictData::default())); { @@ -1557,6 +2846,29 @@ pub fn build(_cache: &ModuleCache) -> Rc { DictKey(Object::from_static("__name__")), Object::from_static("_weave_collections"), ); + for (name, f) in [ + ( + "_deepcopy_plain", + deepcopy_plain as fn(&[Object]) -> Result, + ), + ("_most_common_plain", most_common_plain), + ("_asdict_plain", asdict_plain), + ("_log_methods", log_methods), + ] { + let b = Rc::new(BuiltinFn { + name, + binds_instance: false, + call: Box::new(f), + call_kw: None, + }); + // The copy and the count ranking read plain values and decline + // anything else: their bodies run no code, so compiled callers + // call them in place (`copy.deepcopy`, `most_common(n)`). + if name != "_log_methods" { + crate::leaf_builtins::register(&b); + } + d.insert(DictKey(Object::from_static(name)), Object::Builtin(b)); + } let mut reg = |export: &'static str, name: &'static str, f: fn(&[Object]) -> Result| { @@ -1578,6 +2890,15 @@ pub fn build(_cache: &ModuleCache) -> Rc { reg("__bool__", "__bool__", deque_bool); reg("__getitem__", "__getitem__", deque_getitem); reg("rotate", "rotate", deque_rotate); + reg("_extend_items", "_extend_items", deque_extend_items); + reg("_extend_method", "_extend_method", deque_extend_method); + reg( + "_contains_method", + "_contains_method", + deque_contains_method, + ); + reg("_plain_find", "_plain_find", deque_plain_find); + reg("_plain_count", "_plain_count", deque_plain_count); reg("__iter__", "__iter__", deque_iter); reg("__reversed__", "__reversed__", deque_reversed); reg("iterator_index", "iterator_index", deque_iterator_index); @@ -1599,6 +2920,7 @@ pub fn build(_cache: &ModuleCache) -> Rc { install_defaultdict, ); reg("dd_missing", "__missing__", dd_missing); + reg("install_deque", "install_deque", install_deque); reg("count_elements", "count_elements", count_elements); reg( "namedtuple_register", @@ -1633,6 +2955,31 @@ pub fn build(_cache: &ModuleCache) -> Rc { call_kw: Some(Box::new(dd_init)), })), ); + if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static("dd_missing"))) { + DD_MISSING.store(Rc::as_ptr(b) as usize, std::sync::atomic::Ordering::Relaxed); + } + if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static("chainmap_contains"))) + { + CHAINMAP_CONTAINS.store(Rc::as_ptr(b) as usize, std::sync::atomic::Ordering::Relaxed); + } + // The deque iterators' steps, as leaves (`list(dq)`, `for x in dq`). + for (key, fast) in [ + ( + "iterator_next", + deque_iterator_next_leaf as crate::leaf_builtins::Fast, + ), + ("reverse_iterator_next", deque_reverse_iterator_next_leaf), + ] { + if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static(key))) { + crate::leaf_builtins::register_fast(b, fast); + let slot = if key == "iterator_next" { + &ITER_NEXT + } else { + &RITER_NEXT + }; + slot.store(Rc::as_ptr(b) as usize, std::sync::atomic::Ordering::Relaxed); + } + } // The `OrderedDict` methods (see `collections_odict`). for (export, name, body, kw) in super::collections_odict::exports() { d.insert( @@ -1656,6 +3003,19 @@ pub fn build(_cache: &ModuleCache) -> Rc { })), ); } + for (i, name) in [ + "od_iter", + "odv_keys_iter", + "odv_values_iter", + "odv_items_iter", + ] + .into_iter() + .enumerate() + { + if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static(name))) { + super::collections_odict::note_iter_builtin(i, b); + } + } for name in super::collections_odict::LEAVES { if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static(name))) { crate::leaf_builtins::register(b); @@ -1672,8 +3032,8 @@ pub fn build(_cache: &ModuleCache) -> Rc { } } } - // The end operations, length, truth, iterator construction, and - // iterator steps run no Python code. Indexing and rotation require + // The end operations, length, truth and iterator construction run + // no Python code (the iterator steps have leaf halves, above). Indexing and rotation require // an argument guard because index coercion can invoke Python's // __index__ protocol. for name in [ @@ -1685,8 +3045,6 @@ pub fn build(_cache: &ModuleCache) -> Rc { "__bool__", "__iter__", "__reversed__", - "iterator_next", - "reverse_iterator_next", "tuplegetter_get", ] { if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static(name))) { @@ -1722,9 +3080,15 @@ pub fn build(_cache: &ModuleCache) -> Rc { ] { if let Some(Object::Builtin(b)) = d.get(&DictKey(Object::from_static(name))) { crate::leaf_builtins::register_jit_method(b, op); + if op == OP_LEN { + DEQUE_LEN.with(|c| c.set(Rc::as_ptr(b) as usize)); + } } } } + if let Some(Object::Builtin(b)) = dict.borrow().get(&DictKey(Object::from_static("__iter__"))) { + DEQUE_ITER.with(|c| c.set(Rc::as_ptr(b) as usize)); + } Rc::new(PyModule { name: "_weave_collections".to_owned(), filename: None, diff --git a/crates/weavepy-vm/src/stdlib/collections_odict.rs b/crates/weavepy-vm/src/stdlib/collections_odict.rs index 984de7772..18132a724 100644 --- a/crates/weavepy-vm/src/stdlib/collections_odict.rs +++ b/crates/weavepy-vm/src/stdlib/collections_odict.rs @@ -33,6 +33,10 @@ pub(crate) const ORDER: &str = ""; /// class itself (subclasses are recognized through their MRO). pub(crate) const KIND_ODICT: u8 = 2; +/// [`crate::types::TypeObject::collections_kind`] of the `OrderedDict` +/// view classes (`odict_keys`, `odict_values`, `odict_items`) themselves. +pub(crate) const KIND_ODICT_VIEW: u8 = 3; + /// Whether `cls` is `OrderedDict` or a subclass of it. fn is_odict_class(cls: &TypeObject) -> bool { cls.collections_kind.get() == KIND_ODICT @@ -187,12 +191,27 @@ pub(crate) fn order_iter( order: Rc>, kind: DictViewKind, reverse: bool, +) -> Object { + let it = order_iter_untracked(od, main, order, kind, reverse); + crate::gc_trace::track(&it); + it +} + +/// [`order_iter`]'s iterator, unknown to the collector: for one that +/// nothing but a `for` loop's stack will hold (a plain dict's iterator is +/// never tracked either). +fn order_iter_untracked( + od: &Object, + main: Rc>, + order: Rc>, + kind: DictViewKind, + reverse: bool, ) -> Object { let len = order.borrow().len(); // The order's state is captured now, as CPython's iterator snapshots // `od_state` at creation. let watch = Some(crate::object::DictWatch::new(&order)); - let it = Object::Iter(Rc::new(RefCell::new(PyIterator::DictKeys { + Object::Iter(Rc::new(RefCell::new(PyIterator::DictKeys { kind, index: if reverse { len } else { 0 }, dict: Some(order), @@ -201,13 +220,16 @@ pub(crate) fn order_iter( reverse, owner: Some(od.clone()), odict: Some(main), - }))); - crate::gc_trace::track(&it); - it + }))) } /// `OrderedDict.__setitem__(self, key, value)`. fn od_setitem(args: &[Object]) -> Result { + // (A store compiled code reaches through the class's `__setitem__`, + // tier 2's say, settles as the leaf half does when it can.) + if let Some(done) = od_setitem_leaf(args) { + return done; + } let (inst, main) = receiver(args, "__setitem__")?; let [_, key, value] = args else { return Err(type_error(format!( @@ -245,8 +267,13 @@ fn od_setitem_leaf(args: &[Object]) -> Option> { let Some(Object::Dict(main)) = inst.native.get() else { return None; }; - let order = peek_order(inst)?; let probe = crate::object::LeafProbe::new(key)?; + // (A fresh dict's order starts here, as the full store starts it.) + let order = match peek_order(inst) { + Some(o) => o, + None if inst.slots.try_borrow_mut().is_ok() => order_of(inst), + None => return None, + }; let mut m = main.try_borrow_mut().ok()?; let mut o = order.try_borrow_mut().ok()?; // One probe of each finds the entry or the slot a new key takes. @@ -308,6 +335,185 @@ fn od_delitem(args: &[Object]) -> Result { } } +/// The native `__iter__`s of `OrderedDict` and of its keys, values and +/// items views (see [`note_iter_builtin`]), by address: a class's entry is +/// one while the class keeps it. +static ITER_BUILTINS: [std::sync::atomic::AtomicUsize; 4] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 4]; + +/// Remember a native `__iter__` the module installs (0 the dict's, then +/// the keys, values and items views'). +pub(crate) fn note_iter_builtin(i: usize, b: &Rc) { + ITER_BUILTINS[i].store(Rc::as_ptr(b) as usize, std::sync::atomic::Ordering::Relaxed); +} + +/// Whether `cls`'s `__iter__` is the native one [`note_iter_builtin`] +/// recorded at `i`, with no `__length_hint__` to call (a `len` presize of +/// these is the dict's own, native). +fn native_iter(cls: &TypeObject, i: usize) -> bool { + let ours = ITER_BUILTINS[i].load(std::sync::atomic::Ordering::Relaxed); + matches!(cls.lookup("__iter__"), Some(Object::Builtin(b)) + if Rc::as_ptr(&b) as usize == ours && ours != 0) + && cls.lookup("__length_hint__").is_none() +} + +/// The version tokens of the classes last found to keep each native +/// `__iter__` of [`ITER_BUILTINS`] (and, for the dict's, to be an +/// `OrderedDict` class). +static ITER_LANE_VER: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Which of [`ITER_BUILTINS`] `cls`'s `__iter__` is (0 the dict's, for an +/// `OrderedDict` class only; then the keys, values and items views'), +/// remembered for the class version last asked about. +fn native_iter_index(cls: &TypeObject) -> Option { + use std::sync::atomic::Ordering::Relaxed; + let ver = cls.attr_version.get(); + if ver != 0 { + if let Some(i) = (0..4).find(|&i| ITER_LANE_VER[i].load(Relaxed) == ver) { + return Some(i); + } + } + let Some(Object::Builtin(b)) = cls.lookup("__iter__") else { + return None; + }; + let ours = Rc::as_ptr(&b) as usize; + let i = (0..4).find(|&i| ITER_BUILTINS[i].load(Relaxed) == ours && ours != 0)?; + if i == 0 && !is_odict_class(cls) { + return None; + } + if ver != 0 { + ITER_LANE_VER[i].store(ver, Relaxed); + } + Some(i) +} + +/// `iter(v)` for a `for` loop's `GET_ITER` in compiled code, where `v` is +/// an `OrderedDict` (or a subclass's instance) or one of its keys, values +/// or items views and its class keeps the native `__iter__`: the order +/// iterator that method builds, which runs no code. `None` for anything +/// else. +pub(crate) fn iter_lane(v: &Object) -> Option { + let Object::Instance(inst) = v else { + return None; + }; + let i = native_iter_index(inst.cls_raw())?; + // (The dict itself, or the view's `_mapping`.) + let od = if i == 0 { + v.clone() + } else { + inst.slots.try_borrow().ok()?.get("_mapping").cloned()? + }; + let Object::Instance(oi) = &od else { + return None; + }; + let Some(Object::Dict(main)) = oi.native.get() else { + return None; + }; + if i != 0 && !is_odict_class(oi.cls_raw()) { + return None; + } + // (An order made on first use needs the slots free.) + let order = match peek_order(oi) { + Some(order) => order, + None => { + if oi.slots.try_borrow_mut().is_err() { + return None; + } + order_of(oi) + } + }; + let kind = match i { + 0 | 1 => DictViewKind::Keys, + 2 => DictViewKind::Values, + _ => DictViewKind::Items, + }; + Some(order_iter_untracked(&od, main.clone(), order, kind, false)) +} + +/// `list(view)` of a keys, values or items view of an exact `OrderedDict` +/// whose classes keep their native `__iter__`s: the entries in order, as +/// the view's iterator gives them, where every key looks up in the dict +/// natively. `None` for anything else. +pub(crate) fn exact_view_entries(view: &PyInstance) -> Option> { + if view.cls_raw().collections_kind.get() != KIND_ODICT_VIEW { + return None; + } + let mapping = view.slots.try_borrow().ok()?.get("_mapping").cloned(); + let od = match mapping? { + Object::Instance(od) => od, + _ => return None, + }; + let ocls = od.cls_raw(); + if ocls.collections_kind.get() != KIND_ODICT { + return None; + } + let views = ocls.native_ext.get()?.downcast_ref::()?; + let vcls = view.cls_raw(); + let kind = views + .0 + .iter() + .position(|w| std::ptr::eq(w.as_ptr(), std::ptr::from_ref(vcls)))?; + if !native_iter(vcls, kind + 1) { + return None; + } + let keys = exact_keys(&od)?; + if kind == 0 { + return Some(keys); + } + let Some(Object::Dict(main)) = od.native.get() else { + return None; + }; + let m = main.try_borrow().ok()?; + keys.into_iter() + .map(|k| { + let probe = crate::object::LeafProbe::new(&k)?; + let v = m.get(&probe)?.clone(); + Some(if kind == 1 { + v + } else { + Object::new_tuple_array([k, v]) + }) + }) + .collect() +} + +/// The version token of the `OrderedDict` class last found by +/// [`exact_keys`] to keep the native `__iter__` and `__len__`. +static KEYS_LANE_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The version token of the `OrderedDict` class last found by +/// [`od_pure_new`] to keep the module's `__init__`. +static PURE_INIT_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// `list(od)` of an exact `OrderedDict` whose class keeps the native +/// `__iter__` (and the dict's `__len__`, no `__length_hint__`): its keys +/// in order, as its iterator gives them (cloning them runs no code). +/// `None` for anything else. +pub(crate) fn exact_keys(inst: &PyInstance) -> Option> { + let cls = inst.cls_raw(); + if cls.collections_kind.get() != KIND_ODICT || inst.native.get().is_none() { + return None; + } + let ver = cls.attr_version.get(); + let kept = (ver != 0 && ver == KEYS_LANE_VER.load(std::sync::atomic::Ordering::Relaxed)) + || (native_iter(cls, 0) && matches!(cls.lookup("__len__"), Some(Object::Builtin(_))) && { + KEYS_LANE_VER.store(ver, std::sync::atomic::Ordering::Relaxed); + true + }); + if !kept || inst.slots.try_borrow_mut().is_err() { + return None; + } + let order = order_of(inst); + let keys = order + .try_borrow() + .ok()? + .keys() + .map(|k| k.0.clone()) + .collect(); + Some(keys) +} + /// `OrderedDict.__iter__(self)`. fn od_iter(args: &[Object]) -> Result { let (inst, main) = receiver(args, "__iter__")?; @@ -390,7 +596,7 @@ fn pop_node( ) -> Result<(Object, Object), RuntimeError> { let (key, _) = order .borrow_mut() - .shift_remove_index(index) + .lazy_remove_index(index) .ok_or_else(|| runtime_error("OrderedDict mutated during iteration"))?; crate::object::dict_watch_bump(order); let key = key.0; @@ -480,6 +686,36 @@ fn od_keys_equal(args: &[Object]) -> Result { let (a, _) = receiver(args, "__eq__")?; let (b, _) = receiver(args.get(1..).unwrap_or_default(), "__eq__")?; let (oa, ob) = (order_of(&a), order_of(&b)); + // Both orders' keys as ints, strings or the same objects, compared in + // one pass through views (no comparison runs code); any other key + // takes the walk below. + // SAFETY: views that run no code, ending with the block. + if let (Some(da), Some(db)) = (unsafe { oa.peek() }, unsafe { ob.peek() }) { + let mut verdict = Some(da.len() == db.len()); + for i in 0..da.len().min(db.len()) { + let (Some((ka, _)), Some((kb, _))) = (da.get_index(i), db.get_index(i)) else { + verdict = None; + break; + }; + let same = match (&ka.0, &kb.0) { + (Object::Str(x), Object::Str(y)) => x == y, + (Object::Int(x), Object::Int(y)) => x == y, + (Object::Str(_), Object::Int(_)) | (Object::Int(_), Object::Str(_)) => false, + (x, y) if x.is_same(y) => true, + _ => { + verdict = None; + break; + } + }; + if !same { + verdict = Some(false); + break; + } + } + if let Some(eq) = verdict { + return Ok(Object::Bool(eq)); + } + } let wa = crate::object::DictWatch::new(&oa); let wb = crate::object::DictWatch::new(&ob); let (na, nb) = (oa.borrow().len(), ob.borrow().len()); @@ -517,6 +753,7 @@ fn od_update_fast(args: &[Object]) -> Result { }; receiver(args, "update")?; let pairs: Vec<(Object, Object)> = match other { + Object::Dict(d) if od_dict_into(od, d) => return Ok(Object::Bool(true)), Object::Dict(d) => d .borrow() .iter() @@ -526,6 +763,9 @@ fn od_update_fast(args: &[Object]) -> Result { let Some(Object::Dict(main)) = inst.native.get() else { return Ok(Object::Bool(false)); }; + if od_clone_into(od, inst, main) { + return Ok(Object::Bool(true)); + } let order = order_of(inst); let keys: Vec = order.borrow().keys().map(|k| k.0.clone()).collect(); let mut pairs = Vec::with_capacity(keys.len()); @@ -569,15 +809,133 @@ fn od_update_fast(args: &[Object]) -> Result { Ok(Object::Bool(true)) } +/// `dst.update(src)` for an empty `dst` (`od.copy()`'s fresh one) and an +/// exact `OrderedDict` `src` whose order lists its payload's keys as the +/// payload holds them (nothing was moved to an end): both tables copied +/// whole, hashes and all, with no key hashed or compared. `false`, +/// nothing changed, for anything else. +fn od_clone_into(dst: &Object, src: &PyInstance, src_main: &Rc>) -> bool { + let Object::Instance(dst_inst) = dst else { + return false; + }; + if crate::capi_watchers::dicts_active() { + return false; + } + let Some(Object::Dict(dst_main)) = dst_inst.native.get() else { + return false; + }; + if Rc::ptr_eq(dst_main, src_main) { + return false; + } + let Some(src_order) = peek_order(src) else { + return false; + }; + let dst_order = order_of(dst_inst); + { + let (Ok(sm), Ok(so), Ok(mut dm), Ok(mut dord)) = ( + src_main.try_borrow(), + src_order.try_borrow(), + dst_main.try_borrow_mut(), + dst_order.try_borrow_mut(), + ) else { + return false; + }; + // (Keys that hash and compare natively only: any other key's + // `__hash__` and `__eq__` are the per-key store's to run, a + // changed hash's `KeyError` and all.) + let native_key = |k: &Object| match k { + Object::Str(_) | Object::Int(_) | Object::Bytes(_) => true, + Object::Tuple(t) + if t.iter() + .all(|x| matches!(x, Object::Str(_) | Object::Int(_) | Object::Bytes(_))) => + { + true + } + other => crate::object::LeafProbe::new(other).is_some(), + }; + if sm.is_empty() + || !dm.is_empty() + || !dord.is_empty() + || sm.len() != so.len() + || !sm + .iter() + .zip(so.iter()) + .all(|((a, _), (b, _))| a.0.is_same(&b.0) && native_key(&a.0)) + { + return false; + } + **dm = crate::object::DictMap::clone(&sm); + **dord = crate::object::DictMap::clone(&so); + } + crate::object::dict_watch_bump(dst_main); + crate::object::dict_mutation_event(dst_main); + crate::object::dict_watch_bump(&dst_order); + true +} + +/// [`od_clone_into`] from an exact `dict` (`OrderedDict.fromkeys`'s, +/// `OrderedDict(d)`'s): for an empty `dst` and keys that hash and compare +/// natively, the payload copied whole and the order a copy of it with +/// every value `None`, in the dict's order. `false`, nothing changed, for +/// anything else. +fn od_dict_into(dst: &Object, src: &Rc>) -> bool { + let Object::Instance(dst_inst) = dst else { + return false; + }; + if crate::capi_watchers::dicts_active() { + return false; + } + let Some(Object::Dict(dst_main)) = dst_inst.native.get() else { + return false; + }; + if Rc::ptr_eq(dst_main, src) { + return false; + } + let dst_order = order_of(dst_inst); + { + let (Ok(sm), Ok(mut dm), Ok(mut dord)) = ( + src.try_borrow(), + dst_main.try_borrow_mut(), + dst_order.try_borrow_mut(), + ) else { + return false; + }; + let native_key = |k: &Object| match k { + Object::Str(_) | Object::Int(_) | Object::Bytes(_) => true, + other => crate::object::LeafProbe::new(other).is_some(), + }; + if sm.is_empty() + || !dm.is_empty() + || !dord.is_empty() + || !sm.keys().all(|k| native_key(&k.0)) + { + return false; + } + **dm = crate::object::DictMap::clone(&sm); + let mut order = crate::object::DictMap::clone(&sm); + // (The source still holds every value: these releases free nothing.) + for v in order.values_mut() { + *v = Object::None; + } + **dord = order; + } + crate::object::dict_watch_bump(dst_main); + crate::object::dict_mutation_event(dst_main); + crate::object::dict_watch_bump(&dst_order); + true +} + // --------------------------------------------------------------------- // Leaf halves (see `leaf_builtins::Fast`): the common shapes with a `str` // or `int` key settled by exact native equality, so no Python runs. // Anything else (another key kind, a keyword argument, a key only a // Python `__eq__` could match) declines before changing anything. -/// The payload and order of an `OrderedDict` receiver that has an order. +/// The payload and order of an `OrderedDict` receiver that has an order, +/// borrowed from the receiver (no count changes): a leaf runs no code +/// that could store the instance's slots while it reads them. #[inline] -fn leaf_parts(recv: &Object) -> Option<(Rc>, Rc>)> { +fn leaf_parts(recv: &Object) -> Option<(&Rc>, &Rc>)> { let Object::Instance(inst) = recv else { return None; }; @@ -587,7 +945,13 @@ fn leaf_parts(recv: &Object) -> Option<(Rc>, Rc Some((main, order)), + _ => None, + } } /// `od.move_to_end(key[, last])`. @@ -609,7 +973,7 @@ fn od_move_to_end_leaf(args: &[Object]) -> Option> if i != end { o.move_index(i, end); drop(o); - crate::object::dict_watch_bump(&order); + crate::object::dict_watch_bump(order); } Some(Ok(Object::None)) } @@ -624,9 +988,8 @@ fn leaf_unlink( ) -> Option { let mut m = main.try_borrow_mut().ok()?; let mut o = order.try_borrow_mut().ok()?; - let at = m.get_index_of(probe)?; - let (k, v) = m.shift_remove_index(at)?; - let node = o.shift_remove_index(index); + let (k, v) = m.lazy_remove_entry(probe)?; + let node = o.lazy_remove_index(index); drop((m, o)); crate::object::dict_watch_bump(main); crate::object::dict_mutation_event(main); @@ -652,7 +1015,7 @@ fn od_popitem_leaf(args: &[Object]) -> Option> { (index, o.get_index(index)?.0 .0.clone()) }; let probe = crate::object::LeafProbe::new(&key)?; - let value = leaf_unlink(&main, &order, index, &probe)?; + let value = leaf_unlink(main, order, index, &probe)?; Some(Ok(Object::new_tuple_array([key, value]))) } @@ -676,7 +1039,7 @@ fn od_pop_leaf(args: &[Object]) -> Option> { .ok_or_else(|| key_error_object(key.clone())), ); }; - leaf_unlink(&main, &order, index, &probe).map(Ok) + leaf_unlink(main, order, index, &probe).map(Ok) } /// The view classes `keys()`, `values()` and `items()` hand out (CPython's @@ -693,6 +1056,12 @@ fn install_odict(args: &[Object]) -> Result { )); }; cls.collections_kind.set(KIND_ODICT); + // (`OrderedDict()` of the exact class builds in place: its `__init__` + // does nothing without arguments, the order starting on first use.) + cls.pure_new.set(Some(od_pure_new)); + for view in [k, v, i] { + view.collections_kind.set(KIND_ODICT_VIEW); + } let views = Rc::new(ViewTypes([ Rc::downgrade(k), Rc::downgrade(v), @@ -704,6 +1073,112 @@ fn install_odict(args: &[Object]) -> Result { Ok(Object::None) } +/// The `(key, value)` entries of an exact `OrderedDict` in its order, +/// copied with no code run: each key of the order found in the payload by +/// native equality. `None` for anything else (a subclass, which may +/// override the reads; a key only Python code compares; a guarded cell). +pub(crate) fn ordered_entries(v: &Object) -> Option> { + let Object::Instance(inst) = v else { + return None; + }; + if inst.cls_raw().collections_kind.get() != KIND_ODICT || crate::capi_watchers::dicts_active() { + return None; + } + let Some(Object::Dict(main)) = inst.native.get() else { + return None; + }; + // SAFETY: reads that run no code; the views end with this call. + let m = unsafe { main.peek() }?; + let Some(order) = peek_order(inst) else { + // (No order yet: nothing was ever stored through the class.) + return m.is_empty().then(Vec::new); + }; + // SAFETY: as above (a distinct cell). + let o = unsafe { order.peek() }?; + if o.len() != m.len() { + return None; + } + let mut out = Vec::with_capacity(o.len()); + for (k, _) in o.iter() { + let probe = crate::object::LeafProbe::new(&k.0)?; + out.push((k.0.clone(), m.get(&probe)?.clone())); + } + Some(out) +} + +/// `OrderedDict()` of the exact class, while its `__init__` is still the +/// module's own: the instance over an empty dict, as `__new__` and that +/// `__init__` leave it. `None` for any call with arguments. +fn od_pure_new(cls: &Rc, args: &[Object]) -> Option { + // `OrderedDict(pairs)` of a list or tuple of `(key, value)` tuples, + // `OrderedDict(d)` of an exact dict, or `OrderedDict(od)` of another + // (`od.copy()`), with keys that compare natively: the entries in + // order, stored as `__init__`'s `self[key] = value` stores them (each + // by the store's leaf half, which declines any other key). + let mut pairs: Option> = match args { + [] | [Object::Dict(_)] => None, + [Object::List(l)] => Some(od_pairs(&l.try_borrow().ok()?)?), + [Object::Tuple(t)] => Some(od_pairs(t)?), + [src @ Object::Instance(_)] => Some(ordered_entries(src)?), + _ => return None, + }; + let ver = cls.attr_version.get(); + if ver == 0 || ver != PURE_INIT_VER.load(std::sync::atomic::Ordering::Relaxed) { + match cls.lookup("__init__") { + Some(Object::Function(f)) if f.code().qualname == "OrderedDict.__init__" => {} + _ => return None, + } + PURE_INIT_VER.store(ver, std::sync::atomic::Ordering::Relaxed); + } + let inst = Rc::new(PyInstance::with_native(cls.clone(), Object::new_dict())); + let obj = Object::Instance(inst); + crate::gc_trace::track(&obj); + // (Another `OrderedDict` whose order is its payload's: both tables + // copied whole.) + if let [Object::Instance(src)] = args { + if let Some(Object::Dict(src_main)) = src.native.get() { + if od_clone_into(&obj, src, src_main) { + return Some(obj); + } + } + } + // (An exact dict's tables copied whole, or its entries stored in + // order.) + if let [Object::Dict(d)] = args { + if od_dict_into(&obj, d) { + return Some(obj); + } + pairs = Some( + d.try_borrow() + .ok()? + .iter() + .map(|(k, v)| (k.0.clone(), v.clone())) + .collect(), + ); + } + // (A store the leaf declines leaves the unseen instance to be dropped + // and the full constructor to run.) + for (k, v) in pairs.into_iter().flatten() { + match od_setitem_leaf(&[obj.clone(), k, v]) { + Some(Ok(_)) => {} + _ => return None, + } + } + Some(obj) +} + +/// `(key, value)` pairs of exact two-item tuples, in order; `None` for +/// any other item. +fn od_pairs(items: &[Object]) -> Option> { + items + .iter() + .map(|p| match p { + Object::Tuple(t) if t.len() == 2 => Some((t[0].clone(), t[1].clone())), + _ => None, + }) + .collect() +} + /// A new view of `od` of the given kind (0 keys, 1 values, 2 items): an /// instance of the view class with its `_mapping` slot set, as /// `MappingView.__init__` leaves it. diff --git a/crates/weavepy-vm/src/stdlib/contextvars_native.rs b/crates/weavepy-vm/src/stdlib/contextvars_native.rs index 688dc6801..e0aa42aab 100644 --- a/crates/weavepy-vm/src/stdlib/contextvars_native.rs +++ b/crates/weavepy-vm/src/stdlib/contextvars_native.rs @@ -95,6 +95,29 @@ thread_local! { /// dropped at thread exit: the interpreter may be gone by then. static CURRENT: std::mem::ManuallyDrop> = const { std::mem::ManuallyDrop::new(std::cell::RefCell::new(Object::None)) }; + /// Advanced whenever the current context changes or a context's + /// mapping is written (see [`generation`]). + static GENERATION: std::cell::Cell = const { std::cell::Cell::new(1) }; +} + +/// The last [`GENERATION`] handed out, on any thread: every stamp is +/// unique to its thread and moment. +static GENERATIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +/// Note a change of the current context or of a mapping. +#[inline] +fn bump() { + let next = GENERATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let _ = GENERATION.try_with(|g| g.set(next)); +} + +/// A stamp that stays the same while the thread's current context and +/// every context's mapping do, unique across threads (`0` for none): what +/// a reader of the current context's values (`decimal`'s `getcontext`) may +/// cache against. +#[inline] +pub(crate) fn generation() -> u64 { + GENERATION.try_with(std::cell::Cell::get).unwrap_or(0) } thread_local! { @@ -201,8 +224,12 @@ fn current(st: &State) -> Object { CURRENT.with(|c| { let mut c = c.borrow_mut(); match &*c { - Object::None => *c = new_context(st, new_dict()), + Object::None => { + bump(); + *c = new_context(st, new_dict()); + } Object::Dict(d) => { + bump(); let from = Rc::as_ptr(d) as usize; let data = std::mem::replace(&mut *c, Object::None); *c = new_entered_context(st, data); @@ -244,7 +271,10 @@ fn current_built() -> Object { /// greenlet switches: the slot is emptied. pub(crate) fn take_current() -> Object { let _ = current_built(); - CURRENT.with(|c| std::mem::replace(&mut *c.borrow_mut(), Object::None)) + CURRENT.with(|c| { + bump(); + std::mem::replace(&mut *c.borrow_mut(), Object::None) + }) } /// The thread's current context without creating one (`None` if none). @@ -264,7 +294,10 @@ pub(crate) fn peek_current_data() -> Option>> { /// Make `ctx` (a context or `None`) the thread's current one. pub(crate) fn set_current(ctx: Object) { - let old = CURRENT.with(|c| std::mem::replace(&mut *c.borrow_mut(), ctx)); + let old = CURRENT.with(|c| { + bump(); + std::mem::replace(&mut *c.borrow_mut(), ctx) + }); drop(old); } @@ -328,7 +361,10 @@ pub(crate) fn run_in_snapshot( let Object::Dict(_) = ctx else { return (run_in_context(ctx, f, args), None); }; - let prev = CURRENT.with(|c| std::mem::replace(&mut *c.borrow_mut(), ctx.clone())); + let prev = CURRENT.with(|c| { + bump(); + std::mem::replace(&mut *c.borrow_mut(), ctx.clone()) + }); let hooked = HOOK_SET.load(Ordering::Relaxed); let mut result = if hooked { // The hook is handed the context: build it. @@ -340,7 +376,10 @@ pub(crate) fn run_in_snapshot( } else { call(f, args, &[]) }; - let me = CURRENT.with(|c| std::mem::replace(&mut *c.borrow_mut(), prev.clone())); + let me = CURRENT.with(|c| { + bump(); + std::mem::replace(&mut *c.borrow_mut(), prev.clone()) + }); let made = match me { Object::Instance(i) => { if let Some(slot) = i.slots.borrow_mut().get_hinted_mut(CTX_ENTERED, "_entered") { @@ -435,8 +474,27 @@ fn not_applicable(method: &str, cls: &str, obj: &Object) -> RuntimeError { /// `ContextVar.get([default])`. fn var_get(args: &[Object]) -> Result { - let (var, ext) = var_receiver(args, "get")?; - let st = st(&ext); + // (An exact `ContextVar`'s class state borrowed in place, as + // `var_receiver` checks it but with no clone of the state; anything + // else, and the error, through it.) + let lean = match args.first() { + Some(Object::Instance(i)) => i + .cls_raw() + .native_ext + .get() + .and_then(|e| e.downcast_ref::()) + .filter(|st| std::ptr::eq(i.cls_raw(), Rc::as_ptr(&st.var_cls))) + .map(|st| (i, st)), + _ => None, + }; + let owned; + let (var, st) = match lean { + Some(found) => found, + None => { + owned = var_receiver(args, "get")?; + (owned.0, st(&owned.1)) + } + }; if args.len() > 2 { return Err(type_error(format!( "get expected at most 1 argument, got {}", @@ -475,6 +533,7 @@ fn var_get(args: &[Object]) -> Result { /// Write `var = value` into `ctx`'s mapping, copying it first if another /// context shares it. Returns the previous value (or `missing`). fn ctx_store(ctx: &PyInstance, var: &Object, value: Option, missing: &Object) -> Object { + bump(); let mut slots = ctx.slots.borrow_mut(); let Some(slot) = slots.get_hinted_mut(CTX_DATA, "_data") else { return missing.clone(); @@ -509,6 +568,21 @@ fn ctx_store(ctx: &PyInstance, var: &Object, value: Option, missing: &Ob old.unwrap_or_else(|| missing.clone()) } +/// `var.set(value)` with the token dropped at once (`decimal`'s +/// `setcontext`): `None`, nothing stored, when `var` isn't an exact +/// `ContextVar`. +pub(crate) fn set_untokened(var: &Object, value: Object) -> Option<()> { + let ext = installed_as(var, |st| &st.var_cls)?; + let st = st(&ext); + let ctx = current(st); + let Object::Instance(ci) = &ctx else { + return None; + }; + let old = ctx_store(ci, var, Some(value), &st.missing); + drop(old); + Some(()) +} + /// `ContextVar.set(value)`. fn var_set(args: &[Object]) -> Result { let (_, ext) = var_receiver(args, "set")?; @@ -641,7 +715,10 @@ fn enter(ctx_obj: &Object, ctx: &PyInstance) -> Result { } } } - Ok(CURRENT.with(|c| std::mem::replace(&mut *c.borrow_mut(), ctx_obj.clone()))) + Ok(CURRENT.with(|c| { + bump(); + std::mem::replace(&mut *c.borrow_mut(), ctx_obj.clone()) + })) } /// Undo [`enter`]: restore `prev` as the current context. @@ -653,7 +730,10 @@ fn exit(ctx: &PyInstance, prev: Object) { { *slot = Object::Bool(false); } - let me = CURRENT.with(|c| std::mem::replace(&mut *c.borrow_mut(), prev)); + let me = CURRENT.with(|c| { + bump(); + std::mem::replace(&mut *c.borrow_mut(), prev) + }); drop(me); } diff --git a/crates/weavepy-vm/src/stdlib/csv_mod.rs b/crates/weavepy-vm/src/stdlib/csv_mod.rs index f347d80a7..f51749002 100644 --- a/crates/weavepy-vm/src/stdlib/csv_mod.rs +++ b/crates/weavepy-vm/src/stdlib/csv_mod.rs @@ -118,6 +118,35 @@ fn reader_keys() -> &'static ReaderKeys { }) } +/// A dialect's attribute keys, which every reader's dialect is built with +/// and read by (and a reader's `dialect`): built once. +struct DialectKeys { + delimiter: DictKey, + quotechar: DictKey, + escapechar: DictKey, + lineterminator: DictKey, + quoting: DictKey, + doublequote: DictKey, + skipinitialspace: DictKey, + strict: DictKey, + dialect: DictKey, +} + +fn dialect_keys() -> &'static DialectKeys { + static KEYS: OnceLock = OnceLock::new(); + KEYS.get_or_init(|| DialectKeys { + delimiter: key("delimiter"), + quotechar: key("quotechar"), + escapechar: key("escapechar"), + lineterminator: key("lineterminator"), + quoting: key("quoting"), + doublequote: key("doublequote"), + skipinitialspace: key("skipinitialspace"), + strict: key("strict"), + dialect: key("dialect"), + }) +} + /// A module-level function taking only positional args. fn b(name: &'static str, body: fn(&[Object]) -> Result) -> Object { Object::Builtin(Rc::new(BuiltinFn { @@ -426,21 +455,22 @@ fn dialect_new(args: &[Object], kwargs: &[(String, Object)]) -> Result bool { + let ascii = |c: Option| c.is_none_or(|c| c.is_ascii()); + if !(self.delimiter.is_ascii() + && ascii(self.quotechar) + && ascii(self.escapechar) + && self.lineterminator.is_ascii()) + { + return false; + } + let byte = |c: Option| c.map_or(0, |c| c as u8); + let (d, q, e) = ( + self.delimiter as u8, + byte(self.quotechar), + byte(self.escapechar), + ); + let term = self.lineterminator.as_bytes(); + f.bytes().all(|b| { + b != d + && b != b'\n' + && b != b'\r' + && (b != q || q == 0) + && (b != e || e == 0) + && !term.contains(&b) + }) + } +} + fn read_cfg(dialect: &Object) -> Result { let inst = match dialect { Object::Instance(i) => i, _ => return Err(type_error("invalid dialect")), }; let d = inst.dict_cell().borrow(); - let get = |n: &'static str| d.get(&DictKey(Object::from_static(n))).cloned(); + let get = |k: &DictKey| d.get(k).cloned(); + let k = dialect_keys(); let as_char = |o: Option| -> Option { match o { Some(Object::Str(s)) => one_char(&s), @@ -591,20 +652,20 @@ fn read_cfg(dialect: &Object) -> Result { } }; Ok(DialectCfg { - delimiter: as_char(get("delimiter")).unwrap_or(','), - quotechar: as_char(get("quotechar")), - escapechar: as_char(get("escapechar")), - lineterminator: match get("lineterminator") { + delimiter: as_char(get(&k.delimiter)).unwrap_or(','), + quotechar: as_char(get(&k.quotechar)), + escapechar: as_char(get(&k.escapechar)), + lineterminator: match get(&k.lineterminator) { Some(Object::Str(s)) => s.to_string(), _ => "\r\n".to_owned(), }, - quoting: match get("quoting") { + quoting: match get(&k.quoting) { Some(Object::Int(n)) => n, _ => QUOTE_MINIMAL, }, - doublequote: matches!(get("doublequote"), Some(Object::Bool(true))), - skipinitialspace: matches!(get("skipinitialspace"), Some(Object::Bool(true))), - strict: matches!(get("strict"), Some(Object::Bool(true))), + doublequote: matches!(get(&k.doublequote), Some(Object::Bool(true))), + skipinitialspace: matches!(get(&k.skipinitialspace), Some(Object::Bool(true))), + strict: matches!(get(&k.strict), Some(Object::Bool(true))), }) } @@ -676,6 +737,32 @@ enum St { AfterEscapedCrnl, } +/// How [`Parser::save_field`] converts an unquoted field to a `float` for +/// the numeric quoting styles: through `float` itself, or (for the leaf +/// half, which never reads with those styles) not at all. +trait FloatConv { + fn to_float(&mut self, val: Object) -> Result; +} + +impl FloatConv for Interpreter { + fn to_float(&mut self, val: Object) -> Result { + self.call_object( + Object::Type(builtin_types().float_.clone()), + std::slice::from_ref(&val), + &[], + ) + } +} + +/// The leaf half's [`FloatConv`]: it declines the styles that convert. +struct NoFloats; + +impl FloatConv for NoFloats { + fn to_float(&mut self, _val: Object) -> Result { + Err(type_error("this reader converts no fields")) + } +} + struct Parser { cfg: DialectCfg, state: St, @@ -709,7 +796,7 @@ impl Parser { Ok(()) } - fn save_field(&mut self, interp: &mut Interpreter) -> Result<(), RuntimeError> { + fn save_field(&mut self, interp: &mut impl FloatConv) -> Result<(), RuntimeError> { let q = self.cfg.quoting; if self.unquoted && self.field_len == 0 && (q == QUOTE_NOTNULL || q == QUOTE_STRINGS) { self.fields.push(Object::None); @@ -717,11 +804,7 @@ impl Parser { let mut val = crate::builtins::bridge_to_object(&self.field); if self.unquoted && self.field_len != 0 && (q == QUOTE_NONNUMERIC || q == QUOTE_STRINGS) { - val = interp.call_object( - Object::Type(builtin_types().float_.clone()), - std::slice::from_ref(&val), - &[], - )?; + val = interp.to_float(val)?; } self.fields.push(val); } @@ -793,6 +876,24 @@ impl Parser { true } + /// Run one line through the machine, then its end-of-line marker. + /// Runs of a field's ordinary characters go in whole; the characters + /// that mean something go through [`Parser::process`]. + fn feed_line(&mut self, interp: &mut impl FloatConv, line: &str) -> Result<(), RuntimeError> { + let mut at = 0; + while at < line.len() { + let run = self.plain_run(&line.as_bytes()[at..]); + if run > 0 && self.add_run(&line[at..at + run]) { + at += run; + continue; + } + let ch = line[at..].chars().next().expect("at a character"); + self.process(interp, Some(ch))?; + at += ch.len_utf8(); + } + self.process(interp, None) + } + fn is_quote(&self, c: Option) -> bool { self.cfg.quotechar.is_some_and(|q| c == Some(q)) } @@ -801,7 +902,11 @@ impl Parser { self.cfg.escapechar.is_some_and(|e| c == Some(e)) } - fn process(&mut self, interp: &mut Interpreter, c: Option) -> Result<(), RuntimeError> { + fn process( + &mut self, + interp: &mut impl FloatConv, + c: Option, + ) -> Result<(), RuntimeError> { match self.state { St::StartRecord => { if c.is_none() { @@ -895,7 +1000,7 @@ impl Parser { fn process_start_field( &mut self, - interp: &mut Interpreter, + interp: &mut impl FloatConv, c: Option, ) -> Result<(), RuntimeError> { self.unquoted = true; @@ -924,7 +1029,7 @@ impl Parser { fn process_in_field( &mut self, - interp: &mut Interpreter, + interp: &mut impl FloatConv, c: Option, ) -> Result<(), RuntimeError> { if matches!(c, None | Some('\n') | Some('\r')) { @@ -976,21 +1081,64 @@ fn csv_reader(args: &[Object], kwargs: &[(String, Object)]) -> Result>> = + const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; +} + +/// The dialect a reader made with no dialect and no format parameters +/// reads by (CPython builds an equal one each time; a dialect never +/// changes once built), and its packed view. +fn default_dialect(interp: &mut Interpreter) -> Result<(Object, Object), RuntimeError> { + if let Some(hit) = DEFAULT_DIALECT.with(|d| d.borrow().clone()) { + return Ok(hit); + } + let dialect = call_dialect(interp, None, &[])?; + let cfg = pack_reader_cfg(&read_cfg(&dialect)?); + DEFAULT_DIALECT.with(|d| *d.borrow_mut() = Some((dialect.clone(), cfg.clone()))); + Ok((dialect, cfg)) +} + fn reader_iter_self(args: &[Object]) -> Result { args.first() .cloned() @@ -1011,7 +1159,7 @@ fn reader_iternext(args: &[Object]) -> Result { Some(cfg) => cfg, None => { let dialect = d - .get(&key("dialect")) + .get(&dialect_keys().dialect) .ok_or_else(|| type_error("reader is missing its dialect"))?; read_cfg(dialect)? } @@ -1025,9 +1173,7 @@ fn reader_iternext(args: &[Object]) -> Result { // `__next__` hands it out and leaves NULL behind. A re-entrant // `next(reader)` from inside the input iterator that completes // therefore makes the outer call see NULL and raise (gh-145105). - inst.dict_cell() - .borrow_mut() - .insert(keys.fields_live.clone(), Object::Bool(true)); + set_reader_value(&inst, &keys.fields_live, Object::Bool(true)); loop { match interp.iter_next_object(input_iter.clone())? { None => { @@ -1056,46 +1202,347 @@ fn reader_iternext(args: &[Object]) -> Result { if !matches!(d.get(&keys.fields_live), Some(Object::Bool(true))) { return Err(csv_error("iterator has already advanced the reader")); } - let n = match d.get(&keys.line_num) { - Some(Object::Int(n)) => *n, - _ => 0, - }; - d.insert(keys.line_num.clone(), Object::Int(n + 1)); - } - // Runs of a field's ordinary characters go in whole; the - // characters that mean something go through the machine. - let mut at = 0; - while at < line.len() { - let run = p.plain_run(&line.as_bytes()[at..]); - if run > 0 && p.add_run(&line[at..at + run]) { - at += run; - continue; + // (Updated in place: the key is there after the + // first line.) + match d.get_mut(&keys.line_num) { + Some(v @ Object::Int(_)) => { + let Object::Int(n) = *v else { unreachable!() }; + *v = Object::Int(n + 1); + } + _ => { + d.insert(keys.line_num.clone(), Object::Int(1)); + } } - let ch = line[at..].chars().next().expect("at a character"); - p.process(interp, Some(ch))?; - at += ch.len_utf8(); } - p.process(interp, None)?; + p.feed_line(interp, &line)?; } } if p.state == St::StartRecord { break; } } - inst.dict_cell() - .borrow_mut() - .insert(keys.fields_live.clone(), Object::Bool(false)); + set_reader_value(&inst, &keys.fields_live, Object::Bool(false)); Ok(Object::new_list(std::mem::take(&mut p.fields))) }) } +/// The reader's `__next__` leaf half: a line that is one whole record, +/// read without the dispatch loop's full call, from a list or tuple +/// iterator or from a text stream that has the line in its buffer (see +/// `PyFile::next_line_pure`). A line of plain and quoted fields is split +/// directly (see [`split_direct`]); any other runs through the machine. A +/// record that goes on past its line, a line the machine raises on, a line +/// that isn't a plain `str`, a quoting style that converts fields to +/// `float`, a reader in the middle of a call, and +/// any other input decline to the full parser, which then reads the same +/// line. +/// A reader's state entries, by the position `csv_reader` inserts them at. +const AT_INPUT_ITER: usize = 0; +const AT_CFG: usize = 2; +const AT_LINE_NUM: usize = 3; +const AT_FIELDS_LIVE: usize = 4; + +/// Whether `a` is the very key `b` (the same interned name). +fn same_key(a: &DictKey, b: &DictKey) -> bool { + matches!((&a.0, &b.0), (Object::Str(x), Object::Str(y)) if crate::shared_value::SharedStr::ptr_eq(x, y)) +} + +/// A reader's state entry `key`, read at position `at` while that still +/// holds it (the layout `csv_reader` builds), else found by hash. +fn state_get<'a>(d: &'a DictData, at: usize, key: &DictKey) -> Option<&'a Object> { + match d.get_index(at) { + Some((k, v)) if same_key(k, key) => Some(v), + _ => d.get(key), + } +} + +fn reader_next_fast(args: &[Object]) -> Option> { + let [Object::Instance(inst)] = args else { + return None; + }; + Some(reader_step(inst)?.ok_or_else(stop_iteration)) +} + +/// The class `reader_type` made (its address), its native `__iter__` and +/// `__next__` (theirs), and the class version at which it last kept both. +static READER_CLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static READER_ITER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static READER_NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static READER_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether `inst` is a `csv.reader` whose class keeps its native +/// `__iter__` (which returns the reader) and `__next__`. +#[inline] +pub(crate) fn is_plain_reader(inst: &PyInstance) -> bool { + use std::sync::atomic::Ordering::Relaxed; + let cls = inst.cls_raw(); + if std::ptr::from_ref(cls) as usize != READER_CLS.load(Relaxed) { + return false; + } + let ver = cls.attr_version.get(); + (ver != 0 && ver == READER_VER.load(Relaxed)) + || (!crate::gil::free_threading_enabled() && reader_methods_native_slow(cls, ver)) +} + +#[cold] +#[inline(never)] +fn reader_methods_native_slow(cls: &TypeObject, ver: u64) -> bool { + use std::sync::atomic::Ordering::Relaxed; + let is = |name: &str, want: usize| { + want != 0 + && matches!(cls.lookup(name), Some(Object::Builtin(b)) if Rc::as_ptr(&b) as usize == want) + }; + let ok = ver != 0 + && is("__iter__", READER_ITER.load(Relaxed)) + && is("__next__", READER_NEXT.load(Relaxed)); + if ok { + READER_VER.store(ver, Relaxed); + } + ok +} + +/// A `for` loop's step over the `csv.reader` `inst` in compiled code, as +/// its `__next__`'s leaf half takes it: the next record, or `Some(None)` +/// at the end (no `StopIteration` built); `None` (nothing done) for any +/// other instance or a step the full parser takes. +#[inline] +pub(crate) fn reader_for_step(inst: &PyInstance) -> Option> { + if !is_plain_reader(inst) { + return None; + } + reader_step(inst) +} + +/// [`reader_next_fast`]'s step: the next record, or `Some(None)` at the +/// source's end. +fn reader_step(inst: &PyInstance) -> Option> { + let keys = reader_keys(); + let mut d = inst.dict_cell().try_borrow_mut().ok()?; + let src = match state_get(&d, AT_INPUT_ITER, &keys.input_iter) { + Some(o @ Object::Iter(_)) => o.clone(), + Some(o @ Object::File(f)) if !f.binary => o.clone(), + _ => return None, + }; + if !matches!( + state_get(&d, AT_FIELDS_LIVE, &keys.fields_live), + Some(Object::Bool(false)) + ) || !matches!( + state_get(&d, AT_LINE_NUM, &keys.line_num), + Some(Object::Int(_)) + ) { + return None; + } + let cfg = state_get(&d, AT_CFG, &keys.cfg).and_then(unpack_reader_cfg)?; + if matches!(cfg.quoting, QUOTE_NONNUMERIC | QUOTE_STRINGS) { + return None; + } + let fields = match &src { + Object::Iter(it) => { + let mut it = it.try_borrow_mut().ok()?; + // (`None` at the source's end, with no record begun: the end.) + let next = match &mut *it { + crate::object::PyIterator::List { + items, + index, + owner: None, + } => { + let items = items.try_borrow().ok()?; + match items.get(*index) { + Some(Object::Str(s)) => Some((s.clone(), index)), + None => None, + _ => return None, + } + } + crate::object::PyIterator::Tuple { items, index } => match items.get(*index) { + Some(Object::Str(s)) => Some((s.clone(), index)), + None => None, + _ => return None, + }, + _ => return None, + }; + let Some((line, index)) = next else { + // The step that finds the end, as the full path's leaves the + // iterator, then the end itself. + let end = it.next_value(); + debug_assert!(end.is_none()); + drop(end); + return Some(None); + }; + let fields = record_fields(cfg, &line)?; + *index += 1; + fields + } + Object::File(f) => { + let fields = f.next_line_pure_with(None, |line| match &line { + Object::Str(s) => record_fields(cfg, s), + _ => None, + })?; + // (As a text stream's own `__next__` leaves it.) + f.telling.set(false); + fields + } + _ => return None, + }; + let line_num = match d.get_index_mut(AT_LINE_NUM) { + Some((k, v)) if same_key(k, &keys.line_num) => Some(v), + _ => d.get_mut(&keys.line_num), + }; + if let Some(Object::Int(n)) = line_num { + *n += 1; + } + Some(Some(Object::new_list(fields))) +} + +/// The fields of `line` when it is one whole record the machine reads +/// without raising (and without converting fields, which `cfg` doesn't). +fn record_fields(cfg: DialectCfg, line: &str) -> Option> { + if let Some(fields) = split_direct(&cfg, line) { + return Some(fields); + } + let mut p = Parser::new(cfg); + // (Sized once: no field is longer than its line, and a record has at + // most one field more than the line has delimiters.) + p.field.reserve(line.len()); + if p.cfg.delimiter.is_ascii() { + let d = p.cfg.delimiter as u8; + p.fields + .reserve(memchr::memchr_iter(d, line.as_bytes()).count() + 1); + } + p.feed_line(&mut NoFloats, line).ok()?; + (p.state == St::StartRecord).then_some(p.fields) +} + +/// `line`'s fields read straight off it, which is what the machine makes +/// of it: for a dialect with ASCII characters, no escape in the line, no +/// `skipinitialspace`, and a quoting style that leaves unquoted fields as +/// they are, a line that is one whole record of unquoted fields (in which a +/// quote is an ordinary character) and quoted ones (doubled quotes inside +/// them read as one, when the dialect doubles), each quoted field closed +/// before the next delimiter, and no carriage return or newline outside a +/// quoted field before the line's own terminator. `None` for any other line +/// (a record that goes on past its line, a line the machine raises on or +/// reads characters after a closing quote into, an empty line, one longer +/// than the field limit), which the machine then reads. +fn split_direct(cfg: &DialectCfg, line: &str) -> Option> { + if !matches!(cfg.quoting, QUOTE_MINIMAL | QUOTE_ALL | QUOTE_NONE) || cfg.skipinitialspace { + return None; + } + let ascii = |c: char| c.is_ascii().then_some(c as u8); + let delimiter = ascii(cfg.delimiter).filter(|&b| b != b'\r' && b != b'\n')?; + let quote = match cfg.quotechar { + Some(q) if cfg.quoting != QUOTE_NONE => { + Some(ascii(q).filter(|&q| q != delimiter && q != b'\r' && q != b'\n')?) + } + _ => None, + }; + let bytes = line.as_bytes(); + let body = match bytes { + [.., b'\r', b'\n'] => bytes.len() - 2, + [.., b'\n' | b'\r'] => bytes.len() - 1, + _ => bytes.len(), + }; + if body == 0 || body as i64 > FIELD_LIMIT.load(Ordering::Relaxed) { + return None; + } + let b = &bytes[..body]; + if let Some(e) = cfg.escapechar { + if memchr::memchr(ascii(e)?, b).is_some() { + return None; + } + } + // (Every cut is at an ASCII byte, so every piece is whole text.) + let plain = b.is_ascii(); + let text = |s: &str| { + if plain { + Object::from_str(s) + } else { + crate::builtins::bridge_to_object(s) + } + }; + let mut fields = Vec::with_capacity(memchr::memchr_iter(delimiter, b).count() + 1); + let mut at = 0; + loop { + if let Some(q) = quote.filter(|&q| b.get(at) == Some(&q)) { + let mut from = at + 1; + let mut doubled = String::new(); + let close = loop { + // (No closing quote: the record goes on past the line.) + let next = from + memchr::memchr(q, &b[from..])?; + if b.get(next + 1) != Some(&q) { + break next; + } + if !cfg.doublequote { + return None; + } + doubled.push_str(&line[from..=next]); + from = next + 2; + }; + if doubled.is_empty() { + fields.push(text(&line[from..close])); + } else { + doubled.push_str(&line[from..close]); + fields.push(text(&doubled)); + } + at = close + 1; + match b.get(at) { + None => return Some(fields), + Some(&c) if c == delimiter => at += 1, + Some(_) => return None, + } + } else { + match memchr::memchr3(delimiter, b'\r', b'\n', &b[at..]) { + None => { + fields.push(text(&line[at..body])); + return Some(fields); + } + Some(n) if b[at + n] == delimiter => { + fields.push(text(&line[at..at + n])); + at += n + 1; + } + Some(_) => return None, + } + } + // (A delimiter that ends the line leaves an empty last field.) + if at == body { + fields.push(text("")); + return Some(fields); + } + } +} + +/// `inst. = value` on a reader's state: replaced in place when it is +/// there (every row's), inserted otherwise. +fn set_reader_value(inst: &PyInstance, key: &DictKey, value: Object) { + let mut d = inst.dict_cell().borrow_mut(); + match d.get_mut(key) { + Some(v) => { + let old = std::mem::replace(v, value); + drop(d); + drop(old); + } + None => { + d.insert(key.clone(), value); + } + } +} + fn reader_type() -> Rc { static CLS: OnceLock> = OnceLock::new(); CLS.get_or_init(|| { let bt = builtin_types(); + use std::sync::atomic::Ordering::Relaxed; let mut dict = DictData::default(); - dict.insert(key("__iter__"), method("__iter__", reader_iter_self)); - dict.insert(key("__next__"), method("__next__", reader_iternext)); + let iter = method("__iter__", reader_iter_self); + if let Object::Builtin(b) = &iter { + READER_ITER.store(Rc::as_ptr(b) as usize, Relaxed); + } + dict.insert(key("__iter__"), iter); + let next = method("__next__", reader_iternext); + if let Object::Builtin(b) = &next { + crate::leaf_builtins::register_fast(b, reader_next_fast); + READER_NEXT.store(Rc::as_ptr(b) as usize, Relaxed); + } + dict.insert(key("__next__"), next); dict.insert( key("__new__"), Object::Builtin(Rc::new(BuiltinFn { @@ -1105,8 +1552,10 @@ fn reader_type() -> Rc { call_kw: None, })), ); - TypeObject::new_user("_csv.reader", vec![bt.object_.clone()], dict) - .expect("_csv.reader must linearise") + let cls = TypeObject::new_user("_csv.reader", vec![bt.object_.clone()], dict) + .expect("_csv.reader must linearise"); + READER_CLS.store(Rc::as_ptr(&cls) as usize, Relaxed); + cls }) .clone() } @@ -1156,7 +1605,7 @@ fn csv_writer(args: &[Object], kwargs: &[(String, Object)]) -> Result Result { /// Number predicate for `QUOTE_NONNUMERIC` (`PyNumber_Check`). fn is_number(o: &Object) -> bool { match o { - Object::Int(_) | Object::Float(_) | Object::Complex(_) | Object::Bool(_) => true, + Object::Int(_) + | Object::Long(_) + | Object::Float(_) + | Object::Complex(_) + | Object::Bool(_) => true, Object::Instance(_) => { crate::instance_method(o, "__index__").is_some() || crate::instance_method(o, "__int__").is_some() @@ -1188,6 +1641,23 @@ fn join_append( field: Option<&str>, quoted_in: bool, ) -> Result<(), RuntimeError> { + // A field with nothing to quote or escape (the common case) is copied + // whole. + if let Some(f) = field { + if !f.is_empty() && cfg.plain_field(f) { + if num_fields > 0 { + rec.push(cfg.delimiter); + } + if quoted_in { + rec.push(cfg.quotechar.unwrap_or('"')); + } + rec.push_str(f); + if quoted_in { + rec.push(cfg.quotechar.unwrap_or('"')); + } + return Ok(()); + } + } let field_len = field.map_or(0, |f| f.chars().count()); let mut quoted = quoted_in; if field_len == 0 && cfg.delimiter == ' ' && cfg.skipinitialspace { @@ -1254,66 +1724,139 @@ fn join_append( Ok(()) } -fn writer_writerow_inner( - interp: &mut Interpreter, - inst: &Rc, - seq: Object, -) -> Result { +/// A writer's `write` method and its dialect's settings. +fn writer_parts(inst: &Rc) -> Result<(Object, DialectCfg), RuntimeError> { let (write, dialect_obj) = { let d = inst.dict_cell().borrow(); ( d.get(&key("write")).cloned(), - d.get(&key("dialect")).cloned(), + d.get(&dialect_keys().dialect).cloned(), ) }; let write = write.ok_or_else(|| type_error("writer is missing its write method"))?; let dialect_obj = dialect_obj.ok_or_else(|| type_error("writer is missing its dialect"))?; - let cfg = read_cfg(&dialect_obj)?; + Ok((write, writer_cfg(&dialect_obj)?)) +} - let iter = match interp.iter_object(seq.clone()) { - Ok(it) => it, - Err(RuntimeError::PyException(e)) if e.type_name() == "TypeError" => { - return Err(csv_error(format!( - "iterable expected, not {}", - seq.type_name() - ))) - } - Err(e) => return Err(e), +thread_local! { + /// The last dialect a writer read (by address and its dict's stamp) + /// and its settings: a writer's `writerow` reads them every row. + static WRITER_CFG: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// [`read_cfg`] for a writer, through [`WRITER_CFG`]: the dialect's dict +/// unchanged since (its stamp moves with every store) means the same +/// settings. +fn writer_cfg(dialect: &Object) -> Result { + let Object::Instance(inst) = dialect else { + return read_cfg(dialect); }; + let at = Rc::as_ptr(inst) as usize; + let stamp = inst.dict_cell().borrow().mutation_stamp(); + let hit = WRITER_CFG.with(|c| { + c.try_borrow().ok().and_then(|c| match &*c { + Some((a, st, cfg)) if *a == at && *st == stamp => Some(cfg.clone()), + _ => None, + }) + }); + if let Some(cfg) = hit { + return Ok(cfg); + } + let cfg = read_cfg(dialect)?; + WRITER_CFG.with(|c| { + if let Ok(mut c) = c.try_borrow_mut() { + *c = Some((at, stamp, cfg.clone())); + } + }); + Ok(cfg) +} +fn writer_writerow_inner( + interp: &mut Interpreter, + write: &Object, + cfg: &DialectCfg, + seq: Object, +) -> Result { let mut rec = String::new(); let mut num_fields: i64 = 0; let mut last_null = false; - loop { - let field = match interp.iter_next_object(iter.clone())? { - Some(f) => f, - None => break, - }; + let mut emit = |interp: &mut Interpreter, field: &Object| -> Result<(), RuntimeError> { let quoted = match cfg.quoting { - QUOTE_NONNUMERIC => !is_number(&field), + QUOTE_NONNUMERIC => !is_number(field), QUOTE_ALL => true, QUOTE_STRINGS => matches!(field, Object::Str(_) | Object::WStr(_)), QUOTE_NOTNULL => !matches!(field, Object::None), _ => false, }; last_null = matches!(field, Object::None); - if let Some(s) = str_chars(&field) { - join_append(&mut rec, &cfg, num_fields, Some(&s), quoted)?; - num_fields += 1; + if let Some(s) = str_chars(field) { + join_append(&mut rec, cfg, num_fields, Some(&s), quoted)?; } else if last_null { - join_append(&mut rec, &cfg, num_fields, None, quoted)?; - num_fields += 1; + join_append(&mut rec, cfg, num_fields, None, quoted)?; } else { - let s = interp.call_object( - Object::Type(builtin_types().str_.clone()), - std::slice::from_ref(&field), - &[], - )?; - let s = str_chars(&s).unwrap_or_default(); - join_append(&mut rec, &cfg, num_fields, Some(&s), quoted)?; - num_fields += 1; + // (`str()` of a plain number or bool is its own text.) + let text = match field { + Object::Int(n) => Some(itoa::Buffer::new().format(*n).to_owned()), + Object::Float(x) => Some(crate::object::float_repr(*x)), + Object::Bool(b) => Some(if *b { "True" } else { "False" }.to_owned()), + _ => None, + }; + match text { + Some(t) => join_append(&mut rec, cfg, num_fields, Some(&t), quoted)?, + None => { + let s = interp.call_object( + Object::Type(builtin_types().str_.clone()), + std::slice::from_ref(field), + &[], + )?; + let s = str_chars(&s).unwrap_or_default(); + join_append(&mut rec, cfg, num_fields, Some(&s), quoted)?; + } + } + } + num_fields += 1; + Ok(()) + }; + + // A list or tuple of plain strings, numbers, bools and `None`s: its + // items in order, read at once (writing them runs no code, so + // iterating the sequence live would see the same items). + let plain = |x: &Object| { + matches!( + x, + Object::Str(_) | Object::Int(_) | Object::Float(_) | Object::Bool(_) | Object::None + ) + }; + let items = match &seq { + Object::List(l) => l + .try_borrow() + .ok() + .filter(|v| v.iter().all(plain)) + .map(|v| v.clone()), + Object::Tuple(t) => t.iter().all(plain).then(|| t.to_vec()), + _ => None, + }; + if let Some(items) = items { + for field in &items { + emit(interp, field)?; + } + } else { + let iter = match interp.iter_object(seq.clone()) { + Ok(it) => it, + Err(RuntimeError::PyException(e)) if e.type_name() == "TypeError" => { + return Err(csv_error(format!( + "iterable expected, not {}", + seq.type_name() + ))) + } + Err(e) => return Err(e), + }; + while let Some(field) = interp.iter_next_object(iter.clone())? { + emit(interp, &field)?; } } + drop(emit); if num_fields > 0 && rec.is_empty() { if cfg.quoting == QUOTE_NONE @@ -1321,12 +1864,12 @@ fn writer_writerow_inner( { return Err(csv_error("single empty field record must be quoted")); } - join_append(&mut rec, &cfg, num_fields - 1, None, true)?; + join_append(&mut rec, cfg, num_fields - 1, None, true)?; } rec.push_str(&cfg.lineterminator); let line = Object::from_str(rec); - interp.call_object(write, &[line], &[]) + interp.call_object(write.clone(), &[line], &[]) } fn writer_writerow(args: &[Object]) -> Result { @@ -1335,7 +1878,8 @@ fn writer_writerow(args: &[Object]) -> Result { .get(1) .cloned() .ok_or_else(|| type_error("writerow() takes exactly one argument (0 given)"))?; - with_interp(|interp| writer_writerow_inner(interp, &inst, seq)) + let (write, cfg) = writer_parts(&inst)?; + with_interp(|interp| writer_writerow_inner(interp, &write, &cfg, seq)) } fn writer_writerows(args: &[Object]) -> Result { @@ -1344,6 +1888,9 @@ fn writer_writerows(args: &[Object]) -> Result { .get(1) .cloned() .ok_or_else(|| type_error("writerows() takes exactly one argument (0 given)"))?; + // (CPython's writer holds its `write` and dialect from creation; both + // are read-only attributes there.) + let (write, cfg) = writer_parts(&inst)?; with_interp(|interp| { let row_iter = interp.iter_object(seqseq)?; loop { @@ -1351,7 +1898,7 @@ fn writer_writerows(args: &[Object]) -> Result { Some(r) => r, None => break, }; - writer_writerow_inner(interp, &inst, row)?; + writer_writerow_inner(interp, &write, &cfg, row)?; } Ok(Object::None) }) diff --git a/crates/weavepy-vm/src/stdlib/ctypes_native.rs b/crates/weavepy-vm/src/stdlib/ctypes_native.rs index 7cf7a7b80..31de7bce7 100644 --- a/crates/weavepy-vm/src/stdlib/ctypes_native.rs +++ b/crates/weavepy-vm/src/stdlib/ctypes_native.rs @@ -227,7 +227,7 @@ fn b_read_mem(args: &[Object]) -> Result { return Err(value_error("read_mem: NULL pointer access")); } let slice = unsafe { std::slice::from_raw_parts(addr as *const u8, n) }; - Ok(Object::new_bytes(slice.to_vec())) + Ok(Object::new_bytes(slice)) } /// `write_mem(addr, data)` — copy `data` into raw memory. @@ -638,7 +638,7 @@ fn b_configure_view(args: &[Object]) -> Result { }; let fmt = arg_str(args, 1)?; let itemsize = arg_usize(args, 2)?; - *mv.format.borrow_mut() = fmt; + *mv.format.borrow_mut() = crate::shared_value::SharedStr::from(fmt); mv.itemsize.set(itemsize); mv.strides.borrow_mut().clear(); match arg(args, 3)? { diff --git a/crates/weavepy-vm/src/stdlib/datetime_native.rs b/crates/weavepy-vm/src/stdlib/datetime_native.rs index 1177da376..0f29899d8 100644 --- a/crates/weavepy-vm/src/stdlib/datetime_native.rs +++ b/crates/weavepy-vm/src/stdlib/datetime_native.rs @@ -13,10 +13,13 @@ //! *exact* classes with a [`TypeObject::native_kind`], puts the native //! callables in their class dicts, and records the resulting class //! versions. A native body serves only exact-class operands whose fields -//! hold plain ints and whose `tzinfo` is `None` or an exact `timezone`; -//! anything else — subclasses, custom `tzinfo`s, unusual arguments, and -//! every error whose message the Python code owns — calls the original -//! Python method it replaced, so observable behavior is unchanged. The +//! hold plain ints. A value keeps any `tzinfo` object; what needs its +//! offset is served for `None`, an exact `timezone`, and a +//! `zoneinfo.ZoneInfo` (whose data `stdlib::zoneinfo_native` reads in +//! place). Anything else — subclasses, other `tzinfo` classes' offsets, +//! unusual arguments, and every error whose message the Python code +//! owns — calls the original Python method it replaced, so observable +//! behavior is unchanged. The //! pure fast halves are registered as leaf entries, so the dispatch loop //! runs them inline; the loop's operator and field shortcuts //! ([`leaf_binop`], [`leaf_compare`], [`leaf_field`]) apply only while a @@ -42,7 +45,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use crate::error::{overflow_error, type_error, RuntimeError}; use crate::object::{BuiltinFn, DictKey, Object}; use crate::shared_value::{SharedSlice, SharedStr}; -use crate::sync::{Rc, RefCell, Weak}; +use crate::sync::{Rc, Weak}; use crate::types::{PyInstance, SlotStorage, TypeObject}; pub(crate) const KIND_TIMEDELTA: u8 = 1; @@ -74,6 +77,22 @@ const DT_US: usize = 6; const DT_TZINFO: usize = 7; const DT_FOLD: usize = 9; const TZ_OFFSET: usize = 0; +// A `time`'s slots, in the order its `__slots__` names them. +const T_HOUR: usize = 0; +const T_MINUTE: usize = 1; +const T_SECOND: usize = 2; +const T_US: usize = 3; +const T_TZINFO: usize = 4; +const T_FOLD: usize = 6; +const TIME_SLOTS: [&str; 7] = [ + "_hour", + "_minute", + "_second", + "_microsecond", + "_tzinfo", + "_hashcode", + "_fold", +]; // --------------------------------------------------------------------- // Packed storage. @@ -562,7 +581,6 @@ struct Names { f_days: SharedStr, f_seconds: SharedStr, f_microseconds: SharedStr, - f_fromisoformat: SharedStr, } fn interned(s: &str) -> SharedStr { @@ -601,7 +619,6 @@ impl Names { f_days: interned("days"), f_seconds: interned("seconds"), f_microseconds: interned("microseconds"), - f_fromisoformat: interned("fromisoformat"), } } } @@ -611,8 +628,11 @@ impl Names { struct State { timedelta: Weak, date: Weak, + time: Weak, datetime: Weak, timezone: Weak, + /// `tzinfo`, the base of `timezone`. + tzinfo: Weak, utc: Weak, names: Names, /// The slot layouts natively built instances share (see @@ -621,6 +641,13 @@ struct State { td_layout: SharedSlice, date_layout: SharedSlice, dt_layout: SharedSlice, + /// The `time` class's own slot layout, when it is the seven slots + /// [`new_time`] fills (a `time` is built over it unpacked). + time_layout: Option>, + /// The `datetime` class's own slot layout (an instance the Python + /// `__new__` built is laid out over it), and where it holds each + /// field `dt_fields_slow` reads, in that function's order. + dt_own: Option<(SharedSlice, [u8; 9])>, /// `(kind, name)` → the replaced Python implementation. orig: HashMap<(u8, &'static str), Object>, /// The `attr_version` at which each exact class was last verified to @@ -632,9 +659,10 @@ struct State { expect: std::sync::OnceLock>, /// Dead instances kept for reuse (see [`Pool`]). pool: Pool, - /// The native `datetime.fromisoformat` (the function its - /// `classmethod` wraps). - fromiso: std::sync::OnceLock, + /// The native class methods (`datetime.fromisoformat`, `now`, + /// `fromtimestamp`, `date.today`): the class kind, the interned name, + /// the function the `classmethod` wraps and its fast half. + classmethods: std::sync::OnceLock>, } /// The dunders and fields the dispatch-loop shortcuts serve without a @@ -687,6 +715,36 @@ const SHORTCUT_NAMES: &[(u8, &str)] = &[ (KIND_DATETIME, "tzinfo"), (KIND_DATETIME, "fold"), (KIND_DATETIME, "fromisoformat"), + (KIND_DATETIME, "fromtimestamp"), + (KIND_DATETIME, "now"), + (KIND_DATE, "today"), + (KIND_DATE, "fromisoformat"), + (KIND_DATE, "fromordinal"), + (KIND_DATETIME, "combine"), + (KIND_TIMEDELTA, "__hash__"), + (KIND_DATE, "__hash__"), + (KIND_DATETIME, "__hash__"), + (KIND_TIME, "__hash__"), + (KIND_TIME, "__eq__"), + (KIND_TIME, "__ne__"), + (KIND_TIME, "__lt__"), + (KIND_TIME, "__le__"), + (KIND_TIME, "__gt__"), + (KIND_TIME, "__ge__"), + (KIND_TIME, "__new__"), + (KIND_TIME, "__init__"), + (KIND_TIME, "hour"), + (KIND_TIME, "minute"), + (KIND_TIME, "second"), + (KIND_TIME, "microsecond"), + (KIND_TIME, "tzinfo"), + (KIND_TIME, "fold"), + (KIND_TIME, "_hour"), + (KIND_TIME, "_minute"), + (KIND_TIME, "_second"), + (KIND_TIME, "_microsecond"), + (KIND_TIME, "_tzinfo"), + (KIND_TIME, "_fold"), // The slots behind the fields, which `leaf_field` reads by name too. (KIND_TIMEDELTA, "_days"), (KIND_TIMEDELTA, "_seconds"), @@ -903,6 +961,24 @@ fn dt_packed(i: &PyInstance) -> Option<(u64, *const PyInstance)> { #[inline(never)] fn dt_fields_slow(s: &SlotStorage, st: &State) -> Option
{ let n = &st.names; + // An instance the Python `__new__` built (an aware value whose + // `tzinfo` the natives don't build with): its slots by position. + if let Some((layout, at)) = &st.dt_own { + if let Some(v) = s.values_for_layout(layout) { + let at = |k: usize| v.get(at[k] as usize); + return Some(Dt { + y: as_int(at(0)?)?, + m: as_int(at(1)?)?, + d: as_int(at(2)?)?, + hh: as_int(at(3)?)?, + mm: as_int(at(4)?)?, + ss: as_int(at(5)?)?, + us: as_int(at(6)?)?, + tz: at(7)?.clone(), + fold: as_int(at(8)?)?, + }); + } + } if let Some(v) = s.values_for_layout(&st.dt_layout) { return Some(Dt { y: as_int(&v[D_YEAR])?, @@ -967,6 +1043,202 @@ fn tz_of(tz: &Object, st: &State) -> Option { } } +/// Whether the natives build a value with `tz` for its `tzinfo`: `None`, +/// or an instance of a `tzinfo` subclass (what `_check_tzinfo_arg` +/// takes). The value keeps the object; only what needs its offset asks +/// more of it ([`tz_at`]). +fn tz_ok(tz: &Object, st: &State) -> Option<()> { + match tz { + Object::None => Some(()), + Object::Instance(i) => { + let cls = i.cls_raw(); + let ok = std::ptr::eq(cls, st.timezone.as_ptr()) + || cls.mro.try_borrow().is_ok_and(|mro| { + mro.iter() + .any(|t| std::ptr::eq(Rc::as_ptr(t), st.tzinfo.as_ptr())) + }); + ok.then_some(()) + } + _ => None, + } +} + +/// An offset a zone handed back, in microseconds: an exact `timedelta` +/// strictly within a day (what `_check_utc_offset` lets through). +fn off_us(off: &Object, st: &State) -> Option { + let us = td_us(td_fields(inst(off, KIND_TIMEDELTA)?, st)?); + (us.abs() < US_PER_DAY).then_some(us) +} + +/// What the zone of the aware value `f` (a `zoneinfo.ZoneInfo`, see +/// `stdlib::zoneinfo_native`) says of its local time, taken with `fold`. +fn zone_info(f: &Dt, fold: i64) -> Option { + if !valid_date(f.y, f.m, f.d) { + return None; + } + crate::stdlib::zoneinfo_native::local_info( + &f.tz, + ymd2ord(f.y, f.m, f.d), + f.hh * 3600 + f.mm * 60 + f.ss, + f.y, + fold, + ) +} + +/// `f.utcoffset()` in microseconds for a zone's value, taken with `fold`. +fn zone_off(f: &Dt, st: &State, fold: i64) -> Option { + off_us(&zone_info(f, fold)?.utcoff()?, st) +} + +/// [`tz_of`] for the `tzinfo` of the value `f` itself, a zone's offset at +/// `f`'s local time counting as fixed: what `f.utcoffset()` is. +fn tz_at(f: &Dt, st: &State) -> Option { + match tz_of(&f.tz, st) { + Some(tz) => Some(tz), + None => zone_off(f, st, f.fold).map(Tz::Fixed), + } +} + +/// The value `utc` (a UTC time) in the zone `tz`, as `tz.fromutc` gives +/// it: shifted by the offset in force, `fold` set for the second of two +/// equal local times. +fn zone_from_utc(st: &State, utc: Dt, tz: &Object) -> Option
{ + if !valid_date(utc.y, utc.m, utc.d) { + return None; + } + let (info, fold) = crate::stdlib::zoneinfo_native::utc_info( + tz, + ymd2ord(utc.y, utc.m, utc.d), + utc.hh * 3600 + utc.mm * 60 + utc.ss, + utc.y, + |off| off_us(off, st), + )?; + let mut g = dt_shift(utc, off_us(&info.utcoff()?, st)?)?; + g.tz = tz.clone(); + g.fold = i64::from(fold); + Some(g) +} + +/// The exact `datetime` `dt`'s state and fields, while its class is as +/// [`install`] left it. +fn exact_dt(dt: &Object) -> Option<(&State, Dt)> { + let i = inst(dt, KIND_DATETIME)?; + let cls = i.cls_raw(); + let st = state_of_cls(cls)?; + if !std::ptr::eq(cls, st.datetime.as_ptr()) || !verified(st, cls, KIND_DATETIME) { + return None; + } + let f = dt_fields(i, st)?; + valid_date(f.y, f.m, f.d).then_some((st, f)) +} + +/// What a zone's lookup reads of `dt`, an exact `datetime` (see +/// `stdlib::zoneinfo_native`): its day's ordinal, the seconds into the +/// day, its year and its fold. +pub(crate) fn local_parts(dt: &Object) -> Option<(i64, i64, i64, i64)> { + let (_, f) = exact_dt(dt)?; + Some(( + ymd2ord(f.y, f.m, f.d), + f.hh * 3600 + f.mm * 60 + f.ss, + f.y, + f.fold, + )) +} + +/// `tz.fromutc(dt)` for a zone `tz` and an exact `datetime` whose +/// `tzinfo` it is (any other raises in the Python method). +pub(crate) fn zone_fromutc(tz: &Object, dt: &Object) -> Option { + let (st, f) = exact_dt(dt)?; + if !f.tz.is_same(tz) { + return None; + } + let g = zone_from_utc(st, f, tz)?; + new_dt(st, g) +} + +/// A `time`'s fields (its storage is never packed). +struct Tm { + hh: i64, + mm: i64, + ss: i64, + us: i64, + tz: Object, + fold: i64, +} + +impl Tm { + fn valid(&self) -> bool { + (0..24).contains(&self.hh) + && (0..60).contains(&self.mm) + && (0..60).contains(&self.ss) + && (0..1_000_000).contains(&self.us) + && (0..=1).contains(&self.fold) + } +} + +fn time_fields(i: &PyInstance, st: &State) -> Option { + let n = &st.names; + with_slots(i, |s| { + if s.as_packed().is_some() { + return None; + } + // (Laid out over the class's own slots, as every exact `time` + // is: the fields at their positions, with no name compared.) + if let Some(v) = st + .time_layout + .as_ref() + .and_then(|layout| s.values_for_layout(layout)) + { + let int = |o: &Object| match o { + Object::Int(v) => Some(*v), + _ => None, + }; + return Some(Tm { + hh: int(v.get(T_HOUR)?)?, + mm: int(v.get(T_MINUTE)?)?, + ss: int(v.get(T_SECOND)?)?, + us: int(v.get(T_US)?)?, + tz: v.get(T_TZINFO)?.clone(), + fold: int(v.get(T_FOLD)?)?, + }); + } + let int = |ix: usize, name: &SharedStr| match s.get_hinted(ix, name)? { + Object::Int(v) => Some(*v), + _ => None, + }; + Some(Tm { + hh: int(T_HOUR, &n.hour)?, + mm: int(T_MINUTE, &n.minute)?, + ss: int(T_SECOND, &n.second)?, + us: int(T_US, &n.microsecond)?, + tz: s.get_hinted(T_TZINFO, &n.tzinfo)?.clone(), + fold: int(T_FOLD, &n.fold)?, + }) + }) +} + +/// An exact `time` with validated fields, laid out as its `__new__` +/// fills it (the hash not yet computed). +fn new_time(st: &State, f: Tm) -> Option { + if !f.valid() { + return None; + } + let cls = st.time.upgrade()?; + Some(instance_fixed( + cls, + st.time_layout.as_ref()?, + vec![ + Object::Int(f.hh), + Object::Int(f.mm), + Object::Int(f.ss), + Object::Int(f.us), + f.tz, + Object::Int(-1), + Object::Int(f.fold), + ], + )) +} + // --------------------------------------------------------------------- // Calendar arithmetic (proleptic Gregorian, ordinal 1 = 0001-01-01). @@ -1030,8 +1302,7 @@ fn entry(k: &SharedStr, v: Object) -> (DictKey, Object) { } fn instance(cls: Rc, entries: Vec<(DictKey, Object)>) -> Object { - let mut i = PyInstance::new(cls); - i.slots = RefCell::new(SlotStorage::from_entries(entries)); + let i = PyInstance::with_slots(cls, SlotStorage::from_entries(entries)); Object::Instance(Rc::new(i)) } @@ -1041,12 +1312,11 @@ fn instance_fixed( layout: &SharedSlice, values: Vec, ) -> Object { - let mut i = PyInstance::new(cls); - i.slots = RefCell::new(SlotStorage::from_layout(layout.clone(), values)); + let i = PyInstance::with_slots(cls, SlotStorage::from_layout(layout.clone(), values)); Object::Instance(Rc::new(i)) } -/// `timedelta(...)`, `date(...)` and `datetime(...)` of the exact classes +/// `timedelta(...)`, `date(...)`, `time(...)` and `datetime(...)` of the exact classes /// with plain `int` fields (by position or keyword) and, for `datetime`, a /// naive or fixed-offset zone: the instance the replaced `__new__` builds, /// built natively. `None` for every other shape, which the Python @@ -1095,6 +1365,7 @@ const TD_PARAMS: [&str; 7] = [ "weeks", ]; const DATE_PARAMS: [&str; 3] = ["year", "month", "day"]; +const TIME_PARAMS: [&str; 6] = ["hour", "minute", "second", "microsecond", "tzinfo", "fold"]; const DT_PARAMS: [&str; 9] = [ "year", "month", @@ -1119,16 +1390,17 @@ fn construct_with<'a>( KIND_TIMEDELTA => (st.timedelta.as_ptr(), &TD_PARAMS), KIND_DATE => (st.date.as_ptr(), &DATE_PARAMS), // `fold` is keyword-only. + KIND_TIME => (st.time.as_ptr(), &TIME_PARAMS), KIND_DATETIME => (st.datetime.as_ptr(), &DT_PARAMS), _ => return None, }; if !std::ptr::eq(cls, exact) || !verified(st, cls, kind) { return None; } - let npos = if kind == KIND_DATETIME { - 8 - } else { - params.len() + let npos = match kind { + KIND_DATETIME => 8, + KIND_TIME => 5, + _ => params.len(), }; if args.len() > npos { return None; @@ -1175,6 +1447,18 @@ fn construct_with<'a>( .flatten() .map(Ok) } + KIND_TIME => { + let f = Tm { + hh: int(0, Some(0))?, + mm: int(1, Some(0))?, + ss: int(2, Some(0))?, + us: int(3, Some(0))?, + tz: slots[4].cloned().unwrap_or(Object::None), + fold: int(5, Some(0))?, + }; + tz_ok(&f.tz, st)?; + new_time(st, f).map(Ok) + } _ => { let f = Dt { y: int(0, None)?, @@ -1196,7 +1480,7 @@ fn construct_with<'a>( if !ok { return None; } - tz_of(&f.tz, st)?; + tz_ok(&f.tz, st)?; new_dt(st, f).map(Ok) } } @@ -1375,8 +1659,10 @@ fn new_packed( drop(Rc::into_arc(inst)); } let cls = cls.upgrade()?; - let mut i = PyInstance::new(cls); - *i.slots.get_mut() = SlotStorage::from_packed(PackedSlots::new(kind, word, aux)); + let i = PyInstance::with_slots( + cls, + SlotStorage::from_packed(PackedSlots::new(kind, word, aux)), + ); Some(Object::Instance(Rc::new(i))) } @@ -1596,9 +1882,10 @@ fn date_hash(a: &[Object]) -> Option> { Some(Ok(Object::Int(crate::object::combine_tuple_hash(&[h])))) } -/// The replaced `datetime.__hash__` for a naive or fixed-offset value: -/// the state bytes' hash when naive, else the hash of the UTC value as a -/// `timedelta` since 0001-01-01 (`fold` never changes a fixed offset). +/// The replaced `datetime.__hash__` for a naive, fixed-offset or zone +/// value: the state bytes' hash when naive, else the hash of the UTC +/// value as a `timedelta` since 0001-01-01 (`fold` never changes a fixed +/// offset; a zone's is read as `fold=0` has it). fn dt_hash(a: &[Object]) -> Option> { let [x] = a else { return None }; let st = state_of(x)?; @@ -1606,7 +1893,13 @@ fn dt_hash(a: &[Object]) -> Option> { if !valid_date(f.y, f.m, f.d) { return None; } - let h = match tz_of(&f.tz, st)? { + // (A zone's offset as `fold=0` has it, which the Python code hashes + // by.) + let tz = match tz_of(&f.tz, st) { + Some(tz) => tz, + None => Tz::Fixed(zone_off(&f, st, 0)?), + }; + let h = match tz { Tz::Naive => { let state = [ (f.y / 256) as u8, @@ -1660,6 +1953,172 @@ cmp_fast!(td_le, td_cmp, |o| o.is_le()); cmp_fast!(td_gt, td_cmp, |o| o.is_gt()); cmp_fast!(td_ge, td_cmp, |o| o.is_ge()); +/// The replaced `time.__hash__` for a naive value or one at a zero +/// fixed offset: the hash of its state bytes (`fold` never changes it). +/// Another offset is the Python method's. +fn time_hash(a: &[Object]) -> Option> { + let [x] = a else { return None }; + let st = state_of(x)?; + let f = time_fields(inst(x, KIND_TIME)?, st)?; + if !f.valid() || !matches!(tz_of(&f.tz, st)?, Tz::Naive | Tz::Fixed(0)) { + return None; + } + let state = [ + f.hh as u8, + f.mm as u8, + f.ss as u8, + (f.us >> 16) as u8, + (f.us >> 8 & 0xff) as u8, + (f.us & 0xff) as u8, + ]; + Some(Ok(Object::Int(crate::object::py_bytes_hash(&state)))) +} + +/// `hash(x)` of a natively served `timedelta`, `date`, `time`, +/// `datetime` or `Decimal` whose class keeps the native `__hash__`, for +/// the leaf hashing paths (`hash()`, a dict or set probe). +pub(crate) fn leaf_hash(x: &Object) -> Option { + let Object::Instance(i) = x else { + return None; + }; + let cls = i.cls_raw(); + let kind = cls.native_kind.get(); + if kind == KIND_DECIMAL { + return super::decimal_native::leaf_hash(i); + } + if !matches!(kind, KIND_TIMEDELTA | KIND_DATE | KIND_TIME | KIND_DATETIME) { + return None; + } + let st = state_of_cls(cls)?; + if !verified(st, cls, kind) { + return None; + } + // SAFETY: a shallow copy the fast halves only read; never dropped. + let args = std::mem::ManuallyDrop::new(unsafe { [std::ptr::read(x)] }); + let r = match kind { + KIND_TIMEDELTA => td_hash(&args[..]), + KIND_DATE => date_hash(&args[..]), + KIND_TIME => time_hash(&args[..]), + _ => dt_hash(&args[..]), + }?; + match r { + Ok(Object::Int(h)) => Some(h), + _ => None, + } +} + +/// Two exact `time`s that are both naive or share one zone object, by +/// their fields (`fold` doesn't count). Other pairs compare offsets: +/// the Python method's. +fn time_cmp(a: &[Object]) -> Option { + let [x, y] = a else { return None }; + let st = state_of(x)?; + let p = time_fields(inst(x, KIND_TIME)?, st)?; + let q = time_fields(inst(y, KIND_TIME)?, st)?; + let same_zone = match (&p.tz, &q.tz) { + (Object::None, Object::None) => true, + (Object::Instance(a), Object::Instance(b)) => Rc::ptr_eq(a, b), + _ => false, + }; + same_zone.then(|| (p.hh, p.mm, p.ss, p.us).cmp(&(q.hh, q.mm, q.ss, q.us))) +} + +cmp_fast!(time_eq, time_cmp, |o| o.is_eq()); +cmp_fast!(time_lt, time_cmp, |o| o.is_lt()); +cmp_fast!(time_le, time_cmp, |o| o.is_le()); +cmp_fast!(time_gt, time_cmp, |o| o.is_gt()); +cmp_fast!(time_ge, time_cmp, |o| o.is_ge()); + +/// `dt.time()`: the naive `time` of an exact `datetime`'s fields. +fn dt_time(a: &[Object]) -> Option> { + dt_time_with(a, false) +} + +/// `dt.timetz()`: as `dt.time()`, keeping the zone. +fn dt_timetz(a: &[Object]) -> Option> { + dt_time_with(a, true) +} + +fn dt_time_with(a: &[Object], zone: bool) -> Option> { + let [x] = a else { return None }; + let st = state_of(x)?; + let f = dt_fields(inst(x, KIND_DATETIME)?, st)?; + tz_ok(&f.tz, st)?; + let tz = if zone { f.tz } else { Object::None }; + new_time( + st, + Tm { + hh: f.hh, + mm: f.mm, + ss: f.ss, + us: f.us, + tz, + fold: f.fold, + }, + ) + .map(Ok) +} + +/// `datetime.combine(date, time)` of the exact classes (a `datetime` +/// counts as a date): the date's day at the time's fields, in the +/// time's zone. A `tzinfo` argument is the Python method's. +fn dt_combine(a: &[Object]) -> Option> { + let [Object::Type(cls), d, t] = a else { + return None; + }; + let st = state_of_cls(cls)?; + if !std::ptr::eq(Rc::as_ptr(cls), st.datetime.as_ptr()) { + return None; + } + let di = match kind_of(d) { + KIND_DATE | KIND_DATETIME => match d { + Object::Instance(i) => i, + _ => return None, + }, + _ => return None, + }; + let (y, m, day) = date_fields(di, st)?; + let f = time_fields(inst(t, KIND_TIME)?, st)?; + if !valid_date(y, m, day) || !f.valid() { + return None; + } + tz_ok(&f.tz, st)?; + new_dt( + st, + Dt { + y, + m, + d: day, + hh: f.hh, + mm: f.mm, + ss: f.ss, + us: f.us, + tz: f.tz, + fold: f.fold, + }, + ) + .map(Ok) +} + +/// `date.fromordinal(n)` of the exact class, for an ordinal in range. +fn date_fromordinal(a: &[Object]) -> Option> { + let [Object::Type(cls), Object::Int(n)] = a else { + return None; + }; + let st = state_of_cls(cls)?; + if !std::ptr::eq(Rc::as_ptr(cls), st.date.as_ptr()) || !(1..=MAX_ORDINAL).contains(n) { + return None; + } + let (y, m, d) = ord2ymd(*n); + Some(Ok(new_date(st, y, m, d)?)) +} + +/// `str(dt)`: `dt.isoformat(sep=' ')`. +fn dt_str(a: &[Object]) -> Option> { + let [x] = a else { return None }; + dt_isoformat(&[x.clone(), Object::from_static(" ")]) +} + fn date_toordinal(a: &[Object]) -> Option> { let [x] = a else { return None }; let st = state_of(x)?; @@ -1835,7 +2294,8 @@ fn date_replace(a: &[Object]) -> Option> { return None; } for (i, v) in rest.iter().enumerate() { - if matches!(v, Object::None) { + // (`Unbound`: a keyword call's gap.) + if matches!(v, Object::None | Object::Unbound) { continue; } let v = as_int(v)?; @@ -1924,14 +2384,19 @@ fn dt_sub(a: &[Object]) -> Option> { let j = inst(y, KIND_DATETIME)?; if let (Some((wf, tf)), Some((wg, tg))) = (dt_packed(xi), dt_packed(j)) { let mut diff = i128::from(word_us(wf) - word_us(wg)); + // (A zone's offset is read with the fields, below.) + let mut settled = true; if !std::ptr::eq(tf, tg) { - match (tz_of_ptr(tf, st)?, tz_of_ptr(tg, st)?) { - (Tz::Naive, Tz::Naive) => {} - (Tz::Fixed(a), Tz::Fixed(b)) => diff += b - a, - _ => return None, + match (tz_of_ptr(tf, st), tz_of_ptr(tg, st)) { + (Some(Tz::Naive), Some(Tz::Naive)) => {} + (Some(Tz::Fixed(a)), Some(Tz::Fixed(b))) => diff += b - a, + (Some(Tz::Naive), _) | (_, Some(Tz::Naive)) => return None, + _ => settled = false, } } - return new_td(st, 0, 0, diff); + if settled { + return new_td(st, 0, 0, diff); + } } let f = dt_fields(xi, st)?; if !valid_date(f.y, f.m, f.d) { @@ -1943,7 +2408,7 @@ fn dt_sub(a: &[Object]) -> Option> { } let mut diff = dt_us(&f) - dt_us(&g); if !f.tz.is_same(&g.tz) { - match (tz_of(&f.tz, st)?, tz_of(&g.tz, st)?) { + match (tz_at(&f, st)?, tz_at(&g, st)?) { (Tz::Naive, Tz::Naive) => {} (Tz::Fixed(a), Tz::Fixed(b)) => diff += b - a, // The mixed case raises in the Python code. @@ -1957,8 +2422,10 @@ fn dt_sub(a: &[Object]) -> Option> { } /// `datetime` ordering: `(ordering, comparable)`; `comparable` is false -/// for a naive/aware pair (equality says unequal, ordering raises). -fn dt_cmp_raw(a: &[Object]) -> Option<(std::cmp::Ordering, bool)> { +/// for a naive/aware pair (equality says unequal, ordering raises) and, +/// for equality (`eq`), for a zone's value whose offset depends on its +/// `fold` (a time in a gap or a fold never equals one of another zone). +fn dt_cmp_raw(a: &[Object], eq: bool) -> Option<(std::cmp::Ordering, bool)> { let [x, y] = a else { return None }; let st = state_of(x)?; let (xi, yi) = (inst(x, KIND_DATETIME)?, inst(y, KIND_DATETIME)?); @@ -1967,14 +2434,19 @@ fn dt_cmp_raw(a: &[Object]) -> Option<(std::cmp::Ordering, bool)> { if std::ptr::eq(tf, tg) { return Some(((wf >> 1).cmp(&(wg >> 1)), true)); } - return match (tz_of_ptr(tf, st)?, tz_of_ptr(tg, st)?) { - (Tz::Naive, Tz::Naive) => Some(((wf >> 1).cmp(&(wg >> 1)), true)), - (Tz::Fixed(a), Tz::Fixed(b)) => Some(( - (i128::from(word_us(wf)) - a).cmp(&(i128::from(word_us(wg)) - b)), - true, - )), - _ => Some((std::cmp::Ordering::Equal, false)), - }; + match (tz_of_ptr(tf, st), tz_of_ptr(tg, st)) { + (Some(Tz::Naive), Some(Tz::Naive)) => { + return Some(((wf >> 1).cmp(&(wg >> 1)), true)); + } + (Some(Tz::Fixed(a)), Some(Tz::Fixed(b))) => { + return Some(( + (i128::from(word_us(wf)) - a).cmp(&(i128::from(word_us(wg)) - b)), + true, + )); + } + // (A zone's offset is read with the fields, below.) + _ => {} + } } let f = dt_fields(xi, st)?; let g = dt_fields(yi, st)?; @@ -1984,22 +2456,38 @@ fn dt_cmp_raw(a: &[Object]) -> Option<(std::cmp::Ordering, bool)> { if f.tz.is_same(&g.tz) { return Some((dt_us(&f).cmp(&dt_us(&g)), true)); } - match (tz_of(&f.tz, st)?, tz_of(&g.tz, st)?) { - (Tz::Naive, Tz::Naive) => Some((dt_us(&f).cmp(&dt_us(&g)), true)), - (Tz::Fixed(a), Tz::Fixed(b)) => Some(((dt_us(&f) - a).cmp(&(dt_us(&g) - b)), true)), + // Each side's offset; for equality, `None` inside when its `fold` + // changes it. + let side = |f: &Dt| -> Option> { + match tz_of(&f.tz, st) { + Some(tz) => Some(Some(tz)), + None => { + let off = zone_off(f, st, f.fold)?; + if eq && zone_off(f, st, 1 - f.fold)? != off { + return Some(None); + } + Some(Some(Tz::Fixed(off))) + } + } + }; + match (side(&f)?, side(&g)?) { + (Some(Tz::Naive), Some(Tz::Naive)) => Some((dt_us(&f).cmp(&dt_us(&g)), true)), + (Some(Tz::Fixed(a)), Some(Tz::Fixed(b))) => { + Some(((dt_us(&f) - a).cmp(&(dt_us(&g) - b)), true)) + } _ => Some((std::cmp::Ordering::Equal, false)), } } fn dt_eq(a: &[Object]) -> Option> { - let (o, comparable) = dt_cmp_raw(a)?; + let (o, comparable) = dt_cmp_raw(a, true)?; Some(Ok(Object::Bool(comparable && o.is_eq()))) } macro_rules! dt_order { ($name:ident, $pred:expr) => { fn $name(a: &[Object]) -> Option> { - let (o, comparable) = dt_cmp_raw(a)?; + let (o, comparable) = dt_cmp_raw(a, false)?; if !comparable { // The Python code raises (with its own message). return None; @@ -2046,23 +2534,11 @@ fn format_offset(out: &mut Vec, off: i128, sep: &[u8]) { } } -/// `datetime.isoformat(sep='T', timespec='auto')`, positional form. -fn dt_isoformat(a: &[Object]) -> Option> { - let (x, rest) = a.split_first()?; - let sep = match rest.first() { - None => 'T', - Some(Object::Str(s)) => { - let mut cs = s.chars(); - let c = cs.next()?; - if cs.next().is_some() { - return None; - } - c - } - Some(_) => return None, - }; - let spec = match rest.get(1) { - None => "auto", +/// The `timespec` names `isoformat` takes, the omitted one (`Unbound`, a +/// keyword call's gap) as `auto`. +fn timespec_of(v: Option<&Object>) -> Option<&'static str> { + Some(match v { + None | Some(Object::Unbound) => "auto", Some(Object::Str(s)) => match &**s { "auto" => "auto", "hours" => "hours", @@ -2073,45 +2549,98 @@ fn dt_isoformat(a: &[Object]) -> Option> { _ => return None, }, Some(_) => return None, - }; - if rest.len() > 2 { - return None; - } - let st = state_of(x)?; - let f = dt_fields(inst(x, KIND_DATETIME)?, st)?; - if !valid_date(f.y, f.m, f.d) { - return None; - } - let tz = tz_of(&f.tz, st)?; - let mut out = Vec::with_capacity(40); - push_ymd(&mut out, f.y, f.m, f.d); - out.extend_from_slice(sep.encode_utf8(&mut [0; 4]).as_bytes()); + }) +} + +/// `_format_time(hh, mm, ss, us, timespec)`. +fn push_clock(out: &mut Vec, hh: i64, mm: i64, ss: i64, us: i64, spec: &str) { match spec { - "hours" => push_num(&mut out, f.hh, 2), + "hours" => push_num(out, hh, 2), "minutes" => { - push_num(&mut out, f.hh, 2); + push_num(out, hh, 2); out.push(b':'); - push_num(&mut out, f.mm, 2); + push_num(out, mm, 2); } "milliseconds" => { - push_hms(&mut out, f.hh, f.mm, f.ss); + push_hms(out, hh, mm, ss); out.push(b'.'); - push_num(&mut out, f.us / 1000, 3); + push_num(out, us / 1000, 3); } "microseconds" => { - push_hms(&mut out, f.hh, f.mm, f.ss); + push_hms(out, hh, mm, ss); out.push(b'.'); - push_num(&mut out, f.us, 6); + push_num(out, us, 6); } - "seconds" => push_hms(&mut out, f.hh, f.mm, f.ss), + "seconds" => push_hms(out, hh, mm, ss), _ => { - push_hms(&mut out, f.hh, f.mm, f.ss); - if f.us != 0 { + push_hms(out, hh, mm, ss); + if us != 0 { out.push(b'.'); - push_num(&mut out, f.us, 6); + push_num(out, us, 6); } } } +} + +/// `datetime.isoformat(sep='T', timespec='auto')`, positional form (an +/// `Unbound` argument is an omitted one). +fn dt_isoformat(a: &[Object]) -> Option> { + let (x, rest) = a.split_first()?; + let sep = match rest.first() { + None | Some(Object::Unbound) => 'T', + Some(Object::Str(s)) => { + let mut cs = s.chars(); + let c = cs.next()?; + if cs.next().is_some() { + return None; + } + c + } + Some(_) => return None, + }; + let spec = timespec_of(rest.get(1))?; + if rest.len() > 2 { + return None; + } + let st = state_of(x)?; + let f = dt_fields(inst(x, KIND_DATETIME)?, st)?; + if !valid_date(f.y, f.m, f.d) { + return None; + } + let tz = tz_at(&f, st)?; + let mut out = Vec::with_capacity(40); + push_ymd(&mut out, f.y, f.m, f.d); + out.extend_from_slice(sep.encode_utf8(&mut [0; 4]).as_bytes()); + push_clock(&mut out, f.hh, f.mm, f.ss, f.us, spec); + if let Tz::Fixed(off) = tz { + format_offset(&mut out, off, b":"); + } + Some(Ok(text_object(&out))) +} + +/// `str(t)`: [`time_isoformat_spec`] with the default `timespec`. +fn time_isoformat(a: &[Object]) -> Option> { + let [_] = a else { return None }; + time_isoformat_spec(a) +} + +/// `time.isoformat(timespec='auto')`, positional form (an `Unbound` +/// argument is an omitted one): the fields to the `timespec`, and a fixed +/// zone's offset. +fn time_isoformat_spec(a: &[Object]) -> Option> { + let (x, rest) = a.split_first()?; + if rest.len() > 1 { + return None; + } + let spec = timespec_of(rest.first())?; + let st = state_of(x)?; + let f = time_fields(inst(x, KIND_TIME)?, st)?; + if !f.valid() { + return None; + } + let tz = tz_of(&f.tz, st)?; + let mut out = Vec::with_capacity(24); + push_clock(&mut out, f.hh, f.mm, f.ss, f.us, spec); if let Tz::Fixed(off) = tz { format_offset(&mut out, off, b":"); } @@ -2194,7 +2723,7 @@ fn dt_strftime(a: &[Object]) -> Option> { if !valid_date(f.y, f.m, f.d) { return None; } - let tz = tz_of(&f.tz, st)?; + let tz = tz_at(&f, st)?; let s = strftime_numeric( f.y, f.m, @@ -2345,12 +2874,502 @@ fn parse_hms(t: &[u8]) -> Option<(i64, i64, i64, i64)> { Some((hh, mm, ss, us)) } -/// An exact `timezone` with the fixed offset `us` (non-zero, in range) -/// and no name. -fn new_timezone(st: &State, us: i128) -> Option { - let off = new_td(st, 0, 0, us)?.ok()?; - let cls = st.timezone.upgrade()?; - let n = &st.names; +// --------------------------------------------------------------------- +// Local time: `_pydatetime`'s `_mktime` and `_local_timezone`, through +// the libc `localtime_r` that `time.localtime` uses. + +/// Seconds since the epoch of naive wall-clock fields. +fn epoch_secs(y: i64, m: i64, d: i64, hh: i64, mm: i64, ss: i64) -> i64 { + (ymd2ord(y, m, d) - ymd2ord(1970, 1, 1)) * 86_400 + hh * 3600 + mm * 60 + ss +} + +/// `time.localtime(u)`'s wall-clock fields, `tm_gmtoff` and `tm_zone`; +/// `None` where it would raise (or a leap second, which `datetime` +/// rejects). +#[cfg(unix)] +fn local_tm(u: i64) -> Option<([i64; 6], i64, Option>)> { + let t = libc::time_t::try_from(u).ok()?; + // SAFETY: plain C structs, filled by `localtime_r`. + let mut tm: libc::tm = unsafe { std::mem::zeroed() }; + if unsafe { libc::localtime_r(&raw const t, &raw mut tm) }.is_null() || tm.tm_sec > 59 { + return None; + } + let zone = (!tm.tm_zone.is_null()) + // SAFETY: a NUL-terminated name libc keeps for the process. + .then(|| unsafe { std::ffi::CStr::from_ptr(tm.tm_zone) }.to_bytes().to_vec()); + let f = [ + i64::from(tm.tm_year) + 1900, + i64::from(tm.tm_mon) + 1, + i64::from(tm.tm_mday), + i64::from(tm.tm_hour), + i64::from(tm.tm_min), + i64::from(tm.tm_sec), + ]; + Some((f, tm.tm_gmtoff as i64, zone)) +} + +#[cfg(not(unix))] +fn local_tm(_u: i64) -> Option<([i64; 6], i64, Option>)> { + None +} + +/// `_mktime()` of naive fields with `fold`: the POSIX timestamp whose +/// local time they are (`_pydatetime`'s search, step for step). +fn mktime(f: &Dt, fold: i64) -> Option { + const MAX_FOLD_SECONDS: i64 = 24 * 3600; + let t = epoch_secs(f.y, f.m, f.d, f.hh, f.mm, f.ss); + let local = |u: i64| -> Option { + let ([y, m, d, hh, mm, ss], _, _) = local_tm(u)?; + Some(epoch_secs(y, m, d, hh, mm, ss)) + }; + let a = local(t)? - t; + let u1 = t - a; + let t1 = local(u1)?; + let b = if t1 == t { + let u2 = u1 + + if fold == 0 { + -MAX_FOLD_SECONDS + } else { + MAX_FOLD_SECONDS + }; + let b = local(u2)? - u2; + if a == b { + return Some(u1); + } + b + } else { + t1 - u1 + }; + let u2 = t - b; + if local(u2)? == t { + return Some(u2); + } + if t1 == t { + return Some(u1); + } + // In a gap: neither offset solves it. + Some(if fold == 0 { u1.max(u2) } else { u1.min(u2) }) +} + +/// The timestamp `_local_timezone` reads the local zone at, for naive +/// fields (`None` for an aware value, whose own offset decides). +fn local_ts(f: &Dt) -> Option { + let ts = mktime(f, f.fold)?; + let ts2 = mktime(f, 1 - f.fold)?; + // A gap or a fold. + Some(if ts2 != ts && (ts2 > ts) == (f.fold == 1) { + ts2 + } else { + ts + }) +} + +/// Microseconds since the epoch of fields at a fixed UTC offset `off`. +fn epoch_us(f: &Dt, off: i128) -> i128 { + dt_us(f) - off - i128::from(ymd2ord(1970, 1, 1)) * US_PER_DAY +} + +/// `datetime.timestamp()` of a naive or fixed-offset value. +fn dt_timestamp(a: &[Object]) -> Option> { + let [x] = a else { return None }; + let st = state_of(x)?; + let f = dt_fields(inst(x, KIND_DATETIME)?, st)?; + if !valid_date(f.y, f.m, f.d) { + return None; + } + let secs = match tz_at(&f, st)? { + Tz::Naive => mktime(&f, f.fold)? as f64 + f.us as f64 / 1e6, + Tz::Fixed(off) => { + // (Exact as a float, so the division rounds as the Python + // code's integer true division does.) + let n = epoch_us(&f, off); + if n.unsigned_abs() >= 1 << 53 { + return None; + } + n as f64 / 1e6 + } + }; + Some(Ok(Object::Float(secs))) +} + +/// `datetime.replace(...)` of the fields by position (`year` to `tzinfo`; +/// an absent or `Unbound` one keeps the value's, as does `None` for any +/// but `tzinfo`, whose own default is `True`), `tzinfo` `None` or an +/// instance of a `tzinfo` subclass. `fold` (keyword-only) is the Python +/// method's. +fn dt_replace(a: &[Object]) -> Option> { + let (x, rest) = a.split_first()?; + if rest.len() > 8 { + return None; + } + let st = state_of(x)?; + let mut f = dt_fields(inst(x, KIND_DATETIME)?, st)?; + for (i, v) in rest.iter().enumerate() { + if matches!(v, Object::Unbound) || (i < 7 && matches!(v, Object::None)) { + continue; + } + if i == 7 { + if !matches!(v, Object::Bool(true)) { + tz_ok(v, st)?; + f.tz = v.clone(); + } + continue; + } + let v = as_int(v)?; + match i { + 0 => f.y = v, + 1 => f.m = v, + 2 => f.d = v, + 3 => f.hh = v, + 4 => f.mm = v, + 5 => f.ss = v, + _ => f.us = v, + } + } + let ok = valid_date(f.y, f.m, f.d) + && (0..24).contains(&f.hh) + && (0..60).contains(&f.mm) + && (0..60).contains(&f.ss) + && (0..1_000_000).contains(&f.us); + if !ok { + return None; + } + Some(Ok(new_dt(st, f)?)) +} + +/// `datetime.astimezone(tz)` of a naive, fixed-offset or zone value, to +/// an exact `timezone`, a zone (see `stdlib::zoneinfo_native`) or (no +/// `tz`) the local zone. +fn dt_astimezone(a: &[Object]) -> Option> { + let (x, rest) = a.split_first()?; + let target = match rest { + [] | [Object::None | Object::Unbound] => None, + [t] => Some(t), + _ => return None, + }; + let st = state_of(x)?; + let f = dt_fields(inst(x, KIND_DATETIME)?, st)?; + if !valid_date(f.y, f.m, f.d) { + return None; + } + let mine = tz_at(&f, st)?; + let my_off = match mine { + Tz::Fixed(off) => off, + Tz::Naive => i128::from(local_tm(local_ts(&f)?)?.1) * 1_000_000, + }; + // (A zone's offset, `None` here, is settled from the UTC value.) + let (tz, tz_off) = match target { + Some(t) => match tz_of(t, st) { + Some(Tz::Fixed(off)) => (t.clone(), Some(off)), + Some(Tz::Naive) => return None, + None if crate::stdlib::zoneinfo_native::is_zone(t) => (t.clone(), None), + None => return None, + }, + None => { + let ts = match mine { + Tz::Naive => local_ts(&f)?, + Tz::Fixed(off) => i64::try_from(epoch_us(&f, off).div_euclid(1_000_000)).ok()?, + }; + let (_, gmtoff, zone) = local_tm(ts)?; + let name = Object::from_str(String::from_utf8(zone?).ok()?); + let off = i128::from(gmtoff) * 1_000_000; + (new_named_timezone(st, off, name)?, Some(off)) + } + }; + if matches!(mine, Tz::Fixed(_)) && f.tz.is_same(&tz) { + return Some(Ok(x.clone())); + } + // (Two steps, as the Python code takes them, so an intermediate + // overflow raises there.) + let utc = dt_shift(f, -my_off)?; + let g = match tz_off { + Some(off) => { + let mut g = dt_shift(utc, off)?; + g.tz = tz; + g + } + None => zone_from_utc(st, utc, &tz)?, + }; + Some(Ok(new_dt(st, g)?)) +} + +/// `_fromtimestamp(t, tz is not None, tz)` of whole seconds `t` and +/// microseconds `us` (rounded and carried as `_fromtimestamp` does) into +/// an exact `datetime`, for no `tzinfo` (local time, its fold found as +/// the Python code finds it), an exact `timezone` (UTC, then +/// `timezone.fromutc`) or a zone (UTC, then what its `fromutc` settles). +/// `None` for anything the Python method must run. +fn dt_from_epoch(st: &State, t: i64, us: i64, tz: &Object) -> Option { + // (A zone's offset, `None` here, is settled from the UTC value.) + let off = match tz_of(tz, st) { + Some(Tz::Naive) => return dt_from_epoch_local(st, t, us), + Some(Tz::Fixed(off)) => Some(off), + None if crate::stdlib::zoneinfo_native::is_zone(tz) => None, + None => return None, + }; + let ord = t.div_euclid(86_400) + ymd2ord(1970, 1, 1); + if !(1..=MAX_ORDINAL).contains(&ord) { + return None; + } + let (y, m, d) = ord2ymd(ord); + let rest = t.rem_euclid(86_400); + let f = Dt { + y, + m, + d, + hh: rest / 3600, + mm: rest % 3600 / 60, + ss: rest % 60, + us, + tz: Object::None, + fold: 0, + }; + let g = match off { + Some(off) => { + let mut g = dt_shift(f, off)?; + g.tz = tz.clone(); + g + } + None => zone_from_utc(st, f, tz)?, + }; + new_dt(st, g) +} + +/// [`dt_from_epoch`] for no `tzinfo`: local time. +fn dt_from_epoch_local(st: &State, t: i64, us: i64) -> Option { + // As of version 2015f max fold in IANA database is 23 hours + // (`_fromtimestamp`'s probe a day back). + const MAX_FOLD_SECONDS: i64 = 24 * 3600; + // (A date out of range is the Python method's to reject.) + let local = |u: i64| -> Option
{ + let ([y, m, d, hh, mm, ss], _, _) = local_tm(u)?; + if !valid_date(y, m, d) { + return None; + } + Some(Dt { + y, + m, + d, + hh, + mm, + ss, + us, + tz: Object::None, + fold: 0, + }) + }; + let mut f = local(t)?; + if !(cfg!(windows) && t < MAX_FOLD_SECONDS) { + let probe1 = local(t.checked_sub(MAX_FOLD_SECONDS)?)?; + let trans = dt_us(&f) - dt_us(&probe1) - i128::from(MAX_FOLD_SECONDS) * 1_000_000; + if trans < 0 { + let t2 = t.checked_add(i64::try_from(trans.div_euclid(1_000_000)).ok()?)?; + if dt_us(&local(t2)?) == dt_us(&f) { + f.fold = 1; + } + } + } + new_dt(st, f) +} + +/// `dt.utcoffset()` (`part` 0), `dt.dst()` (1) and `dt.tzname()` (2): +/// `None` for a naive value, a zone's answer for its local time (checked +/// as the Python methods check it), an exact `timezone`'s offset and its +/// lack of a daylight shift. +fn dt_zone_part(a: &[Object], part: u8) -> Option> { + let [x] = a else { return None }; + let st = state_of(x)?; + let f = dt_fields(inst(x, KIND_DATETIME)?, st)?; + if matches!(f.tz, Object::None) { + return Some(Ok(Object::None)); + } + if let Some(tz) = inst(&f.tz, KIND_TIMEZONE) { + if !std::ptr::eq(tz.cls_raw(), st.timezone.as_ptr()) { + return None; + } + return match part { + 0 => { + let off = tz + .slots + .try_borrow() + .ok()? + .get_hinted(TZ_OFFSET, &st.names.offset)? + .clone(); + off_us(&off, st)?; + Some(Ok(off)) + } + 1 => Some(Ok(Object::None)), + _ => None, + }; + } + let info = zone_info(&f, f.fold)?; + match part { + 0 => { + let off = info.utcoff()?; + off_us(&off, st)?; + Some(Ok(off)) + } + 1 => { + let off = info.dstoff()?; + if !matches!(off, Object::None) { + off_us(&off, st)?; + } + Some(Ok(off)) + } + _ => { + let name = info.tzname()?; + matches!(name, Object::None | Object::Str(_)).then_some(Ok(name)) + } + } +} + +fn dt_utcoffset(a: &[Object]) -> Option> { + dt_zone_part(a, 0) +} + +fn dt_dst(a: &[Object]) -> Option> { + dt_zone_part(a, 1) +} + +fn dt_tzname(a: &[Object]) -> Option> { + dt_zone_part(a, 2) +} + +/// A timestamp's whole seconds and microseconds as `_fromtimestamp` +/// splits a `float` (`modf`, the fraction rounded half to even, carried) +/// or takes an `int`; `None` for anything else or out of range. +fn epoch_parts(t: &Object) -> Option<(i64, i64)> { + match *t { + Object::Int(i) => Some((i, 0)), + Object::Bool(b) => Some((i64::from(b), 0)), + Object::Float(x) => { + if !x.is_finite() || x.abs() >= 1e15 { + return None; + } + let whole = x.trunc(); + let mut us = ((x - whole) * 1e6).round_ties_even() as i64; + let mut secs = whole as i64; + if us >= 1_000_000 { + secs += 1; + us -= 1_000_000; + } else if us < 0 { + secs -= 1; + us += 1_000_000; + } + Some((secs, us)) + } + _ => None, + } +} + +/// The system clock now: whole seconds and microseconds (the nanoseconds +/// rounded half to even, as `datetime.now()` in CPython rounds them). +fn clock_now() -> Option<(i64, i64)> { + let d = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .ok()?; + let mut secs = i64::try_from(d.as_secs()).ok()?; + let nanos = i64::from(d.subsec_nanos()); + let (q, r) = (nanos / 1000, nanos % 1000); + let mut us = q + i64::from(r > 500 || (r == 500 && q % 2 == 1)); + if us == 1_000_000 { + secs += 1; + us = 0; + } + Some((secs, us)) +} + +/// `datetime.fromtimestamp(t, tz=None)` of the exact class. +fn dt_fromtimestamp(a: &[Object]) -> Option> { + let (cls, t, tz) = match a { + [Object::Type(c), t] => (c, t, &Object::None), + [Object::Type(c), t, tz] => (c, t, tz), + _ => return None, + }; + let st = state_of_cls(cls)?; + if !std::ptr::eq(Rc::as_ptr(cls), st.datetime.as_ptr()) { + return None; + } + let (secs, us) = epoch_parts(t)?; + Some(Ok(dt_from_epoch(st, secs, us, tz)?)) +} + +/// `datetime.now(tz=None)` of the exact class. +fn dt_now(a: &[Object]) -> Option> { + let (cls, tz) = match a { + [Object::Type(c)] => (c, &Object::None), + [Object::Type(c), tz] => (c, tz), + _ => return None, + }; + let st = state_of_cls(cls)?; + if !std::ptr::eq(Rc::as_ptr(cls), st.datetime.as_ptr()) { + return None; + } + let (secs, us) = clock_now()?; + Some(Ok(dt_from_epoch(st, secs, us, tz)?)) +} + +/// `date.today()` of the exact class: `time.localtime()`'s date. +/// `date.fromisoformat` for an ASCII `YYYY-MM-DD` or `YYYYMMDD` naming a +/// real date, on the exact class. Anything else (week dates, a subclass, +/// a bad field) declines to the Python method, which raises its errors. +fn date_fromisoformat(a: &[Object]) -> Option> { + let [Object::Type(cls), Object::Str(s)] = a else { + return None; + }; + let st = state_of_cls(cls)?; + if !std::ptr::eq(Rc::as_ptr(cls), st.date.as_ptr()) { + return None; + } + let b = s.as_bytes(); + let (y, m, d) = match b.len() { + 10 if b[4] == b'-' && b[7] == b'-' => { + (digits(&b[0..4])?, digits(&b[5..7])?, digits(&b[8..10])?) + } + 8 => (digits(&b[0..4])?, digits(&b[4..6])?, digits(&b[6..8])?), + _ => return None, + }; + if !valid_date(y, m, d) { + return None; + } + Some(Ok(new_date(st, y, m, d)?)) +} + +fn date_today(a: &[Object]) -> Option> { + let [Object::Type(cls)] = a else { return None }; + let st = state_of_cls(cls)?; + if !std::ptr::eq(Rc::as_ptr(cls), st.date.as_ptr()) { + return None; + } + let (secs, _) = clock_now()?; + let ([y, m, d, ..], _, _) = local_tm(secs)?; + if !valid_date(y, m, d) { + return None; + } + Some(Ok(new_date(st, y, m, d)?)) +} + +/// An exact `timezone` with the offset `us` and the name `name`, as +/// `timezone(offset, name)` builds it (even for a zero offset). +fn new_named_timezone(st: &State, us: i128, name: Object) -> Option { + if us.unsigned_abs() >= US_PER_DAY as u128 { + return None; + } + let off = new_td(st, 0, 0, us)?.ok()?; + let cls = st.timezone.upgrade()?; + let n = &st.names; + Some(instance( + cls, + vec![entry(&n.offset, off), entry(&n.name, name)], + )) +} + +/// An exact `timezone` with the fixed offset `us` (non-zero, in range) +/// and no name. +fn new_timezone(st: &State, us: i128) -> Option { + let off = new_td(st, 0, 0, us)?.ok()?; + let cls = st.timezone.upgrade()?; + let n = &st.names; Some(instance( cls, vec![entry(&n.offset, off), entry(&n.name, Object::None)], @@ -2439,17 +3458,22 @@ pub(crate) fn leaf_compare( b: &Object, ) -> Option> { use weavepy_compiler::CompareKind as C; - let (Object::Instance(i), Object::Instance(j)) = (a, b) else { + let Object::Instance(i) = a else { return None; }; - let (ci, cj) = (i.cls_raw(), j.cls_raw()); + let ci = i.cls_raw(); let kind = ci.native_kind.get(); - if kind == 0 || cj.native_kind.get() != kind { - return None; - } + // (A `Decimal` compares with numbers too.) if kind == KIND_DECIMAL { return super::decimal_native::leaf_compare(op, a, b); } + let Object::Instance(j) = b else { + return None; + }; + let cj = j.cls_raw(); + if kind == 0 || cj.native_kind.get() != kind { + return None; + } let st = state_of_cls(ci)?; if !verified(st, ci, kind) || !verified(st, cj, kind) { return None; @@ -2459,7 +3483,8 @@ pub(crate) fn leaf_compare( let r = match kind { KIND_TIMEDELTA => td_cmp(&args[..]).map(|o| (o, true)), KIND_DATE => date_cmp(&args[..]).map(|o| (o, true)), - KIND_DATETIME => dt_cmp_raw(&args[..]), + KIND_TIME => time_cmp(&args[..]).map(|o| (o, true)), + KIND_DATETIME => dt_cmp_raw(&args[..], matches!(op, C::Eq | C::NotEq)), _ => None, }?; let (o, comparable) = r; @@ -2475,21 +3500,28 @@ pub(crate) fn leaf_compare( } /// The function under the native class method `name` of the exact class -/// `cls` while the class still has it (`datetime.fromisoformat`), for -/// the dispatch loop to bind to `cls` without the descriptor protocol. +/// `cls` while the class still has it (`datetime.fromisoformat`, +/// `datetime.now`, `date.today`, …), for the dispatch loop to bind to +/// `cls` without the descriptor protocol. pub(crate) fn type_classmethod(cls: &TypeObject, name: &SharedStr) -> Option { let kind = cls.native_kind.get(); - if kind != KIND_DATETIME { + if kind != KIND_DATETIME && kind != KIND_DATE { return None; } let st = state_of_cls(cls)?; - if !SharedStr::ptr_eq(name, &st.names.f_fromisoformat) - || !std::ptr::eq(cls, st.datetime.as_ptr()) - || !verified(st, cls, kind) - { + let exact = if kind == KIND_DATETIME { + st.datetime.as_ptr() + } else { + st.date.as_ptr() + }; + if !std::ptr::eq(cls, exact) || !verified(st, cls, kind) { return None; } - st.fromiso.get().cloned() + st.classmethods + .get()? + .iter() + .find(|(k, n, _, _)| *k == kind && SharedStr::ptr_eq(name, n)) + .map(|(_, _, f, _)| f.clone()) } /// The fast half of `function` bound to `receiver` when that is a native @@ -2499,13 +3531,16 @@ pub(crate) fn bound_fast(function: &Object, receiver: &Object) -> Option { let (Object::Builtin(f), Object::Type(cls)) = (function, receiver) else { return None; }; - if cls.native_kind.get() != KIND_DATETIME { + let kind = cls.native_kind.get(); + if kind != KIND_DATETIME && kind != KIND_DATE { return None; } - match state_of_cls(cls)?.fromiso.get()? { - Object::Builtin(g) if Rc::ptr_eq(f, g) => Some(dt_fromisoformat), - _ => None, - } + state_of_cls(cls)? + .classmethods + .get()? + .iter() + .find(|(_, _, g, _)| matches!(g, Object::Builtin(g) if Rc::ptr_eq(f, g))) + .map(|&(.., fast)| fast) } /// A public field (`dt.hour`, `d.year`, …) of a natively served instance @@ -2513,7 +3548,7 @@ pub(crate) fn bound_fast(function: &Object, receiver: &Object) -> Option { pub(crate) fn leaf_field(i: &PyInstance, name: &SharedStr) -> Option { let cls = i.cls_raw(); let kind = cls.native_kind.get(); - if kind != KIND_DATE && kind != KIND_DATETIME && kind != KIND_TIMEDELTA { + if !matches!(kind, KIND_TIMEDELTA | KIND_DATE | KIND_TIME | KIND_DATETIME) { return None; } let st = state_of_cls(cls)?; @@ -2526,6 +3561,27 @@ pub(crate) fn leaf_field(i: &PyInstance, name: &SharedStr) -> Option { let is = |public: &SharedStr, private: &SharedStr| { SharedStr::ptr_eq(name, public) || SharedStr::ptr_eq(name, private) }; + if kind == KIND_TIME { + let (idx, slot) = if is(&n.f_hour, &n.hour) { + (T_HOUR, &n.hour) + } else if is(&n.f_minute, &n.minute) { + (T_MINUTE, &n.minute) + } else if is(&n.f_second, &n.second) { + (T_SECOND, &n.second) + } else if is(&n.f_microsecond, &n.microsecond) { + (T_US, &n.microsecond) + } else if is(&n.f_tzinfo, &n.tzinfo) { + (T_TZINFO, &n.tzinfo) + } else if is(&n.f_fold, &n.fold) { + (T_FOLD, &n.fold) + } else { + return None; + }; + return with_slots(i, |s| match s.as_packed() { + Some(_) => None, + None => Some(s.get_hinted(idx, slot)?.clone()), + }); + } if kind == KIND_TIMEDELTA { let ix = if is(&n.f_days, &n.days) { 0 @@ -2608,26 +3664,45 @@ fn with_interp( /// One native method: its name, the class kind it lives on, and the /// pure fast half. /// A keyword call of a native method whose fast half takes its optional -/// parameters by position, `None` standing for an omitted one: the -/// positional argument list (receiver first), or `None` for the replaced -/// Python method (unknown or repeated names, other methods). +/// parameters by position, `None` standing for an omitted one (`Unbound` +/// where the method tells an omitted one from `None`): `fast` on the +/// positional argument list (receiver first), built on the stack, or +/// `None` for the replaced Python method (unknown or repeated names, +/// other methods, or a fast half that declines). fn kw_positional( key: (u8, &'static str), a: &[Object], kw: &[(String, Object)], -) -> Option> { + fast: Fast, +) -> Option> { let params: &[&str] = match key { (KIND_DATE, "replace") => &["year", "month", "day"], + (KIND_DATETIME, "replace") => &[ + "year", + "month", + "day", + "hour", + "minute", + "second", + "microsecond", + "tzinfo", + ], + (KIND_DATETIME, "astimezone" | "now") => &["tz"], + (KIND_DATETIME, "fromtimestamp") => &["timestamp", "tz"], + (KIND_DATETIME, "isoformat") => &["sep", "timespec"], + (KIND_TIME, "isoformat") => &["timespec"], _ => return None, }; let (recv, pos) = a.split_first()?; - if pos.len() > params.len() { + let n = params.len() + 1; + if pos.len() > params.len() || n > 9 { return None; } - let mut out = Vec::with_capacity(params.len() + 1); - out.push(recv.clone()); - out.extend(pos.iter().cloned()); - out.resize(params.len() + 1, Object::Unbound); + let mut out: [Object; 9] = std::array::from_fn(|_| Object::Unbound); + out[0] = recv.clone(); + for (o, v) in out[1..].iter_mut().zip(pos) { + *o = v.clone(); + } for (name, v) in kw { let ix = params.iter().position(|p| p == name)? + 1; if !matches!(out[ix], Object::Unbound) { @@ -2635,12 +3710,43 @@ fn kw_positional( } out[ix] = v.clone(); } - for o in &mut out { - if matches!(o, Object::Unbound) { - *o = Object::None; + // (A datetime's `replace` tells an omitted `tzinfo` from `None`, and + // `isoformat` an omitted `sep` or `timespec` from a given `None`.) + if !matches!( + key, + (KIND_DATETIME, "replace" | "isoformat") | (KIND_TIME, "isoformat") + ) { + for o in &mut out[..n] { + if matches!(o, Object::Unbound) { + *o = Object::None; + } } } - Some(out) + fast(&out[..n]) +} + +/// The parameters of a native method whose fast half takes keyword calls +/// with an omitted parameter `Unbound` (see `leaf_builtins::register_fast_kw`; +/// `?` marks an optional one). `fold`, keyword-only, isn't listed: a call +/// naming it takes the replaced Python method. +fn kw_names(key: (u8, &'static str)) -> Option { + Some(match key { + (KIND_DATETIME, "isoformat") => &["?sep", "?timespec"], + (KIND_TIME, "isoformat") => &["?timespec"], + (KIND_DATE, "replace") => &["?year", "?month", "?day"], + (KIND_DATETIME, "replace") => &[ + "?year", + "?month", + "?day", + "?hour", + "?minute", + "?second", + "?microsecond", + "?tzinfo", + ], + (KIND_DATETIME, "astimezone") => &["?tz"], + _ => return None, + }) } struct Spec { @@ -2652,6 +3758,90 @@ struct Spec { } const SPECS: &[Spec] = &[ + Spec { + kind: KIND_TIME, + name: "__hash__", + fast: time_hash, + classmethod: false, + }, + Spec { + kind: KIND_TIME, + name: "__eq__", + fast: time_eq, + classmethod: false, + }, + Spec { + kind: KIND_TIME, + name: "__lt__", + fast: time_lt, + classmethod: false, + }, + Spec { + kind: KIND_TIME, + name: "__le__", + fast: time_le, + classmethod: false, + }, + Spec { + kind: KIND_TIME, + name: "__gt__", + fast: time_gt, + classmethod: false, + }, + Spec { + kind: KIND_TIME, + name: "__ge__", + fast: time_ge, + classmethod: false, + }, + Spec { + kind: KIND_TIME, + name: "isoformat", + fast: time_isoformat_spec, + classmethod: false, + }, + Spec { + kind: KIND_TIME, + name: "__str__", + fast: time_isoformat, + classmethod: false, + }, + Spec { + kind: KIND_DATETIME, + name: "time", + fast: dt_time, + classmethod: false, + }, + Spec { + kind: KIND_DATETIME, + name: "timetz", + fast: dt_timetz, + classmethod: false, + }, + Spec { + kind: KIND_DATETIME, + name: "combine", + fast: dt_combine, + classmethod: true, + }, + Spec { + kind: KIND_DATE, + name: "fromordinal", + fast: date_fromordinal, + classmethod: true, + }, + Spec { + kind: KIND_DATE, + name: "__str__", + fast: date_isoformat, + classmethod: false, + }, + Spec { + kind: KIND_DATETIME, + name: "__str__", + fast: dt_str, + classmethod: false, + }, Spec { kind: KIND_TIMEDELTA, name: "__add__", @@ -2712,6 +3902,24 @@ const SPECS: &[Spec] = &[ fast: dt_hash, classmethod: false, }, + Spec { + kind: KIND_DATETIME, + name: "utcoffset", + fast: dt_utcoffset, + classmethod: false, + }, + Spec { + kind: KIND_DATETIME, + name: "dst", + fast: dt_dst, + classmethod: false, + }, + Spec { + kind: KIND_DATETIME, + name: "tzname", + fast: dt_tzname, + classmethod: false, + }, Spec { kind: KIND_TIMEDELTA, name: "__eq__", @@ -2892,12 +4100,54 @@ const SPECS: &[Spec] = &[ fast: dt_date, classmethod: false, }, + Spec { + kind: KIND_DATETIME, + name: "replace", + fast: dt_replace, + classmethod: false, + }, + Spec { + kind: KIND_DATETIME, + name: "timestamp", + fast: dt_timestamp, + classmethod: false, + }, + Spec { + kind: KIND_DATETIME, + name: "astimezone", + fast: dt_astimezone, + classmethod: false, + }, Spec { kind: KIND_DATETIME, name: "fromisoformat", fast: dt_fromisoformat, classmethod: true, }, + Spec { + kind: KIND_DATETIME, + name: "fromtimestamp", + fast: dt_fromtimestamp, + classmethod: true, + }, + Spec { + kind: KIND_DATETIME, + name: "now", + fast: dt_now, + classmethod: true, + }, + Spec { + kind: KIND_DATE, + name: "today", + fast: date_today, + classmethod: true, + }, + Spec { + kind: KIND_DATE, + name: "fromisoformat", + fast: date_fromisoformat, + classmethod: true, + }, ]; /// `install(timedelta, date, time, datetime, timezone)`: put the native @@ -2954,21 +4204,57 @@ pub(crate) fn install(args: &[Object]) -> Result { } let names = Names::new(); let [td_layout, date_layout, dt_layout, _] = layouts().clone(); + let time_layout = time.own_slot_layout().cloned().filter(|layout| { + layout.len() == TIME_SLOTS.len() + && layout + .iter() + .zip(TIME_SLOTS) + .all(|(k, n)| matches!(&k.0, Object::Str(s) if s.as_ref() == n)) + }); + let dt_own = dt.own_slot_layout().cloned().and_then(|layout| { + let at = |name: &str| { + layout + .iter() + .position(|k| matches!(&k.0, Object::Str(s) if s.as_ref() == name)) + .and_then(|i| u8::try_from(i).ok()) + }; + let at = [ + at("_year")?, + at("_month")?, + at("_day")?, + at("_hour")?, + at("_minute")?, + at("_second")?, + at("_microsecond")?, + at("_tzinfo")?, + at("_fold")?, + ]; + Some((layout, at)) + }); + // (`timezone`'s base.) + let tzinfo = match tz.mro.borrow().get(1) { + Some(t) => Rc::downgrade(t), + None => return Err(type_error("install(): timezone has no base")), + }; let state = Rc::new(State { timedelta: Rc::downgrade(td), date: Rc::downgrade(date), + time: Rc::downgrade(time), datetime: Rc::downgrade(dt), timezone: Rc::downgrade(tz), + tzinfo, utc, names, td_layout, date_layout, dt_layout, + time_layout, + dt_own, orig, sealed: Default::default(), expect: std::sync::OnceLock::new(), pool: Pool::default(), - fromiso: std::sync::OnceLock::new(), + classmethods: std::sync::OnceLock::new(), }); // Each class carries the state (a class in `native_ext` resolves to // it from any of its instances). @@ -2978,6 +4264,7 @@ pub(crate) fn install(args: &[Object]) -> Result { .set(crate::rc_unsize!(state.clone() => dyn std::any::Any + Send + Sync)); cls.native_kind.set(*kind); } + let mut classmethods = Vec::new(); for spec in SPECS { let cls = classes .iter() @@ -3003,7 +4290,7 @@ pub(crate) fn install(args: &[Object]) -> Result { if let Some(r) = fast(a) { return r; } - } else if let Some(r) = kw_positional(key, a, kw).and_then(|a| fast(&a)) { + } else if let Some(r) = kw_positional(key, a, kw, fast) { return r; } let f = st_kw.orig.get(&key).cloned().unwrap_or(Object::None); @@ -3011,10 +4298,18 @@ pub(crate) fn install(args: &[Object]) -> Result { })), }); crate::leaf_builtins::register_fast(&b, fast); + // (Its keyword calls bind in place, an omitted parameter + // `Unbound`: see `Interpreter::core_native_kw_call`.) + if let Some(names) = kw_names(key) { + crate::leaf_builtins::register_fast_kw(&b, names, fast); + } let value = if spec.classmethod { - if spec.name == "fromisoformat" { - let _ = state.fromiso.set(Object::Builtin(b.clone())); - } + classmethods.push(( + spec.kind, + interned(spec.name), + Object::Builtin(b.clone()), + fast, + )); Object::ClassMethod(crate::object::MethodWrapper::new(Object::Builtin(b))) } else { Object::Builtin(b) @@ -3023,6 +4318,7 @@ pub(crate) fn install(args: &[Object]) -> Result { .borrow_mut() .insert(DictKey(Object::Str(interned(spec.name))), value); } + let _ = state.classmethods.set(classmethods); for (_, cls) in &classes { cls.bump_attr_version(); } diff --git a/crates/weavepy-vm/src/stdlib/decimal_native.rs b/crates/weavepy-vm/src/stdlib/decimal_native.rs index 99b4053b7..680ff917d 100644 --- a/crates/weavepy-vm/src/stdlib/decimal_native.rs +++ b/crates/weavepy-vm/src/stdlib/decimal_native.rs @@ -139,7 +139,7 @@ fn digits_u128(v: u128) -> u64 { fn digits_big(b: &BigUint) -> u64 { let bits = b.bits(); let t = (bits * 1233) >> 12; - if *b >= pow10_big(t) { + if *b >= *pow10_big(t) { t + 1 } else { t @@ -161,8 +161,26 @@ fn divrem_pow10_u128(v: u128, k: u64) -> (u128, u128) { (v / p, v % p) } -fn pow10_big(k: u64) -> BigUint { - num_traits::pow(BigUint::from(10u32), k as usize) +/// The largest power of ten [`pow10_big`] keeps. +const POW10_KEPT: usize = 256; + +/// `10**k`: from a table made once for the exponents arithmetic at +/// ordinary precisions asks for, computed for a larger one. +fn pow10_big(k: u64) -> std::borrow::Cow<'static, BigUint> { + static TABLE: std::sync::OnceLock> = std::sync::OnceLock::new(); + let table = TABLE.get_or_init(|| { + let mut t = Vec::with_capacity(POW10_KEPT + 1); + let mut p = BigUint::from(1u32); + for _ in 0..=POW10_KEPT { + t.push(p.clone()); + p *= 10u32; + } + t + }); + match usize::try_from(k).ok().and_then(|k| table.get(k)) { + Some(p) => std::borrow::Cow::Borrowed(p), + None => std::borrow::Cow::Owned(num_traits::pow(BigUint::from(10u32), k as usize)), + } } impl Coef { @@ -216,7 +234,7 @@ impl Coef { if self.ndigits().saturating_add(k) > MAX_DIGITS { return None; } - Some(Coef::from_big(self.to_big() * pow10_big(k))) + Some(Coef::from_big(self.to_big() * &*pow10_big(k))) } /// `divmod(self, 10**k)`. @@ -666,6 +684,617 @@ fn fix(d: Fin, c: &CtxP, sig: &mut u16) -> Option { Some(d) } +/// `Decimal.sqrt` of a finite value that isn't negative: the root to one +/// digit more than the precision, rounded down, with its last digit +/// nudged off 0 or 5 when the root is inexact, so the final half-even +/// rounding is correct and raises the right flags. +fn sqrt(x: &Fin, c: &CtxP, sig: &mut u16) -> Option { + let exp = i128::from(x.exp); + if x.is_zero() { + // (`sqrt(-0)` is `-0`; the exponent halves, rounding down.) + return fix(Fin::new(x.sign, Coef::ZERO, exp >> 1)?, c, sig); + } + let prec = c.prec + 1; + if x.sign == 1 || 2 * prec > i128::from(MAX_DIGITS) { + return None; + } + // `x` as `v * 100**e`, with `l` base-100 digits in `v`. + let len = i128::from(x.coef.ndigits()); + let mut e = exp >> 1; + let (mut v, l) = if exp & 1 != 0 { + (x.coef.to_big() * 10u32, (len >> 1) + 1) + } else { + (x.coef.to_big(), (len + 1) >> 1) + }; + // Scaled so that `v` has exactly `prec` base-100 digits. + let shift = prec - l; + let mut exact = true; + if shift >= 0 { + v *= &*pow10_big(2 * shift as u64); + } else { + let (q, r) = v.div_rem(&pow10_big((-2 * shift) as u64)); + exact = r.is_zero(); + v = q; + } + e -= shift; + let mut n = v.sqrt(); + exact = exact && &n * &n == v; + if exact { + // An exact root goes back to the ideal exponent. + if shift >= 0 { + n /= &*pow10_big(shift as u64); + } else { + n *= &*pow10_big((-shift) as u64); + } + e += shift; + } else if (&n % 5u32).is_zero() { + n += 1u32; + } + let ans = Fin::new(0, Coef::from_big(n), e)?; + fix( + ans, + &CtxP { + round: Round::HalfEven, + ..*c + }, + sig, + ) +} + +// --------------------------------------------------------------------- +// The integer algorithms behind `exp`, `ln` and `log10`: the Python +// module's (`_ilog`, `_iexp`, `_dlog`, `_dlog10`, `_dexp`), step for +// step, so a result agrees with the Python methods' digit for digit. + +/// The largest precision the transcendental methods serve here (the +/// work grows with its square, and nothing interrupts it). +const TRANSCENDENTAL_PREC: i128 = 1000; + +/// `10**k` as a signed integer, for a `k` these algorithms reach. +fn spow10(k: i128) -> Option { + let k = u64::try_from(k).ok().filter(|k| *k <= 2 * MAX_DIGITS)?; + Some(BigInt::from(pow10_big(k).into_owned())) +} + +/// `len(str(abs(v)))`. +fn dec_len(v: &BigInt) -> i128 { + if v.is_zero() { + 1 + } else { + i128::from(digits_big(v.magnitude())) + } +} + +/// `_div_nearest(a, b)`: the integer closest to `a / b` for a positive +/// `b`, an even one on a tie. +fn div_nearest(a: &BigInt, b: &BigInt) -> BigInt { + let (q, r) = a.div_mod_floor(b); + if (r << 1u32) + BigInt::from(u8::from(q.is_odd())) > *b { + q + 1 + } else { + q + } +} + +/// `_rshift_nearest(x, shift)`: the integer closest to `x / 2**shift`, +/// an even one on a tie. +fn rshift_nearest(x: &BigInt, shift: u64) -> BigInt { + let q: BigInt = x >> shift; + let r = x - (&q << shift); + let b = BigInt::from(1u8) << shift; + if (r << 1u32) + BigInt::from(u8::from(q.is_odd())) > b { + q + 1 + } else { + q + } +} + +/// `_sqrt_nearest(n, a)`: the integer closest to the square root of a +/// positive `n`, by Newton's method from the approximation `a`. +fn sqrt_nearest(n: &BigInt, mut a: BigInt) -> BigInt { + let mut b = BigInt::zero(); + while a != b { + // (`a - (-n // a) >> 1`.) + let next: BigInt = (&a - (-n).div_floor(&a)) >> 1u32; + b = std::mem::replace(&mut a, next); + } + a +} + +/// The number of series terms `_ilog` and `_iexp` take for the scale +/// `m`: `ceil(10 * len(str(m)) / 24)`. +fn series_terms(m: &BigInt) -> i128 { + (10 * dec_len(m) + 23) / 24 +} + +/// `_ilog(x, M)`: an integer approximation to `M * log(x / M)`. +fn ilog(x: &BigInt, m: &BigInt) -> BigInt { + const L: u64 = 8; + let mut y = x - m; + let mut r: u64 = 0; + loop { + let mag = y.magnitude(); + let more = if r <= L { + BigInt::from(mag << (L - r)) >= *m + } else { + BigInt::from(mag >> (r - L)) >= *m + }; + if !more { + break; + } + let root = sqrt_nearest(&(m * (m + rshift_nearest(&y, r))), m.clone()); + y = div_nearest(&((m * &y) << 1u32), &(m + root)); + r += 1; + } + let t = series_terms(m); + let yshift = rshift_nearest(&y, r); + let mut w = div_nearest(m, &BigInt::from(t)); + for k in (1..t).rev() { + w = div_nearest(m, &BigInt::from(k)) - div_nearest(&(&yshift * &w), m); + } + div_nearest(&(w * y), m) +} + +/// `_log10_digits(p)`: `floor(10**p * log(10))`, from digits kept (and +/// extended when a call needs more) for the process. +fn log10_digits(p: i128) -> Option { + static DIGITS: std::sync::Mutex = std::sync::Mutex::new(String::new()); + let p = usize::try_from(p).ok()?; + let mut digits = DIGITS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if digits.is_empty() { + digits.push_str("23025850929940456840179914546843642076011014886"); + } + if p >= digits.len() { + let mut extra = 3usize; + loop { + let m = spow10((p + extra + 2) as i128)?; + let text = div_nearest(&ilog(&(&m * 10u32), &m), &BigInt::from(100u8)).to_string(); + if !text.ends_with(&"0".repeat(extra)) { + let kept = text.trim_end_matches('0'); + *digits = kept[..kept.len() - 1].to_owned(); + break; + } + extra += 3; + } + } + digits.get(..=p)?.parse().ok() +} + +/// `c * 10**k`, or the nearest integer to it for a negative `k`. +fn scale_nearest(c: &BigInt, k: i128) -> Option { + Some(if k >= 0 { + c * spow10(k)? + } else { + div_nearest(c, &spow10(-k)?) + }) +} + +/// `_dlog10(c, e, p)`: an integer approximation to +/// `10**p * log10(c * 10**e)` for a positive `c`. +fn dlog10(c: &BigInt, e: i128, p: i128) -> Option { + let p = p + 2; + let l = dec_len(c); + let f = e + l - i128::from(e + l >= 1); + let (log_d, log_tenpower) = if p > 0 { + let m = spow10(p)?; + let c = scale_nearest(c, e + p - f)?; + let log_d = div_nearest(&(ilog(&c, &m) * &m), &log10_digits(p)?); + (log_d, BigInt::from(f) * m) + } else { + (BigInt::zero(), div_nearest(&BigInt::from(f), &spow10(-p)?)) + }; + Some(div_nearest(&(log_tenpower + log_d), &BigInt::from(100u8))) +} + +/// `_dlog(c, e, p)`: an integer approximation to +/// `10**p * log(c * 10**e)` for a positive `c`. +fn dlog(c: &BigInt, e: i128, p: i128) -> Option { + let p = p + 2; + let l = dec_len(c); + let f = e + l - i128::from(e + l >= 1); + let log_d = if p > 0 { + ilog(&scale_nearest(c, e + p - f)?, &spow10(p)?) + } else { + BigInt::zero() + }; + let f_log_ten = if f != 0 { + let extra = f.unsigned_abs().to_string().len() as i128 - 1; + if p + extra >= 0 { + div_nearest( + &(BigInt::from(f) * log10_digits(p + extra)?), + &spow10(extra)?, + ) + } else { + BigInt::zero() + } + } else { + BigInt::zero() + }; + Some(div_nearest(&(f_log_ten + log_d), &BigInt::from(100u8))) +} + +/// `_iexp(x, M)`: an integer approximation to `M * exp(x / M)` for a +/// small `x / M`. +fn iexp(x: &BigInt, m: &BigInt) -> BigInt { + const L: u32 = 8; + let r = (x << L).div_floor(m).bits(); + let t = series_terms(m); + let mut y = div_nearest(x, &BigInt::from(t)); + let mut mshift: BigInt = m << r; + for i in (1..t).rev() { + y = div_nearest(&(x * (&mshift + &y)), &(&mshift * BigInt::from(i))); + } + for k in (0..r).rev() { + mshift = m << (k + 2); + y = div_nearest(&(&y * (&y + &mshift)), &mshift); + } + m + y +} + +/// `_dexp(c, e, p)`: `(d, f)` with `d * 10**f` an approximation to +/// `exp(c * 10**e)` of `p` digits. +fn dexp(c: &BigInt, e: i128, p: i128) -> Option<(BigInt, i128)> { + let p = p + 2; + // (`len(str(c))` counts a minus sign.) + let len = dec_len(c) + i128::from(c.sign() == Sign::Minus); + let extra = (e + len - 1).max(0); + let q = p + extra; + let shift = e + q; + let cshift = if shift >= 0 { + c * spow10(shift)? + } else { + c.div_floor(&spow10(-shift)?) + }; + let (quot, rem) = cshift.div_mod_floor(&log10_digits(q)?); + let rem = div_nearest(&rem, &spow10(extra)?); + let d = div_nearest(&iexp(&rem, &spow10(p)?), &BigInt::from(1000u16)); + Some((d, quot.to_i128()? - p + 3)) +} + +/// Whether the approximation `coeff` settles a rounding to `prec` +/// digits: it isn't halfway between two of them (nor exactly one). +fn settles(coeff: &BigInt, prec: i128) -> Option { + let step = BigInt::from(5u8) * spow10(dec_len(coeff) - prec - 1)?; + Some(!(coeff % step).is_zero()) +} + +/// The value `(-1)**neg * |coeff| * 10**exp`, rounded half-even under +/// the context (how the three methods finish). +fn finish_approx(coeff: &BigInt, exp: i128, c: &CtxP, sig: &mut u16) -> Option { + let ans = Fin::new( + u8::from(coeff.sign() == Sign::Minus), + Coef::from_big(coeff.magnitude().clone()), + exp, + )?; + fix( + ans, + &CtxP { + round: Round::HalfEven, + ..*c + }, + sig, + ) +} + +/// `Decimal.exp` of a finite nonzero value. +fn exp(x: &Fin, c: &CtxP, sig: &mut u16) -> Option { + let p = c.prec; + if p > TRANSCENDENTAL_PREC { + return None; + } + let adj = x.adjusted(); + let len = |v: i128| v.to_string().len() as i128; + let (coeff, exp) = if x.sign == 0 && adj > len((c.emax + 1) * 3) { + // (Overflows below.) + (BigInt::from(1u8), c.emax + 1) + } else if x.sign == 1 && adj > len((-c.etiny() + 1) * 3) { + (BigInt::from(1u8), c.etiny() - 1) + } else if x.sign == 0 && adj < -p { + // `1` and a little: rounds to `1.000...1` or `1`. + (spow10(p)? + 1, -p) + } else if x.sign == 1 && adj < -p - 1 { + (spow10(p + 1)? - 1, -p - 1) + } else { + let mut v = BigInt::from(x.coef.to_big()); + if x.sign == 1 { + v = -v; + } + let mut extra = 3; + loop { + let (coeff, exp) = dexp(&v, i128::from(x.exp), p + extra)?; + if settles(&coeff, p)? { + break (coeff, exp); + } + extra += 3; + } + }; + finish_approx(&coeff, exp, c, sig) +} + +/// A lower bound for the adjusted exponent of `ln(x)` +/// (`Decimal._ln_exp_bound`) or of `log10(x)` (`_log10_exp_bound`), for +/// a positive `x` other than one. +fn log_exp_bound(x: &Fin, base10: bool) -> Option { + let len = |v: i128| v.to_string().len() as i128; + let adj = x.adjusted(); + if adj >= 1 { + return Some(len(if base10 { adj } else { adj * 23 / 10 }) - 1); + } + if adj <= -2 { + return Some( + len(if base10 { + -1 - adj + } else { + (-1 - adj) * 23 / 10 + }) - 1, + ); + } + let v = BigInt::from(x.coef.to_big()); + let e = i128::from(x.exp); + let unit = spow10(-e)?; + // (The Python code compares the decimal texts, as strings.) + if adj == 0 { + let num = (&v - unit).to_string(); + let den = if base10 { v * 231u32 } else { v }.to_string(); + let below = i128::from(num < den); + let d = num.len() as i128 - den.len() as i128 - below; + return Some(if base10 { d + 2 } else { d }); + } + let num = (unit - v).to_string(); + Some(if base10 { + num.len() as i128 + e - i128::from(num.as_str() < "231") - 1 + } else { + e + num.len() as i128 - 1 + }) +} + +/// `Decimal.ln` (`base10` false) and `Decimal.log10` of a positive finite +/// value. +fn log(x: &Fin, c: &CtxP, sig: &mut u16, base10: bool) -> Option { + let p = c.prec; + if p > TRANSCENDENTAL_PREC || x.sign == 1 || x.is_zero() { + return None; + } + if base10 { + // A power of ten: its exponent, exactly. + let d = x.coef.to_digits(); + if d.starts_with('1') && d.bytes().skip(1).all(|b| b == b'0') { + return finish_approx(&BigInt::from(x.adjusted()), 0, c, sig); + } + } + let v = BigInt::from(x.coef.to_big()); + let mut places = p - log_exp_bound(x, base10)? + 2; + let coeff = loop { + let coeff = if base10 { + dlog10(&v, i128::from(x.exp), places)? + } else { + dlog(&v, i128::from(x.exp), places)? + }; + if settles(&coeff, p)? { + break coeff; + } + places += 3; + }; + finish_approx(&coeff, -places, c, sig) +} + +/// `Decimal.remainder_near` for finite operands: `None` where the method +/// raises (a zero divisor, a quotient past the precision). +fn remainder_near(x: &Fin, y: &Fin, c: &CtxP, sig: &mut u16) -> Option { + if y.is_zero() { + return None; + } + let ideal = i128::from(x.exp.min(y.exp)); + if x.is_zero() { + return fix(Fin::new(x.sign, Coef::ZERO, ideal)?, c, sig); + } + let expdiff = x.adjusted() - y.adjusted(); + if expdiff > c.prec { + return None; + } + if expdiff <= -2 { + // `abs(x / y) < 0.1`: the remainder is `x`. + return fix(rescale(x, ideal, c.round)?, c, sig); + } + let (mut a, mut b) = (x.coef.clone(), y.coef.clone()); + if x.exp >= y.exp { + a = a.mul_pow10(x.exp.abs_diff(y.exp))?; + } else { + b = b.mul_pow10(x.exp.abs_diff(y.exp))?; + } + let (mut q, mut r) = a.divrem(&b); + // The nearest multiple, an even quotient on a tie: a remainder past + // half of `y` crosses to the other side. + let twice = r.add(&r); + let twice = if q.rem_small(2) == 1 { + twice.incr() + } else { + twice + }; + let mut sign = x.sign; + if twice.cmp(&b) == Ordering::Greater { + r = b.sub(&r); + q = q.incr(); + sign ^= 1; + } + if i128::from(q.ndigits()) > c.prec { + return None; + } + fix(Fin::new(sign, r, ideal)?, c, sig) +} + +/// `Decimal.next_plus` (`up`) and `next_minus` of a finite value: the +/// value rounded toward the direction when the context can't hold it, +/// else moved by less than its last place and rounded the same way. No +/// flag is raised (the methods work on a copy of the context that ignores +/// them all). `None` where a result would overflow. +fn next_step(x: &Fin, c: &CtxP, up: bool) -> Option { + let p = CtxP { + round: if up { Round::Ceiling } else { Round::Floor }, + ..*c + }; + let mut ignored = 0; + let fixed = fix(x.clone(), &p, &mut ignored)?; + if cmp(&fixed, x)? != Ordering::Equal { + return Some(fixed); + } + let tiny = Fin::new(u8::from(!up), Coef::S(1), p.etiny() - 1)?; + add(x, &tiny, &p, &mut ignored) +} + +/// The flags `next_toward` raises for its finite result `ans`. +fn next_toward_flags(ans: &Fin, c: &CtxP) -> u16 { + if ans.adjusted() >= c.emin { + return 0; + } + let mut sig = S_UNDERFLOW | S_SUBNORMAL | S_INEXACT | S_ROUNDED; + if ans.is_zero() { + sig |= S_CLAMPED; + } + sig +} + +/// The integer a finite operand with a zero exponent holds, within +/// `-limit..=limit` (`scaleb`'s, `shift`'s and `rotate`'s second +/// operand): `None` where the methods raise. +fn small_int(y: &Fin, limit: i128) -> Option { + if y.exp != 0 { + return None; + } + let Coef::S(v) = y.coef else { return None }; + let v = i128::try_from(v).ok().filter(|v| *v <= limit)?; + Some(if y.sign == 1 { -v } else { v }) +} + +/// `Decimal.scaleb` for finite operands. +fn scaleb(x: &Fin, y: &Fin, c: &CtxP, sig: &mut u16) -> Option { + let n = small_int(y, 2 * (c.emax + c.prec))?; + fix( + Fin::new(x.sign, x.coef.clone(), i128::from(x.exp) + n)?, + c, + sig, + ) +} + +/// A coefficient's digits as exactly `prec` of them: zeros added on the +/// left, or the leading digits past `prec` dropped (what `rotate`, +/// `shift` and the logical operations start from). +fn digits_to_prec(coef: &Coef, prec: i128) -> Option> { + let prec = usize::try_from(prec) + .ok() + .filter(|p| *p as u64 <= MAX_DIGITS)?; + let d = coef.to_digits().into_bytes(); + Some(if d.len() >= prec { + d[d.len() - prec..].to_vec() + } else { + let mut v = vec![b'0'; prec - d.len()]; + v.extend_from_slice(&d); + v + }) +} + +/// `Decimal.rotate` (`rotate`) and `Decimal.shift` of a finite value by +/// the digits count `y` holds, over the context's precision. +fn rotate_shift(x: &Fin, y: &Fin, c: &CtxP, rotate: bool) -> Option { + let n = small_int(y, c.prec)?; + let d = digits_to_prec(&x.coef, c.prec)?; + let len = d.len(); + let out: Vec = if rotate { + // (`digits[n:] + digits[:n]`, a negative `n` counted from the end.) + let k = if n >= 0 { + n as usize + } else { + len - n.unsigned_abs() as usize + }; + [&d[k..], &d[..k]].concat() + } else if n < 0 { + d[..len - n.unsigned_abs() as usize].to_vec() + } else { + // (Zeros come in on the right; the last `prec` digits stay.) + let n = n as usize; + let mut v = d[n..].to_vec(); + v.resize(len, b'0'); + v + }; + let coef = if out.is_empty() { + Coef::ZERO + } else { + Coef::parse(&out)? + }; + Some(Fin { + sign: x.sign, + coef, + exp: x.exp, + }) +} + +/// `Decimal.compare_total` for finite operands: the sign, then the value, +/// then the exponent (reversed for negative values). +fn compare_total(x: &Fin, y: &Fin) -> Option { + if x.sign != y.sign { + return Some(if x.sign == 1 { + Ordering::Less + } else { + Ordering::Greater + }); + } + Some(match cmp(x, y)? { + Ordering::Equal => { + let e = x.exp.cmp(&y.exp); + if x.sign == 1 { + e.reverse() + } else { + e + } + } + c => c, + }) +} + +/// A logical operand's digits over the context's precision +/// (`Decimal._islogical` and `_fill_logical`): `None` for an operand the +/// logical methods reject. +fn logical_digits(x: &Fin, c: &CtxP) -> Option> { + if x.sign != 0 || x.exp != 0 { + return None; + } + let d = x.coef.to_digits(); + if !d.bytes().all(|b| b == b'0' || b == b'1') { + return None; + } + digits_to_prec(&x.coef, c.prec) +} + +/// `Decimal.logical_and` (`op` 0), `logical_or` (1) and `logical_xor` +/// (2) of two logical operands. +fn logical(x: &Fin, y: &Fin, c: &CtxP, op: u8) -> Option { + let (a, b) = (logical_digits(x, c)?, logical_digits(y, c)?); + let out: Vec = a + .iter() + .zip(&b) + .map(|(p, q)| { + let (p, q) = (p - b'0', q - b'0'); + b'0' + match op { + 0 => p & q, + 1 => p | q, + _ => p ^ q, + } + }) + .collect(); + let coef = if out.is_empty() { + Coef::ZERO + } else { + Coef::parse(&out)? + }; + Some(Fin { + sign: 0, + coef, + exp: 0, + }) +} + /// `Decimal._rescale` (quiet). #[inline] fn rescale(d: &Fin, exp: i128, mode: Round) -> Option { @@ -1315,9 +1944,20 @@ struct State { ctx_epoch: AtomicU64, /// The last context read (see [`State::read_ctx`]). ctx_cache: RefCell>, + /// The context [`State::current`] found last, with the `contextvars` + /// generation it was found under (see + /// `contextvars_native::generation`). + current_memo: RefCell)>>, /// The native `Decimal` methods (by address) → their [`SPECS`] index, /// for keyword calls from the dispatch loop (see [`method_kw`]). methods: HashMap, + /// `DefaultContext`, `BasicContext` and `ExtendedContext` (held + /// weakly, as the classes are): `setcontext` installs a copy of one + /// of them, and a new context takes its defaults from the first. + templates: Vec>, + /// The nine signals, in `_signals` order, each mapped to `False`: + /// what a new context's flags start as. + clear_flags: DictData, } const POOL_CAP: usize = 64; @@ -1412,6 +2052,38 @@ const OWNER_CACHE: usize = 16; const C_DECIMAL: u8 = 0; const C_CONTEXT: u8 = 1; +/// The native `Context.__setattr__`'s name, in storage of its own: a +/// builtin whose name is this very string is that method (see +/// [`is_setattr_hook`]). +static CTX_SETATTR: [u8; 11] = *b"__setattr__"; + +/// Whether `b` is the native `Context.__setattr__`, which compiled code +/// calls in place (see [`setattr_fast`]). +pub(crate) fn is_setattr_hook(b: &BuiltinFn) -> bool { + std::ptr::eq(b.name.as_ptr(), CTX_SETATTR.as_ptr()) +} + +/// The largest precision and exponent a context takes (`MAX_PREC` and +/// `MAX_EMAX`, and `-MIN_EMIN`). +const CTX_CAP: i64 = if cfg!(target_pointer_width = "64") { + 999_999_999_999_999_999 +} else { + 425_000_000 +}; + +/// `object.__setattr__(inst, name, value)` for a plain instance +/// attribute: no descriptor or hook is consulted. +fn store_attr(inst: &PyInstance, name: &SharedStr, value: Object) { + let old = match inst.split_store(name, value) { + Ok(old) => old, + Err(value) => inst + .dict_cell() + .borrow_mut() + .insert(DictKey(Object::Str(name.clone())), value), + }; + drop(old); +} + /// The [`State`] a class marked by [`install`] carries in its /// `native_ext` slot. #[inline] @@ -1575,8 +2247,10 @@ impl State { drop(Rc::into_arc(inst)); } let cls = self.decimal.upgrade()?; - let mut i = PyInstance::new(cls); - *i.slots.get_mut() = SlotStorage::from_packed(PackedSlots::new_decimal(parts)); + let i = PyInstance::with_slots( + cls, + SlotStorage::from_packed(PackedSlots::new_decimal(parts)), + ); Some(Object::Instance(Rc::new(i))) } @@ -1584,15 +2258,17 @@ impl State { fn make_fixed(&self, d: &Fin) -> Option { let cls = self.decimal.upgrade()?; let digits = Object::Str(d.coef.with_digits(SharedStr::from_ascii)); - let mut i = PyInstance::new(cls); - *i.slots.get_mut() = SlotStorage::from_layout( - self.layout.clone(), - vec![ - Object::Int(i64::from(d.sign)), - digits, - Object::Int(d.exp), - Object::Bool(false), - ], + let i = PyInstance::with_slots( + cls, + SlotStorage::from_layout( + self.layout.clone(), + vec![ + Object::Int(i64::from(d.sign)), + digits, + Object::Int(d.exp), + Object::Bool(false), + ], + ), ); Some(Object::Instance(Rc::new(i))) } @@ -1626,8 +2302,10 @@ impl State { /// A new exact `Decimal` with the slot values `v` (a copy). fn make_raw(&self, v: [Object; 4]) -> Option { let cls = self.decimal.upgrade()?; - let mut i = PyInstance::new(cls); - *i.slots.get_mut() = SlotStorage::from_layout(self.layout.clone(), v.to_vec()); + let i = PyInstance::with_slots( + cls, + SlotStorage::from_layout(self.layout.clone(), v.to_vec()), + ); Some(Object::Instance(Rc::new(i))) } @@ -1635,6 +2313,221 @@ impl State { &self.signals[bit] } + /// The `_signals` position of the signal class `key`. + fn signal_bit(&self, key: &Object) -> Option { + let Object::Type(t) = key else { return None }; + self.signals + .iter() + .position(|s| matches!(s, Object::Type(w) if Rc::ptr_eq(w, t))) + } + + /// Whether `map`'s keys are exactly the nine signals (what + /// `Context._set_signal_dict` checks of a mapping). + fn exact_signals(&self, map: &DictData) -> bool { + if map.len() != N_SIGNALS { + return false; + } + // (Usually in `_signals` order, as every mapping made here is.) + let ordered = (0..N_SIGNALS).all(|i| { + matches!( + (map.get_index(i), &self.signals[i]), + (Some((DictKey(Object::Type(k)), _)), Object::Type(w)) if Rc::ptr_eq(k, w) + ) + }); + ordered + || (0..N_SIGNALS).all(|i| { + map.get_index(i) + .is_some_and(|(k, _)| self.signal_bit(&k.0).is_some()) + }) + } + + /// The mapping of the exact `SignalDict` `d` while it is usable + /// (`SignalDict._check_valid`): it holds entries, and its owner is + /// alive. + fn valid_signal_map<'a>(&self, d: &'a PyInstance) -> Option<&'a Rc>> { + if !std::ptr::eq(d.cls_raw(), self.signal_dict.as_ptr()) { + return None; + } + let Some(Object::Dict(map)) = d.native.get() else { + return None; + }; + // SAFETY: a read that runs no code. + if unsafe { map.peek() }?.is_empty() { + return None; + } + let owner = d.attr_get_str(&self.names.owner)?; + match crate::stdlib::weakref_real::c_referent(&owner) { + Some(Some(_)) => Some(map), + _ => None, + } + } + + /// `weakref.ref(ctx)`: what a context's mappings name it by. + fn owner_ref(ctx: &Rc) -> Option { + crate::stdlib::weakref_real::ref_pure(&Object::Instance(ctx.clone()), None) + } + + /// A mapping of the nine signals, in `_signals` order, each to + /// whether it is in `set` (by position): a copy of the all-clear + /// mapping, with the set ones raised. + fn signal_data(&self, set: u16) -> DictData { + let mut d = self.clear_flags.clone(); + if set != 0 { + let m = d.map_mut_value_store(); + for bit in 0..N_SIGNALS { + if set & (1 << bit) != 0 { + if let Some((_, v)) = m.get_index_mut(bit) { + *v = Object::Bool(true); + } + } + } + } + d + } + + /// The mapping `Context.__init__` stores for a `flags` or `traps` + /// argument: a list of signals as `{signal: int(signal in list)}`, or + /// a mapping as [`Self::signal_dict_value`] takes it. + fn signal_arg(&self, ctx: &Rc, o: &Object) -> Option { + match o { + Object::List(l) => { + let mut set = 0u16; + // SAFETY: a read that runs no code. + for item in unsafe { l.peek() }?.iter() { + set |= 1 << self.signal_bit(item)?; + } + self.new_signal_dict(self.signal_data(set), Self::owner_ref(ctx)?) + } + _ => self.signal_dict_value(ctx, o), + } + } + + /// The names of a context's attributes, in `Context.__init__`'s + /// order. + fn ctx_names(&self) -> [&SharedStr; 9] { + let n = &self.names; + [ + &n.prec, + &n.rounding, + &n.emin, + &n.emax, + &n.capitals, + &n.clamp, + &n.ignored, + &n.traps, + &n.flags, + ] + } + + /// What `Context.__setattr__` stores for the attribute at position + /// `field` of [`Self::ctx_names`] given `value`, where the method + /// only checks the value: an `int` in range for the five numeric + /// attributes, a rounding mode, the ignored-flags list, or a mapping + /// [`Self::signal_dict_value`] accepts. `None` for anything else (the + /// Python method raises or converts). + fn ctx_checked(&self, ctx: &Rc, field: usize, value: &Object) -> Option { + let int = |lo: i64, hi: i64| matches!(value, Object::Int(v) if (lo..=hi).contains(v)); + let fits = match field { + 0 => int(1, CTX_CAP), + 1 => round_of(value).is_some(), + 2 => int(-CTX_CAP, 0), + 3 => int(0, CTX_CAP), + 4 | 5 => int(0, 1), + 6 => !matches!(value, Object::BoundMethod(_)), + _ => return self.signal_dict_value(ctx, value), + }; + fits.then(|| value.clone()) + } + + /// A new `SignalDict` over `data` whose `_owner` is `owner` + /// (`SignalDict(d)`, with the reference `Context._set_signal_dict` + /// gives it). + fn new_signal_dict(&self, data: DictData, owner: Object) -> Option { + let cls = self.signal_dict.upgrade()?; + let d = Rc::new(PyInstance::with_native( + cls, + Object::Dict(Rc::new(RefCell::new(data))), + )); + store_attr(&d, &self.names.owner, owner); + let d = Object::Instance(d); + crate::gc_trace::track(&d); + Some(d) + } + + /// What `ctx.flags = d` (or `traps`) stores when + /// `Context._set_signal_dict` accepts `d` on its checks alone: a + /// usable `SignalDict` as it is, or a new one over a plain `dict` of + /// the nine signals. `None` for anything else (the Python method + /// converts or raises). + fn signal_dict_value(&self, ctx: &Rc, d: &Object) -> Option { + match d { + Object::Instance(i) => { + let map = self.valid_signal_map(i)?; + // SAFETY: a read that runs no code. + self.exact_signals(unsafe { map.peek() }?) + .then(|| d.clone()) + } + Object::Dict(map) => { + // SAFETY: as above; the copy is taken before anything + // else runs. + let data = unsafe { map.peek() }?; + if !self.exact_signals(data) { + return None; + } + self.new_signal_dict(data.clone(), Self::owner_ref(ctx)?) + } + _ => None, + } + } + + /// Whether a context's attributes may be stored in place: a plain + /// instance, with nothing watching its dictionary. + fn ctx_storable(ctx: &PyInstance) -> bool { + ctx.native.get().is_none() + && ctx.c_body.get() == 0 + && !crate::object::exotic_str_keys_possible() + && !crate::capi_watchers::dicts_active() + } + + /// `Context.__setattr__(ctx, name, value)` where the method only + /// checks the value and stores it (see [`Self::ctx_checked`]). `None` + /// stores nothing (the Python method raises or converts). + fn ctx_store(&self, ctx: &Rc, name: &str, value: &Object) -> Option<()> { + if !Self::ctx_storable(ctx) { + return None; + } + let field = match name { + "prec" => 0, + "rounding" => 1, + "Emin" => 2, + "Emax" => 3, + "capitals" => 4, + "clamp" => 5, + "_ignored_flags" => 6, + "traps" => 7, + "flags" => 8, + _ => return None, + }; + let stored = self.ctx_checked(ctx, field, value)?; + store_attr(ctx, self.ctx_names()[field], stored); + self.ctx_epoch.fetch_add(1, Relaxed); + Some(()) + } + + /// A context's nine attribute values, in `Context.__init__`'s order, + /// however its attributes are laid out (`None` when one is missing). + fn ctx_values(&self, inst: &PyInstance) -> Option<[Object; 9]> { + // SAFETY: the values are cloned before anything else runs. + if let Some(v) = unsafe { self.ctx_fields(inst) } { + return Some(std::array::from_fn(|i| v[i].clone())); + } + let mut out: [Object; 9] = std::array::from_fn(|_| Object::None); + for (slot, name) in out.iter_mut().zip(self.ctx_names()) { + *slot = inst.attr_get_str(name)?; + } + Some(out) + } + /// Whether `d` (an exact `SignalDict`) names `ctx` as its live owner /// (`SignalDict._check_valid`). fn owned_by(&self, d: &Rc, ctx: &Rc) -> bool { @@ -1676,6 +2569,26 @@ impl State { /// (an exact `Context`): the thread's current `contextvars.Context`'s /// `_data[var]`. fn current(&self) -> Option> { + // While the thread's current context and the mappings stand, the + // context found last. + let gen = crate::stdlib::contextvars_native::generation(); + // SAFETY: a guard-free read that runs no code. + if let Some((g, w)) = unsafe { self.current_memo.peek() }.and_then(Option::as_ref) { + if *g == gen && gen != 0 { + if let Some(c) = w.upgrade() { + return Some(c); + } + } + } + let c = self.current_lookup()?; + if let Ok(mut memo) = self.current_memo.try_borrow_mut() { + *memo = Some((gen, Rc::downgrade(&c))); + } + Some(c) + } + + /// [`Self::current`] past its memo. + fn current_lookup(&self) -> Option> { let data = crate::stdlib::contextvars_native::peek_current_data()?; // SAFETY: reads that run no code (the key is a plain instance, // which hashes and compares natively); the context is cloned @@ -2041,6 +2954,15 @@ impl State { } } } + } + self.raise_flags(ctx, sig) + } + + /// Set the flags of the conditions `sig` in the context, trapped or + /// not (`context.flags[signal] = 1`). + fn raise_flags(&self, ctx: &Ctx, sig: u16) -> Option<()> { + // SAFETY: as in `commit`. + unsafe { let flags = (*ctx.flags).peek_mut()?; for bit in 0..N_SIGNALS { if sig & (1 << bit) != 0 { @@ -2448,34 +3370,57 @@ fn d_abs(a: &[Object]) -> Option> { unary(&rest, x.sign == 1) } -/// The comparison of the receiver with an exact `Decimal` or an `int`. -fn compare_with(a: &[Object]) -> Option { +/// The comparison of the finite value `x` with `other`, as +/// `_convert_for_comparison` readies it: an exact `Decimal`, an `int`, or +/// a finite `float`, compared by its exact value. A float records +/// `FloatOperation` on the current context first: its flag alone for +/// equality (`eq`), the signal for an ordering (trapped, the Python code +/// raises). +fn compare_operand(st: &State, x: &Fin, other: &Object, eq: bool) -> Option { + let y = match other { + Object::Float(f) => { + let y = from_f64(*f)?; + let ctx = st.resolve(None)?; + if eq { + st.raise_flags(&ctx, S_FLOATOP)?; + } else { + st.commit(&ctx, S_FLOATOP)?; + } + y + } + o => st.operand(o)?, + }; + cmp(x, &y) +} + +/// The comparison of the receiver with an exact `Decimal`, an `int` or a +/// `float` (see [`compare_operand`]). +fn compare_with(a: &[Object], eq: bool) -> Option { let (st, x) = recv(a, 3)?; - let y = st.operand(a.get(1)?)?; if arg(a, 2).is_some_and(|c| !matches!(c, Object::None)) { return None; } - cmp(&x, &y) + compare_operand(st, &x, a.get(1)?, eq) } fn d_eq(a: &[Object]) -> Option> { - ok(Object::Bool(compare_with(a)? == Ordering::Equal)) + ok(Object::Bool(compare_with(a, true)? == Ordering::Equal)) } fn d_lt(a: &[Object]) -> Option> { - ok(Object::Bool(compare_with(a)?.is_lt())) + ok(Object::Bool(compare_with(a, false)?.is_lt())) } fn d_le(a: &[Object]) -> Option> { - ok(Object::Bool(compare_with(a)?.is_le())) + ok(Object::Bool(compare_with(a, false)?.is_le())) } fn d_gt(a: &[Object]) -> Option> { - ok(Object::Bool(compare_with(a)?.is_gt())) + ok(Object::Bool(compare_with(a, false)?.is_gt())) } fn d_ge(a: &[Object]) -> Option> { - ok(Object::Bool(compare_with(a)?.is_ge())) + ok(Object::Bool(compare_with(a, false)?.is_ge())) } fn d_hash(a: &[Object]) -> Option> { @@ -2840,7 +3785,7 @@ fn d_as_integer_ratio(a: &[Object]) -> Option> { } let mut n = x.coef.to_big(); let d = if x.exp >= 0 { - n *= pow10_big(u64::try_from(x.exp).ok().filter(|e| *e <= MAX_DIGITS)?); + n *= &*pow10_big(u64::try_from(x.exp).ok().filter(|e| *e <= MAX_DIGITS)?); BigUint::from(1u32) } else { let k = x.exp.unsigned_abs(); @@ -2938,6 +3883,44 @@ pub(crate) fn construct_names( construct_value(st, value, context) } +/// `Decimal((sign, digits, exponent))` for a finite value: an `int` sign +/// of 0 or 1, a tuple or list of `int` digits, and an `int` exponent. +/// `None` for anything else (a special value's letter, a `bool`, a +/// value to reject). +fn triple_fin(t: &[Object]) -> Option { + let [Object::Int(sign @ 0..=1), digits, Object::Int(exp)] = t else { + return None; + }; + let mut text: Vec = Vec::new(); + let mut push = |items: &[Object]| -> Option<()> { + for d in items { + let d = match d { + Object::Int(d @ 0..=9) => *d as u8, + Object::Bool(b) => u8::from(*b), + _ => return None, + }; + text.push(b'0' + d); + } + Some(()) + }; + match digits { + Object::Tuple(items) => push(items)?, + // SAFETY: a read that runs no code. + Object::List(l) => push(unsafe { l.peek() }?)?, + _ => return None, + } + let coef = if text.is_empty() { + Coef::ZERO + } else { + Coef::parse(&text)? + }; + Some(Fin { + sign: *sign as u8, + coef, + exp: *exp, + }) +} + fn construct_value( st: &State, value: Option<&Object>, @@ -2965,6 +3948,7 @@ fn construct_value( return ok(r); } Some(Object::Instance(i)) if st.is_decimal(i) => return ok(st.copy_of(i)?), + Some(Object::Tuple(t)) => triple_fin(t)?, Some(o) => int_fin(o)?, }; // The context-free constructor's exact range. @@ -3131,6 +4115,655 @@ fn c_to_sci_string(a: &[Object]) -> Option> { ok(Object::Str(SharedStr::from_ascii(&s))) } +/// `Context.__setattr__(recv, name, value)` where it runs no Python code +/// (see [`State::ctx_store`]): `true` once stored, `false` touching +/// nothing. +pub(crate) fn setattr_fast(recv: &Object, name: &Object, value: &Object) -> bool { + let (Object::Instance(inst), Object::Str(n)) = (recv, name) else { + return false; + }; + let Some(st) = state_of(recv) else { + return false; + }; + std::ptr::eq(inst.cls_raw(), st.context.as_ptr()) + && st.ctx_store(inst, n.as_ref(), value).is_some() +} + +/// `Decimal.sqrt(context=None)`. +fn d_sqrt(a: &[Object]) -> Option> { + let (st, x) = recv(a, 2)?; + let ctx = st.resolve(ctx_arg(a, 1))?; + let mut sig = 0; + let r = sqrt(&x, &ctx.p, &mut sig)?; + ok(st.finish(&ctx, sig, &r)?) +} + +/// `Context.sqrt(a)`. +fn c_sqrt(a: &[Object]) -> Option> { + let (st, ctx) = ctx_recv(a, 2, 2)?; + let x = st.operand(a.get(1)?)?; + let mut sig = 0; + let r = sqrt(&x, &ctx.p, &mut sig)?; + ok(st.finish(&ctx, sig, &r)?) +} + +/// `x * y + z` with the product exact (`Decimal.fma`'s finite case). +fn fma(x: &Fin, y: &Fin, z: &Fin, c: &CtxP, sig: &mut u16) -> Option { + let product = Fin::new( + x.sign ^ y.sign, + x.coef.mul(&y.coef)?, + i128::from(x.exp) + i128::from(y.exp), + )?; + add(&product, z, c, sig) +} + +/// `Decimal.fma(other, third, context=None)`. +fn d_fma(a: &[Object]) -> Option> { + let (st, x) = recv(a, 4)?; + let y = st.operand(a.get(1)?)?; + let z = st.operand(a.get(2)?)?; + let ctx = st.resolve(ctx_arg(a, 3))?; + let mut sig = 0; + let r = fma(&x, &y, &z, &ctx.p, &mut sig)?; + ok(st.finish(&ctx, sig, &r)?) +} + +/// `Context.fma(a, b, c)`. +fn c_fma(a: &[Object]) -> Option> { + let (st, ctx) = ctx_recv(a, 4, 4)?; + let x = st.operand(a.get(1)?)?; + let y = st.operand(a.get(2)?)?; + let z = st.operand(a.get(3)?)?; + let mut sig = 0; + let r = fma(&x, &y, &z, &ctx.p, &mut sig)?; + ok(st.finish(&ctx, sig, &r)?) +} + +/// `Context.Etiny()`: `Emin - prec + 1`. +fn c_etiny(a: &[Object]) -> Option> { + let (_, ctx) = ctx_recv(a, 1, 1)?; + ok(Object::Int(i64::try_from(ctx.p.etiny()).ok()?)) +} + +/// `Context.Etop()`: `Emax - prec + 1`. +fn c_etop(a: &[Object]) -> Option> { + let (_, ctx) = ctx_recv(a, 1, 1)?; + ok(Object::Int(i64::try_from(ctx.p.etop()).ok()?)) +} + +/// A `Decimal` method of `(other, context=None)` that rounds its result +/// under the context: `f(x, y)`. +fn d_with_other( + a: &[Object], + f: impl FnOnce(&Fin, &Fin, &CtxP, &mut u16) -> Option, +) -> Option> { + binary(a, false, f) +} + +fn d_remainder_near(a: &[Object]) -> Option> { + d_with_other(a, remainder_near) +} + +fn c_remainder_near(a: &[Object]) -> Option> { + ctx_binary(a, remainder_near) +} + +fn d_scaleb(a: &[Object]) -> Option> { + d_with_other(a, scaleb) +} + +fn c_scaleb(a: &[Object]) -> Option> { + ctx_binary(a, scaleb) +} + +fn d_rotate(a: &[Object]) -> Option> { + d_with_other(a, |x, y, c, _| rotate_shift(x, y, c, true)) +} + +fn c_rotate(a: &[Object]) -> Option> { + ctx_binary(a, |x, y, c, _| rotate_shift(x, y, c, true)) +} + +fn d_shift(a: &[Object]) -> Option> { + d_with_other(a, |x, y, c, _| rotate_shift(x, y, c, false)) +} + +fn c_shift(a: &[Object]) -> Option> { + ctx_binary(a, |x, y, c, _| rotate_shift(x, y, c, false)) +} + +fn d_logical_and(a: &[Object]) -> Option> { + d_with_other(a, |x, y, c, _| logical(x, y, c, 0)) +} + +fn c_logical_and(a: &[Object]) -> Option> { + ctx_binary(a, |x, y, c, _| logical(x, y, c, 0)) +} + +fn d_logical_or(a: &[Object]) -> Option> { + d_with_other(a, |x, y, c, _| logical(x, y, c, 1)) +} + +fn c_logical_or(a: &[Object]) -> Option> { + ctx_binary(a, |x, y, c, _| logical(x, y, c, 1)) +} + +fn d_logical_xor(a: &[Object]) -> Option> { + d_with_other(a, |x, y, c, _| logical(x, y, c, 2)) +} + +fn c_logical_xor(a: &[Object]) -> Option> { + ctx_binary(a, |x, y, c, _| logical(x, y, c, 2)) +} + +/// `x ^ 111...1` over the precision (`logical_invert`). +fn logical_invert(x: &Fin, c: &CtxP) -> Option { + let prec = usize::try_from(c.prec) + .ok() + .filter(|p| *p as u64 <= MAX_DIGITS)?; + let ones = Fin { + sign: 0, + coef: Coef::parse(&vec![b'1'; prec])?, + exp: 0, + }; + logical(x, &ones, c, 2) +} + +fn d_logical_invert(a: &[Object]) -> Option> { + let (st, x) = recv(a, 2)?; + let ctx = st.resolve(ctx_arg(a, 1))?; + ok(st.make(&logical_invert(&x, &ctx.p)?)?) +} + +fn c_logical_invert(a: &[Object]) -> Option> { + let (st, ctx) = ctx_recv(a, 2, 2)?; + let x = st.operand(a.get(1)?)?; + ok(st.make(&logical_invert(&x, &ctx.p)?)?) +} + +/// `next_plus(context=None)` and `next_minus(context=None)`. +fn d_next(a: &[Object], up: bool) -> Option> { + let (st, x) = recv(a, 2)?; + let ctx = st.resolve(ctx_arg(a, 1))?; + ok(st.make(&next_step(&x, &ctx.p, up)?)?) +} + +fn d_next_plus(a: &[Object]) -> Option> { + d_next(a, true) +} + +fn d_next_minus(a: &[Object]) -> Option> { + d_next(a, false) +} + +fn c_next(a: &[Object], up: bool) -> Option> { + let (st, ctx) = ctx_recv(a, 2, 2)?; + let x = st.operand(a.get(1)?)?; + ok(st.make(&next_step(&x, &ctx.p, up)?)?) +} + +fn c_next_plus(a: &[Object]) -> Option> { + c_next(a, true) +} + +fn c_next_minus(a: &[Object]) -> Option> { + c_next(a, false) +} + +/// `next_toward`: a copy with the other's sign for equal values, else +/// the next value toward it, with the flags its size calls for. +fn next_toward(st: &State, ctx: &Ctx, x: &Fin, y: &Fin) -> Option { + let up = match cmp(x, y)? { + Ordering::Equal => { + return st.make(&Fin { + sign: y.sign, + coef: x.coef.clone(), + exp: x.exp, + }) + } + Ordering::Less => true, + Ordering::Greater => false, + }; + let ans = next_step(x, &ctx.p, up)?; + st.finish(ctx, next_toward_flags(&ans, &ctx.p), &ans) +} + +fn d_next_toward(a: &[Object]) -> Option> { + let (st, x) = recv(a, 3)?; + let y = st.operand(a.get(1)?)?; + let ctx = st.resolve(ctx_arg(a, 2))?; + ok(next_toward(st, &ctx, &x, &y)?) +} + +fn c_next_toward(a: &[Object]) -> Option> { + let (st, ctx) = ctx_recv(a, 3, 3)?; + let x = st.operand(a.get(1)?)?; + let y = st.operand(a.get(2)?)?; + ok(next_toward(st, &ctx, &x, &y)?) +} + +/// `logb`: the adjusted exponent of a nonzero value, as a `Decimal`. +fn logb(x: &Fin, c: &CtxP, sig: &mut u16) -> Option { + if x.is_zero() { + return None; + } + let e = x.adjusted(); + fix( + Fin { + sign: u8::from(e < 0), + coef: Coef::S(e.unsigned_abs()), + exp: 0, + }, + c, + sig, + ) +} + +fn d_logb(a: &[Object]) -> Option> { + let (st, x) = recv(a, 2)?; + let ctx = st.resolve(ctx_arg(a, 1))?; + let mut sig = 0; + let r = logb(&x, &ctx.p, &mut sig)?; + ok(st.finish(&ctx, sig, &r)?) +} + +fn c_logb(a: &[Object]) -> Option> { + let (st, ctx) = ctx_recv(a, 2, 2)?; + let x = st.operand(a.get(1)?)?; + let mut sig = 0; + let r = logb(&x, &ctx.p, &mut sig)?; + ok(st.finish(&ctx, sig, &r)?) +} + +/// `number_class` of a finite value. +fn number_class(x: &Fin, c: &CtxP) -> Object { + let name = match (x.is_zero(), x.adjusted() < c.emin, x.sign == 1) { + (true, _, false) => "+Zero", + (true, _, true) => "-Zero", + (false, true, false) => "+Subnormal", + (false, true, true) => "-Subnormal", + (false, false, false) => "+Normal", + (false, false, true) => "-Normal", + }; + Object::from_static(name) +} + +fn d_number_class(a: &[Object]) -> Option> { + let (st, x) = recv(a, 2)?; + if x.is_zero() { + // (A zero's class needs no context, and the method reads none.) + return ok(Object::from_static(if x.sign == 1 { + "-Zero" + } else { + "+Zero" + })); + } + let ctx = st.resolve(ctx_arg(a, 1))?; + ok(number_class(&x, &ctx.p)) +} + +fn c_number_class(a: &[Object]) -> Option> { + let (st, ctx) = ctx_recv(a, 2, 2)?; + let x = st.operand(a.get(1)?)?; + ok(number_class(&x, &ctx.p)) +} + +/// An ordering as the `Decimal` `-1`, `0` or `1`. +fn ordering_decimal(st: &State, c: Ordering) -> Option { + let v = match c { + Ordering::Less => -1, + Ordering::Equal => 0, + Ordering::Greater => 1, + }; + st.make(&int_fin(&Object::Int(v))?) +} + +/// `compare_total(other, context=None)` and `compare_total_mag` +/// (`mag`): the context isn't read. +fn d_compare_total_impl(a: &[Object], mag: bool) -> Option> { + let (st, x) = recv(a, 3)?; + let y = st.operand(a.get(1)?)?; + let c = if mag { + compare_total(&x.abs(), &y.abs())? + } else { + compare_total(&x, &y)? + }; + ok(ordering_decimal(st, c)?) +} + +fn d_compare_total(a: &[Object]) -> Option> { + d_compare_total_impl(a, false) +} + +fn d_compare_total_mag(a: &[Object]) -> Option> { + d_compare_total_impl(a, true) +} + +fn c_compare_total_impl(a: &[Object], mag: bool) -> Option> { + if a.len() != 3 { + return None; + } + let st = state_of(a.first()?)?; + let x = st.operand(a.get(1)?)?; + let y = st.operand(a.get(2)?)?; + let c = if mag { + compare_total(&x.abs(), &y.abs())? + } else { + compare_total(&x, &y)? + }; + ok(ordering_decimal(st, c)?) +} + +fn c_compare_total(a: &[Object]) -> Option> { + c_compare_total_impl(a, false) +} + +fn c_compare_total_mag(a: &[Object]) -> Option> { + c_compare_total_impl(a, true) +} + +/// `max_mag` (`want_max`) and `min_mag`: the operand of the larger (or +/// smaller) magnitude, the total order settling a tie, rounded under the +/// context. +fn mag_pick(x: Fin, y: Fin, c: &CtxP, sig: &mut u16, want_max: bool) -> Option { + let mut order = cmp(&x.abs(), &y.abs())?; + if order == Ordering::Equal { + order = compare_total(&x, &y)?; + } + let pick_y = (order == Ordering::Less) == want_max; + fix(if pick_y { y } else { x }, c, sig) +} + +fn d_max_mag(a: &[Object]) -> Option> { + d_with_other(a, |x, y, c, s| mag_pick(x.clone(), y.clone(), c, s, true)) +} + +fn d_min_mag(a: &[Object]) -> Option> { + d_with_other(a, |x, y, c, s| mag_pick(x.clone(), y.clone(), c, s, false)) +} + +fn c_max_mag(a: &[Object]) -> Option> { + ctx_binary(a, |x, y, c, s| mag_pick(x.clone(), y.clone(), c, s, true)) +} + +fn c_min_mag(a: &[Object]) -> Option> { + ctx_binary(a, |x, y, c, s| mag_pick(x.clone(), y.clone(), c, s, false)) +} + +/// `exp`, `ln` and `log10` of `x` under `ctx` (`which` 0, 1, 2), with the +/// exact answers the methods return as they are: `exp(0)` is `1`, and +/// `ln(1)` is `0`. +fn transcendental(st: &State, ctx: &Ctx, x: &Fin, which: u8) -> Option { + let exact = |v: i64| st.make(&int_fin(&Object::Int(v))?); + let mut sig = 0; + let r = match which { + 0 if x.is_zero() => return exact(1), + 0 => exp(x, &ctx.p, &mut sig)?, + 1 if cmp(x, &int_fin(&Object::Int(1))?)? == Ordering::Equal => return exact(0), + 1 => log(x, &ctx.p, &mut sig, false)?, + _ => log(x, &ctx.p, &mut sig, true)?, + }; + st.finish(ctx, sig, &r) +} + +fn d_transcendental(a: &[Object], which: u8) -> Option> { + let (st, x) = recv(a, 2)?; + let ctx = st.resolve(ctx_arg(a, 1))?; + ok(transcendental(st, &ctx, &x, which)?) +} + +fn c_transcendental(a: &[Object], which: u8) -> Option> { + let (st, ctx) = ctx_recv(a, 2, 2)?; + let x = st.operand(a.get(1)?)?; + ok(transcendental(st, &ctx, &x, which)?) +} + +fn d_exp(a: &[Object]) -> Option> { + d_transcendental(a, 0) +} + +fn d_ln(a: &[Object]) -> Option> { + d_transcendental(a, 1) +} + +fn d_log10(a: &[Object]) -> Option> { + d_transcendental(a, 2) +} + +fn c_exp(a: &[Object]) -> Option> { + c_transcendental(a, 0) +} + +fn c_ln(a: &[Object]) -> Option> { + c_transcendental(a, 1) +} + +fn c_log10(a: &[Object]) -> Option> { + c_transcendental(a, 2) +} + +/// `radix()`: `Decimal(10)`. +fn d_radix(a: &[Object]) -> Option> { + let [recv] = a else { return None }; + let st = state_of(recv)?; + ok(st.make(&int_fin(&Object::Int(10))?)?) +} + +fn c_setattr(a: &[Object]) -> Option> { + let [recv, name, value] = a else { return None }; + setattr_fast(recv, name, value).then(|| Ok(Object::None)) +} + +/// `Context.copy()` (and `__copy__()`): a new exact `Context` holding the +/// source's values, with flag and trap mappings of its own. +fn c_copy(a: &[Object]) -> Option> { + let [recv @ Object::Instance(src)] = a else { + return None; + }; + let st = state_of(recv)?; + if !std::ptr::eq(src.cls_raw(), st.context.as_ptr()) + || crate::object::exotic_str_keys_possible() + || crate::capi_watchers::dicts_active() + { + return None; + } + let map_of = |o: &Object| -> Option { + let Object::Instance(d) = o else { return None }; + if !std::ptr::eq(d.cls_raw(), st.signal_dict.as_ptr()) { + return None; + } + let Some(Object::Dict(m)) = d.native.get() else { + return None; + }; + // SAFETY: a read that runs no code. + Some(unsafe { m.peek() }?.clone()) + }; + let mut values = st.ctx_values(src)?; + let (traps, flags) = (map_of(&values[7])?, map_of(&values[8])?); + let nc = PyInstance::new_deferred(st.context.upgrade()?); + let owner = State::owner_ref(&nc)?; + values[7] = st.new_signal_dict(traps, owner.clone())?; + values[8] = st.new_signal_dict(flags, owner)?; + for (name, value) in st.ctx_names().into_iter().zip(values) { + store_attr(&nc, name, value); + } + st.ctx_epoch.fetch_add(1, Relaxed); + ok(Object::Instance(nc)) +} + +/// `Context.__init__(self, prec=None, rounding=None, Emin=None, +/// Emax=None, capitals=None, clamp=None, flags=None, traps=None)` of an +/// exact `Context`: every attribute stored in the method's order, an +/// omitted one from `DefaultContext`, each value checked as +/// `Context.__setattr__` checks it. `None` stores nothing (the Python +/// method raises or converts). +fn c_init(a: &[Object]) -> Option> { + let (recv, given) = a.split_first()?; + let Object::Instance(inst) = recv else { + return None; + }; + let st = state_of(recv)?; + if given.len() > 8 + || !std::ptr::eq(inst.cls_raw(), st.context.as_ptr()) + || !State::ctx_storable(inst) + { + return None; + } + let dc = st.templates.first()?.upgrade()?; + let given = |i: usize| match given.get(i) { + None | Some(Object::Unbound | Object::None) => None, + Some(o) => Some(o), + }; + let defaults = st.ctx_values(&dc)?; + let owner = State::owner_ref(inst)?; + let mut values: Vec = Vec::with_capacity(9); + for (field, default) in defaults[..6].iter().enumerate() { + values.push(st.ctx_checked(inst, field, given(field).unwrap_or(default))?); + } + values.push(Object::new_list(Vec::new())); + let traps = match given(7) { + // (`dc.traps.copy()`, checked and wrapped as any mapping is.) + None => { + let Object::Instance(t) = &defaults[7] else { + return None; + }; + // SAFETY: a read that runs no code; the copy is taken before + // anything else runs. + let data = unsafe { st.valid_signal_map(t)?.peek() }?; + if !st.exact_signals(data) { + return None; + } + st.new_signal_dict(data.clone(), owner.clone())? + } + Some(o) => st.signal_arg(inst, o)?, + }; + let flags = match given(6) { + None => st.new_signal_dict(st.signal_data(0), owner)?, + Some(o) => st.signal_arg(inst, o)?, + }; + values.push(traps); + values.push(flags); + for (name, value) in st.ctx_names().into_iter().zip(values) { + store_attr(inst, name, value); + } + st.ctx_epoch.fetch_add(1, Relaxed); + ok(Object::None) +} + +/// `setcontext(context)` for an exact `Context` that isn't one of the +/// three templates (which the Python function copies first). +fn m_setcontext(a: &[Object]) -> Option> { + let [c @ Object::Instance(i)] = a else { + return None; + }; + let st = state_of(c)?; + if !std::ptr::eq(i.cls_raw(), st.context.as_ptr()) + || st + .templates + .iter() + .any(|t| std::ptr::eq(t.as_ptr(), Rc::as_ptr(i))) + { + return None; + } + crate::stdlib::contextvars_native::set_untokened(&st.var, c.clone())?; + ok(Object::None) +} + +/// `clear_flags()` (`field` 8) and `clear_traps()` (`field` 7): every +/// entry of the context's mapping set to `False`. +fn ctx_clear(a: &[Object], field: usize) -> Option> { + let [recv @ Object::Instance(inst)] = a else { + return None; + }; + let st = state_of(recv)?; + if !std::ptr::eq(inst.cls_raw(), st.context.as_ptr()) { + return None; + } + let values = st.ctx_values(inst)?; + let Object::Instance(d) = &values[field] else { + return None; + }; + // SAFETY: reads and in-place stores that run no code (the displaced + // values are checked to be ints or bools first). + unsafe { + let data = st.valid_signal_map(d)?.peek_mut()?; + if !st.exact_signals(data) + || !(0..N_SIGNALS).all(|i| { + matches!( + data.get_index(i), + Some((_, Object::Bool(_) | Object::Int(_))) + ) + }) + { + return None; + } + let m = data.map_mut_value_store(); + for i in 0..N_SIGNALS { + if let Some((_, v)) = m.get_index_mut(i) { + *v = Object::Bool(false); + } + } + } + ok(Object::None) +} + +fn c_clear_flags(a: &[Object]) -> Option> { + ctx_clear(a, 8) +} + +fn c_clear_traps(a: &[Object]) -> Option> { + ctx_clear(a, 7) +} + +/// The state and usable mapping of the exact `SignalDict` `d`. +fn sd_recv(d: &PyInstance) -> Option<(&State, &Rc>)> { + let st = state_of_cls(d.cls_raw())?; + Some((st, st.valid_signal_map(d)?)) +} + +/// `SignalDict.__getitem__(self, signal)` of a usable mapping. +fn sd_getitem(a: &[Object]) -> Option> { + let [Object::Instance(d), key] = a else { + return None; + }; + let (st, map) = sd_recv(d)?; + let bit = st.signal_bit(key)?; + // SAFETY: a read that runs no code (a class hashes and compares + // natively). + let v = st.signal_entry(unsafe { map.peek() }?, bit)?.clone(); + ok(v) +} + +/// `SignalDict.__setitem__(self, signal, value)` of a usable mapping, +/// for an `int` or `bool` value: the entry becomes `bool(value)`. +fn sd_setitem(a: &[Object]) -> Option> { + let [Object::Instance(d), key, value] = a else { + return None; + }; + let (st, map) = sd_recv(d)?; + let bit = st.signal_bit(key)?; + let truth = match value { + Object::Bool(b) => *b, + Object::Int(v) => *v != 0, + _ => return None, + }; + // SAFETY: as in `sd_getitem`; the displaced value is an int or bool. + unsafe { + let data = map.peek_mut()?; + let i = st.signal_index(data, bit)?; + if !matches!( + data.get_index(i), + Some((_, Object::Bool(_) | Object::Int(_))) + ) { + return None; + } + if let Some((_, v)) = data.map_mut_value_store().get_index_mut(i) { + *v = Object::Bool(truth); + } + } + ok(Object::None) +} + /// `create_decimal(num='0')`: the conversion, then `_fix` under the /// context. fn c_create_decimal(a: &[Object]) -> Option> { @@ -3652,14 +5285,27 @@ pub(crate) fn leaf_compare( b: &Object, ) -> Option> { use weavepy_compiler::CompareKind as C; - let (Object::Instance(i), Object::Instance(j)) = (a, b) else { + let Object::Instance(i) = a else { return None; }; let st = state_of_cls(i.cls_raw())?; - if !st.is_decimal(i) || !st.is_decimal(j) || !sealed(st, i.cls_raw()) { + if !st.is_decimal(i) || !sealed(st, i.cls_raw()) { return None; } - let o = cmp(&st.fin_of(i)?, &st.fin_of(j)?)?; + let o = match b { + Object::Instance(j) => { + if !st.is_decimal(j) { + return None; + } + cmp(&st.fin_of(i)?, &st.fin_of(j)?)? + } + // (An `int` or a `float`, as the methods take them.) + Object::Int(_) | Object::Bool(_) | Object::Long(_) | Object::Float(_) => { + let eq = matches!(op, C::Eq | C::NotEq); + compare_operand(st, &st.fin_of(i)?, b, eq)? + } + _ => return None, + }; Some(Ok(Object::Bool(match op { C::Eq => o.is_eq(), C::NotEq => !o.is_eq(), @@ -3673,6 +5319,18 @@ pub(crate) fn leaf_compare( // --------------------------------------------------------------------- // Installation. +/// Give the native `builtin` the docstring and the `__module__` of +/// `orig`, the Python function it stands in for (so `help` describes it, +/// and `doctest` still finds its examples under the module). +fn carry_doc(builtin: &Object, orig: &Object) { + if let Ok(doc @ Object::Str(_)) = with_interp(|i| i.load_attr(orig, "__doc__")) { + crate::descr_registry::register_doc(builtin, doc); + } + if let Ok(module @ Object::Str(_)) = with_interp(|i| i.load_attr(orig, "__module__")) { + crate::descr_registry::set_builtin_module(builtin, module); + } +} + fn with_interp( f: impl FnOnce(&mut crate::Interpreter) -> Result, ) -> Result { @@ -3963,6 +5621,107 @@ const SPECS: &[Spec] = &[ d_is_subnormal, "($self, /, context=None)" ), + spec!( + D, + "remainder_near", + ["other", "context"], + d_remainder_near, + "($self, /, other, context=None)" + ), + spec!( + D, + "scaleb", + ["other", "context"], + d_scaleb, + "($self, /, other, context=None)" + ), + spec!( + D, + "rotate", + ["other", "context"], + d_rotate, + "($self, /, other, context=None)" + ), + spec!( + D, + "shift", + ["other", "context"], + d_shift, + "($self, /, other, context=None)" + ), + spec!( + D, + "logical_and", + ["other", "context"], + d_logical_and, + "($self, /, other, context=None)" + ), + spec!( + D, + "logical_or", + ["other", "context"], + d_logical_or, + "($self, /, other, context=None)" + ), + spec!( + D, + "logical_xor", + ["other", "context"], + d_logical_xor, + "($self, /, other, context=None)" + ), + spec!(D, "logical_invert", ["context"], d_logical_invert, "($self, /, context=None)"), + spec!(D, "next_plus", ["context"], d_next_plus, "($self, /, context=None)"), + spec!(D, "next_minus", ["context"], d_next_minus, "($self, /, context=None)"), + spec!( + D, + "next_toward", + ["other", "context"], + d_next_toward, + "($self, /, other, context=None)" + ), + spec!(D, "logb", ["context"], d_logb, "($self, /, context=None)"), + spec!(D, "number_class", ["context"], d_number_class, "($self, /, context=None)"), + spec!( + D, + "compare_total", + ["other", "context"], + d_compare_total, + "($self, /, other, context=None)" + ), + spec!( + D, + "compare_total_mag", + ["other", "context"], + d_compare_total_mag, + "($self, /, other, context=None)" + ), + spec!( + D, + "max_mag", + ["other", "context"], + d_max_mag, + "($self, /, other, context=None)" + ), + spec!( + D, + "min_mag", + ["other", "context"], + d_min_mag, + "($self, /, other, context=None)" + ), + spec!(D, "radix", [], d_radix, "($self, /)"), + spec!(D, "exp", ["context"], d_exp, "($self, /, context=None)"), + spec!(D, "ln", ["context"], d_ln, "($self, /, context=None)"), + spec!(D, "log10", ["context"], d_log10, "($self, /, context=None)"), + spec!(D, "sqrt", ["context"], d_sqrt, "($self, /, context=None)"), + spec!( + D, + "fma", + ["other", "third", "context"], + d_fma, + "($self, /, other, third, context=None)" + ), spec!(D, "as_tuple", [], d_as_tuple, "($self, /)"), spec!(D, "as_integer_ratio", [], d_as_integer_ratio, "($self, /)"), spec!( @@ -4043,6 +5802,42 @@ const SPECS: &[Spec] = &[ c_create_decimal_from_float, "($self, f, /)" ), + spec!( + CX, + "__init__", + ["prec", "rounding", "Emin", "Emax", "capitals", "clamp", "flags", "traps"], + c_init, + "($self, /, prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None)" + ), + spec!(CX, "remainder_near", [], c_remainder_near, "($self, a, b, /)"), + spec!(CX, "scaleb", [], c_scaleb, "($self, a, b, /)"), + spec!(CX, "rotate", [], c_rotate, "($self, a, b, /)"), + spec!(CX, "shift", [], c_shift, "($self, a, b, /)"), + spec!(CX, "logical_and", [], c_logical_and, "($self, a, b, /)"), + spec!(CX, "logical_or", [], c_logical_or, "($self, a, b, /)"), + spec!(CX, "logical_xor", [], c_logical_xor, "($self, a, b, /)"), + spec!(CX, "logical_invert", [], c_logical_invert, "($self, a, /)"), + spec!(CX, "next_plus", [], c_next_plus, "($self, a, /)"), + spec!(CX, "next_minus", [], c_next_minus, "($self, a, /)"), + spec!(CX, "next_toward", [], c_next_toward, "($self, a, b, /)"), + spec!(CX, "logb", [], c_logb, "($self, a, /)"), + spec!(CX, "number_class", [], c_number_class, "($self, a, /)"), + spec!(CX, "compare_total", [], c_compare_total, "($self, a, b, /)"), + spec!(CX, "compare_total_mag", [], c_compare_total_mag, "($self, a, b, /)"), + spec!(CX, "max_mag", [], c_max_mag, "($self, a, b, /)"), + spec!(CX, "min_mag", [], c_min_mag, "($self, a, b, /)"), + spec!(CX, "radix", [], d_radix, "($self, /)"), + spec!(CX, "exp", [], c_exp, "($self, a, /)"), + spec!(CX, "ln", [], c_ln, "($self, a, /)"), + spec!(CX, "log10", [], c_log10, "($self, a, /)"), + spec!(CX, "sqrt", [], c_sqrt, "($self, a, /)"), + spec!(CX, "fma", [], c_fma, "($self, a, b, c, /)"), + spec!(CX, "Etiny", [], c_etiny, "($self, /)"), + spec!(CX, "Etop", [], c_etop, "($self, /)"), + spec!(CX, "copy", [], c_copy, "($self, /)"), + spec!(CX, "__copy__", [], c_copy, "($self, /)"), + spec!(CX, "clear_flags", [], c_clear_flags, "($self, /)"), + spec!(CX, "clear_traps", [], c_clear_traps, "($self, /)"), ]; /// A keyword call of a native method: the positional argument list @@ -4073,11 +5868,31 @@ fn kw_positional(params: &[&str], a: &[Object], kw: &[(String, Object)]) -> Opti /// native `getcontext` (or `None` when the classes were already /// installed). pub(crate) fn install(args: &[Object]) -> Result { - let [Object::Type(dec), Object::Type(ctx), Object::Type(sd), Object::Type(dt), Object::List(signals), var, _, Object::Tuple(roundings), getcontext] = + let [Object::Type(dec), Object::Type(ctx), Object::Type(sd), Object::Type(dt), Object::List(signals), var, extra, Object::Tuple(roundings), getcontext] = args else { return Err(type_error("install() expects the decimal classes")); }; + // `(setcontext, DefaultContext, BasicContext, ExtendedContext)`. + let (setcontext, templates) = match extra { + Object::Tuple(t) => { + let mut items = t.iter(); + let f = items.next().cloned(); + let templates: Vec> = items + .filter_map(|o| match o { + Object::Instance(i) => Some(Rc::downgrade(i)), + _ => None, + }) + .collect(); + if templates.len() != 3 { + return Err(type_error( + "install(): expected the three template contexts", + )); + } + (f, templates) + } + _ => (None, Vec::new()), + }; let roundings: Vec = roundings .iter() .filter_map(|o| match o { @@ -4129,7 +5944,6 @@ pub(crate) fn install(args: &[Object]) -> Result { context: Rc::downgrade(ctx), signal_dict: Rc::downgrade(sd), decimal_tuple: Rc::downgrade(dt), - signals, var: var.clone(), roundings, names, @@ -4143,7 +5957,17 @@ pub(crate) fn install(args: &[Object]) -> Result { ctx_keys: AtomicUsize::new(0), ctx_epoch: AtomicU64::new(1), ctx_cache: RefCell::new(None), + current_memo: RefCell::new(None), methods: HashMap::new(), + templates, + clear_flags: { + let mut d = DictData::default(); + for s in &signals { + d.insert(DictKey(s.clone()), Object::Bool(false)); + } + d + }, + signals, }; // The natives go in first, then the class version they leave is the // sealed one. @@ -4189,6 +6013,9 @@ pub(crate) fn install(args: &[Object]) -> Result { } let value = Object::Builtin(b.clone()); crate::descr_registry::register_text_signature(&value, spec.sig); + if let Some(replaced) = state.orig.get(&key) { + carry_doc(&value, replaced); + } let value = if spec.classmethod { Object::ClassMethod(crate::object::MethodWrapper::new(value)) } else { @@ -4202,13 +6029,67 @@ pub(crate) fn install(args: &[Object]) -> Result { .borrow_mut() .insert(DictKey(Object::Str(interned(name))), value); } + // `Context.__setattr__` and the signal mappings' item methods: the + // native half, or the Python method each replaces. + let hand: [( + &Rc, + &'static str, + &'static str, + Fast, + &'static str, + ); 3] = [ + ( + ctx, + "__setattr__", + std::str::from_utf8(&CTX_SETATTR).expect("ASCII"), + c_setattr, + "($self, name, value, /)", + ), + ( + sd, + "__getitem__", + "__getitem__", + sd_getitem, + "($self, key, /)", + ), + ( + sd, + "__setitem__", + "__setitem__", + sd_setitem, + "($self, key, value, /)", + ), + ]; + for (cls, name, own_name, fast, sig) in hand { + let Some(orig) = cls.dict.borrow().get(&crate::object::StrKey(name)).cloned() else { + return Err(type_error(format!("install(): {} has no {name}", cls.name))); + }; + let replaced = orig.clone(); + let b = Rc::new(BuiltinFn { + name: own_name, + binds_instance: true, + call: Box::new(move |a: &[Object]| match fast(a) { + Some(r) => r, + None => with_interp(|i| i.call_object(orig.clone(), a, &[])), + }), + call_kw: None, + }); + crate::leaf_builtins::register_fast(&b, fast); + let value = Object::Builtin(b); + crate::descr_registry::register_text_signature(&value, sig); + carry_doc(&value, &replaced); + cls.dict + .borrow_mut() + .insert(DictKey(Object::Str(interned(name))), value); + } + sd.bump_attr_version(); for (_, cls) in &classes { cls.bump_attr_version(); } state.sealed = dec.attr_version.get(); let state = Rc::new(state); let _ = pending.set(state.clone()); - for (_, cls) in &classes { + for cls in [dec, ctx, sd] { let _ = cls .native_ext .set(crate::rc_unsize!(state.clone() => dyn std::any::Any + Send + Sync)); @@ -4240,6 +6121,7 @@ pub(crate) fn install(args: &[Object]) -> Result { })); crate::descr_registry::register_module(&native_getcontext, "decimal"); crate::descr_registry::register_text_signature(&native_getcontext, "()"); + carry_doc(&native_getcontext, getcontext); // `_context_changed()`: `Context.__setattr__`'s note that a context // attribute changed (see `State::read_ctx`). let st_changed = state.clone(); @@ -4253,9 +6135,40 @@ pub(crate) fn install(args: &[Object]) -> Result { call_kw: None, }); crate::leaf_builtins::register(&changed); + // `setcontext(context)`: the store for a context of the caller's own, + // else the Python function (which copies a template, or raises). + let native_setcontext = match setcontext { + Some(orig) => { + let (orig_kw, replaced) = (orig.clone(), orig.clone()); + let b = Rc::new(BuiltinFn { + name: "setcontext", + binds_instance: false, + call: Box::new(move |a: &[Object]| match m_setcontext(a) { + Some(r) => r, + None => with_interp(|i| i.call_object(orig.clone(), a, &[])), + }), + call_kw: Some(Box::new(move |a: &[Object], kw: &[(String, Object)]| { + if kw.is_empty() { + if let Some(r) = m_setcontext(a) { + return r; + } + } + with_interp(|i| i.call_object(orig_kw.clone(), a, kw)) + })), + }); + crate::leaf_builtins::register_fast(&b, m_setcontext); + let f = Object::Builtin(b); + carry_doc(&f, &replaced); + crate::descr_registry::register_module(&f, "decimal"); + crate::descr_registry::register_text_signature(&f, "(context, /)"); + f + } + None => Object::None, + }; Ok(Object::new_tuple_array([ native_getcontext, Object::Builtin(changed), + native_setcontext, ])) } diff --git a/crates/weavepy-vm/src/stdlib/elementtree_native.rs b/crates/weavepy-vm/src/stdlib/elementtree_native.rs index 67c0f6598..6eec48384 100644 --- a/crates/weavepy-vm/src/stdlib/elementtree_native.rs +++ b/crates/weavepy-vm/src/stdlib/elementtree_native.rs @@ -140,6 +140,8 @@ pub(crate) struct State { handlers: std::sync::OnceLock<[usize; 3]>, /// Each class's [`KeyMap`]. keymaps: [KeyMap; 3], + /// The paths [`path_steps`] last compiled. + path_memo: RefCell<[Option; PATH_MEMOS]>, } impl State { @@ -353,6 +355,29 @@ const E_ATTRIB: usize = 1; const E_CHILDREN: usize = 2; const E_TEXT: usize = 3; +/// Field `f` of `i`, an `Element`: read by position when the instance's +/// values lie over its class's shared names with the field where +/// `Element.__init__` puts it (what the class's [`KeyMap`] says of that +/// position, once a [`scan`] has filled it), else by name +/// ([`get_field`]). `None` for a field not set. +#[inline] +fn field(st: &State, i: &PyInstance, f: usize) -> Option { + if let Some(keys) = class_of(i).shared_keys.get() { + let kp: *const crate::inst_dict::SharedKeys = keys; + let km = &st.keymaps[ELEMENT]; + if km.keys.load(Ordering::Relaxed) == kp as usize + && km.len.load(Ordering::Relaxed) > f + && km.field_at(f) == f + 1 + { + // SAFETY: a read that ends before anything else runs. + if let Some(v) = unsafe { i.dict.split_peek() }.and_then(|s| s.get_over(kp, f)) { + return Some(v.clone()); + } + } + } + get_field(i, &st.names.element_fields[f]) +} + /// Which of `fields` the attribute name `s` is: the name at position /// `hint` first, then by identity (interned names), then by contents. #[inline] @@ -754,7 +779,12 @@ fn el_getitem(st: &State, a: &[Object], _kw: Kw) -> Option Option { - match element_view(st, o)?.attrib? { + let i = plain(st, o)?; + // (As `view` asks of the children: a list, when set.) + if !matches!(field(st, i, E_CHILDREN), None | Some(Object::List(_))) { + return None; + } + match field(st, i, E_ATTRIB)? { Object::Dict(d) => Some(d), _ => None, } @@ -925,17 +955,19 @@ fn new_iter(cls: Rc, root: Object, tag: Object, mode: i64) -> Object } else { (new_list(vec![root, Object::Int(F_VISIT_ROOT)]), tag) }; - let mut i = PyInstance::new(t.cls.clone()); - i.slots = RefCell::new(SlotStorage::from_layout( - t.layout.clone(), - vec![ - stack, - tag, - Object::Int(mode), - Object::Bool(false), - Object::Type(cls), - ], - )); + let i = PyInstance::with_slots( + t.cls.clone(), + SlotStorage::from_layout( + t.layout.clone(), + vec![ + stack, + tag, + Object::Int(mode), + Object::Bool(false), + Object::Type(cls), + ], + ), + ); let o = Object::Instance(Rc::new(i)); crate::gc_trace::track(&o); o @@ -1127,10 +1159,53 @@ fn iter_next(a: &[Object]) -> Result { /// runs in place over the iterator's fields and stack, since it runs no /// Python code. fn iter_next_fast(a: &[Object]) -> Option> { - let t = iter_type(); let Some(Object::Instance(it)) = a.first() else { return None; }; + match leaf_step(it)? { + Ok(Step::Yield(v)) => Some(Ok(v)), + // The full body raises `StopIteration` (the core loop asks it + // again for an exhausted leaf iterator anyway). + Ok(Step::Done | Step::Decline) => None, + Err(e) => Some(Err(e)), + } +} + +/// How a `for` loop's step of an element iterator went (see +/// [`for_step`]). +pub(crate) enum ForStep { + Item(Object), + /// The iterator is exhausted (and stays so). + End, + /// Not an element iterator, or a step that needs its full `__next__`. + Other, +} + +/// A `for` loop's step over `it` in compiled code: an element iterator's +/// next element or text (`for e in elem`, `elem.iter()`, +/// `elem.itertext()`), or its end with no `StopIteration` raised to say +/// so, when the step runs no Python code. +#[inline] +pub(crate) fn for_step(it: &PyInstance) -> ForStep { + if !std::ptr::eq(class_of(it), Rc::as_ptr(&iter_type().cls)) + || crate::gil::free_threading_enabled() + { + return ForStep::Other; + } + match leaf_step(it) { + Some(Ok(Step::Yield(v))) => ForStep::Item(v), + Some(Ok(Step::Done)) => ForStep::End, + _ => ForStep::Other, + } +} + +/// One step of the element iterator `it` over its fields and stack in +/// place, when it runs no Python code: what it yields, or `Done` at its +/// end (which it keeps: the next step is `Done` too). `None`, or +/// `Decline`, with nothing consumed, for a step the full body takes (a +/// running iterator, an element the natives don't serve). +fn leaf_step(it: &PyInstance) -> Option> { + let t = iter_type(); let mut exhausted = Object::None; let r = write(&it.slots, |s| { let v = s.values_for_layout_mut(&t.layout)?; @@ -1141,9 +1216,12 @@ fn iter_next_fast(a: &[Object]) -> Option> { // negative and the element is dropped (after this borrow); // the full body raises `StopIteration`. let i = *i; - if i < 0 || !matches!(v[IT_RUNNING], Object::Bool(false)) { + if !matches!(v[IT_RUNNING], Object::Bool(false)) { return None; } + if i < 0 { + return Some(Ok(Step::Done)); + } let st = state_of_cls(cls)?; return match child_native(st, &v[IT_TAG], i)? { Some(c) => { @@ -1153,7 +1231,7 @@ fn iter_next_fast(a: &[Object]) -> Option> { None => { v[IT_STACK] = Object::Int(-1); exhausted = std::mem::replace(&mut v[IT_TAG], Object::None); - None + Some(Ok(Step::Done)) } }; } @@ -1169,13 +1247,7 @@ fn iter_next_fast(a: &[Object]) -> Option> { }) .flatten(); release(exhausted); - match r? { - Ok(Step::Yield(v)) => Some(Ok(v)), - // The full body raises `StopIteration` (the core loop asks it - // again for an exhausted leaf iterator anyway). - Ok(Step::Done | Step::Decline) => None, - Err(e) => Some(Err(e)), - } + r } /// One step of a sequence iterator (`iter(elem)`): `elem[i]`. @@ -1275,7 +1347,6 @@ fn step_iter( it: &PyInstance, leaf: bool, ) -> Result { - let n = &st.names; loop { let Some((obj, marker)) = frames.top() else { return Ok(Step::Done); @@ -1322,7 +1393,7 @@ fn step_iter( frames.pop(); continue; }; - match get_field(e, &n.children) { + match field(st, e, E_CHILDREN) { Some(l @ Object::List(_)) => frames.set_top(l, 0), _ if leaf => return Ok(Step::Decline), other => { @@ -1418,7 +1489,7 @@ fn text_bearing(tag: &Object) -> bool { /// element whose children are a list): `Some(None)` past the end. fn child_native(st: &State, e: &Object, i: i64) -> Option> { let inst = st.exact(ELEMENT, e)?; - match get_field(inst, &st.names.children)? { + match field(st, inst, E_CHILDREN)? { Object::List(l) => Some(item(&l, i as usize)), _ => None, } @@ -1602,6 +1673,23 @@ fn el_itertext(st: &State, a: &[Object], kw: Kw) -> Option>, +} + +/// How many paths' steps a module keeps (one `find` or `findall` call +/// site each, in the common loop). +const PATH_MEMOS: usize = 4; + /// One step of a selector `ElementPath` compiled: which of its `select` /// closures it is, with the closure's tag, key or value. enum PathStep { @@ -1691,16 +1779,63 @@ fn path_steps( which: usize, path: &Object, namespaces: &Object, -) -> Option> { +) -> Option>> { let Object::Str(p) = path else { return None; }; - if !matches!(namespaces, Object::None) || p.ends_with('/') { + if !matches!(namespaces, Object::None) { + return None; + } + let (ns, path_ns) = (st.ns.upgrade()?, st.path_ns.upgrade()?); + // SAFETY: stamp reads, each ended before anything else runs. + let stamps = |cache: &Dict| unsafe { + Some([ + ns.peek()?.mutation_stamp(), + path_ns.peek()?.mutation_stamp(), + cache.peek()?.mutation_stamp(), + crate::object::global_value_epoch(), + ]) + }; + let slot = (SharedStr::as_ptr(p).cast::() as usize >> 4).wrapping_add(which) % PATH_MEMOS; + // SAFETY: nothing below runs code while the memo is viewed. + if let Some(Some(m)) = unsafe { st.path_memo.peek() }.map(|ms| &ms[slot]) { + if m.which == which + && (SharedStr::ptr_eq(&m.path, p) || *m.path == **p) + && stamps(&m.cache) == Some(m.stamps) + { + return Some(m.steps.clone()); + } + } + let (steps, cache) = path_steps_slow(st, &path_ns, which, path, p)?; + let steps = Rc::new(steps); + if let (Some(stamps), Ok(mut ms)) = (stamps(&cache), st.path_memo.try_borrow_mut()) { + ms[slot] = Some(PathMemo { + path: p.clone(), + which, + stamps, + cache, + steps: steps.clone(), + }); + } + Some(steps) +} + +/// [`path_steps`] from `ElementPath`'s own cache (`path_ns` its +/// namespace, `p` the path's text): the steps, and the cache they came +/// from. +#[inline(never)] +fn path_steps_slow( + st: &State, + path_ns: &Dict, + which: usize, + path: &Object, + p: &SharedStr, +) -> Option<(Vec, Dict)> { + if p.ends_with('/') { return None; } - let path_ns = st.path_ns.upgrade()?; match st.global("ElementPath")? { - Object::Module(m) if Rc::ptr_eq(&m.dict, &path_ns) => {} + Object::Module(m) if Rc::ptr_eq(&m.dict, path_ns) => {} _ => return None, } let (cache, ok) = { @@ -1730,7 +1865,7 @@ fn path_steps( if probe.exotic.get() { return None; } - compile_selector(&path_ns, &selector) + Some((compile_selector(path_ns, &selector)?, cache)) } /// An `ElementPath._cache` probe for the key `(path,)`, compared natively: @@ -1770,7 +1905,7 @@ impl crate::dictmap::Probe for PathKey<'_> { /// `e.tag == tag` for an exact element `e` and a `str` tag. fn tag_is(st: &State, e: &Object, tag: &SharedStr) -> Option { let inst = st.exact(ELEMENT, e)?; - match get_field(inst, &st.names.tag).unwrap_or(Object::None) { + match field(st, inst, E_TAG).unwrap_or(Object::None) { Object::Str(s) => Some(SharedStr::ptr_eq(&s, tag) || *s == **tag), Object::None | Object::Function(_) | Object::Builtin(_) => Some(false), _ => None, @@ -1916,7 +2051,7 @@ fn el_findtext(st: &State, a: &[Object], kw: Kw) -> Option Object::from_static(""), Some(t) => t, })) @@ -3446,6 +3581,7 @@ fn install(args: &[Object]) -> Result { path_funcs, handlers: std::sync::OnceLock::new(), keymaps: Default::default(), + path_memo: RefCell::new(Default::default()), }); let mut handlers = [0; 3]; for spec in SPECS { diff --git a/crates/weavepy-vm/src/stdlib/functools_mod.rs b/crates/weavepy-vm/src/stdlib/functools_mod.rs index 142bd0edf..b660d2d8e 100644 --- a/crates/weavepy-vm/src/stdlib/functools_mod.rs +++ b/crates/weavepy-vm/src/stdlib/functools_mod.rs @@ -45,6 +45,15 @@ pub fn build(_cache: &ModuleCache) -> Rc { call_kw: None, })), ); + d.insert( + DictKey(Object::from_static("_update_wrapper_plain")), + Object::Builtin(Rc::new(BuiltinFn { + name: "_update_wrapper_plain", + binds_instance: false, + call: Box::new(update_wrapper_plain), + call_kw: None, + })), + ); d.insert( DictKey(Object::from_static("cmp_to_key")), Object::Builtin(Rc::new(BuiltinFn { @@ -96,6 +105,9 @@ struct PartialReg { cls: crate::sync::Weak, placeholder: Object, py_new: Object, + /// Whether the class lays out exactly [`PARTIAL_SLOTS`], in order (its + /// instances' slots are then built in one piece). + laid_out: std::sync::OnceLock, } /// `_partial_new_for(partial, Placeholder, _partial_new)`: the native @@ -111,7 +123,17 @@ fn partial_new_for(args: &[Object]) -> Result { cls: Rc::downgrade(cls), placeholder: placeholder.clone(), py_new: py_new.clone(), + laid_out: std::sync::OnceLock::new(), }); + // (`partial(f, *args)` of the exact class builds in place through the + // class's constructor hook, which finds this registration on it.) + if cls + .native_ext + .set(crate::rc_unsize!(reg.clone() => dyn std::any::Any + Send + Sync)) + .is_ok() + { + cls.pure_new.set(Some(partial_pure_new)); + } let reg_kw = reg.clone(); Ok(Object::Builtin(Rc::new(BuiltinFn { name: "__new__", @@ -182,7 +204,7 @@ pub(crate) fn with_partial_call( thread_local! { /// The interned names of a partial's first four slots. - static PARTIAL_KEYS: [crate::shared_value::SharedStr; 4] = PARTIAL_SLOTS[..4] + static PARTIAL_KEYS: crate::gil::ReleaseUnderGil<[crate::shared_value::SharedStr; 4]> = crate::gil::ReleaseUnderGil::new(PARTIAL_SLOTS[..4] .iter() .map(|name| match crate::stdlib::sys::intern_name(name) { Object::Str(s) => s, @@ -190,7 +212,7 @@ thread_local! { }) .collect::>() .try_into() - .unwrap_or_else(|_| unreachable!("four names")); + .unwrap_or_else(|_| unreachable!("four names"))); } /// `f` over a partial instance's `_func`, `_args`, `_keywords`, and @@ -200,10 +222,20 @@ fn with_partial_fields( inst: &crate::types::PyInstance, f: impl FnOnce([&Object; 4]) -> R, ) -> Option { + /// The `__slots__` layout found led by the four names (see + /// `SlotStorage::leading_memo`): a store with it skips their + /// comparison at every call. + static PARTIAL_LAYOUT: crate::types::LayoutMemo = crate::types::LayoutMemo::new(); + // (The remembered layout first: it needs no names, so no thread-local.) + // SAFETY: a read; `f` runs no code that could borrow the slots. + if let Some(fields) = unsafe { inst.slots.peek() }?.leading_memo_hit(&PARTIAL_LAYOUT) { + return Some(f(fields)); + } PARTIAL_KEYS.with(|keys| { // SAFETY: a read; `f` runs no code that could borrow the slots. let slots = unsafe { inst.slots.peek() }?; - let fields = slots.leading_interned([&keys[0], &keys[1], &keys[2], &keys[3]])?; + let fields = + slots.leading_memo(&PARTIAL_LAYOUT, [&keys[0], &keys[1], &keys[2], &keys[3]])?; Some(f(fields)) }) } @@ -250,6 +282,41 @@ fn partial_new( let Object::Type(sub) = &args[0] else { unreachable!("checked above"); }; + Ok(build_partial(reg, &cls, sub, &args[1], &args[2..], kwargs)) +} + +/// `partial(func, *args)` of the exact class, from its constructor hook: +/// as [`partial_new`] builds the common shape (a callable that isn't a +/// partial, no `Placeholder`), anything else left to the call. +fn partial_pure_new(cls: &Rc, args: &[Object]) -> Option { + let reg = cls.native_ext.get()?.downcast_ref::()?; + let own = reg.cls.upgrade()?; + if !Rc::ptr_eq(&own, cls) { + return None; + } + let [func, rest @ ..] = args else { + return None; + }; + if !crate::builtins::object_is_callable(func) + || matches!(func, Object::Instance(i) if i.cls().is_subclass_of(&own)) + || rest.iter().any(|a| a.is_same(®.placeholder)) + { + return None; + } + Some(build_partial(reg, &own, cls, func, rest, &[])) +} + +/// A new `partial` instance of `sub` (a subclass of `cls`, the registered +/// class) over `func`, the stored positionals and keywords, its slots laid +/// out as both constructors lay them out. +fn build_partial( + reg: &PartialReg, + cls: &Rc, + sub: &Rc, + func: &Object, + rest: &[Object], + kwargs: &[(String, Object)], +) -> Object { let mut kw = DictData::default(); for (k, v) in kwargs { kw.insert(DictKey(Object::from_str(k.clone())), v.clone()); @@ -257,19 +324,42 @@ fn partial_new( let keywords = Object::Dict(Rc::new(RefCell::new(kw))); crate::gc_trace::track(&keywords); let values = [ - args[1].clone(), - Object::new_tuple(args[2..].to_vec()), + func.clone(), + Object::tuple_from_slice(rest), keywords, Object::Int(0), Object::None, ]; - let inst = crate::types::PyInstance::new(sub.clone()); - for (name, v) in PARTIAL_SLOTS.iter().zip(values) { - inst.slot_set(name, v); - } + // (The exact class's slots in one piece; a subclass's own layout has + // its own slots after these.) + let layout = Rc::ptr_eq(sub, cls) + .then(|| cls.own_slot_layout()) + .flatten() + .filter(|layout| { + *reg.laid_out.get_or_init(|| { + layout.len() == PARTIAL_SLOTS.len() + && layout + .iter() + .zip(PARTIAL_SLOTS) + .all(|(k, n)| matches!(&k.0, Object::Str(s) if s.as_ref() == n)) + }) + }); + let inst = match layout { + Some(layout) => crate::types::PyInstance::with_slots( + sub.clone(), + crate::types::SlotStorage::from_layout_array(layout.clone(), values), + ), + None => { + let inst = crate::types::PyInstance::new(sub.clone()); + for (name, v) in PARTIAL_SLOTS.iter().zip(values) { + inst.slot_set(name, v); + } + inst + } + }; let obj = Object::Instance(Rc::new(inst)); crate::gc_trace::track(&obj); - Ok(obj) + obj } /// `partial.__call__(self, /, *args, **keywords)` without a Python @@ -326,6 +416,13 @@ fn partial_call(args: &[Object], kwargs: &[(String, Object)]) -> Result = Vec::with_capacity(stored.len() + args.len() - 1); call_args.extend(stored.iter().cloned()); call_args.extend_from_slice(&args[1..]); @@ -363,8 +460,9 @@ fn partial_call(args: &[Object], kwargs: &[(String, Object)]) -> Result Result { let mycmp = match (args, kwargs) { ([m], []) => m.clone(), @@ -389,11 +487,38 @@ fn cmp_to_key(args: &[Object], kwargs: &[(String, Object)]) -> Result = const { std::cell::Cell::new(0) }; +} + +/// The comparison function a `cmp_to_key(mycmp)` key factory wraps, when +/// `key` is one: a sort by it can compare items with `mycmp(a, b) < 0` +/// directly, which is what the wrappers' `<` does (CPython's +/// `KeyWrapper.__lt__`), without making a wrapper per item. +pub(crate) fn cmp_key_func(key: &Object) -> Option { + let Object::Instance(inst) = key else { + return None; + }; + let cls = inst.class.try_borrow().ok()?; + if Rc::as_ptr(&cls) as usize != CMP_TO_KEY_CLASS.with(|c| c.get()) || !cls.immutable.get() { + return None; + } + inst.slots.try_borrow().ok()?.get("_mycmp").cloned() +} + // --------------------------------------------------------------------------- // `_lru_cache_wrapper` — native `functools.lru_cache` core. // @@ -440,8 +565,7 @@ static LRU_TYPE_ADDR: std::sync::atomic::AtomicUsize = std::sync::atomic::Atomic fn lru_type() -> Rc { thread_local! { - static LRU_TYPE: RefCell>> = - const { RefCell::new(None) }; + static LRU_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } LRU_TYPE.with(|slot| { if let Some(t) = slot.borrow().as_ref() { @@ -774,10 +898,115 @@ fn native_lru_tuple_key(key: &Object, depth: usize, remaining: &mut usize) -> bo || Rc::ptr_eq(cls, &builtins.str_) || Rc::ptr_eq(cls, &builtins.bytes_) || Rc::ptr_eq(cls, &builtins.tuple_) + // (Or a user class that hashes and compares by identity, + // `typing`'s generics; see the instance arm below. The + // other builtin classes stay off this path: a typed key's + // `float` or `bool` would meet `1 == 1.0 == True`.) + || (!cls.flags.is_builtin && crate::object::type_hash_is_identity(cls)) } Object::Tuple(items) if depth > 0 && items.len() <= *remaining => items .iter() .all(|item| native_lru_tuple_key(item, depth - 1, remaining)), + // An argument that hashes and compares by identity (`typing`'s + // `_tp_cache` keys an alias and a class): nothing runs for either, + // and an evicted key is released with the cache consistent. + Object::Instance(i) => crate::object::identity_instance(i), + _ => false, + } +} + +/// The Python hash of a key item a probe takes (native scalars, objects +/// that hash by identity, and, `depth` deep, tuples of these), or `None`. +fn item_hash(item: &Object, depth: u32) -> Option { + Some(match item { + Object::Int(i) => crate::object::py_hash_long_i64(*i), + Object::Str(s) => crate::shared_value::SharedStr::hash_cached(s), + Object::None | Object::Bool(_) | Object::Float(_) | Object::Bytes(_) => { + crate::object::py_hash_value(item)? + } + // An object that hashes and compares by identity (`typing`'s + // `_tp_cache` keys an alias and a class), as the native key admits + // it (see `native_lru_tuple_key`). + Object::Instance(_) | Object::Type(_) if identity_item(item) => { + crate::object::identity_hash(item) + } + // (`Dict[str, Any]`'s parameters.) + Object::Tuple(items) if depth > 0 => { + let mut hash = crate::object::TupleHasher::new(); + for it in items.iter() { + hash.push(item_hash(it, depth - 1)?); + } + hash.finish(items.len()) + } + _ => return None, + }) +} + +/// Whether a probe's key item `arg` equals a stored key's `item`, as the +/// tuples' comparison would find, when that runs no Python code: `None` +/// when it might (a pairing only Python's `==` settles). +fn item_eq(arg: &Object, item: &Object, depth: u32) -> Option { + Some(match (arg, item) { + (Object::Int(a), Object::Int(b)) => a == b, + (Object::Str(a), Object::Str(b)) => { + crate::shared_value::SharedStr::ptr_eq(a, b) + || crate::dictmap::key_bytes_eq(a.as_bytes(), b.as_bytes()) + } + (Object::Bytes(a), Object::Bytes(b)) => a[..] == b[..], + // Two identity-comparing objects: the same one or unequal (no + // `__eq__` of either runs). + (a @ (Object::Instance(_) | Object::Type(_)), b) + if identity_item(a) && identity_item(b) => + { + a.is_same(b) + } + (Object::Instance(_) | Object::Type(_), _) => return None, + (Object::Tuple(a), Object::Tuple(b)) if depth > 0 => { + if a.len() != b.len() { + return Some(false); + } + for (x, y) in a.iter().zip(b.iter()) { + if !item_eq(x, y, depth - 1)? { + return Some(false); + } + } + true + } + // A tuple against anything else (or past the depth): Python's. + (Object::Tuple(_), _) => return None, + // A scalar never equals a tuple. + (_, Object::Tuple(_)) => false, + // (`bytes` against a `str` may warn under `-b`.) + (Object::Bytes(_), _) | (_, Object::Bytes(_)) => return None, + // Builtin scalars compare natively (`1 == 1.0 == True`), identity + // first as a tuple's items do. + ( + arg, + item @ (Object::None + | Object::Bool(_) + | Object::Int(_) + | Object::Long(_) + | Object::Float(_) + | Object::Str(_) + | Object::WStr(_)), + ) => arg.is_same(item) || arg.eq_value(item), + _ => return None, + }) +} + +/// Whether `item` hashes and compares by identity with nothing run, as +/// [`native_lru_tuple_key`] admits an instance or a class. +fn identity_item(item: &Object) -> bool { + match item { + Object::Instance(i) => crate::object::identity_instance(i), + Object::Type(cls) => { + let builtins = crate::builtin_types::builtin_types(); + Rc::ptr_eq(cls, &builtins.int_) + || Rc::ptr_eq(cls, &builtins.str_) + || Rc::ptr_eq(cls, &builtins.bytes_) + || Rc::ptr_eq(cls, &builtins.tuple_) + || (!cls.flags.is_builtin && crate::object::type_hash_is_identity(cls)) + } _ => false, } } @@ -956,6 +1185,10 @@ fn lru_native_lookup( let value = data.get_index(index)?.1.clone(); if bounded { lru_state::Links::new(&mut bytes, data.len())?.touch(index)?; + // (Counted with the scalar path's: the bounded native hits + // keep the same recency links.) + #[cfg(test)] + note_scalar_lru_event(0); } lru_state::hit(&mut bytes)?; Some(NativeLookup::Hit(value)) @@ -1034,6 +1267,8 @@ fn native_store_in( return Ok(None); }; links.touch(head).ok_or_else(invalid_lru_order)?; + #[cfg(test)] + note_scalar_lru_event(1); let evicted = data.replace_index_unique(head, hash, DictKey(key.clone()), result.clone()); return Ok(Some(evicted)); } @@ -1140,8 +1375,8 @@ fn lru_flush_deferred() -> Result<(), RuntimeError> { /// `args`, settled natively without running Python code: the hit, or the /// exact miss the caller may run the wrapped function for in place (see /// [`LruProbe`]), or `None`, nothing touched, for the full call. The core -/// loop and the frame JIT try it at a `CALL` of an instance: a sole exact -/// `int` or `str` argument of an untyped wrapper, while nothing else holds +/// loop and the frame JIT try it at a `CALL` of an instance: native +/// positional arguments (of a typed wrapper too), while nothing else holds /// its state. #[inline] pub(crate) fn lru_probe(inst: &crate::types::PyInstance, args: &[Object]) -> Option { @@ -1152,21 +1387,47 @@ pub(crate) fn lru_probe(inst: &crate::types::PyInstance, args: &[Object]) -> Opt return None; } match args { - // A sole exact `int` or `str` is its own key. - [key @ (Object::Int(_) | Object::Str(_))] => { - lru_probe_with::<_, true>(inst, &crate::object::LeafProbe::new(key)?, || key.clone()) - } + // A sole exact `int` or `str` is its own key (an untyped wrapper's). + [key @ (Object::Int(_) | Object::Str(_))] => lru_probe_with::<_, true>( + inst, + |typed| CallProbe::sole(key, typed), + |typed| sole_key(key, typed), + ), // Other native positional arguments key on their tuple, probed // without building it unless the call misses. - [_, ..] if args.len() <= LRU_ARGS_MAX => { - lru_probe_with::<_, true>(inst, &ArgsProbe::new(args, &[], &[])?, || { - Object::new_tuple(args.to_vec()) - }) - } + [_, ..] if args.len() <= LRU_ARGS_MAX => lru_probe_with::<_, true>( + inst, + |typed| CallProbe::args(args, typed), + |typed| lru_make_key(args, &[], typed), + ), _ => None, } } +/// The key of a sole exact `int` or `str` argument: itself, or with its +/// class for a typed wrapper. +fn sole_key(key: &Object, typed: bool) -> Object { + if typed { + lru_make_key(std::slice::from_ref(key), &[], true) + } else { + key.clone() + } +} + +/// [`lru_hit`] of `inst` if it's a wrapper (`f(*args)` forwarded to one, +/// as `typing`'s `_tp_cache` does). +pub(crate) fn lru_hit_if_wrapper( + inst: &crate::types::PyInstance, + args: &[Object], +) -> Option { + if std::ptr::from_ref(inst.cls_raw()) as usize + != LRU_TYPE_ADDR.load(std::sync::atomic::Ordering::Relaxed) + { + return None; + } + lru_hit(inst, args) +} + /// [`lru_probe`]'s hit for a native caller (`Interpreter::call`), which /// can't run a miss in place: `None`, nothing touched, for the full call. fn lru_hit(inst: &crate::types::PyInstance, args: &[Object]) -> Option { @@ -1174,16 +1435,16 @@ fn lru_hit(inst: &crate::types::PyInstance, args: &[Object]) -> Option { return None; } let probe = match args { - [key @ (Object::Int(_) | Object::Str(_))] => { - lru_probe_with::<_, false>(inst, &crate::object::LeafProbe::new(key)?, || { - unreachable!("no miss is run") - }) - } - [_, ..] if args.len() <= LRU_ARGS_MAX => { - lru_probe_with::<_, false>(inst, &ArgsProbe::new(args, &[], &[])?, || { - unreachable!("no miss is run") - }) - } + [key @ (Object::Int(_) | Object::Str(_))] => lru_probe_with::<_, false>( + inst, + |typed| CallProbe::sole(key, typed), + |_| unreachable!("no miss is run"), + ), + [_, ..] if args.len() <= LRU_ARGS_MAX => lru_probe_with::<_, false>( + inst, + |typed| CallProbe::args(args, typed), + |_| unreachable!("no miss is run"), + ), _ => None, }; match probe? { @@ -1232,8 +1493,15 @@ pub(crate) fn lru_hit_kw( { return None; } - let probe = ArgsProbe::new(args, names, values)?; - match lru_probe_with::<_, false>(inst, &probe, || unreachable!("no miss is run"))? { + match lru_probe_with::<_, false>( + inst, + |typed| { + (!typed) + .then(|| ArgsProbe::new(args, names, values)) + .flatten() + }, + |_| unreachable!("no miss is run"), + )? { LruProbe::Hit(value) => Some(value), LruProbe::Miss(..) => None, } @@ -1297,14 +1565,7 @@ impl<'a> ArgsProbe<'a> { }; let mut hash = crate::object::TupleHasher::new(); for i in 0..len { - hash.push(match probe.item(i) { - Object::Int(i) => crate::object::py_hash_long_i64(*i), - Object::Str(s) => crate::shared_value::SharedStr::hash_cached(s), - item @ (Object::None | Object::Bool(_) | Object::Float(_) | Object::Bytes(_)) => { - crate::object::py_hash_value(item)? - } - _ => return None, - }); + hash.push(item_hash(probe.item(i), 1)?); } probe.hash = hash.finish(len); Some(probe) @@ -1350,44 +1611,126 @@ impl crate::dictmap::Probe for ArgsProbe<'_> { // unequal pair settles it. Object::Tuple(items) if items.len() == self.len => { for (i, item) in items.iter().enumerate() { - let equal = match (self.item(i), item) { - (Object::Int(a), Object::Int(b)) => a == b, - (Object::Str(a), Object::Str(b)) => { - crate::shared_value::SharedStr::ptr_eq(a, b) - || crate::dictmap::key_bytes_eq(a.as_bytes(), b.as_bytes()) + match item_eq(self.item(i), item, 1) { + Some(true) => {} + Some(false) => return false, + None => { + self.foreign.set(true); + return false; } - (Object::Bytes(a), Object::Bytes(b)) => a[..] == b[..], - // A scalar never equals a tuple. - (_, Object::Tuple(_)) => false, - // (`bytes` against a `str` may warn under `-b`.) - (Object::Bytes(_), _) | (_, Object::Bytes(_)) => { + } + } + true + } + // Builtin keys a tuple of these never equals. + Object::Int(_) + | Object::Long(_) + | Object::Str(_) + | Object::WStr(_) + | Object::Bytes(_) + | Object::Tuple(_) => false, + _ => { + self.foreign.set(true); + false + } + } + } +} + +impl ExactProbe for ArgsProbe<'_> { + #[inline(always)] + fn exact(&self) -> bool { + !self.foreign.get() + } +} + +/// The most positional arguments a typed wrapper's call is probed with +/// natively. +const LRU_TYPED_MAX: usize = 4; + +/// A builtin class the typed key admits natively: it hashes and compares by +/// identity (see [`identity_item`]). +#[inline] +fn identity_class(cls: &Rc) -> bool { + let builtins = crate::builtin_types::builtin_types(); + Rc::ptr_eq(cls, &builtins.str_) + || Rc::ptr_eq(cls, &builtins.int_) + || Rc::ptr_eq(cls, &builtins.bytes_) + || Rc::ptr_eq(cls, &builtins.tuple_) + || (!cls.flags.is_builtin && crate::object::type_hash_is_identity(cls)) +} + +/// A typed wrapper's key for positional `args` (the arguments, then each +/// one's class), probed in place as [`ArgsProbe`] probes an untyped one. +struct TypedArgsProbe<'a> { + args: &'a [Object], + classes: [Option>; LRU_TYPED_MAX], + hash: i64, + foreign: std::cell::Cell, +} + +impl<'a> TypedArgsProbe<'a> { + #[inline] + fn new(args: &'a [Object]) -> Option { + if args.len() > LRU_TYPED_MAX { + return None; + } + let mut classes: [Option>; LRU_TYPED_MAX] = Default::default(); + let mut hash = crate::object::TupleHasher::new(); + for a in args { + hash.push(item_hash(a, 1)?); + } + for (slot, a) in classes.iter_mut().zip(args) { + let cls = crate::builtins::class_of(a); + if !identity_class(&cls) { + return None; + } + // (As `identity_hash` hashes a class.) + hash.push(crate::object::pointer_hash(Rc::as_ptr(&cls).cast())); + *slot = Some(cls); + } + Some(Self { + args, + classes, + hash: hash.finish(2 * args.len()), + foreign: std::cell::Cell::new(false), + }) + } +} + +impl crate::dictmap::Probe for TypedArgsProbe<'_> { + #[inline(always)] + fn probe_hash(&self) -> i64 { + self.hash + } + + fn probe_eq(&self, stored: &DictKey) -> bool { + let n = self.args.len(); + match &stored.0 { + // Item by item, as the tuple's own comparison goes. + Object::Tuple(items) if items.len() == 2 * n => { + for (arg, item) in self.args.iter().zip(items.iter()) { + match item_eq(arg, item, 1) { + Some(true) => {} + Some(false) => return false, + None => { self.foreign.set(true); return false; } - // Builtin scalars compare natively (`1 == 1.0 == - // True`), identity first as a tuple's items do. - ( - arg, - item @ (Object::None - | Object::Bool(_) - | Object::Int(_) - | Object::Long(_) - | Object::Float(_) - | Object::Str(_) - | Object::WStr(_)), - ) => arg.is_same(item) || arg.eq_value(item), + } + } + for (cls, item) in self.classes.iter().zip(items[n..].iter()) { + match (cls, item) { + (Some(c), Object::Type(t)) if Rc::ptr_eq(c, t) => {} + (_, Object::Type(t)) if identity_class(t) => return false, _ => { self.foreign.set(true); return false; } - }; - if !equal { - return false; } } true } - // Builtin keys a tuple of these never equals. Object::Int(_) | Object::Long(_) | Object::Str(_) @@ -1402,20 +1745,73 @@ impl crate::dictmap::Probe for ArgsProbe<'_> { } } -impl ExactProbe for ArgsProbe<'_> { +/// The probe of a positional call's key: an untyped wrapper's sole scalar +/// or argument tuple, or a typed wrapper's tuple with the classes. +enum CallProbe<'a> { + Leaf(crate::object::LeafProbe<'a>), + Args(ArgsProbe<'a>), + Typed(TypedArgsProbe<'a>), +} + +impl<'a> CallProbe<'a> { + #[inline(always)] + fn sole(key: &'a Object, typed: bool) -> Option { + if typed { + TypedArgsProbe::new(std::slice::from_ref(key)).map(CallProbe::Typed) + } else { + crate::object::LeafProbe::new(key).map(CallProbe::Leaf) + } + } + + #[inline(always)] + fn args(args: &'a [Object], typed: bool) -> Option { + if typed { + TypedArgsProbe::new(args).map(CallProbe::Typed) + } else { + ArgsProbe::new(args, &[], &[]).map(CallProbe::Args) + } + } +} + +impl crate::dictmap::Probe for CallProbe<'_> { + #[inline(always)] + fn probe_hash(&self) -> i64 { + match self { + CallProbe::Leaf(p) => p.probe_hash(), + CallProbe::Args(p) => p.probe_hash(), + CallProbe::Typed(p) => p.probe_hash(), + } + } + + #[inline(always)] + fn probe_eq(&self, stored: &DictKey) -> bool { + match self { + CallProbe::Leaf(p) => p.probe_eq(stored), + CallProbe::Args(p) => p.probe_eq(stored), + CallProbe::Typed(p) => p.probe_eq(stored), + } + } +} + +impl ExactProbe for CallProbe<'_> { #[inline(always)] fn exact(&self) -> bool { - !self.foreign.get() + match self { + CallProbe::Leaf(p) => p.miss_is_exact(), + CallProbe::Args(p) => !p.foreign.get(), + CallProbe::Typed(p) => !p.foreign.get(), + } } } -/// [`lru_probe`] of the key `probe` stands for (`key` makes it), with a -/// miss to run in place when `MISS` (else `None`, nothing touched). +/// [`lru_probe`] of the key the probe `make` makes stands for (`key` makes +/// it; both are told whether the wrapper is typed), with a miss to run in +/// place when `MISS` (else `None`, nothing touched). #[inline(always)] fn lru_probe_with( inst: &crate::types::PyInstance, - probe: &P, - key: impl FnOnce() -> Object, + make: impl FnOnce(bool) -> Option

, + key: impl FnOnce(bool) -> Object, ) -> Option { let keys = lru_keys(); // SAFETY: reads that run no code. The slots of a wrapper are set once @@ -1431,9 +1827,11 @@ fn lru_probe_with( // thread's included: it declines once cells are shared). let (data, bytes) = unsafe { (cache.peek()?, state.peek_mut()?) }; let (limit, flags) = lru_state::mode(bytes)?; - if limit == 0 || flags & (lru_state::TYPED | lru_state::FALLBACK) != 0 { + if limit == 0 || flags & lru_state::FALLBACK != 0 { return None; } + let typed = flags & lru_state::TYPED != 0; + let probe = &make(typed)?; let found = data.get_index_of(probe); if !probe.exact() { return None; @@ -1455,7 +1853,7 @@ fn lru_probe_with( func.clone(), LruPending { wrapper: Object::Unbound, - key: key(), + key: key(typed), hash: probe.probe_hash(), _depth: depth, }, @@ -1920,6 +2318,63 @@ fn reduce(args: &[Object], kwargs: &[(String, Object)]) -> Result Result { + let [wrapper @ Object::Function(_), wrapped @ Object::Function(_)] = args else { + return Ok(Object::None); + }; + let interp = crate::builtins::reentrant_interp()?; + let attribute_error = &crate::builtin_types::builtin_types().attribute_error; + for attr in [ + "__module__", + "__name__", + "__qualname__", + "__doc__", + "__annotate__", + "__type_params__", + ] { + match interp.load_attr_public(wrapped, attr) { + Ok(v) => interp.store_attr(wrapper, attr, v)?, + Err(RuntimeError::PyException(pe)) if matches!(&pe.instance, Object::Instance(i) if i.cls().is_subclass_of(attribute_error)) => + {} + Err(e) => return Err(e), + } + } + let target = interp.load_attr_public(wrapper, "__dict__")?; + let source = match interp.load_attr_public(wrapped, "__dict__") { + Ok(v) => v, + Err(RuntimeError::PyException(pe)) if matches!(&pe.instance, Object::Instance(i) if i.cls().is_subclass_of(attribute_error)) => { + Object::new_dict() + } + Err(e) => return Err(e), + }; + match (&target, &source) { + (Object::Dict(t), Object::Dict(s)) => { + let pairs: Vec<(Object, Object)> = s + .borrow() + .iter() + .map(|(k, v)| (k.0.clone(), v.clone())) + .collect(); + for (k, v) in pairs { + crate::builtins::dict_insert(t, k, v)?; + } + } + _ => { + let update = interp.load_attr_public(&target, "update")?; + let globals = interp.builtins_dict(); + interp.call(&update, std::slice::from_ref(&source), &[], &globals)?; + } + } + interp.store_attr(wrapper, "__wrapped__", wrapped.clone())?; + Ok(wrapper.clone()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/weavepy-vm/src/stdlib/gc_real.rs b/crates/weavepy-vm/src/stdlib/gc_real.rs index 1dd737c82..1622913c3 100644 --- a/crates/weavepy-vm/src/stdlib/gc_real.rs +++ b/crates/weavepy-vm/src/stdlib/gc_real.rs @@ -521,12 +521,15 @@ fn object_is_tracked(target: &Object) -> bool { // A list/dict/set born holding only scalars has its tracking // deferred; CPython tracks it from birth, so answer as CPython // does and hand it to the collector from here on. - Object::List(_) | Object::Dict(_) | Object::Set(_) => gc_trace::with_state(|s| { - if !s.is_tracked_instance(target) { - s.track_now(target); - } - s.is_tracked_instance(target) - }), + // (So is a frozenset of atomic values, which is never registered.) + Object::List(_) | Object::Dict(_) | Object::Set(_) | Object::FrozenSet(_) => { + gc_trace::with_state(|s| { + if !s.is_tracked_instance(target) { + s.track_now(target); + } + s.is_tracked_instance(target) + }) + } other => gc_trace::with_state(|s| s.is_tracked_obj(other)), } } diff --git a/crates/weavepy-vm/src/stdlib/handle_table.rs b/crates/weavepy-vm/src/stdlib/handle_table.rs new file mode 100644 index 000000000..7b799f989 --- /dev/null +++ b/crates/weavepy-vm/src/stdlib/handle_table.rs @@ -0,0 +1,134 @@ +//! Tables of native state that Python objects refer to by an integer +//! `_handle` attribute (compressors, decompressors, hashers). +//! +//! An instance of a class registered with [`watch_owner_class`] lets its +//! entry go as it dies, as CPython frees such an object's state. Each entry +//! also watches the instance that owns it, and the states of instances that +//! died without the hook (a subclass's, one that died on another thread) +//! go at the next insertion once the table has doubled since it was last +//! swept, so a table holds about as many states as its owners have live +//! instances. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; + +use crate::fasthash::FxBuildHasher; +use crate::object::{DictKey, Object}; +use crate::sync::{Rc, RefCell, Weak}; +use crate::types::{PyInstance, TypeObject}; + +/// The smallest table that is swept. +const FIRST_SWEEP: usize = 64; + +pub(crate) struct HandleTable { + states: HashMap, Rc>), FxBuildHasher>, + sweep_at: usize, +} + +impl Default for HandleTable { + fn default() -> Self { + HandleTable { + states: HashMap::with_hasher(FxBuildHasher), + sweep_at: FIRST_SWEEP, + } + } +} + +impl HandleTable { + /// `state` under `id`, owned by `owner`. + pub(crate) fn insert(&mut self, id: i64, owner: &Rc, state: S) { + if self.states.len() >= self.sweep_at { + // (A state's own drop runs no code.) + self.states.retain(|_, (owner, _)| owner.strong_count() > 0); + self.sweep_at = (self.states.len() * 2).max(FIRST_SWEEP); + } + self.states + .insert(id, (Rc::downgrade(owner), Rc::new(RefCell::new(state)))); + } + + /// The state under `id`. + pub(crate) fn get(&self, id: i64) -> Option>> { + self.states.get(&id).map(|(_, state)| state.clone()) + } + + /// Let the state under `id` go (a holder of a clone keeps it until it + /// lets go too). + pub(crate) fn remove(&mut self, id: i64) -> Option>> { + self.states.remove(&id).map(|(_, state)| state) + } +} + +/// The `_handle` attribute of `inst`, read without waiting on its dict. +pub(crate) fn handle_of(inst: &PyInstance) -> Option { + match inst + .dict_cell() + .try_borrow() + .ok()? + .get(&DictKey(Object::from_static("_handle")))? + { + Object::Int(id) => Some(*id), + _ => None, + } +} + +/// How many classes [`watch_owner_class`] takes (others' instances leave +/// their entries to the sweep). +const OWNER_SLOTS: usize = 16; + +static OWNERS: AtomicUsize = AtomicUsize::new(0); +static OWNER_CLASS: [AtomicUsize; OWNER_SLOTS] = [const { AtomicUsize::new(0) }; OWNER_SLOTS]; +static OWNER_HOOK: [AtomicUsize; OWNER_SLOTS] = [const { AtomicUsize::new(0) }; OWNER_SLOTS]; + +/// One bit per watched class (see [`owner_bit`]): a dying instance whose +/// class's bit is clear skips the slot scan. +static OWNER_BITS: AtomicU64 = AtomicU64::new(0); + +/// A class address's bit in [`OWNER_BITS`]. +#[inline] +fn owner_bit(addr: usize) -> u64 { + 1 << ((addr as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 58) +} + +/// Run `hook` on each dying instance of exactly `cls` (not a subclass's), +/// which lets the instance's table entry go. The class is kept alive from +/// here on, so no other class ever takes its address. +pub(crate) fn watch_owner_class(cls: &Rc, hook: fn(&PyInstance)) { + static PINNED: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + let Ok(mut pinned) = PINNED.lock() else { + return; + }; + let addr = Rc::as_ptr(cls) as usize; + let n = OWNERS.load(Ordering::Acquire); + if n == OWNER_SLOTS || (0..n).any(|i| OWNER_CLASS[i].load(Ordering::Relaxed) == addr) { + return; + } + pinned.push(cls.clone()); + OWNER_HOOK[n].store(hook as usize, Ordering::Relaxed); + OWNER_CLASS[n].store(addr, Ordering::Relaxed); + OWNERS.store(n + 1, Ordering::Release); + OWNER_BITS.fetch_or(owner_bit(addr), Ordering::Release); +} + +/// The hook [`watch_owner_class`] registered for the class at `cls_addr` +/// (the dying `inst`'s), if any: one load and a bit test for most classes. +#[inline] +pub(crate) fn on_instance_death(inst: &PyInstance, cls_addr: usize) { + if OWNER_BITS.load(Ordering::Acquire) & owner_bit(cls_addr) != 0 { + on_instance_death_slow(inst, cls_addr); + } +} + +#[cold] +#[inline(never)] +fn on_instance_death_slow(inst: &PyInstance, addr: usize) { + let n = OWNERS.load(Ordering::Acquire); + for i in 0..n { + if OWNER_CLASS[i].load(Ordering::Relaxed) == addr { + let hook = OWNER_HOOK[i].load(Ordering::Relaxed); + // SAFETY: the slot holds the `fn(&PyInstance)` stored with it. + let hook: fn(&PyInstance) = unsafe { std::mem::transmute(hook) }; + hook(inst); + return; + } + } +} diff --git a/crates/weavepy-vm/src/stdlib/hashlib_mod.rs b/crates/weavepy-vm/src/stdlib/hashlib_mod.rs index 4a2edad0f..b250b001a 100644 --- a/crates/weavepy-vm/src/stdlib/hashlib_mod.rs +++ b/crates/weavepy-vm/src/stdlib/hashlib_mod.rs @@ -17,14 +17,13 @@ use crate::sync::Rc; use crate::sync::RefCell; -use std::collections::HashMap; use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::{Mutex, OnceLock}; use digest::Digest; use md5::Md5; use sha1::Sha1; -use sha2::{Sha224, Sha256, Sha384, Sha512}; +use sha2::{Sha224, Sha256, Sha512}; use sha3::digest::{ExtendableOutput, XofReader}; use sha3::{Sha3_224, Sha3_256, Sha3_384, Sha3_512, Shake128, Shake256}; @@ -39,13 +38,24 @@ use crate::types::{PyInstance, TypeObject}; /// unlike RustCrypto's `blake2`, exposes the `salt`/`person`/tree /// parameters CPython's `_blake2` surfaces). The trailing `usize` on the /// BLAKE2 variants is the configured digest length. +/// A running `ring` digest (see [`AnyHasher::Sha256`]). +type RingHash = ring::digest::Context; + +fn ring_hash(algorithm: &'static ring::digest::Algorithm) -> RingHash { + ring::digest::Context::new(algorithm) +} + enum AnyHasher { Md5(Md5), Sha1(Sha1), + // (SHA-256, SHA-384 and SHA-512 through `ring`, whose compression + // functions are assembly that takes the CPU's SHA or vector + // extensions: up to twice the portable code's speed. Its SHA-1 is + // slower than the portable one, and it has no SHA-224.) Sha224(Sha224), - Sha256(Sha256), - Sha384(Sha384), - Sha512(Sha512), + Sha256(RingHash), + Sha384(RingHash), + Sha512(RingHash), Sha3_224(Sha3_224), Sha3_256(Sha3_256), Sha3_384(Sha3_384), @@ -62,10 +72,8 @@ impl AnyHasher { match self { Self::Md5(h) => Update::update(h, data), Self::Sha1(h) => Update::update(h, data), + Self::Sha256(h) | Self::Sha384(h) | Self::Sha512(h) => h.update(data), Self::Sha224(h) => Update::update(h, data), - Self::Sha256(h) => Update::update(h, data), - Self::Sha384(h) => Update::update(h, data), - Self::Sha512(h) => Update::update(h, data), Self::Sha3_224(h) => Update::update(h, data), Self::Sha3_256(h) => Update::update(h, data), Self::Sha3_384(h) => Update::update(h, data), @@ -91,10 +99,10 @@ impl AnyHasher { match self { Self::Md5(h) => h.clone().finalize().to_vec(), Self::Sha1(h) => h.clone().finalize().to_vec(), + Self::Sha256(h) | Self::Sha384(h) | Self::Sha512(h) => { + h.clone().finish().as_ref().to_vec() + } Self::Sha224(h) => h.clone().finalize().to_vec(), - Self::Sha256(h) => h.clone().finalize().to_vec(), - Self::Sha384(h) => h.clone().finalize().to_vec(), - Self::Sha512(h) => h.clone().finalize().to_vec(), Self::Sha3_224(h) => h.clone().finalize().to_vec(), Self::Sha3_256(h) => h.clone().finalize().to_vec(), Self::Sha3_384(h) => h.clone().finalize().to_vec(), @@ -201,12 +209,13 @@ impl AnyHasher { // Process-global state (mirrors the `bz2`/`lzma` streaming objects): // hashers live in a registry keyed by an integer handle stored on the // instance, so a hasher created on one thread can be updated from -// another under the GIL (test_hashlib.test_threaded_hashing). -type HasherReg = Mutex>>>; +// another under the GIL (test_hashlib.test_threaded_hashing). The table +// lets the states of dead hashers go (see `handle_table`). +type HasherReg = Mutex>; fn hasher_reg() -> &'static HasherReg { static REG: OnceLock = OnceLock::new(); - REG.get_or_init(|| Mutex::new(HashMap::new())) + REG.get_or_init(Mutex::default) } static HASHER_NEXT_ID: AtomicI64 = AtomicI64::new(1); @@ -219,21 +228,26 @@ static HASHER_CLASS: Mutex>> = Mutex::new(None); /// We share one `dict` object between the module attribute and `new`. static CTOR_CACHE: Mutex>>> = Mutex::new(None); -fn register_hasher(state: AnyHasher) -> i64 { +fn register_hasher(owner: &Rc, state: AnyHasher) -> i64 { let id = HASHER_NEXT_ID.fetch_add(1, Ordering::Relaxed); - hasher_reg() - .lock() - .unwrap() - .insert(id, Rc::new(RefCell::new(state))); + hasher_reg().lock().unwrap().insert(id, owner, state); id } +/// A hasher instance's state goes with it (see `handle_table`). +fn hasher_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + if let Ok(mut reg) = hasher_reg().try_lock() { + reg.remove(id); + } + } +} + fn lookup_hasher(id: i64) -> Result>, RuntimeError> { hasher_reg() .lock() .unwrap() - .get(&id) - .cloned() + .get(id) .ok_or_else(|| value_error("hashlib: stale hasher handle")) } @@ -265,7 +279,7 @@ fn make_hasher_instance(state: AnyHasher) -> Object { fn fill_hasher_instance(inst: &Rc, state: AnyHasher) { let (name, digest_size, block_size) = (state.name(), state.digest_size(), state.block_size()); let sha3 = state.sha3_params(); - let id = register_hasher(state); + let id = register_hasher(inst, state); { let mut d = inst.dict_cell().borrow_mut(); d.insert(DictKey(Object::from_static("_handle")), Object::Int(id)); @@ -324,6 +338,16 @@ fn hasher_class() -> Rc { method!("digest", hasher_digest); method!("hexdigest", hasher_hexdigest); method!("copy", hasher_copy); + let halves: [(&str, crate::leaf_builtins::Fast); 3] = [ + ("update", hasher_update_fast), + ("digest", hasher_digest_fast), + ("hexdigest", hasher_hexdigest_fast), + ]; + for (name, fast) in halves { + if let Some(Object::Builtin(b)) = dict.get(&DictKey(Object::from_static(name))) { + crate::leaf_builtins::register_fast(b, fast); + } + } // Built-in (immutable) like CPython's HASH types: setting a class // attribute raises "cannot set … attribute of immutable type" // (test_hashlib.test_readonly_types). @@ -336,6 +360,7 @@ fn hasher_class() -> Rc { is_builtin: true, }, ) + .inspect(|cls| super::handle_table::watch_owner_class(cls, hasher_died)) .expect("hasher class must linearise"); *slot = Some(cls.clone()); cls @@ -359,8 +384,20 @@ fn hasher_update(args: &[Object]) -> Result { let data = args .get(1) .ok_or_else(|| type_error("update: missing data"))?; - let bytes = bytes_of(data)?; let state = lookup_hasher(id)?; + data.check_simple_buffer()?; + // (A `bytearray`'s or a live `memoryview`'s bytes hashed where they + // are: hashing runs no code while it reads.) + if matches!( + data, + Object::Bytes(_) | Object::ByteArray(_) | Object::MemoryView(_) + ) { + let mut hasher = state.borrow_mut(); + if data.with_bytes_view(|d| hasher.update(d)).is_some() { + return Ok(Object::None); + } + } + let bytes = bytes_of(data)?; state.borrow_mut().update(&bytes); Ok(Object::None) } @@ -401,12 +438,59 @@ fn hasher_hexdigest(args: &[Object]) -> Result { let st = state.borrow(); let length = digest_length(&st, args)?; let bytes = st.digest(length); - let mut out = String::with_capacity(bytes.len() * 2); - for b in bytes { - use std::fmt::Write; - write!(out, "{b:02x}").unwrap(); - } - Ok(Object::from_str(out)) + Ok(Object::from_str(crate::object::hex_lower(&bytes))) +} + +/// The state of a hasher instance, for a leaf half: `None` for anything +/// the full method must see (another object, a missing or stale handle). +fn hasher_state_fast(recv: &Object) -> Option>> { + let Object::Instance(inst) = recv else { + return None; + }; + let id = match inst + .dict_cell() + .try_borrow() + .ok()? + .get(&DictKey(Object::from_static("_handle")))? + { + Object::Int(v) => *v, + _ => return None, + }; + lookup_hasher(id).ok() +} + +/// `h.update(data)` of a `bytes`, `bytearray` or simple `memoryview`, hashed +/// where the bytes are. A leaf half: hashing runs no code. +fn hasher_update_fast(args: &[Object]) -> Option> { + let [recv, data @ (Object::Bytes(_) | Object::ByteArray(_) | Object::MemoryView(_))] = args + else { + return None; + }; + data.check_simple_buffer().ok()?; + let state = hasher_state_fast(recv)?; + let mut hasher = state.try_borrow_mut().ok()?; + data.with_bytes_view(|d| hasher.update(d))?; + Some(Ok(Object::None)) +} + +/// `h.digest()` of a fixed-size digest. A leaf half. +fn hasher_digest_fast(args: &[Object]) -> Option> { + let [recv] = args else { + return None; + }; + let state = hasher_state_fast(recv)?; + let st = state.try_borrow().ok()?; + (!st.is_xof()).then(|| Ok(Object::new_bytes(st.digest(None)))) +} + +/// `h.hexdigest()` of a fixed-size digest. A leaf half. +fn hasher_hexdigest_fast(args: &[Object]) -> Option> { + let [recv] = args else { + return None; + }; + let state = hasher_state_fast(recv)?; + let st = state.try_borrow().ok()?; + (!st.is_xof()).then(|| Ok(Object::from_str(crate::object::hex_lower(&st.digest(None))))) } fn hasher_copy(args: &[Object]) -> Result { @@ -670,21 +754,6 @@ fn seed_arg_checked( .cloned()) } -/// The digest seed passed to a constructor: positional index 0, or the -/// `data=`/`string=` keyword, validated with clinic precedence. -/// `usedforsecurity=` is accepted and ignored (we never link OpenSSL, so -/// FIPS mode is moot). -fn seed_arg( - fname: &str, - args: &[Object], - kwargs: &[(String, Object)], -) -> Result>, RuntimeError> { - match seed_arg_checked(fname, 0, args, kwargs, &[])? { - None => Ok(None), - Some(o) => Ok(Some(bytes_of(&o)?)), - } -} - fn algos_set() -> Object { Object::new_set_from( [ @@ -870,9 +939,9 @@ fn make_by_name(name: &str) -> Result { "md5" => AnyHasher::Md5(Md5::new()), "sha1" => AnyHasher::Sha1(Sha1::new()), "sha224" => AnyHasher::Sha224(Sha224::new()), - "sha256" => AnyHasher::Sha256(Sha256::new()), - "sha384" => AnyHasher::Sha384(Sha384::new()), - "sha512" => AnyHasher::Sha512(Sha512::new()), + "sha256" => AnyHasher::Sha256(ring_hash(&ring::digest::SHA256)), + "sha384" => AnyHasher::Sha384(ring_hash(&ring::digest::SHA384)), + "sha512" => AnyHasher::Sha512(ring_hash(&ring::digest::SHA512)), "sha3_224" => AnyHasher::Sha3_224(Sha3_224::default()), "sha3_256" => AnyHasher::Sha3_256(Sha3_256::default()), "sha3_384" => AnyHasher::Sha3_384(Sha3_384::default()), @@ -939,7 +1008,7 @@ fn parse_blake2_params( "last_node", ], )? - .map(|o| bytes_of(&o)) + .map(|o| bytes_of(&o).map(std::borrow::Cow::into_owned)) .transpose()?; // Integer parameter with clinic-style range enforcement. `hard_max` // distinguishes a *representation* overflow (leaf_size ≥ 2**32, @@ -971,7 +1040,7 @@ fn parse_blake2_params( let bytes_kw = |name: &str| -> Result, RuntimeError> { match kw(kwargs, name) { None => Ok(Vec::new()), - Some(o) => bytes_of(o), + Some(o) => bytes_of(o).map(std::borrow::Cow::into_owned), } }; @@ -1151,6 +1220,7 @@ fn blake2_class( is_builtin: true, }, ) + .inspect(|cls| super::handle_table::watch_owner_class(cls, hasher_died)) .expect("blake2 class must linearise") } @@ -1232,37 +1302,70 @@ fn make_sha224(args: &[Object], kwargs: &[(String, Object)]) -> Result Result { - seeded(AnyHasher::Sha256(Sha256::new()), args, kwargs) + seeded( + AnyHasher::Sha256(ring_hash(&ring::digest::SHA256)), + args, + kwargs, + ) } fn make_sha384(args: &[Object], kwargs: &[(String, Object)]) -> Result { - seeded(AnyHasher::Sha384(Sha384::new()), args, kwargs) + seeded( + AnyHasher::Sha384(ring_hash(&ring::digest::SHA384)), + args, + kwargs, + ) } fn make_sha512(args: &[Object], kwargs: &[(String, Object)]) -> Result { - seeded(AnyHasher::Sha512(Sha512::new()), args, kwargs) + seeded( + AnyHasher::Sha512(ring_hash(&ring::digest::SHA512)), + args, + kwargs, + ) } +/// A constructor's hasher, fed its seed: positional index 0, or the +/// `data=`/`string=` keyword, validated with clinic precedence. +/// `usedforsecurity=` is accepted and ignored (we never link OpenSSL, so +/// FIPS mode is moot). fn seeded( mut hasher: AnyHasher, args: &[Object], kwargs: &[(String, Object)], ) -> Result { - if let Some(bytes) = seed_arg(hasher.name(), args, kwargs)? { - hasher.update(&bytes); + match seed_arg_checked(hasher.name(), 0, args, kwargs, &[])? { + None => {} + // (A `bytes`, `bytearray` or contiguous `memoryview` hashed where + // it is.) + Some(o) + if matches!( + o, + Object::Bytes(_) | Object::ByteArray(_) | Object::MemoryView(_) + ) => + { + o.check_simple_buffer()?; + if o.with_bytes_view(|d| hasher.update(d)).is_none() { + hasher.update(&bytes_of(&o)?); + } + } + Some(o) => hasher.update(&bytes_of(&o)?), } Ok(make_hasher_instance(hasher)) } -fn bytes_of(obj: &Object) -> Result, RuntimeError> { +fn bytes_of(obj: &Object) -> Result, RuntimeError> { + use std::borrow::Cow; + obj.check_simple_buffer()?; // Hashers consume the buffer protocol only: `bytes`, `bytearray`, // `memoryview` (and their subclasses). A `str` is rejected with // CPython's exact message — `test_hmac` asserts `update("…")` raises. - if let Some(v) = obj.as_bytes_view() { + // (A `bytes` object's bytes are hashed where they are.) + if let Some(v) = obj.bytes_cow() { return Ok(v); } if let Some(v) = obj.native_value().as_ref().and_then(Object::as_bytes_view) { - return Ok(v); + return Ok(Cow::Owned(v)); } // Buffer-protocol fallback for objects that expose memory but aren't // bytes/bytearray/memoryview themselves (`array.array`, `mmap`, …): @@ -1283,7 +1386,7 @@ fn bytes_of(obj: &Object) -> Result, RuntimeError> { if let Some(mv_ctor) = mv_ctor { if let Ok(mv) = interp.call_object(mv_ctor, &[obj.clone()], &[]) { if let Some(v) = mv.as_bytes_view() { - return Ok(v); + return Ok(Cow::Owned(v)); } } } @@ -1362,7 +1465,7 @@ fn file_digest(args: &[Object], kwargs: &[(String, Object)]) -> Result Rc { let mut all: Vec = Vec::new(); macro_rules! reg { ($name:literal, $f:expr) => {{ - let f = Object::Builtin(Rc::new(BuiltinFn { + reg!($name, $f, None::) + }}; + ($name:literal, $f:expr, $fast:expr) => {{ + let b = Rc::new(BuiltinFn { name: $name, binds_instance: false, call: Box::new($f), call_kw: None, - })); + }); + if let Some(fast) = $fast { + crate::leaf_builtins::register_fast(&b, fast); + } + let f = Object::Builtin(b); crate::descr_registry::register_module(&f, "_heapq"); d.insert(DictKey(Object::from_static($name)), f); // `from _heapq import *` only exports the public names. @@ -52,8 +59,16 @@ pub fn build(_cache: &ModuleCache) -> Rc { } }}; } - reg!("heappush", heappush); - reg!("heappop", heappop); + reg!( + "heappush", + heappush, + Some(heappush_fast as crate::leaf_builtins::Fast) + ); + reg!( + "heappop", + heappop, + Some(heappop_fast as crate::leaf_builtins::Fast) + ); reg!("heapify", heapify); reg!("heapreplace", heapreplace); reg!("heappushpop", heappushpop); @@ -81,17 +96,14 @@ pub fn build(_cache: &ModuleCache) -> Rc { }) } -/// Borrow the active interpreter published on this thread by the dispatch -/// loop. Always present while a builtin runs. -fn with_interp(f: F) -> Result -where - F: FnOnce(&mut crate::Interpreter) -> Result, -{ +/// The active interpreter published on this thread by the dispatch loop +/// (always present while a builtin runs), looked up only for a comparison +/// that may run Python: a heap of scalars never needs it. +fn interp() -> Result<&'static mut crate::Interpreter, RuntimeError> { let ptr = crate::vm_singletons::current_interpreter_ptr() .ok_or_else(|| type_error("_heapq: no active interpreter"))?; // SAFETY: published by the enclosing VM frame on this thread. - let interp = unsafe { &mut *ptr }; - f(interp) + Ok(unsafe { &mut *ptr }) } /// The first argument must be a `list` (CPython requires `PyList_Check`). @@ -102,31 +114,83 @@ fn heap_arg(args: &[Object]) -> Result>>, RuntimeError> { } } -/// `heap[i] < heap[j]`: in place for a pair of `int`s, `float`s or `str`s +/// `a < b` where the comparison consults no protocol: two native scalars +/// (see [`crate::native_scalar_compare`]), in line, or two exact tuples +/// [`tuple_item_lt`] settles. `None` for anything else. +#[inline(always)] +fn native_item_lt(a: &Object, b: &Object) -> Option { + match crate::native_scalar_compare(a, b, CompareKind::Lt) { + Some(lt) => Some(lt), + None => tuple_item_lt(a, b), + } +} + +/// `a < b` for two exact tuples that differ first at a pair of native +/// scalars (`(priority, count, task)` entries, the usual heap item), or +/// that are equal throughout such pairs and differ in length. `None` for +/// anything else: a pair of items only their own comparison settles, and +/// a NaN, whose equality inside a tuple goes by identity. (Out of line: +/// the scalar comparison above is the sift loops' own.) +#[inline(never)] +fn tuple_item_lt(a: &Object, b: &Object) -> Option { + let (Object::Tuple(x), Object::Tuple(y)) = (a, b) else { + return None; + }; + for (p, q) in x.iter().zip(y.iter()) { + if let (Object::Float(f), Object::Float(g)) = (p, q) { + if f.is_nan() || g.is_nan() { + return None; + } + } + if !crate::native_scalar_compare(p, q, CompareKind::Eq)? { + return crate::native_scalar_compare(p, q, CompareKind::Lt); + } + } + Some(x.len() < y.len()) +} + +/// `heap[i] < heap[j]`: in place for a pair [`native_item_lt`] settles /// (which runs no code, so the heap can't change under it), else on /// copies through the full comparison. #[inline] -fn heap_lt( - interp: &mut crate::Interpreter, - heap: &Rc>>, - i: usize, - j: usize, -) -> Result { +fn heap_lt(heap: &Rc>>, i: usize, j: usize) -> Result { + // SAFETY: a view that runs no code, ending with the statement. + let native = unsafe { heap.peek() }.and_then(|h| native_item_lt(h.get(i)?, h.get(j)?)); + if let Some(lt) = native { + return Ok(lt); + } let (a, b) = { let h = heap.borrow(); - if let Some(lt) = crate::native_scalar_compare(&h[i], &h[j], CompareKind::Lt) { - return Ok(lt); - } (h[i].clone(), h[j].clone()) }; - interp.op_compare(&a, &b, CompareKind::Lt) + interp()?.op_compare(&a, &b, CompareKind::Lt) +} + +/// `heap[i] < heap[j]` for a pair [`native_item_lt`] settles, and when it +/// holds, `heap[a]` and `heap[b]` swapped, under one view of the list: no +/// code runs, so nothing can change it meanwhile. `None`, touching +/// nothing, for any other pair. +#[inline] +fn native_lt_swap( + heap: &Rc>>, + i: usize, + j: usize, + a: usize, + b: usize, +) -> Option { + // SAFETY: a view that runs no code, ending with this call. + let h = unsafe { heap.peek_mut() }?; + let lt = native_item_lt(h.get(i)?, h.get(j)?)?; + if lt { + h.swap(a, b); + } + Some(lt) } /// `siftdown` (CPython's confusingly named "move toward the root"): the item /// at `pos` bubbles up past larger parents until it fits. `max_heap` flips the /// comparison direction so the `_*_max` helpers build a max-heap. fn siftdown( - interp: &mut crate::Interpreter, heap: &Rc>>, startpos: usize, mut pos: usize, @@ -138,11 +202,26 @@ fn siftdown( } while pos > startpos { let parentpos = (pos - 1) >> 1; + // (Two native scalars, or tuples that differ at one: compared, and + // swapped when out of order, under one view of the list.) + let (x, y) = if max_heap { + (parentpos, pos) + } else { + (pos, parentpos) + }; + match native_lt_swap(heap, x, y, pos, parentpos) { + Some(true) => { + pos = parentpos; + continue; + } + Some(false) => break, + None => {} + } // min-heap: `cur < parent`; max-heap: `parent < cur`. let cmp = if max_heap { - heap_lt(interp, heap, parentpos, pos)? + heap_lt(heap, parentpos, pos)? } else { - heap_lt(interp, heap, pos, parentpos)? + heap_lt(heap, pos, parentpos)? }; if heap.borrow().len() != size { return Err(runtime_error("list changed size during iteration")); @@ -159,7 +238,6 @@ fn siftdown( /// `siftup` (CPython's "move toward the leaves"): bubble the smaller (or, for a /// max-heap, larger) child up until reaching a leaf, then `siftdown` to settle. fn siftup( - interp: &mut crate::Interpreter, heap: &Rc>>, mut pos: usize, max_heap: bool, @@ -175,10 +253,29 @@ fn siftup( if childpos + 1 < endpos { // Pick the smaller child (min) / larger child (max); ties go right, // matching CPython's `childpos += (cmp ^ 1)`. + let (x, y) = if max_heap { + (childpos + 1, childpos) + } else { + (childpos, childpos + 1) + }; + // (Two native scalars, or tuples that differ at one: compared + // in place, nothing swapped.) + // SAFETY: a view that runs no code, ending with the statement. + let native = unsafe { heap.peek() }.and_then(|h| native_item_lt(h.get(x)?, h.get(y)?)); + if let Some(cmp) = native { + childpos += usize::from(!cmp); + // SAFETY: as above; both positions are in the list. + if let Some(h) = unsafe { heap.peek_mut() } { + h.swap(pos, childpos); + pos = childpos; + continue; + } + childpos -= usize::from(!cmp); + } let cmp = if max_heap { - heap_lt(interp, heap, childpos + 1, childpos)? + heap_lt(heap, childpos + 1, childpos)? } else { - heap_lt(interp, heap, childpos, childpos + 1)? + heap_lt(heap, childpos, childpos + 1)? }; childpos += usize::from(!cmp); if heap.borrow().len() != endpos { @@ -188,7 +285,7 @@ fn siftup( heap.borrow_mut().swap(pos, childpos); pos = childpos; } - siftdown(interp, heap, startpos, pos, max_heap) + siftdown(heap, startpos, pos, max_heap) } fn heappush_impl(args: &[Object], max_heap: bool) -> Result { @@ -197,24 +294,96 @@ fn heappush_impl(args: &[Object], max_heap: bool) -> Result Result { heappush_impl(args, false) } +/// `heappush`'s leaf half: when every comparison the push makes (the new +/// item against each parent up its path) is one [`native_item_lt`] +/// settles, they're made first, touching nothing, and then the item goes +/// in; anything else declines untouched for the full body. +fn heappush_fast(args: &[Object]) -> Option> { + let [Object::List(l), item] = args else { + return None; + }; + let mut h = l.try_borrow_mut().ok()?; + let end = h.len(); + let mut pos = end; + while pos > 0 { + let parent = (pos - 1) >> 1; + if !native_item_lt(item, &h[parent])? { + break; + } + pos = parent; + } + h.push(item.clone()); + let mut at = end; + while at > pos { + let parent = (at - 1) >> 1; + h.swap(at, parent); + at = parent; + } + Some(Ok(Object::None)) +} + +/// `heappop`'s leaf half: the comparisons the pop makes (between the +/// children down the path `siftup` takes, then the last item against the +/// items it moved up) all on items still in their places, so they're made +/// first, touching nothing, when [`native_item_lt`] settles each; then +/// the items move. Anything else (an empty heap, which raises) declines +/// untouched. +fn heappop_fast(args: &[Object]) -> Option> { + let [Object::List(l)] = args else { + return None; + }; + let mut h = l.try_borrow_mut().ok()?; + let n = h.len(); + if n <= 1 { + return h.pop().map(Ok); + } + let end = n - 1; + // The path down from the root: at each step the smaller child (ties + // go right). + let mut path = [0usize; 64]; + let mut m = 0; + let mut pos = 0; + while pos < end >> 1 { + let mut c = 2 * pos + 1; + if c + 1 < end && !native_item_lt(&h[c], &h[c + 1])? { + c += 1; + } + pos = c; + m += 1; + *path.get_mut(m)? = c; + } + // The last item climbs back past each moved-up item it's below. + let mut stop = m; + while stop > 0 && native_item_lt(&h[end], &h[path[stop]])? { + stop -= 1; + } + let last = h.pop()?; + let out = std::mem::replace(&mut h[0], Object::None); + for k in 0..stop { + h.swap(path[k], path[k + 1]); + } + h[path[stop]] = last; + Some(Ok(out)) +} + fn heappop_impl(args: &[Object], max_heap: bool) -> Result { let heap = heap_arg(args)?; - with_interp(|interp| { + { let lastelt = { let mut h = heap.borrow_mut(); match h.pop() { @@ -229,9 +398,9 @@ fn heappop_impl(args: &[Object], max_heap: bool) -> Result let mut h = heap.borrow_mut(); std::mem::replace(&mut h[0], lastelt) }; - siftup(interp, &heap, 0, max_heap)?; + siftup(&heap, 0, max_heap)?; Ok(returnitem) - }) + } } fn heappop(args: &[Object]) -> Result { @@ -244,7 +413,7 @@ fn heapreplace_impl(args: &[Object], max_heap: bool) -> Result Result Result { @@ -267,7 +436,7 @@ fn heappushpop_impl(args: &[Object], max_heap: bool) -> Result Result Result Result { @@ -307,14 +476,14 @@ fn heappushpop(args: &[Object]) -> Result { fn heapify_impl(args: &[Object], max_heap: bool) -> Result { let heap = heap_arg(args)?; - with_interp(|interp| { + { let n = heap.borrow().len(); // Transform bottom-up: the largest index with a child is n//2 - 1. for i in (0..n / 2).rev() { - siftup(interp, &heap, i, max_heap)?; + siftup(&heap, i, max_heap)?; } Ok(Object::None) - }) + } } fn heapify(args: &[Object]) -> Result { diff --git a/crates/weavepy-vm/src/stdlib/hmac_mod.rs b/crates/weavepy-vm/src/stdlib/hmac_mod.rs index 9ae64f09a..435717a99 100644 --- a/crates/weavepy-vm/src/stdlib/hmac_mod.rs +++ b/crates/weavepy-vm/src/stdlib/hmac_mod.rs @@ -104,10 +104,9 @@ struct MacRegEntry { } thread_local! { - static MAC_REGISTRY: RefCell>> = - RefCell::new(HashMap::new()); + static MAC_REGISTRY: crate::gil::ReleaseUnderGil>>> = crate::gil::ReleaseUnderGil::new(RefCell::new(HashMap::new())); static MAC_NEXT_ID: RefCell = const { RefCell::new(1) }; - static MAC_CLASS: RefCell>> = const { RefCell::new(None) }; + static MAC_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } fn register_mac(state: AnyMac, key: Vec, digest_name: String) -> i64 { @@ -233,12 +232,7 @@ fn mac_hexdigest(args: &[Object]) -> Result { let id = instance_handle(args)?; let entry = lookup_mac(id)?; let bytes = entry.state.borrow().digest(); - let mut out = String::with_capacity(bytes.len() * 2); - for b in bytes { - use std::fmt::Write; - write!(out, "{b:02x}").unwrap(); - } - Ok(Object::from_str(out)) + Ok(Object::from_str(crate::object::hex_lower(&bytes))) } fn mac_copy(args: &[Object]) -> Result { diff --git a/crates/weavepy-vm/src/stdlib/interpreters_mod.rs b/crates/weavepy-vm/src/stdlib/interpreters_mod.rs index d19c769fb..82d53690e 100644 --- a/crates/weavepy-vm/src/stdlib/interpreters_mod.rs +++ b/crates/weavepy-vm/src/stdlib/interpreters_mod.rs @@ -1237,47 +1237,66 @@ fn c_send(args: &[Object]) -> Result { } // Drop the GIL for the wait (`Py_BEGIN_ALLOW_THREADS`): the // receiving thread needs to run Python code to drain the item. - crate::gil::allow_threads_then(|| { + // Nothing in the wait builds or releases an object: its outcome, + // with any item it withdrew, comes back to be handled under the GIL. + enum Waited { + Received, + Closed, + TimedOut(Vec), + Poisoned, + } + let waited = crate::gil::allow_threads_then(|| { let deadline = timeout.map(|t| std::time::Instant::now() + std::time::Duration::from_secs_f64(t)); - let mut guard = registry() - .lock() - .map_err(|_| runtime_error("sub-interpreter registry poisoned"))?; + let Ok(mut guard) = registry().lock() else { + return Waited::Poisoned; + }; loop { let Some(entry) = guard.channels.get_mut(&id) else { // Destroyed while waiting — the item is gone with it. - return Err(channel_closed(id)); + return Waited::Closed; }; if !entry.buffer.iter().any(|it| it.seq == token) { if entry.closed { // A force-close dropped the pending item before anyone // received it (test_send_closed_while_waiting). - return Err(channel_closed(id)); + return Waited::Closed; } - return Ok(Object::None); + return Waited::Received; } if entry.closed { - return Err(channel_closed(id)); + return Waited::Closed; } - if let Some(dl) = deadline { - let now = std::time::Instant::now(); - if now >= dl { - entry.buffer.retain(|it| it.seq != token); - return Err(crate::error::timeout_error("channel send timed out")); + let wait = match deadline { + Some(dl) => { + let now = std::time::Instant::now(); + if now >= dl { + let (withdrawn, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut entry.buffer) + .into_iter() + .partition(|it| it.seq == token); + entry.buffer = kept.into(); + return Waited::TimedOut(withdrawn); + } + dl - now } - let (g, _) = channel_cv() - .wait_timeout(guard, dl - now) - .map_err(|_| runtime_error("sub-interpreter registry poisoned"))?; - guard = g; - } else { // Periodic re-check guards against a missed notify. - let (g, _) = channel_cv() - .wait_timeout(guard, std::time::Duration::from_millis(100)) - .map_err(|_| runtime_error("sub-interpreter registry poisoned"))?; - guard = g; - } + None => std::time::Duration::from_millis(100), + }; + let Ok((g, _)) = channel_cv().wait_timeout(guard, wait) else { + return Waited::Poisoned; + }; + guard = g; } - }) + }); + match waited { + Waited::Received => Ok(Object::None), + Waited::Closed => Err(channel_closed(id)), + Waited::TimedOut(withdrawn) => { + drop(withdrawn); + Err(crate::error::timeout_error("channel send timed out")) + } + Waited::Poisoned => Err(runtime_error("sub-interpreter registry poisoned")), + } } /// `channel_recv(cid[, default])` → `(obj, unboundop)` — pop the next diff --git a/crates/weavepy-vm/src/stdlib/io.rs b/crates/weavepy-vm/src/stdlib/io.rs index f771e530d..d1196b58d 100644 --- a/crates/weavepy-vm/src/stdlib/io.rs +++ b/crates/weavepy-vm/src/stdlib/io.rs @@ -420,6 +420,10 @@ fn bytesio_file(args: &[Object], kwargs: &[(String, Object)]) -> Result Some(b.clone()), + _ => None, + }; let data = match initial { Some(Object::Bytes(b)) => b.to_vec(), Some(Object::ByteArray(b)) => b.borrow().clone(), @@ -447,6 +451,9 @@ fn bytesio_file(args: &[Object], kwargs: &[(String, Object)]) -> Result) { /// An empty in-memory backing file for a memory-stream *subclass* (the base /// type's buffer is built directly in `__new__`). -fn empty_mem_file(name: &str, mode: &str, backend: FileBackend) -> Rc { +fn empty_mem_file(name: &'static str, mode: &'static str, backend: FileBackend) -> Rc { let f = PyFile::new(name, mode, backend); f.no_name.set(true); Rc::new(f) @@ -952,6 +959,7 @@ fn bytesio_init(args: &[Object], kwargs: &[(String, Object)]) -> Result IoFamily { fam } +/// `io.BytesIO()` / `io.BytesIO(b)` of the exact type with plain `bytes`: +/// the stream its `__new__` builds, which its `__init__` would leave as it +/// is. `None` for other arguments, for the full constructor. +fn bytesio_new_pure(cls: &Rc, args: &[Object]) -> Option { + match args { + [] => bytesio_new(&[Object::Type(cls.clone())], &[]).ok(), + [b @ Object::Bytes(_)] => bytesio_new(&[Object::Type(cls.clone()), b.clone()], &[]).ok(), + _ => None, + } +} + +/// `io.StringIO()` / `io.StringIO(s)` of the exact type with a plain `str` +/// (see [`bytesio_new_pure`]). +fn stringio_new_pure(cls: &Rc, args: &[Object]) -> Option { + match args { + [] => stringio_new(&[Object::Type(cls.clone())], &[]).ok(), + [s @ Object::Str(_)] => stringio_new(&[Object::Type(cls.clone()), s.clone()], &[]).ok(), + _ => None, + } +} + /// Whether a native [`PyFile`] should be considered an instance of one of the /// `io` ABCs (`info` is the candidate class). `None` means "not an io ABC" /// (the caller falls back to ordinary MRO matching). A native binary stream is @@ -1954,6 +1983,8 @@ fn build_iobase_family_inner() -> IoFamily { ] { set_type_module(conc, "_io"); } + bytes_io.pure_new.set(Some(bytesio_new_pure)); + string_io.pure_new.set(Some(stringio_new_pure)); IoFamily { iobase, raw, @@ -2210,7 +2241,7 @@ fn rawiobase_read(args: &[Object]) -> Result { } let n = n_i as usize; let bytes = buf.as_bytes_view().unwrap_or_default(); - Ok(Object::new_bytes(bytes[..n.min(bytes.len())].to_vec())) + Ok(Object::new_bytes(&bytes[..n.min(bytes.len())])) } /// `RawIOBase.readall()` — read and return all bytes until EOF by repeatedly @@ -2727,7 +2758,7 @@ fn raw_write(target: &RawTarget, data: &[u8]) -> Result, RuntimeEr match target { RawTarget::Native(raw) => Ok(Some(raw.write_bytes(data)?)), RawTarget::Py(raw) => { - let res = py_call(raw, "write", &[Object::new_bytes(data.to_vec())])?; + let res = py_call(raw, "write", &[Object::new_bytes(data)])?; if matches!(res, Object::None) { return Ok(None); } @@ -3526,7 +3557,7 @@ fn tw_fill_chunk(inst: &Rc) -> Result<(), RuntimeError if is_wstr { tw_set(inst, "_dec_wstr", Object::Bool(true)); } - tw_set(inst, "_dec_partial", Object::new_bytes(leftover.to_vec())); + tw_set(inst, "_dec_partial", Object::new_bytes(leftover)); if eof { tw_set(inst, "_dec_done", Object::Bool(true)); } diff --git a/crates/weavepy-vm/src/stdlib/io_full.rs b/crates/weavepy-vm/src/stdlib/io_full.rs index 1bfe92b39..d61b23695 100644 --- a/crates/weavepy-vm/src/stdlib/io_full.rs +++ b/crates/weavepy-vm/src/stdlib/io_full.rs @@ -401,7 +401,7 @@ fn file_from_fd(fd_obj: &Object, mode: &str, name: String) -> Result Result Rc { reg!("islice_set_cnt", islice_set_cnt); reg!("repeat_core", repeat_core); reg!("tee_core", tee_core); + reg!("tee_native", tee_native); reg!("lazy_state", lazy_state); reg!("count_core", count_core); reg!("cycle_core", cycle_core); @@ -74,6 +75,35 @@ pub fn build(_cache: &ModuleCache) -> Rc { register_classmethod_descriptor ); reg!("_register_types", register_types); + // `__next__` for the classes whose Python one is + // `return next(self._core)`: a method (it binds the instance). + let core_next_fn = Rc::new(BuiltinFn { + name: "__next__", + binds_instance: true, + call: Box::new(core_next), + call_kw: None, + }); + crate::leaf_builtins::register_fast(&core_next_fn, core_next_fast); + // `__iter__` returning the instance (CPython's `PyObject_SelfIter`, + // `_tee`'s): a method with a leaf half. + let iter_self_fn = Rc::new(BuiltinFn { + name: "__iter__", + binds_instance: true, + call: Box::new(iter_self), + call_kw: None, + }); + crate::leaf_builtins::register_fast(&iter_self_fn, |a| match a { + [o] => Some(Ok(o.clone())), + _ => None, + }); + d.insert( + DictKey(Object::from_static("_iter_self")), + Object::Builtin(iter_self_fn), + ); + d.insert( + DictKey(Object::from_static("_core_next")), + Object::Builtin(core_next_fn), + ); reg!("groupby_core", groupby_core); reg!("grouper_core", grouper_core); reg!("groupby_setstate", groupby_setstate); @@ -270,6 +300,96 @@ fn repeat_core(args: &[Object]) -> Result { /// live entry. static TEE_REGISTRY: Mutex>>>> = Mutex::new(None); +/// `tee_native(iterable, n, tee_cls, data_cls)`: `itertools.tee(iterable, +/// n)` for a plain int `n` of at least one and an iterable that isn't a +/// tee already (whose copies are the Python path's), built as the Python +/// `tee` builds it, with no frame per branch: one `data_cls` instance +/// (`_tee_dataobject`) over `iter(iterable)`, and `n` instances of +/// `tee_cls` (`_tee`) over it, each with a native branch as its `_core`. +/// `None` for any other call, which the Python body then makes. +fn tee_native(args: &[Object]) -> Result { + let [iterable, Object::Int(n), Object::Type(tee_cls), Object::Type(data_cls)] = args else { + return Ok(Object::None); + }; + let Ok(n) = usize::try_from(*n) else { + return Ok(Object::None); + }; + if n == 0 + || n > 1 << 16 + || matches!(iterable, Object::LazyIter(l) if l.cls.is_some()) + || crate::builtins::class_of(iterable).is_subclass_of(tee_cls) + { + return Ok(Object::None); + } + let Some(ptr) = crate::vm_singletons::current_interpreter_ptr() else { + return Ok(Object::None); + }; + // SAFETY: published by the enclosing VM frame on this thread. + let interp = unsafe { &mut *ptr }; + let globals = interp.builtins_dict(); + let source = interp.make_iter(iterable, &globals)?; + // (As `_tee_dataobject.__init__` leaves it.) + let data = crate::types::PyInstance::new(data_cls.clone()); + { + let buffer = Object::new_list(Vec::new()); + crate::gc_trace::track_built(&buffer); + let [k_source, k_buffer, k_busy] = tee_keys(); + let mut d = data.dict_cell().borrow_mut(); + d.insert(k_source.clone(), source); + d.insert(k_buffer.clone(), buffer); + d.insert(k_busy.clone(), Object::Bool(false)); + } + let data = Object::Instance(Rc::new(data)); + crate::gc_trace::track(&data); + // (The first branch registers the shared state the others read.) + let first = tee_core(&[data.clone(), Object::Int(0)])?; + let shared = match &first { + Object::LazyIter(l) => match &*l.state.borrow() { + LazyIterKind::TeeBranch { shared, .. } => shared.clone(), + _ => return Ok(Object::None), + }, + _ => return Ok(Object::None), + }; + // Each branch an instance of `tee_cls` (weakly referenceable, as + // CPython's tee objects are) with its `_data` and native `_core`, as + // `_tee.__new__` leaves it. + let branch = |core: Object| { + let inst = crate::types::PyInstance::new(tee_cls.clone()); + { + let [k_data, k_core] = tee_branch_keys(); + let mut d = inst.dict_cell().borrow_mut(); + d.insert(k_data.clone(), data.clone()); + d.insert(k_core.clone(), core); + } + let obj = Object::Instance(Rc::new(inst)); + crate::gc_trace::track(&obj); + obj + }; + let mut out = Vec::with_capacity(n); + out.push(branch(first)); + for _ in 1..n { + out.push(branch(make_lazy(LazyIterKind::TeeBranch { + shared: shared.clone(), + data: data.clone(), + index: 0, + }))); + } + Ok(Object::new_tuple(out)) +} + +/// A `_tee` instance's attribute keys (`_data`, `_core`), built once. +fn tee_branch_keys() -> &'static [DictKey; 2] { + static KEYS: std::sync::OnceLock<[DictKey; 2]> = std::sync::OnceLock::new(); + KEYS.get_or_init(|| ["_data", "_core"].map(|k| DictKey(Object::from_static(k)))) +} + +/// The `_tee_dataobject` attribute keys (`source`, `buffer`, `busy`), +/// built once. +fn tee_keys() -> &'static [DictKey; 3] { + static KEYS: std::sync::OnceLock<[DictKey; 3]> = std::sync::OnceLock::new(); + KEYS.get_or_init(|| ["source", "buffer", "busy"].map(|k| DictKey(Object::from_static(k)))) +} + /// `tee_core(data, index)` — one branch over a `_tee_dataobject`. fn tee_core(args: &[Object]) -> Result { let [data, index] = args else { @@ -286,12 +406,13 @@ fn tee_core(args: &[Object]) -> Result { let shared = match registry.get(&key).and_then(Weak::upgrade) { Some(shared) => shared, None => { + let [k_source, k_buffer, _] = tee_keys(); let d = inst.dict_cell().borrow(); - let source = match d.get(&DictKey(Object::from_static("source"))) { + let source = match d.get(k_source) { Some(Object::None) | None => None, Some(src) => Some(src.clone()), }; - let buffer = match d.get(&DictKey(Object::from_static("buffer"))) { + let buffer = match d.get(k_buffer) { Some(Object::List(items)) => items.clone(), _ => return Err(type_error("tee_core: data.buffer must be a list")), }; @@ -479,6 +600,79 @@ const KINDS: [(&str, u8); 19] = [ ("batched", K_BATCHED), ]; +/// `__next__(self)` of the frozen `itertools.py` classes that step their +/// native core (`return next(self._core)`): the adapter itself when the +/// instance is one (an exact class's), else the instance's `_core` (a +/// subclass's), stepped in place with no Python frame, as CPython's C +/// types step (`c.__next__()`, `threading`'s `_counter`). +fn core_next(args: &[Object]) -> Result { + let [slf] = args else { + return Err(type_error(format!( + "expected 0 arguments, got {}", + args.len().saturating_sub(1) + ))); + }; + let interp = crate::builtins::reentrant_interp()?; + let core = match slf { + Object::LazyIter(_) => slf.clone(), + _ => interp.load_attr_public(slf, "_core")?, + }; + let globals = interp.builtins_dict(); + // (A `StopIteration` the source raised goes on, value and all.) + match interp.iter_step(&core, &globals)? { + Some(v) => Ok(v), + None => Err(crate::error::stop_iteration()), + } +} + +/// `__iter__(self)`: `self`. +fn iter_self(args: &[Object]) -> Result { + match args { + [o] => Ok(o.clone()), + _ => Err(type_error(format!( + "expected 0 arguments, got {}", + args.len().saturating_sub(1) + ))), + } +} + +/// [`core_next`]'s leaf half for an instance (a `_tee`, a subclass's): +/// its `_core`, read from its dict under the default attribute access, +/// stepped when the step runs no code. `None` for anything else (an +/// adapter itself, a step that needs the interpreter, the end). +fn core_next_fast(args: &[Object]) -> Option> { + let inst = match args { + [Object::Instance(inst)] => inst, + // An exact object is its own core (`c.__next__()`, `nx()` of a + // bound `__next__`). + [Object::LazyIter(l)] => return crate::seqiter::itertools_pure_next(l)?.map(Ok), + _ => return None, + }; + let cls = inst.cls_raw(); + if !cls.memo_verdict(crate::types::Verdict::CoreInDict, "", || { + cls.dunder(crate::types::Dunder::GetAttribute) + .object_owner() + && cls.lookup("_core").is_none() + }) { + return None; + } + let [_, k_core] = tee_branch_keys(); + let core = match inst.dict.published() { + Some(d) => d.try_borrow().ok()?.get(k_core).cloned(), + None => inst + .dict + .split_cell() + .try_borrow() + .ok()? + .get_str("_core") + .cloned(), + }?; + let Object::LazyIter(l) = &core else { + return None; + }; + crate::seqiter::itertools_pure_next(l)?.map(Ok) +} + /// `_register_types(namespace)`: mark the module's exact classes. fn register_types(args: &[Object]) -> Result { let [Object::Dict(ns)] = args else { @@ -685,7 +879,7 @@ pub(crate) fn native_new( let core = match kind { K_CHAIN => { let source = Object::Iter(Rc::new(RefCell::new( - Object::new_tuple(args.to_vec()).make_iter().ok()?, + Object::tuple_from_slice(args).make_iter().ok()?, ))); chain_core(&[source, Object::None]) } @@ -896,6 +1090,10 @@ fn pure_pool(o: &Object) -> Option> { match o { Object::Tuple(_) => Some(Ok(o.clone())), Object::List(l) => Some(Ok(Object::new_tuple(l.try_borrow().ok()?.clone()))), + // A short str's characters (`product("ab", repeat=2)`). + Object::Str(t) if t.len() <= 256 => Some(Ok(Object::new_tuple( + t.chars().map(Object::from_char).collect(), + ))), _ => None, } } @@ -917,6 +1115,33 @@ pub(crate) fn native_new_pure( Some(with_class(core, cls)) } +/// [`native_new_pure`] with keywords, `names` (strings) naming `values` +/// (`product(xs, repeat=2)`): `None` for every other shape. +pub(crate) fn native_new_pure_kw( + cls: &Rc, + args: &[Object], + names: &[Object], + values: &[Object], +) -> Option { + let kwargs = names + .iter() + .zip(values) + .map(|(n, v)| match n { + Object::Str(s) => Some((s.to_string(), v.clone())), + _ => None, + }) + .collect::>>()?; + let core = native_new( + cls.lazy_ctor.get(), + args, + &kwargs, + &mut pure_iter, + &mut pure_pool, + )? + .ok()?; + Some(with_class(core, cls)) +} + /// `cls(*args, **kwargs)` for a registered exact class: `None` to run /// the class's own `__new__`. pub(crate) fn native_new_interp( @@ -1346,7 +1571,8 @@ fn lazy_state(args: &[Object]) -> Result { LazyIterKind::Map { .. } | LazyIterKind::Filter { .. } | LazyIterKind::Zip { .. } - | LazyIterKind::Enumerate { .. } => { + | LazyIterKind::Enumerate { .. } + | LazyIterKind::CallIter { .. } => { return Err(type_error("lazy_state: not a native itertools core")) } }; diff --git a/crates/weavepy-vm/src/stdlib/json_accel.rs b/crates/weavepy-vm/src/stdlib/json_accel.rs index 813ed6a51..104604345 100644 --- a/crates/weavepy-vm/src/stdlib/json_accel.rs +++ b/crates/weavepy-vm/src/stdlib/json_accel.rs @@ -226,8 +226,7 @@ thread_local! { /// without memoisation each call re-decodes the whole document to code /// points — O(n) per call, O(n^2) over a parse. Keyed on the string's /// heap identity (holding the object so the pointer can't be reused). - static SCANSTRING_CACHE: std::cell::RefCell>)>> = - const { std::cell::RefCell::new(None) }; + static SCANSTRING_CACHE: crate::gil::ReleaseUnderGil>)>>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(None)) }; } /// Code points of `o`, reusing the thread-local cache when the same @@ -1079,29 +1078,53 @@ fn parse_object( /// Only immutable string storage can enter the decoder's key memo. /// Separate tables allow lookup with borrowed input text before allocating /// a string. Escaped spellings still share the same canonical storage. +/// +/// UTF-8 keys are filed under their `hash(key)`: computed once, from the +/// input text, and kept on the new key string, so the dict insert that +/// follows reuses it (a keyed set hashed each new key twice more, about +/// 90 instructions apiece). The hash is the interpreter's own randomized +/// one, so a document can't flood the table; two keys that share a hash +/// keep the first in the memo and give the second a string of its own. #[derive(Default)] struct KeyMemo { - utf8: HashSet, + utf8: crate::fasthash::FxHashMap, wide: HashSet>, } impl KeyMemo { fn utf8(&mut self, text: &str) -> Object { - if let Some(existing) = self.utf8.get(text) { - return Object::Str(existing.clone()); + use std::collections::hash_map::Entry; + let h = crate::object::py_str_hash(text); + match self.utf8.entry(h) { + Entry::Occupied(e) if e.get().as_str() == text => Object::Str(e.get().clone()), + Entry::Occupied(_) => { + let value = SharedStr::from(text); + SharedStr::prime_hash(&value, h); + Object::Str(value) + } + Entry::Vacant(e) => { + let value = SharedStr::from(text); + SharedStr::prime_hash(&value, h); + e.insert(value.clone()); + Object::Str(value) + } } - let value: SharedStr = SharedStr::from(text); - self.utf8.insert(value.clone()); - Object::Str(value) } fn intern(&mut self, value: Object) -> Object { match value { Object::Str(text) => { - if let Some(existing) = self.utf8.get(text.as_ref()) { - return Object::Str(existing.clone()); + let h = SharedStr::hash_cached(&text); + match self.utf8.entry(h) { + std::collections::hash_map::Entry::Occupied(e) => { + if e.get().as_str() == text.as_str() { + return Object::Str(e.get().clone()); + } + } + std::collections::hash_map::Entry::Vacant(e) => { + e.insert(text.clone()); + } } - self.utf8.insert(text.clone()); Object::Str(text) } Object::WStr(cps) => { @@ -1136,11 +1159,14 @@ fn finish_object( .map(|(k, v)| Object::new_tuple_array([k, v])) .collect(); let arg = Object::new_list(pair_objs); + crate::gc_trace::track_built(&arg); return interp.call_object(cfg.object_pairs_hook.clone(), &[arg], &[]); } DecodedObject::Dict(dict) => dict, }; let dict_obj = Object::Dict(Rc::new(RefCell::new(d))); + // (Deferred without scanning, as every built container's.) + crate::gc_trace::track_built(&dict_obj); if is_set(&cfg.object_hook) { return interp.call_object(cfg.object_hook.clone(), &[dict_obj], &[]); } @@ -1170,7 +1196,7 @@ fn parse_array( } if nextchar == Some(0x5d) { // ']' - return Ok((Object::new_list(values), end + 1)); + return Ok((built_list(values), end + 1)); } loop { let (value, new_end) = match scan_once(interp, cfg, doc, cps, end, memo) { @@ -1233,7 +1259,14 @@ fn parse_array( ))); } } - Ok((Object::new_list(values), end)) + Ok((built_list(values), end)) +} + +/// A decoded array: a new list, its tracking deferred without a scan. +fn built_list(values: Vec) -> Object { + let list = Object::new_list(values); + crate::gc_trace::track_built(&list); + list } // --------------------------------------------------------------------------- @@ -1554,7 +1587,7 @@ fn encoder_call(cfg: &EncoderCfg, args: &[Object]) -> Result = HashSet::new(); + let mut cycle: crate::fasthash::FxHashSet = crate::fasthash::FxHashSet::default(); let track = !matches!(cfg.markers, Object::None); encode_value( interp, @@ -1790,7 +1823,7 @@ fn encode_value( level: usize, out: &mut JsonWriter, track: bool, - cycle: &mut HashSet, + cycle: &mut crate::fasthash::FxHashSet, ) -> Result<(), RuntimeError> { let _depth_guard = match crate::recursion::enter() { crate::recursion::Enter::Ok(g) => g, @@ -1816,7 +1849,7 @@ fn encode_value_impl( level: usize, out: &mut JsonWriter, track: bool, - cycle: &mut HashSet, + cycle: &mut crate::fasthash::FxHashSet, ) -> Result<(), RuntimeError> { match json_kind(o) { Kind::Str => write_encoded_string(interp, cfg, o, out)?, @@ -1880,7 +1913,7 @@ fn encode_list( level: usize, out: &mut JsonWriter, track: bool, - cycle: &mut HashSet, + cycle: &mut crate::fasthash::FxHashSet, ) -> Result<(), RuntimeError> { // A native `list` is indexed *live* each iteration (re-reading its // current length), exactly like `_json.c`'s `PyList_GET_SIZE` loop, so a @@ -1956,7 +1989,7 @@ fn encode_dict( level: usize, out: &mut JsonWriter, track: bool, - cycle: &mut HashSet, + cycle: &mut crate::fasthash::FxHashSet, ) -> Result<(), RuntimeError> { if items.is_empty() { out.push_str("{}"); @@ -2035,8 +2068,18 @@ fn encode_dict( /// (`test_speedups.test_unsortable_keys`). fn sort_items( interp: &mut Interpreter, - items: Vec<(Object, Object)>, + mut items: Vec<(Object, Object)>, ) -> Result, RuntimeError> { + // All `str` keys (a dict's are distinct, so no two items ever compare + // their values): the keys' code-point order, which their UTF-8 bytes + // sort in, with no tuples built and no `list.sort` call. + if items.iter().all(|(k, _)| matches!(k, Object::Str(_))) { + items.sort_unstable_by(|(a, _), (b, _)| match (a, b) { + (Object::Str(a), Object::Str(b)) => a.as_bytes().cmp(b.as_bytes()), + _ => std::cmp::Ordering::Equal, + }); + return Ok(items); + } let tuples: Vec = items .into_iter() .map(|(k, v)| Object::new_tuple_array([k, v])) diff --git a/crates/weavepy-vm/src/stdlib/local_native.rs b/crates/weavepy-vm/src/stdlib/local_native.rs index c551d26bb..a503fd420 100644 --- a/crates/weavepy-vm/src/stdlib/local_native.rs +++ b/crates/weavepy-vm/src/stdlib/local_native.rs @@ -137,7 +137,13 @@ pub(crate) fn getattribute_fast(recv: &Object, name: &Object) -> Option if &**name == "__dict__" { return Some(Object::Dict(space)); } - let own = space.try_borrow().ok()?.get(&StrKey(name)).cloned(); + // (The name's memoized hash: a site's name is the same object on + // every read.) + let key = crate::object::StrKeyHashed { + s: name, + hash: crate::shared_value::SharedStr::hash_cached(name), + }; + let own = space.try_borrow().ok()?.get(&key).cloned(); own } diff --git a/crates/weavepy-vm/src/stdlib/lzma_mod.rs b/crates/weavepy-vm/src/stdlib/lzma_mod.rs index 26fe4dba5..02e680487 100644 --- a/crates/weavepy-vm/src/stdlib/lzma_mod.rs +++ b/crates/weavepy-vm/src/stdlib/lzma_mod.rs @@ -6,7 +6,6 @@ use crate::sync::Rc; use crate::sync::RefCell; -use std::collections::HashMap; use std::io::{Read, Write}; use std::os::raw::c_void; use std::sync::atomic::{AtomicI64, Ordering}; @@ -649,17 +648,35 @@ struct LzmaDecompState { check_known: bool, } -type CompReg = Mutex>>>; -type DecompReg = Mutex>>>; +type CompReg = Mutex>; +type DecompReg = Mutex>; fn comp_reg() -> &'static CompReg { static REG: OnceLock = OnceLock::new(); - REG.get_or_init(|| Mutex::new(HashMap::new())) + REG.get_or_init(Mutex::default) +} + +/// A compressor's state goes with it (see `handle_table`). +fn comp_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + if let Ok(mut reg) = comp_reg().try_lock() { + reg.remove(id); + } + } +} + +/// A decompressor's state goes with it (see `handle_table`). +fn decomp_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + if let Ok(mut reg) = decomp_reg().try_lock() { + reg.remove(id); + } + } } fn decomp_reg() -> &'static DecompReg { static REG: OnceLock = OnceLock::new(); - REG.get_or_init(|| Mutex::new(HashMap::new())) + REG.get_or_init(Mutex::default) } fn lzma_next_id() -> i64 { @@ -668,11 +685,11 @@ fn lzma_next_id() -> i64 { } fn comp_state(id: i64) -> Option>> { - comp_reg().lock().ok()?.get(&id).cloned() + comp_reg().lock().ok()?.get(id) } fn decomp_state(id: i64) -> Option>> { - decomp_reg().lock().ok()?.get(&id).cloned() + decomp_reg().lock().ok()?.get(id) } /// The `_lzma.LZMAError` exception type (a plain `Exception` subclass, as in @@ -912,6 +929,7 @@ fn compressor_class() -> Rc { is_builtin: true, }, ) + .inspect(|cls| super::handle_table::watch_owner_class(cls, comp_died)) .expect("LZMACompressor must linearise") }) .clone() @@ -936,6 +954,7 @@ fn decompressor_class() -> Rc { is_builtin: true, }, ) + .inspect(|cls| super::handle_table::watch_owner_class(cls, decomp_died)) .expect("LZMADecompressor must linearise") }) .clone() @@ -1062,10 +1081,11 @@ fn compressor_init(args: &[Object], kwargs: &[(String, Object)]) -> Result Result Result Result<(), RuntimeError> { if self.plan.is_none() || kinds.is_empty() { - return self.write_table_bytes(&Object::new_bytes(kinds.to_vec())); + return self.write_table_bytes(&Object::new_bytes(kinds)); } self.write_byte(TYPE_STRING); self.write_int(kinds.len() as i32); diff --git a/crates/weavepy-vm/src/stdlib/math.rs b/crates/weavepy-vm/src/stdlib/math.rs index 43cc7d854..013ed0e9e 100644 --- a/crates/weavepy-vm/src/stdlib/math.rs +++ b/crates/weavepy-vm/src/stdlib/math.rs @@ -294,7 +294,9 @@ pub fn build(_cache: &ModuleCache) -> Rc { /// computed without the body's argument conversion and result checks. A /// domain or range error, or a NaN (which the body re-tags), declines to /// the full body. -const FAST_HALVES: [(&str, crate::leaf_builtins::Fast); 12] = [ +const FAST_HALVES: [(&str, crate::leaf_builtins::Fast); 14] = [ + ("prod", prod_fast), + ("fsum", fsum_fast), ("floor", floor_fast), ("ceil", ceil_fast), ("sqrt", sqrt_fast), @@ -309,13 +311,67 @@ const FAST_HALVES: [(&str, crate::leaf_builtins::Fast); 12] = [ ("isnan", isnan_fast), ]; -/// Whether `f` is one of [`FAST_HALVES`] (all pure). -pub(crate) fn is_fast_half(f: crate::leaf_builtins::Fast) -> bool { - FAST_HALVES.iter().any(|&(_, g)| std::ptr::fn_addr_eq(g, f)) +/// The module's fast halves, which read their arguments and build a fresh +/// result (see `pure_fast_half`). +pub(crate) fn fast_halves() -> impl Iterator { + FAST_HALVES.iter().map(|&(_, g)| g) } type FastResult = Option>; +/// A list's or tuple's items, when every one is a plain `int` or `float` +/// (reading them runs no code), handed to `f`. +fn plain_numbers(seq: &Object, f: impl FnOnce(&[Object]) -> Option) -> Option { + let plain = |xs: &[Object]| { + xs.iter() + .all(|x| matches!(x, Object::Int(_) | Object::Float(_))) + }; + match seq { + Object::List(l) => { + let xs = l.try_borrow().ok()?; + plain(&xs).then(|| f(&xs)).flatten() + } + Object::Tuple(t) => plain(t).then(|| f(t)).flatten(), + _ => None, + } +} + +/// `math.prod(xs)` (no `start`) of a list or tuple of plain numbers: the +/// left-to-right product, machine ints while they don't overflow, then +/// doubles once a `float` comes, as CPython's int and float paths compute +/// it. An overflowing int product declines to the full body. +fn prod_fast(args: &[Object]) -> FastResult { + let [seq] = args else { + return None; + }; + plain_numbers(seq, |xs| { + let mut int_acc: i64 = 1; + let mut flt: Option = None; + for x in xs { + match (flt, x) { + (None, Object::Int(i)) => int_acc = int_acc.checked_mul(*i)?, + (None, Object::Float(f)) => flt = Some(int_acc as f64 * f), + (Some(a), Object::Float(f)) => flt = Some(a * f), + (Some(a), Object::Int(i)) => flt = Some(a * *i as f64), + _ => return None, + } + } + Some(Ok(match flt { + Some(f) => Object::Float(f), + None => Object::Int(int_acc), + })) + }) +} + +/// `math.fsum(xs)` of a list or tuple of plain numbers: the full body, +/// which reads such items with no code run. +fn fsum_fast(args: &[Object]) -> FastResult { + let [seq] = args else { + return None; + }; + plain_numbers(seq, |_| Some(math_fsum(args))) +} + /// A plain `float` or `int` argument's value. #[inline] fn plain_f64(x: &Object) -> Option { @@ -985,10 +1041,11 @@ fn math_gcd(args: &[Object]) -> Result { Object::Bool(b) => Some(u64::from(*b)), _ => None, }; - if let Some(words) = args.iter().map(small).collect::>>() { - let g = words - .into_iter() - .fold(0u64, |a, b| gcd_u128(u128::from(a), u128::from(b)) as u64); + // (Folded as they come, no list of them built.) + if let Some(g) = args + .iter() + .try_fold(0u64, |a, o| small(o).map(|b| gcd_u64(a, b))) + { return Ok(i64::try_from(g).map_or_else( |_| Object::int_from_bigint(num_bigint::BigInt::from(g)), Object::Int, @@ -1002,6 +1059,28 @@ fn math_gcd(args: &[Object]) -> Result { Ok(Object::int_from_bigint(acc)) } +/// Binary GCD of two words (half the work of [`gcd_u128`]'s steps). +fn gcd_u64(mut a: u64, mut b: u64) -> u64 { + if a == 0 { + return b; + } + if b == 0 { + return a; + } + let shift = (a | b).trailing_zeros(); + a >>= a.trailing_zeros(); + loop { + b >>= b.trailing_zeros(); + if a > b { + std::mem::swap(&mut a, &mut b); + } + b -= a; + if b == 0 { + return a << shift; + } + } +} + /// Binary GCD of two machine words. fn gcd_u128(mut a: u128, mut b: u128) -> u128 { if a == 0 { @@ -1068,6 +1147,25 @@ fn math_lcm(args: &[Object]) -> Result { if args.is_empty() { return Ok(Object::Int(1)); } + // Machine-word arguments whose least common multiple stays one: in + // words, no big integers built (a zero argument makes it zero). + let small = |o: &Object| match o { + Object::Int(i) => Some(i.unsigned_abs()), + Object::Bool(b) => Some(u64::from(*b)), + _ => None, + }; + if args.iter().all(|o| small(o).is_some()) { + let word = args.iter().try_fold(1u64, |acc, o| { + let v = small(o)?; + if acc == 0 || v == 0 { + return Some(0); + } + (acc / gcd_u64(acc, v)).checked_mul(v) + }); + if let Some(l) = word.and_then(|l| i64::try_from(l).ok()) { + return Ok(Object::Int(l)); + } + } let mut acc = index_bigint(&args[0])?.abs(); for a in &args[1..] { // Every argument is coerced (so a bad type raises TypeError) even @@ -1132,6 +1230,20 @@ fn math_isclose(args: &[Object], kwargs: &[(String, Object)]) -> Result Some(f), + // (Exactly as `float(i)` rounds it.) + Object::Int(i) => Some(i as f64), + _ => None, + }; + if let [x, y] = args { + if let (Some(a), Some(b)) = (plain(x), plain(y)) { + return Ok(Object::Bool(isclose_f64(a, b, 1e-9, 0.0))); + } + } + } if args.len() > 2 { return Err(type_error(format!( "isclose() takes at most 2 positional arguments ({} given)", @@ -1176,16 +1288,20 @@ fn math_isclose(args: &[Object], kwargs: &[(String, Object)]) -> Result bool { #[allow(clippy::float_cmp)] if a == b { - return Ok(Object::Bool(true)); + return true; } if a.is_infinite() || b.is_infinite() { - return Ok(Object::Bool(false)); + return false; } let diff = (b - a).abs(); - let result = diff <= (rel_tol * b).abs() || diff <= (rel_tol * a).abs() || diff <= abs_tol; - Ok(Object::Bool(result)) + diff <= (rel_tol * b).abs() || diff <= (rel_tol * a).abs() || diff <= abs_tol } // --------------------------------------------------------------------- @@ -1196,6 +1312,27 @@ fn math_isclose(args: &[Object], kwargs: &[(String, Object)]) -> Result Result, RuntimeError> { + // An exact list or tuple of floats and machine ints: read in place. + let plain = |items: &[Object]| -> Option> { + items + .iter() + .map(|x| match *x { + Object::Float(f) => Some(f), + // (Exactly as `float(i)` rounds it.) + Object::Int(i) => Some(i as f64), + Object::Bool(b) => Some(f64::from(u8::from(b))), + _ => None, + }) + .collect() + }; + let read = match arg { + Object::List(l) => l.try_borrow().ok().and_then(|v| plain(&v)), + Object::Tuple(t) => plain(t), + _ => None, + }; + if let Some(values) = read { + return Ok(values); + } // Iterate through the interpreter so tuple subclasses, generators, and // user `__iter__` work (CPython's `dist`/`fsum` accept any iterable): // `dist(T((1,2,3)), ...)` for a `tuple` subclass `T` reaches here as an @@ -1223,10 +1360,13 @@ fn object_to_f64(value: &Object, func: &str) -> Result { // take `FloatLike` and `Fraction`-style operands). match crate::builtins::coerce_f64_opt(value)? { Some(f) => Ok(f), - None => Err(type_error(format!( - "{func}() element must be a real number, not '{}'", - value.type_name() - ))), + None => { + let _ = func; + Err(type_error(format!( + "must be real number, not {}", + value.type_name() + ))) + } } } @@ -1817,6 +1957,33 @@ fn math_modf(args: &[Object]) -> Result { ])) } +/// `comb(n, k)` or `perm(n, k)` of two machine ints whose product stays +/// within 128 bits at every step (each step of `comb` is exact: +/// `C(n, i + 1) = C(n, i) * (n - i) / (i + 1)`). `None` for a negative +/// argument (whose error the general path raises) or an overflow (which +/// it computes with big ints). +fn comb_perm_small(n: i64, k: i64, comb: bool) -> Option { + if n < 0 || k < 0 { + return None; + } + if k > n { + return Some(Object::Int(0)); + } + let (n, k) = (n as u128, k as u128); + let steps = if comb { k.min(n - k) } else { k }; + let mut r: u128 = 1; + for i in 0..steps { + r = r.checked_mul(n - i)?; + if comb { + r /= i + 1; + } + } + Some(match i64::try_from(r) { + Ok(v) => Object::Int(v), + Err(_) => Object::int_from_bigint(num_bigint::BigInt::from(r)), + }) +} + fn math_comb(args: &[Object]) -> Result { use num_traits::{Signed, ToPrimitive}; if args.len() != 2 { @@ -1825,6 +1992,11 @@ fn math_comb(args: &[Object]) -> Result { args.len() ))); } + if let [Object::Int(n), Object::Int(k)] = args { + if let Some(r) = comb_perm_small(*n, *k, true) { + return Ok(r); + } + } let n = index_bigint(&args[0])?; let k = index_bigint(&args[1])?; if n.is_negative() { @@ -1868,6 +2040,11 @@ fn math_perm(args: &[Object]) -> Result { if matches!(args.get(1), None | Some(Object::None)) { return factorial_impl(&args[0]); } + if let [Object::Int(n), Object::Int(k)] = args { + if let Some(r) = comb_perm_small(*n, *k, false) { + return Ok(r); + } + } let n = index_bigint(&args[0])?; let k = index_bigint(&args[1])?; if n.is_negative() { @@ -2408,6 +2585,21 @@ fn math_lgamma(args: &[Object]) -> Result { fn math_isqrt(args: &[Object]) -> Result { use num_traits::Signed; expect_nargs(args, "isqrt", 1)?; + // A non-negative machine int: the float root's estimate, corrected to + // the exact floor (the estimate is within one of it). + if let Object::Int(n) = &args[0] { + if let Ok(n) = u64::try_from(*n) { + let n = u128::from(n); + let mut r = (n as f64).sqrt() as u128; + while r * r > n { + r -= 1; + } + while (r + 1) * (r + 1) <= n { + r += 1; + } + return Ok(Object::Int(r as i64)); + } + } // Accept any integer, including big and `__index__`-able values // (CPython uses `_PyNumber_Index`). A float approximation overflows for // large inputs, so we take the exact integer square root over BigInt. diff --git a/crates/weavepy-vm/src/stdlib/mod.rs b/crates/weavepy-vm/src/stdlib/mod.rs index 79cd834c8..8f3738fc2 100644 --- a/crates/weavepy-vm/src/stdlib/mod.rs +++ b/crates/weavepy-vm/src/stdlib/mod.rs @@ -82,6 +82,7 @@ pub mod gc_mod; #[cfg(unix)] pub mod grp_mod; pub mod gzip_mod; +pub(crate) mod handle_table; pub mod hashlib_mod; pub mod heapq_accel; pub mod hmac_mod; @@ -94,6 +95,7 @@ pub mod lzma_mod; pub mod marshal_mod; pub mod math; pub mod pickle_accel; +pub(crate) mod zoneinfo_native; // RFC 0063 — the Windows wave: shared NT plumbing (CRT fd layer, // winerror bridge) plus the native module quartet the frozen Windows // stdlib consumes. @@ -324,6 +326,7 @@ pub fn register_all(cache: &ModuleCache) { cache.register_builtin("_weave_datetime", datetime_accel::build); cache.register_builtin("_weave_decimal", decimal_native::build); cache.register_builtin("_weave_elementtree", elementtree_native::build); + cache.register_builtin("_weave_zoneinfo", zoneinfo_native::build); cache.register_builtin("_weave_pickle", pickle_accel::build); cache.register_builtin("gc", gc_real::build); cache.register_builtin("_multiprocessing", multiprocessing_mod::build); diff --git a/crates/weavepy-vm/src/stdlib/multiprocessing_mod.rs b/crates/weavepy-vm/src/stdlib/multiprocessing_mod.rs index 1e34502f9..3db5a4136 100644 --- a/crates/weavepy-vm/src/stdlib/multiprocessing_mod.rs +++ b/crates/weavepy-vm/src/stdlib/multiprocessing_mod.rs @@ -318,7 +318,7 @@ unsafe impl Sync for SemInner {} #[cfg(unix)] thread_local! { - static SEMLOCK_TYPE: RefCell>> = const { RefCell::new(None) }; + static SEMLOCK_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } /// The `_multiprocessing.SemLock` type. Built lazily so @@ -997,7 +997,7 @@ impl Drop for NtSemInner { #[cfg(windows)] thread_local! { - static NT_SEMLOCK_TYPE: RefCell>> = const { RefCell::new(None) }; + static NT_SEMLOCK_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } /// The `_multiprocessing.SemLock` type (NT arm). Built lazily so diff --git a/crates/weavepy-vm/src/stdlib/operator_accel.rs b/crates/weavepy-vm/src/stdlib/operator_accel.rs index 3a98a193f..c038ab65a 100644 --- a/crates/weavepy-vm/src/stdlib/operator_accel.rs +++ b/crates/weavepy-vm/src/stdlib/operator_accel.rs @@ -132,7 +132,7 @@ pub fn build(_cache: &ModuleCache) -> Rc { // have no dunders, so the native arithmetic is the whole call (a // core-loop or compiled caller, and a `partial` over one, run it in // place). Anything else declines to the full body. - for (name, fast) in BINARY_FAST { + for (name, fast) in BINARY_FAST.iter().chain(OTHER_FAST) { if let Some(Object::Builtin(b)) = d.get(&crate::object::StrKey(name)) { crate::leaf_builtins::register_fast(b, *fast); } @@ -181,6 +181,10 @@ pub fn build(_cache: &ModuleCache) -> Rc { // A plain attribute read that runs no code, in place. crate::leaf_builtins::register_fast(&b, attrgetter_fast); } + if name == ".methodcaller.__call__" { + // A native value's leaf method, in place. + crate::leaf_builtins::register_fast(&b, methodcaller_fast); + } d.insert(DictKey(Object::from_static(export)), Object::Builtin(b)); } @@ -217,6 +221,7 @@ pub fn build(_cache: &ModuleCache) -> Rc { None, ); } + register_getter_ctor(cls); } Ok(Object::None) }), @@ -341,10 +346,56 @@ const BINARY_FAST: &[(&str, crate::leaf_builtins::Fast)] = &[ ("rshift", |a| binary_fast(a, BinOpKind::RShift)), ]; -/// Whether `f` is one of [`BINARY_FAST`]'s halves, which run no code (a -/// frameless leaf may call them). -pub(crate) fn is_fast_half(f: crate::leaf_builtins::Fast) -> bool { - BINARY_FAST.iter().any(|&(_, p)| std::ptr::fn_addr_eq(p, f)) +/// The leaf halves of the unary and comparison functions: a plain int or +/// float operand has no dunders, so the native operation is the whole call +/// (`sorted(xs, key=operator.neg)` computes its keys in place). +const OTHER_FAST: &[(&str, crate::leaf_builtins::Fast)] = &[ + ("neg", |a| unary_fast(a, UnaryKind::Neg)), + ("pos", |a| unary_fast(a, UnaryKind::Pos)), + ("invert", |a| unary_fast(a, UnaryKind::Invert)), + ("inv", |a| unary_fast(a, UnaryKind::Invert)), + ("lt", |a| compare_fast(a, CompareKind::Lt)), + ("le", |a| compare_fast(a, CompareKind::LtE)), + ("eq", |a| compare_fast(a, CompareKind::Eq)), + ("ne", |a| compare_fast(a, CompareKind::NotEq)), + ("gt", |a| compare_fast(a, CompareKind::Gt)), + ("ge", |a| compare_fast(a, CompareKind::GtE)), +]; + +fn unary_fast(args: &[Object], op: UnaryKind) -> Option> { + Some(Ok(match (args, op) { + ([Object::Int(x)], UnaryKind::Neg) => Object::Int(x.checked_neg()?), + ([Object::Int(x)], UnaryKind::Pos) => Object::Int(*x), + ([Object::Int(x)], UnaryKind::Invert) => Object::Int(!x), + ([Object::Float(x)], UnaryKind::Neg) => Object::Float(-x), + ([Object::Float(x)], UnaryKind::Pos) => Object::Float(*x), + _ => return None, + })) +} + +fn compare_fast(args: &[Object], op: CompareKind) -> Option> { + use std::cmp::Ordering; + let ord = match args { + [Object::Int(x), Object::Int(y)] => Some(x.cmp(y)), + [Object::Float(x), Object::Float(y)] => x.partial_cmp(y), + _ => return None, + }; + let r = match op { + CompareKind::Lt => ord == Some(Ordering::Less), + CompareKind::LtE => matches!(ord, Some(Ordering::Less | Ordering::Equal)), + CompareKind::Eq => ord == Some(Ordering::Equal), + // (NaN is unequal to everything, itself included.) + CompareKind::NotEq => ord != Some(Ordering::Equal), + CompareKind::Gt => ord == Some(Ordering::Greater), + CompareKind::GtE => matches!(ord, Some(Ordering::Greater | Ordering::Equal)), + }; + Some(Ok(Object::Bool(r))) +} + +/// The module's fast halves, which read their arguments and build a fresh +/// result (see `pure_fast_half`). +pub(crate) fn fast_halves() -> impl Iterator { + BINARY_FAST.iter().chain(OTHER_FAST).map(|&(_, p)| p) } fn binary(args: &[Object], op: BinOpKind, name: &str) -> Result { @@ -479,28 +530,124 @@ fn itemgetter_call(args: &[Object]) -> Result { }) } -/// `attrgetter.__call__`'s leaf half: one attribute name without dots, read -/// off the operand as `getattr(obj, name)`'s leaf reads it (an instance's -/// own value, a class function bound, a plain class value, a named tuple's -/// field) when that runs no code. Anything else declines to the full body. +/// `attrgetter.__call__`'s leaf half: each attribute name (a dotted one step +/// by step) read off the operand as `getattr(obj, name)`'s leaf reads it +/// (an instance's own value, a class function bound, a plain class value, +/// a named tuple's field) when that runs no code: the one value, or the +/// tuple of several. Anything else declines to the full body, nothing +/// having run. fn attrgetter_fast(args: &[Object]) -> Option> { let [Object::Instance(inst), obj] = args else { return None; }; + // SAFETY: a view that ends with the reads, which run no code (so + // nothing can rebind the getter's names meanwhile). + let Object::Tuple(attrs) = unsafe { inst.slots.peek() }?.get_hinted(0, "_attrs")? else { + return None; + }; + // (Names are short: a plain scan beats `memchr`'s set-up.) + let dotless = |name: &Object| matches!(name, Object::Str(s) if !s.as_bytes().contains(&b'.')); + match &attrs[..] { + [name] if dotless(name) => crate::Interpreter::leaf_getattr_value(obj, name).map(Ok), + [a, b] if dotless(a) && dotless(b) => { + let x = crate::Interpreter::leaf_getattr_value(obj, a)?; + let y = crate::Interpreter::leaf_getattr_value(obj, b)?; + Some(Ok(Object::new_tuple_array([x, y]))) + } + names if !names.is_empty() && names.iter().all(dotless) => names + .iter() + .map(|name| crate::Interpreter::leaf_getattr_value(obj, name)) + .collect::>>() + .map(|values| Ok(Object::new_tuple(values))), + // A dotted name (`attrgetter("a.b")`): each step read in turn, its + // name interned as the full call's `getattr` would see it. + [name] => dotted_value(obj, name).map(Ok), + names => names + .iter() + .map(|name| dotted_value(obj, name)) + .collect::>>() + .map(|values| Ok(Object::new_tuple(values))), + } +} + +/// `obj.a.b...` of the dotted `name` as [`attrgetter_fast`] reads it, or +/// `None` where a step needs the full path (nothing has run by then: the +/// steps read without running code). +fn dotted_value(obj: &Object, name: &Object) -> Option { + let Object::Str(path) = name else { + return None; + }; + if !path.as_bytes().contains(&b'.') { + return crate::Interpreter::leaf_getattr_value(obj, name); + } + let mut cur = obj.clone(); + for part in path.as_str().split('.') { + let part = crate::stdlib::sys::intern_name(part); + cur = crate::Interpreter::leaf_getattr_value(&cur, &part)?; + } + Some(cur) +} + +/// The one dotless name an `attrgetter(name)` holds, when `f` is an +/// instance whose class's `__call__` is the native getter's (a sort's key, +/// read once for every item). +pub(crate) fn attrgetter_single_name(f: &Object) -> Option { + let Object::Instance(inst) = f else { + return None; + }; + match inst.cls_raw().lookup("__call__")? { + Object::Builtin(b) if b.name == ".attrgetter.__call__" => {} + _ => return None, + } + // SAFETY: a read that runs no code. + let Object::Tuple(attrs) = unsafe { inst.slots.peek() }?.get_hinted(0, "_attrs")? else { + return None; + }; + match &attrs[..] { + [name @ Object::Str(s)] if !s.as_bytes().contains(&b'.') => Some(name.clone()), + _ => None, + } +} + +/// The one int index an `itemgetter(i)` holds, when `f` is an instance +/// whose class's `__call__` is the native getter's (a sort's key, read once +/// for every item). +pub(crate) fn itemgetter_single_index(f: &Object) -> Option { + let Object::Instance(inst) = f else { + return None; + }; + match inst.cls_raw().lookup("__call__")? { + Object::Builtin(b) if b.name == ".itemgetter.__call__" => {} + _ => return None, + } // SAFETY: a read that runs no code. - let Object::Tuple(attrs) = unsafe { inst.slots.peek() }? - .get_hinted(0, "_attrs")? - .clone() - else { + let Object::Tuple(items) = unsafe { inst.slots.peek() }?.get_hinted(0, "_items")? else { return None; }; - let [name @ Object::Str(s)] = &attrs[..] else { + match &items[..] { + [Object::Int(i)] => Some(*i), + _ => None, + } +} + +/// The one `str` key an `itemgetter(key)` holds, as +/// [`itemgetter_single_index`] finds its one index. +pub(crate) fn itemgetter_single_key(f: &Object) -> Option { + let Object::Instance(inst) = f else { return None; }; - if s.contains('.') { + match inst.cls_raw().lookup("__call__")? { + Object::Builtin(b) if b.name == ".itemgetter.__call__" => {} + _ => return None, + } + // SAFETY: a read that runs no code. + let Object::Tuple(items) = unsafe { inst.slots.peek() }?.get_hinted(0, "_items")? else { return None; + }; + match &items[..] { + [key @ Object::Str(_)] => Some(key.clone()), + _ => None, } - crate::Interpreter::leaf_getattr_value(obj, name).map(Ok) } /// [`itemgetter_call`]'s pure fast half (the dispatch loop's leaf call): @@ -511,42 +658,229 @@ fn itemgetter_fast(args: &[Object]) -> Option> { let [Object::Instance(inst), obj] = args else { return None; }; - // SAFETY: a read that runs no code. - let Object::Tuple(items) = unsafe { inst.slots.peek() }? - .get_hinted(0, "_items")? - .clone() - else { - return None; + // A subclass of one of them (a named tuple) whose `__getitem__` is + // still the base's own reads its payload the same way. + let obj = match obj { + Object::Instance(o) => match o.native.get() { + Some(native @ (Object::Tuple(_) | Object::List(_) | Object::Dict(_))) + if crate::Interpreter::native_payload_getitem(o) => + { + native + } + _ => return None, + }, + _ => obj, }; - let get = |item: &Object| -> Option { - let index = |len: usize| -> Option { - let Object::Int(i) = item else { - return None; - }; - let len = len as i64; - let k = if *i < 0 { i + len } else { *i }; - (0..len).contains(&k).then_some(k as usize) + // SAFETY: guard-free reads that run no code (nothing below can change + // the instance's slots or the operand). + unsafe { + let Object::Tuple(items) = inst.slots.peek()?.get_hinted(0, "_items")? else { + return None; }; - match obj { - Object::List(l) => { - let v = l.try_borrow().ok()?; - v.get(index(v.len())?).cloned() - } - Object::Tuple(t) => t.get(index(t.len())?).cloned(), - Object::Dict(d) => { - let probe = crate::object::LeafProbe::new(item)?; - if matches!(item, Object::Instance(_)) { + let get = |item: &Object| -> Option { + let index = |len: usize| -> Option { + let Object::Int(i) = item else { return None; + }; + let len = len as i64; + let k = if *i < 0 { i + len } else { *i }; + (0..len).contains(&k).then_some(k as usize) + }; + match obj { + Object::Tuple(t) => t.get(index(t.len())?).cloned(), + Object::List(l) => { + let v = l.peek()?; + v.get(index(v.len())?).cloned() + } + Object::Dict(d) => { + if matches!(item, Object::Instance(_)) { + return None; + } + let probe = crate::object::LeafProbe::new(item)?; + d.peek()?.get(&probe).cloned() } - d.try_borrow().ok()?.get(&probe).cloned() + _ => None, } - _ => None, - } + }; + Some(Ok(match &items[..] { + [item] => get(item)?, + // (Two or three, the common record keys: the tuple built from + // an array, with no vector between.) + [a, b] => Object::new_tuple_array([get(a)?, get(b)?]), + [a, b, c] => Object::new_tuple_array([get(a)?, get(b)?, get(c)?]), + many => Object::new_tuple(many.iter().map(get).collect::>>()?), + })) + } +} + +/// Which of the three classes a pure constructor builds, and the class's +/// attribute version when it was registered (a class changed since, its +/// `__init__` replaced say, constructs through its Python methods). +struct GetterCtor { + slots: &'static [&'static str], + version: u64, +} + +/// The exact `attrgetter`, `itemgetter` and `methodcaller` classes' pure +/// constructors (see `TypeObject::pure_new`): `itemgetter(1)` builds its +/// instance in place, as CPython's C constructor does, rather than running +/// the Python `__init__` with its `*items`. +fn register_getter_ctor(cls: &Rc) { + let (slots, pure): (&'static [&'static str], crate::types::PureNew) = match cls.name.as_str() { + "itemgetter" => (&["_items"], itemgetter_new_pure), + "attrgetter" => (&["_attrs"], attrgetter_new_pure), + "methodcaller" => (&["_name", "_args", "_kwargs"], methodcaller_new_pure), + _ => return, }; - Some(Ok(match &items[..] { - [item] => get(item)?, - many => Object::new_tuple(many.iter().map(get).collect::>>()?), - })) + let laid_out = cls.own_slot_layout().is_some_and(|layout| { + layout.len() == slots.len() + && layout + .iter() + .zip(slots) + .all(|(k, n)| matches!(&k.0, Object::Str(s) if s.as_ref() == *n)) + }); + let reg = Rc::new(GetterCtor { + slots, + version: cls.attr_version.get(), + }); + if laid_out + && cls + .native_ext + .set(crate::rc_unsize!(reg => dyn std::any::Any + Send + Sync)) + .is_ok() + { + cls.pure_new.set(Some(pure)); + } +} + +/// An instance of `cls` with `values` in its slots, laid out at once, +/// when `cls` is the registered class unchanged since. +fn getter_instance( + cls: &Rc, + values: [Object; N], +) -> Option { + let reg = cls.native_ext.get()?.downcast_ref::()?; + if reg.version != cls.attr_version.get() || reg.slots.len() != N { + return None; + } + let layout = cls.own_slot_layout()?; + let inst = crate::types::PyInstance::with_slots( + cls.clone(), + crate::types::SlotStorage::from_layout_array(layout.clone(), values), + ); + let obj = Object::Instance(Rc::new(inst)); + crate::gc_trace::track(&obj); + Some(obj) +} + +/// `itemgetter(item, *items)`. +fn itemgetter_new_pure(cls: &Rc, args: &[Object]) -> Option { + if args.is_empty() { + return None; + } + getter_instance(cls, [Object::tuple_from_slice(args)]) +} + +/// `attrgetter(attr, *attrs)` of `str` names (anything else raises from +/// the Python `__init__`). +fn attrgetter_new_pure(cls: &Rc, args: &[Object]) -> Option { + if args.is_empty() || !args.iter().all(|a| matches!(a, Object::Str(_))) { + return None; + } + getter_instance(cls, [Object::tuple_from_slice(args)]) +} + +/// `methodcaller(name, *args)` of a `str` name, with no keywords. +fn methodcaller_new_pure(cls: &Rc, args: &[Object]) -> Option { + let [name @ Object::Str(_), rest @ ..] = args else { + return None; + }; + let kwargs = Object::Dict(Rc::new(RefCell::new(DictData::default()))); + crate::gc_trace::track(&kwargs); + getter_instance(cls, [name.clone(), Object::tuple_from_slice(rest), kwargs]) +} + +/// A `methodcaller`'s stored name and positional arguments, read from its +/// slots, when it stores no keywords. +pub(crate) fn methodcaller_parts(inst: &crate::types::PyInstance) -> Option<(Object, Object)> { + // SAFETY: reads that run no code; the values are cloned out before + // anything runs. + unsafe { + inst.slots.peek().and_then(|slots| { + let name = slots.get_hinted(0, "_name")?.clone(); + let stored = slots.get_hinted(1, "_args")?.clone(); + let plain = match slots.get_hinted(2, "_kwargs")? { + Object::Dict(d) => d.peek()?.is_empty(), + _ => false, + }; + plain.then_some((name, stored)) + }) + } +} + +/// `methodcaller(name, *args)(obj)` (`slf` the methodcaller) of a plain +/// instance whose class's method `name` is a Python function (see +/// `Interpreter::plain_instance_method`), with no stored keywords: the +/// function and the stored positional arguments, which the compiled call +/// site calls directly. `None` for anything else. +pub(crate) fn methodcaller_target( + slf: &crate::types::PyInstance, + obj: &Object, +) -> Option<(Rc, Object)> { + let (Object::Str(name), stored @ Object::Tuple(_)) = methodcaller_parts(slf)? else { + return None; + }; + Some(( + crate::Interpreter::plain_instance_method_named(obj, &name)?, + stored, + )) +} + +/// `methodcaller(name, *args)(obj)`'s leaf half: a native value's method +/// (`str.lower`, `dict.get`) that is itself a leaf builtin, called with +/// `obj` and the stored arguments as the core loop's leaf call of +/// `obj.name(*args)` calls it. `None` (nothing run) for anything else: an +/// instance, stored keywords, a method that isn't a leaf, or arguments +/// its leaf doesn't take. +fn methodcaller_fast(args: &[Object]) -> Option> { + let [Object::Instance(slf), obj] = args else { + return None; + }; + // (Only the receivers `leaf_builtin_method` knows, tested first: a + // declined call may try the half again on its way to the full path.) + if !matches!( + obj, + Object::List(_) + | Object::Dict(_) + | Object::Set(_) + | Object::Str(_) + | Object::Int(_) + | Object::Bytes(_) + | Object::ByteArray(_) + ) { + return None; + } + let (Object::Str(name), Object::Tuple(stored)) = methodcaller_parts(slf)? else { + return None; + }; + let ptr = crate::vm_singletons::current_interpreter_ptr()?; + // SAFETY: published by the enclosing VM frame on this thread; only its + // method tables are read. + let interp = unsafe { &*ptr }; + let method = interp.leaf_builtin_method(obj, &name)?; + let kind = interp.leaf_call_kind(&method)?; + let call = |a: &[Object]| interp.leaf_builtin_call(kind, &method, a); + match &stored[..] { + [] => call(std::slice::from_ref(obj)), + [a] => call(&[obj.clone(), a.clone()]), + [a, b] => call(&[obj.clone(), a.clone(), b.clone()]), + more => { + let mut call_args = Vec::with_capacity(more.len() + 1); + call_args.push(obj.clone()); + call_args.extend_from_slice(more); + call(&call_args) + } + } } /// `methodcaller.__call__(self, obj, /)` without a Python frame. Looks up @@ -554,6 +888,24 @@ fn itemgetter_fast(args: &[Object]) -> Option> { /// args/kwargs through the interpreter. fn methodcaller_call(args: &[Object]) -> Result { let (slf, obj) = two_args(args, "methodcaller.__call__")?; + // The usual shape: the stored fields in their slots, positional + // arguments only, and a Python method of a plain instance, called + // with the instance first (no bound method, no attribute read). + if let Object::Instance(inst) = slf { + if let Some((Object::Str(name), Object::Tuple(stored))) = methodcaller_parts(inst) { + if let Some(f) = crate::Interpreter::plain_instance_method(obj, &name) { + return with_interp(|interp| { + if stored.is_empty() { + return interp.call_dunder_function(f, std::slice::from_ref(obj)); + } + let mut call_args = Vec::with_capacity(stored.len() + 1); + call_args.push(obj.clone()); + call_args.extend_from_slice(&stored); + interp.call_dunder_function(f, &call_args) + }); + } + } + } with_interp(|interp| { let name = field(interp, slf, "_name")?; let Object::Str(name) = &name else { diff --git a/crates/weavepy-vm/src/stdlib/os.rs b/crates/weavepy-vm/src/stdlib/os.rs index 5e185d0f7..2e7115d33 100644 --- a/crates/weavepy-vm/src/stdlib/os.rs +++ b/crates/weavepy-vm/src/stdlib/os.rs @@ -284,10 +284,15 @@ pub fn build(cache: &ModuleCache) -> Rc { DictKey(Object::from_static("listdir")), builtin("listdir", os_listdir), ); - d.insert( - DictKey(Object::from_static("urandom")), - builtin("urandom", os_urandom), - ); + d.insert(DictKey(Object::from_static("urandom")), { + // Takes only a plain int (no `__index__` call): no Python + // runs, whatever the arguments. + let f = builtin("urandom", os_urandom); + if let Object::Builtin(b) = &f { + crate::leaf_builtins::register(b); + } + f + }); d.insert( DictKey(Object::from_static("close")), builtin("close", os_close_stub), @@ -2019,7 +2024,7 @@ fn os_listdir(args: &[Object]) -> Result { name.to_string_lossy().into_owned().into_bytes(), )); } else { - out.push(Object::from_str(name.to_string_lossy())); + out.push(Object::from_str(os_text(&name))); } } Ok(Object::new_list(out)) @@ -2440,8 +2445,9 @@ fn os_fdopen(args: &[Object], kwargs: &[(String, Object)]) -> Result"), mode, FileBackend::Disk(file)); - pf.no_name.set(true); + // (`name` is the descriptor, as `open(fd)` reports it.) + let pf = PyFile::new(fd.to_string(), mode, FileBackend::Disk(file)); + pf.name_is_fd.set(true); // CPython's `os.fdopen` *is* `io.open(fd, …)`: the text-layer // configuration (buffering / encoding / errors / newline) applies the // same way — fileinput's inplace mode fdopens its output with @@ -2493,8 +2499,9 @@ fn os_fdopen(args: &[Object], kwargs: &[(String, Object)]) -> Result"), mode, FileBackend::Disk(file)); - pf.no_name.set(true); + // (`name` is the descriptor, as `open(fd)` reports it.) + let pf = PyFile::new(fd.to_string(), mode, FileBackend::Disk(file)); + pf.name_is_fd.set(true); let kw = |name: &str| kwargs.iter().find(|(k, _)| k == name).map(|(_, v)| v); let buffering = args.get(2).or_else(|| kw("buffering")); let encoding = args.get(3).or_else(|| kw("encoding")); @@ -2752,11 +2759,88 @@ fn stat_seq_finish(inst: &crate::types::PyInstance) { } } +/// A `stat_result`'s named fields as a builder collects them (each name +/// once), for [`stat_fields_finish`]. +struct StatFields(Vec<(&'static str, Object)>); + +impl StatFields { + fn insert(&mut self, name: &'static str, value: Object) { + debug_assert!(self.0.iter().all(|(n, _)| *n != name), "{name} twice"); + self.0.push((name, value)); + } + + fn get(&self, name: &str) -> Option<&Object> { + self.0.iter().find(|(n, _)| *n == name).map(|(_, v)| v) + } +} + +/// [`stat_seq_finish`] of the fields a builder collected: the tuple view +/// from them directly, and the instance dict laid down in one go, its keys +/// (and their hashes) made once per thread for each position a builder +/// fills. +fn stat_fields_finish(inst: &crate::types::PyInstance, fields: StatFields) { + #[cfg(target_os = "macos")] + let fields = { + let mut fields = fields; + for f in ["st_flags", "st_gen"] { + if fields.get(f).is_none() { + fields.insert(f, Object::Int(0)); + } + } + if fields.get("st_birthtime").is_none() { + let v = fields + .get("st_ctime") + .cloned() + .unwrap_or(Object::Float(0.0)); + fields.insert("st_birthtime", v); + } + fields + }; + let mut seq: Vec = Vec::with_capacity(10); + for f in [ + "st_mode", "st_ino", "st_dev", "st_nlink", "st_uid", "st_gid", "st_size", + ] { + seq.push(fields.get(f).cloned().unwrap_or(Object::Int(0))); + } + for f in ["st_atime", "st_mtime", "st_ctime"] { + seq.push(match fields.get(f) { + Some(Object::Float(x)) => Object::Int(*x as i64), + Some(other) => other.clone(), + None => Object::Int(0), + }); + } + let _ = inst.native.set(Object::new_tuple(seq)); + thread_local! { + static KEYS: crate::gil::ReleaseUnderGil>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(Vec::new())) }; + } + let n = fields.0.len(); + let mut values = fields.0.into_iter(); + let map = KEYS.with(|keys| { + let mut keys = keys.borrow_mut(); + crate::dictmap::DictMap::from_unique_hashed(n, |i| { + let (name, value) = values.next().expect("n fields"); + let at = name.as_ptr() as usize; + if keys.get(i).is_none_or(|k| k.0 != at) { + let key = static_name_key(name); + let entry = (at, crate::object::dict_key_hash(&key.0), key); + if i < keys.len() { + keys[i] = entry; + } else { + keys.push(entry); + } + } + let (_, hash, key) = &keys[i]; + (*hash, key.clone(), value) + }) + }); + *inst.dict_cell().borrow_mut() = DictData::from(map); +} + fn stat_result_from_meta(meta: &std::fs::Metadata) -> Object { use crate::types::PyInstance; let ty = stat_result_type(); let inst = PyInstance::new(ty); - let mut d = inst.dict_cell().borrow_mut(); + let mut d = StatFields(Vec::with_capacity(24)); // On Unix the OS already encodes the full `st_mode` — file-type bits // (S_IFREG / S_IFDIR / S_IFCHR / S_IFBLK / S_IFLNK / S_IFIFO / S_IFSOCK) // *and* permissions — so use it verbatim; otherwise char/block devices, @@ -2786,11 +2870,8 @@ fn stat_result_from_meta(meta: &std::fs::Metadata) -> Object { }; kind_bits | perm_bits }; - d.insert( - DictKey(Object::from_static("st_size")), - Object::Int(meta.len() as i64), - ); - d.insert(DictKey(Object::from_static("st_mode")), Object::Int(mode)); + d.insert("st_size", Object::Int(meta.len() as i64)); + d.insert("st_mode", Object::Int(mode)); // On Unix derive the float `st_*time` straight from the integer // nanosecond fields below, so `st_atime` and `st_atime_ns` describe the // *same* instant (CPython invariant: `test_stat_attributes` checks they @@ -2825,18 +2906,9 @@ fn stat_result_from_meta(meta: &std::fs::Metadata) -> Object { .map_or(mtime, |d| d.as_secs_f64()); (atime, mtime, ctime) }; - d.insert( - DictKey(Object::from_static("st_mtime")), - Object::Float(mtime), - ); - d.insert( - DictKey(Object::from_static("st_atime")), - Object::Float(atime), - ); - d.insert( - DictKey(Object::from_static("st_ctime")), - Object::Float(ctime), - ); + d.insert("st_mtime", Object::Float(mtime)); + d.insert("st_atime", Object::Float(atime)); + d.insert("st_ctime", Object::Float(ctime)); // The remaining fields come straight from the OS `stat(2)` record on // Unix. Real `st_ino`/`st_dev` are essential: `posixpath.samefile`/ // `samestat` compare exactly those two, so leaving them 0 made every @@ -2846,77 +2918,41 @@ fn stat_result_from_meta(meta: &std::fs::Metadata) -> Object { #[cfg(unix)] { use std::os::unix::fs::MetadataExt; - d.insert( - DictKey(Object::from_static("st_ino")), - Object::Int(meta.ino() as i64), - ); - d.insert( - DictKey(Object::from_static("st_dev")), - Object::Int(meta.dev() as i64), - ); - d.insert( - DictKey(Object::from_static("st_nlink")), - Object::Int(meta.nlink() as i64), - ); - d.insert( - DictKey(Object::from_static("st_uid")), - Object::Int(i64::from(meta.uid())), - ); - d.insert( - DictKey(Object::from_static("st_gid")), - Object::Int(i64::from(meta.gid())), - ); - d.insert( - DictKey(Object::from_static("st_rdev")), - Object::Int(meta.rdev() as i64), - ); - d.insert( - DictKey(Object::from_static("st_blocks")), - Object::Int(meta.blocks() as i64), - ); - d.insert( - DictKey(Object::from_static("st_blksize")), - Object::Int(meta.blksize() as i64), - ); - d.insert( - DictKey(Object::from_static("st_mtime_ns")), + d.insert("st_ino", Object::Int(meta.ino() as i64)); + d.insert("st_dev", Object::Int(meta.dev() as i64)); + d.insert("st_nlink", Object::Int(meta.nlink() as i64)); + d.insert("st_uid", Object::Int(i64::from(meta.uid()))); + d.insert("st_gid", Object::Int(i64::from(meta.gid()))); + d.insert("st_rdev", Object::Int(meta.rdev() as i64)); + d.insert("st_blocks", Object::Int(meta.blocks() as i64)); + d.insert("st_blksize", Object::Int(meta.blksize() as i64)); + d.insert( + "st_mtime_ns", Object::Int(meta.mtime() * 1_000_000_000 + meta.mtime_nsec()), ); d.insert( - DictKey(Object::from_static("st_atime_ns")), + "st_atime_ns", Object::Int(meta.atime() * 1_000_000_000 + meta.atime_nsec()), ); d.insert( - DictKey(Object::from_static("st_ctime_ns")), + "st_ctime_ns", Object::Int(meta.ctime() * 1_000_000_000 + meta.ctime_nsec()), ); } #[cfg(not(unix))] { - d.insert(DictKey(Object::from_static("st_ino")), Object::Int(0)); - d.insert(DictKey(Object::from_static("st_dev")), Object::Int(0)); - d.insert(DictKey(Object::from_static("st_nlink")), Object::Int(1)); - d.insert(DictKey(Object::from_static("st_uid")), Object::Int(0)); - d.insert(DictKey(Object::from_static("st_gid")), Object::Int(0)); - d.insert(DictKey(Object::from_static("st_rdev")), Object::Int(0)); - d.insert(DictKey(Object::from_static("st_blocks")), Object::Int(0)); - d.insert( - DictKey(Object::from_static("st_blksize")), - Object::Int(4096), - ); + d.insert("st_ino", Object::Int(0)); + d.insert("st_dev", Object::Int(0)); + d.insert("st_nlink", Object::Int(1)); + d.insert("st_uid", Object::Int(0)); + d.insert("st_gid", Object::Int(0)); + d.insert("st_rdev", Object::Int(0)); + d.insert("st_blocks", Object::Int(0)); + d.insert("st_blksize", Object::Int(4096)); let mtime_ns = (mtime * 1e9) as i64; - d.insert( - DictKey(Object::from_static("st_mtime_ns")), - Object::Int(mtime_ns), - ); - d.insert( - DictKey(Object::from_static("st_atime_ns")), - Object::Int((atime * 1e9) as i64), - ); - d.insert( - DictKey(Object::from_static("st_ctime_ns")), - Object::Int((ctime * 1e9) as i64), - ); + d.insert("st_mtime_ns", Object::Int(mtime_ns)); + d.insert("st_atime_ns", Object::Int((atime * 1e9) as i64)); + d.insert("st_ctime_ns", Object::Int((ctime * 1e9) as i64)); } // Windows-only extras CPython adds to `stat_result` (posixmodule.c's // `STRUCT_STAT` under `MS_WINDOWS`): the raw `dwFileAttributes` word — @@ -2927,16 +2963,12 @@ fn stat_result_from_meta(meta: &std::fs::Metadata) -> Object { { use std::os::windows::fs::MetadataExt; d.insert( - DictKey(Object::from_static("st_file_attributes")), + "st_file_attributes", Object::Int(i64::from(meta.file_attributes())), ); - d.insert( - DictKey(Object::from_static("st_reparse_tag")), - Object::Int(0), - ); + d.insert("st_reparse_tag", Object::Int(0)); } - drop(d); - stat_seq_finish(&inst); + stat_fields_finish(&inst, d); Object::Instance(Rc::new(inst)) } @@ -2985,29 +3017,26 @@ fn stat_result_from_libc_stat(st: &libc::stat) -> Object { st.st_ctime as i64 * 1_000_000_000 + st.st_ctime_nsec as i64, ), ] { - d.insert(DictKey(Object::from_static(k)), Object::Int(v)); + d.insert(static_name_key(k), Object::Int(v)); } for (k, v) in [ ("st_mtime", mtime), ("st_atime", atime), ("st_ctime", ctime), ] { - d.insert(DictKey(Object::from_static(k)), Object::Float(v)); + d.insert(static_name_key(k), Object::Float(v)); } // The BSD extras CPython exposes on macOS (`st_flags`, `st_gen`, // `st_birthtime`) come straight off the raw struct. #[cfg(target_os = "macos")] { d.insert( - DictKey(Object::from_static("st_flags")), + static_name_key("st_flags"), Object::Int(i64::from(st.st_flags)), ); + d.insert(static_name_key("st_gen"), Object::Int(i64::from(st.st_gen))); d.insert( - DictKey(Object::from_static("st_gen")), - Object::Int(i64::from(st.st_gen)), - ); - d.insert( - DictKey(Object::from_static("st_birthtime")), + static_name_key("st_birthtime"), Object::Float(ns(st.st_birthtime as i64, st.st_birthtime_nsec as i64)), ); } @@ -3377,14 +3406,14 @@ fn os_scandir(args: &[Object]) -> Result { .map_err(|e| crate::error::io_error_to_py_named(&e, Some(&dir_path)))? .filter_map(|r| r.ok()) .map(|entry| { - let fs_path = entry.path().to_string_lossy().into_owned(); - let (name_obj, path_obj) = if bytes_mode { - (dir_entry_name_bytes(&entry), dir_entry_path_bytes(&entry)) - } else { + let (name_obj, path_obj, fs_path) = if bytes_mode { ( - Object::from_str(entry.file_name().to_string_lossy()), - Object::from_str(fs_path.clone()), + dir_entry_name_bytes(&entry), + dir_entry_path_bytes(&entry), + os_text(entry.path().as_os_str()).into_owned(), ) + } else { + scandir_entry_str(&dir_path, &entry) }; // CPython caches the inode from the directory read, so // `DirEntry.inode()` keeps working after the entry is unlinked @@ -3401,6 +3430,54 @@ fn os_scandir(args: &[Object]) -> Result { Ok(build_scandir_iterator(entries)) } +/// A `str`-mode entry's name and path, as `os_text` gives the entry's +/// `file_name()` and `path()`, and the path's text: on Unix the directory +/// `dir` read joined to the name, validating only the name (`dir` is text +/// already). +fn scandir_entry_str(dir: &str, entry: &std::fs::DirEntry) -> (Object, Object, String) { + #[cfg(unix)] + { + let name = entry.file_name(); + let name = os_text(&name); + let mut text = String::with_capacity(dir.len() + 1 + name.len()); + text.push_str(dir); + // (As `Path::join` adds a separator.) + if !dir.ends_with('/') { + text.push('/'); + } + text.push_str(&name); + ( + Object::from_str(&name), + Object::from_str(text.as_str()), + text, + ) + } + #[cfg(not(unix))] + { + let _ = dir; + let text = os_text(entry.path().as_os_str()).into_owned(); + ( + Object::from_str(os_text(&entry.file_name())), + Object::from_str(text.as_str()), + text, + ) + } +} + +/// An OS string as text, as `to_string_lossy` gives it: validated as UTF-8 +/// first, which runs several times faster than the lossy decoder's scan +/// for the valid names nearly every directory holds. +fn os_text(s: &std::ffi::OsStr) -> std::borrow::Cow<'_, str> { + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + if let Ok(t) = std::str::from_utf8(s.as_bytes()) { + return std::borrow::Cow::Borrowed(t); + } + } + s.to_string_lossy() +} + /// `DirEntry.name` as `bytes` for a `bytes`-mode `scandir`. On Unix the OS /// name is already a byte string (no transcoding); elsewhere we encode the /// lossy UTF-8 form as a best effort. @@ -3481,6 +3558,44 @@ fn os_access(args: &[Object], _kwargs: &[(String, Object)]) -> Result>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; +} + +/// Whether `inst` is a `ScandirIterator` (whose `__iter__` returns it). +#[inline] +pub(crate) fn is_scandir(inst: &crate::types::PyInstance) -> bool { + // (Every other class is told apart by its name, without the + // thread-local's read.) + if inst.cls_raw().name.as_str() != "posix.ScandirIterator" { + return false; + } + SCANDIR_CLS.with(|slot| { + slot.try_borrow().is_ok_and(|c| { + c.as_ref() + .is_some_and(|c| std::ptr::eq(Rc::as_ptr(c), inst.cls_raw())) + }) + }) +} + +/// `next(it)` of a `ScandirIterator` (`os.walk`'s loop, a `for` over +/// one), as its `__next__` steps it: `Some(Some(entry))`, or `Some(None)` +/// at the end (the iterator then closed); `None` for any other instance. +pub(crate) fn scandir_step(inst: &crate::types::PyInstance) -> Option> { + if !is_scandir(inst) { + return None; + } + let Some(Object::Iter(it)) = inst.native.get() else { + return None; + }; + let v = it.try_borrow_mut().ok()?.next_value(); + if v.is_none() { + scandir_mark_closed(inst); + } + Some(v) +} + /// Wrap the materialised `DirEntry` list in a CPython-shaped /// `ScandirIterator`: an iterator that is *also* a context manager /// (`with os.scandir(p) as it:`) with a no-op `close()`. CPython's @@ -3488,20 +3603,27 @@ fn os_access(args: &[Object], _kwargs: &[(String, Object)]) -> Result) -> Object { use crate::types::{PyInstance, TypeObject}; - thread_local! { - static CLS: RefCell>> = const { RefCell::new(None) }; - } - let class = CLS.with(|slot| { + let class = SCANDIR_CLS.with(|slot| { if let Some(c) = slot.borrow().as_ref() { return c.clone(); } let bt = crate::builtin_types::builtin_types(); let mut dict = DictData::default(); - scandir_method(&mut dict, "__iter__", scandir_self); - scandir_method(&mut dict, "__next__", scandir_next); - scandir_method(&mut dict, "__enter__", scandir_self); - scandir_method(&mut dict, "__exit__", scandir_exit); - scandir_method(&mut dict, "close", scandir_exit); + // (These run no Python code: compiled code and the core loop step + // the iterator through its `__next__` in place.) + for (name, body) in [ + ( + "__iter__", + scandir_self as fn(&[Object]) -> Result, + ), + ("__next__", scandir_next), + ("__enter__", scandir_self), + ("__exit__", scandir_exit), + ("close", scandir_exit), + ] { + let b = scandir_method(&mut dict, name, body); + crate::leaf_builtins::register(&b); + } // CPython's `ScandirIterator` keeps an open `DIR*`; if it is dropped // without being exhausted or closed, `__del__` emits a // `ResourceWarning` (`test_os.TestScandir.test_resource_warning`). @@ -3532,16 +3654,18 @@ fn scandir_method( dict: &mut DictData, name: &'static str, body: fn(&[Object]) -> Result, -) { +) -> Rc { + let b = Rc::new(crate::object::BuiltinFn { + name, + binds_instance: true, + call: Box::new(body), + call_kw: None, + }); dict.insert( DictKey(Object::from_static(name)), - Object::Builtin(Rc::new(crate::object::BuiltinFn { - name, - binds_instance: true, - call: Box::new(body), - call_kw: None, - })), + Object::Builtin(b.clone()), ); + b } fn scandir_self(args: &[Object]) -> Result { @@ -3576,25 +3700,44 @@ fn scandir_exit(args: &[Object]) -> Result { Ok(Object::None) } -/// Sentinel key marking a `ScandirIterator` as closed/exhausted so its -/// `__del__` stays silent. Mirrors CPython closing the `DIR*` on `close()`, +/// The entries' iterator of a closed (or exhausted) `ScandirIterator`: an +/// empty range in place of the entry list, so `__del__` stays silent and +/// `next()` ends at once. Mirrors CPython closing the `DIR*` on `close()`, /// `__exit__`, or exhaustion. -const SCANDIR_CLOSED_KEY: &str = "__weavepy_scandir_closed__"; - +const SCANDIR_CLOSED: crate::object::PyIterator = crate::object::PyIterator::Range { + current: 0, + stop: 0, + step: 1, +}; + +/// Close `inst`'s scandir iterator: its entries go, and it owes no +/// finalizer (a closed iterator's `__del__` has nothing to do), so its +/// death runs none. fn scandir_mark_closed(inst: &crate::types::PyInstance) { - inst.dict_cell().borrow_mut().insert( - DictKey(Object::from_static(SCANDIR_CLOSED_KEY)), - Object::Bool(true), - ); + if let Some(Object::Iter(it)) = inst.native.get() { + if let Ok(mut it) = it.try_borrow_mut() { + let entries = std::mem::replace(&mut *it, SCANDIR_CLOSED); + drop(it); + drop(entries); + } + } + inst.finalize_ran.set(true); } fn scandir_is_closed(inst: &crate::types::PyInstance) -> bool { - matches!( - inst.dict_cell() - .borrow() - .get(&DictKey(Object::from_static(SCANDIR_CLOSED_KEY))), - Some(Object::Bool(true)) - ) + let Some(Object::Iter(it)) = inst.native.get() else { + return true; + }; + it.try_borrow().map_or(true, |it| { + matches!( + *it, + crate::object::PyIterator::Range { + current: 0, + stop: 0, + step: 1 + } + ) + }) } /// `ScandirIterator.__del__`: warn if the iterator was never closed or @@ -3636,7 +3779,7 @@ fn dir_entry_follow(kwargs: &[(String, Object)]) -> bool { pub(crate) fn dir_entry_type() -> Rc { use crate::types::TypeObject; thread_local! { - static CLS: RefCell>> = const { RefCell::new(None) }; + static CLS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } CLS.with(|slot| { if let Some(c) = slot.borrow().as_ref() { @@ -3664,12 +3807,9 @@ pub(crate) fn dir_entry_type() -> Rc { binds_instance: true, call: Box::new(|args| { let name = match args.first() { - Some(Object::Instance(i)) => i - .dict_cell() - .borrow() - .get(&DictKey(Object::from_static("name"))) - .cloned() - .unwrap_or(Object::None), + Some(Object::Instance(i)) => { + entry_get(i, &entry_keys().name).unwrap_or(Object::None) + } _ => Object::None, }; Ok(Object::from_str(format!("", name.repr()))) @@ -3775,6 +3915,85 @@ fn entry_self(args: &[Object]) -> Result<&Rc, RuntimeE } } +/// A `DirEntry`'s attribute `key` (one of [`entry_keys`]), read where it +/// sits without making the instance's dictionary. +fn entry_get(inst: &crate::types::PyInstance, key: &DictKey) -> Option { + match &key.0 { + Object::Str(name) => inst.attr_get_str(name), + _ => None, + } +} + +/// Store a `DirEntry`'s attribute `key` (one of [`entry_keys`]) as an +/// instance's own assignment would: in the class's shared layout while +/// the entries store their names in one order (so a method call on an +/// entry stays on the compiled method cache, which proves no instance +/// value shadows the method through that layout), else in the +/// instance's dictionary. +fn entry_set(inst: &crate::types::PyInstance, key: &DictKey, value: Object) { + let Object::Str(name) = &key.0 else { + return; + }; + match inst.split_store(name, value) { + Ok(old) => drop(old), + Err(value) => { + inst.dict_cell().borrow_mut().insert(key.clone(), value); + } + } +} + +/// A fresh `DirEntry` holding `items`, its attributes in the order they +/// are stored (see [`entry_set`]). The longest run that matches the +/// class's shared layout from its start goes down at once, the rest +/// through the stores. +fn new_dir_entry(items: &mut [(&DictKey, Option)]) -> crate::types::PyInstance { + let cls = dir_entry_type(); + let inst = crate::types::PyInstance::new(cls.clone()); + let mut filled = 0; + if inst.c_body.get() == 0 && !crate::gil::free_threading_enabled() { + if let Some(keys) = cls.shared_keys.get() { + let same = |k: &DictKey, want: &DictKey| match (&k.0, &want.0) { + (Object::Str(a), Object::Str(b)) => { + crate::shared_value::SharedStr::ptr_eq(a, b) || a.as_str() == b.as_str() + } + _ => false, + }; + let m = items + .iter() + .enumerate() + .take_while(|(i, (want, _))| keys.get(*i).is_some_and(|k| same(k, want))) + .count(); + if m > 0 { + if inst.deferred.get() + && !items[..m] + .iter() + .all(|(_, v)| v.as_ref().is_none_or(Object::is_gc_atomic)) + { + inst.ensure_gc_tracked(); + } + // SAFETY: the instance is fresh and unshared. + if let Some(split) = unsafe { inst.dict.split_peek_mut() } { + split.reserve_for(|| cls.shared_keys.share(), items.len().max(keys.len())); + if split.fill_fresh( + keys, + || cls.shared_keys.share(), + m, + |k| items[k].1.take().unwrap_or(Object::None), + ) { + filled = m; + } + } + } + } + } + for (key, value) in &mut items[filled..] { + if let Some(value) = value.take() { + entry_set(&inst, key, value); + } + } + inst +} + /// Where a `DirEntry` is on the file system: a path, or a name under an /// open directory. enum EntryPlace { @@ -3786,42 +4005,17 @@ enum EntryPlace { impl EntryPlace { fn of(inst: &crate::types::PyInstance) -> Result { let keys = entry_keys(); - let d = inst.dict_cell().borrow(); - let Some(Object::Str(fs)) = d.get(&keys.fs).or_else(|| d.get(&keys.path)) else { + let Some(Object::Str(fs)) = + entry_get(inst, &keys.fs).or_else(|| entry_get(inst, &keys.path)) + else { return Err(type_error("DirEntry is missing its path")); }; #[cfg(unix)] - if let Some(Object::Int(fd)) = d.get(&keys.dir_fd) { - return Ok(Self::Under(*fd as libc::c_int, fs.to_string())); + if let Some(Object::Int(fd)) = entry_get(inst, &keys.dir_fd) { + return Ok(Self::Under(fd as libc::c_int, fs.to_string())); } Ok(Self::Path(fs.to_string())) } - - /// The entry's kind by `stat` (`follow`) or `lstat`; `None` when that - /// fails (a dangling link, an entry removed since the read). - fn kind(&self, follow: bool) -> Option { - match self { - Self::Path(path) => { - let md = if follow { - std::fs::metadata(path) - } else { - std::fs::symlink_metadata(path) - }; - md.ok().map(|m| entry_kind_of(m.file_type())) - } - #[cfg(unix)] - Self::Under(fd, name) => { - fstatat_mode(*fd, name, follow) - .ok() - .map(|m| match m & libc::S_IFMT { - libc::S_IFDIR => ENTRY_DIR, - libc::S_IFREG => ENTRY_FILE, - libc::S_IFLNK => ENTRY_LINK, - _ => ENTRY_OTHER, - }) - } - } - } } fn entry_kind_of(ft: std::fs::FileType) -> i64 { @@ -3841,27 +4035,104 @@ fn entry_kind_of(ft: std::fs::FileType) -> i64 { /// entry is a link to follow, or the file system didn't say. fn entry_is(args: &[Object], follow: bool, want: i64) -> Result { let inst = entry_self(args)?; - let read = match inst.dict_cell().borrow().get(&entry_keys().kind) { - Some(Object::Int(kind)) => *kind, + let read = match entry_get(inst, &entry_keys().kind) { + Some(Object::Int(kind)) => kind, _ => ENTRY_UNKNOWN, }; + // (An entry with no path to look at raises, as before.) let kind = match read { - ENTRY_UNKNOWN => EntryPlace::of(inst)?.kind(follow), - ENTRY_LINK if follow => EntryPlace::of(inst)?.kind(true), + ENTRY_UNKNOWN => EntryPlace::of(inst).map(|_| entry_stat_kind(args, follow))?, + ENTRY_LINK if follow => EntryPlace::of(inst).map(|_| entry_stat_kind(args, true))?, known => Some(known), }; Ok(Object::Bool(kind == Some(want))) } +/// The kind of a `DirEntry` by its `stat()` (`follow`) or `lstat()` +/// result, which the entry keeps once fetched (so a link's target answers +/// from the first look, as CPython's entry does); `None` when the look +/// fails (a dangling link, an entry removed since the read). +fn entry_stat_kind(args: &[Object], follow: bool) -> Option { + let Ok(Object::Instance(st)) = entry_stat(args, follow) else { + return None; + }; + let Some(Object::Int(mode)) = st.attr_get_str("st_mode") else { + return None; + }; + // (The `S_IF*` file-type bits, the same on every platform `st_mode` + // is synthesized for.) + Some(match mode & 0o170_000 { + 0o040_000 => ENTRY_DIR, + 0o100_000 => ENTRY_FILE, + 0o120_000 => ENTRY_LINK, + _ => ENTRY_OTHER, + }) +} + +/// The value of a `DirEntry`'s attribute `key` in its split values, +/// `None` while its dictionary is published (whose lookup could reach a +/// key's `__eq__`): what the fast halves below read. +fn entry_split_get(inst: &crate::types::PyInstance, key: &DictKey) -> Option { + let Object::Str(name) = &key.0 else { + return None; + }; + if inst.dict.published().is_some() { + return None; + } + inst.dict + .split_cell() + .try_borrow() + .ok()? + .get_str(name) + .cloned() +} + +/// [`entry_is`]'s pure fast half (no keywords): the kind the directory +/// read stored, unless it's unknown or a link to follow. +fn entry_is_fast(args: &[Object], follow: bool, want: i64) -> Option> { + let [Object::Instance(inst)] = args else { + return None; + }; + match entry_split_get(inst, &entry_keys().kind)? { + Object::Int(ENTRY_UNKNOWN) => None, + Object::Int(ENTRY_LINK) if follow => None, + Object::Int(kind) => Some(Ok(Object::Bool(kind == want))), + _ => None, + } +} + +/// [`entry_is_symlink`]'s pure fast half. +fn entry_is_symlink_fast(args: &[Object]) -> Option> { + let [Object::Instance(inst)] = args else { + return None; + }; + match entry_split_get(inst, &entry_keys().kind)? { + Object::Int(ENTRY_UNKNOWN) => None, + Object::Int(kind) => Some(Ok(Object::Bool(kind == ENTRY_LINK))), + _ => None, + } +} + +/// [`entry_inode`]'s pure fast half: the number the directory read stored. +fn entry_inode_fast(args: &[Object]) -> Option> { + let [Object::Instance(inst)] = args else { + return None; + }; + match entry_split_get(inst, &entry_keys().ino)? { + ino @ Object::Int(_) => Some(Ok(ino)), + _ => None, + } +} + /// `DirEntry.is_symlink()`: always the link itself, never its target. fn entry_is_symlink(args: &[Object]) -> Result { let inst = entry_self(args)?; - let read = match inst.dict_cell().borrow().get(&entry_keys().kind) { - Some(Object::Int(kind)) => *kind, + let read = match entry_get(inst, &entry_keys().kind) { + Some(Object::Int(kind)) => kind, _ => ENTRY_UNKNOWN, }; let kind = match read { - ENTRY_UNKNOWN => EntryPlace::of(inst)?.kind(false), + ENTRY_UNKNOWN => EntryPlace::of(inst).map(|_| entry_stat_kind(args, false))?, known => Some(known), }; Ok(Object::Bool(kind == Some(ENTRY_LINK))) @@ -3871,8 +4142,8 @@ fn entry_is_symlink(args: &[Object]) -> Result { /// survives the entry being unlinked; an `lstat` only when there is none. fn entry_inode(args: &[Object]) -> Result { let inst = entry_self(args)?; - if let Some(ino @ Object::Int(_)) = inst.dict_cell().borrow().get(&entry_keys().ino) { - return Ok(ino.clone()); + if let Some(ino @ Object::Int(_)) = entry_get(inst, &entry_keys().ino) { + return Ok(ino); } Ok(Object::Int(match EntryPlace::of(inst)? { EntryPlace::Path(path) => dir_entry_inode(&path), @@ -3890,14 +4161,13 @@ fn entry_stat(args: &[Object], follow: bool) -> Result { let inst = entry_self(args)?; let keys = entry_keys(); let (cached, is_link) = { - let d = inst.dict_cell().borrow(); let is_link = !matches!( - d.get(&keys.kind), + entry_get(inst, &keys.kind), Some(Object::Int(ENTRY_DIR | ENTRY_FILE | ENTRY_OTHER)) ); let follow = follow && is_link; let key = if follow { &keys.stat } else { &keys.lstat }; - (d.get(key).cloned(), is_link) + (entry_get(inst, key), is_link) }; if let Some(result) = cached { return Ok(result); @@ -3909,9 +4179,7 @@ fn entry_stat(args: &[Object], follow: bool) -> Result { EntryPlace::Under(fd, name) => fstatat_stat_result(fd, &name, follow, None)?, }; let key = if follow { &keys.stat } else { &keys.lstat }; - inst.dict_cell() - .borrow_mut() - .insert(key.clone(), result.clone()); + entry_set(inst, key, result.clone()); Ok(result) } @@ -3919,25 +4187,19 @@ fn entry_stat(args: &[Object], follow: bool) -> Result { /// for a `bytes` one), which is what lets `shutil.copytree` recurse with an /// entry as its source. fn entry_fspath(args: &[Object]) -> Result { - entry_self(args)? - .dict_cell() - .borrow() - .get(&entry_keys().path) - .cloned() + entry_get(entry_self(args)?, &entry_keys().path) .ok_or_else(|| type_error("DirEntry is missing its path")) } /// The methods every `DirEntry` shares, for its type's dict. fn dir_entry_methods(dict: &mut DictData) { use crate::object::BuiltinFn; - let mut method = |name: &'static str, - call: fn(&[Object]) -> Result, - call_kw: Option< - fn(&[Object], &[(String, Object)]) -> Result, - >| { - dict.insert( - DictKey(Object::from_static(name)), - Object::Builtin(Rc::new(BuiltinFn { + let mut method = + |name: &'static str, + call: fn(&[Object]) -> Result, + call_kw: Option Result>, + fast: Option| { + let b = Rc::new(BuiltinFn { name, binds_instance: true, call: Box::new(call), @@ -3949,30 +4211,41 @@ fn dir_entry_methods(dict: &mut DictData) { + Sync, > }), - })), - ); - }; - method("__fspath__", entry_fspath, None); + }); + if let Some(fast) = fast { + crate::leaf_builtins::register_fast(&b, fast); + } + dict.insert(DictKey(Object::from_static(name)), Object::Builtin(b)); + }; + method("__fspath__", entry_fspath, None, None); method( "is_dir", |args| entry_is(args, true, ENTRY_DIR), Some(|args, kwargs| entry_is(args, dir_entry_follow(kwargs), ENTRY_DIR)), + Some(|args| entry_is_fast(args, true, ENTRY_DIR)), ); method( "is_file", |args| entry_is(args, true, ENTRY_FILE), Some(|args, kwargs| entry_is(args, dir_entry_follow(kwargs), ENTRY_FILE)), + Some(|args| entry_is_fast(args, true, ENTRY_FILE)), + ); + method( + "is_symlink", + entry_is_symlink, + None, + Some(entry_is_symlink_fast), ); - method("is_symlink", entry_is_symlink, None); // Windows reparse-point junctions: always `False` on POSIX (matching // `os.path.isjunction`). `os.walk`'s `_walk_symlinks_as_files` mode // calls this. - method("is_junction", |_args| Ok(Object::Bool(false)), None); - method("inode", entry_inode, None); + method("is_junction", |_args| Ok(Object::Bool(false)), None, None); + method("inode", entry_inode, None, Some(entry_inode_fast)); method( "stat", |args| entry_stat(args, true), Some(|args, kwargs| entry_stat(args, dir_entry_follow(kwargs))), + None, ); } @@ -3987,22 +4260,28 @@ fn build_dir_entry( kind: i64, cached_inode: Option, ) -> Object { - use crate::types::PyInstance; let keys = entry_keys(); - let inst = PyInstance::new(dir_entry_type()); - { - let mut d = inst.dict_cell().borrow_mut(); - d.insert(keys.name.clone(), name); - if !matches!(path, Object::Str(_)) { - d.insert(keys.fs.clone(), Object::from_str(fs_path)); - } - d.insert(keys.path.clone(), path); - d.insert(keys.kind.clone(), Object::Int(kind)); - if let Some(ino) = cached_inode { - d.insert(keys.ino.clone(), Object::Int(ino)); + // (In one order for every entry: name, path, kind, then what only + // some entries have.) + let fs = (!matches!(path, Object::Str(_))).then(|| Object::from_str(fs_path)); + let mut items = [ + (&keys.name, Some(name)), + (&keys.path, Some(path)), + (&keys.kind, Some(Object::Int(kind))), + (&keys.ino, cached_inode.map(Object::Int)), + (&keys.fs, fs), + ]; + // (Absent ones close the run: their names hold other values' places.) + let n = match (cached_inode.is_some(), items[4].1.is_some()) { + (true, true) => 5, + (true, false) => 4, + (false, false) => 3, + (false, true) => { + items.swap(3, 4); + 4 } - } - Object::Instance(Rc::new(inst)) + }; + Object::Instance(Rc::new(new_dir_entry(&mut items[..n]))) } /// Read every entry of the directory referred to by `fd` as `(name, inode)` @@ -4102,31 +4381,22 @@ fn fstatat_raw(dir_fd: libc::c_int, name: &str, follow: bool) -> std::io::Result Ok(st) } -/// `st_mode` of an `fstatat`-relative entry (helper for the `is_*` predicates). -#[cfg(unix)] -fn fstatat_mode(dir_fd: libc::c_int, name: &str, follow: bool) -> std::io::Result { - fstatat_raw(dir_fd, name, follow).map(|st| st.st_mode) -} - /// An `os.DirEntry` for an `os.scandir(fd)` listing: `name` and `path` are /// the bare entry name (there is no directory path to join onto), and its /// methods resolve it against `dir_fd` (RFC 0040 WS1), which the caller keeps /// open across them, as CPython's caller does. #[cfg(unix)] fn build_dir_entry_fd(name: String, dir_fd: libc::c_int, kind: i64, inode: i64) -> Object { - use crate::types::PyInstance; let keys = entry_keys(); - let inst = PyInstance::new(dir_entry_type()); let name = Object::from_str(name); - { - let mut d = inst.dict_cell().borrow_mut(); - d.insert(keys.name.clone(), name.clone()); - d.insert(keys.path.clone(), name); - d.insert(keys.dir_fd.clone(), Object::Int(i64::from(dir_fd))); - d.insert(keys.kind.clone(), Object::Int(kind)); - d.insert(keys.ino.clone(), Object::Int(inode)); - } - Object::Instance(Rc::new(inst)) + let mut items = [ + (&keys.name, Some(name.clone())), + (&keys.path, Some(name)), + (&keys.kind, Some(Object::Int(kind))), + (&keys.ino, Some(Object::Int(inode))), + (&keys.dir_fd, Some(Object::Int(i64::from(dir_fd)))), + ]; + Object::Instance(Rc::new(new_dir_entry(&mut items))) } /// `DirEntry.stat(follow_symlinks=True)` — a full `stat_result` for the entry, @@ -6526,7 +6796,7 @@ fn added_dll_directory_type() -> Rc { use crate::object::BuiltinFn; use crate::types::TypeObject; thread_local! { - static CLS: RefCell>> = const { RefCell::new(None) }; + static CLS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } fn self_dict(args: &[Object]) -> Option>> { match args.first() { @@ -7076,12 +7346,19 @@ impl StructSeqLayout { thread_local! { /// name → (memoised type, leaked layout). Memoisation keeps type /// identity stable across module rebuilds so `isinstance` holds. - static STRUCT_SEQ_REGISTRY: RefCell< + static STRUCT_SEQ_REGISTRY: crate::gil::ReleaseUnderGil, &'static StructSeqLayout), >, - > = RefCell::new(std::collections::HashMap::new()); + >> = crate::gil::ReleaseUnderGil::new(RefCell::new(std::collections::HashMap::new())); +} + +thread_local! { + /// The addresses of the registry's types, for [`struct_seq_tuple_of`]'s + /// check (a handful, scanned without hashing a name). + static STRUCT_SEQ_TYPES: RefCell> = + const { RefCell::new(Vec::new()) }; } /// Fetch a memoised struct-sequence type (and its layout) by name. @@ -7104,6 +7381,141 @@ pub(crate) fn is_struct_seq_type(ty: &Rc) -> bool { }) } +/// The tuple a struct sequence's instance keeps of its visible fields: +/// `None` for any other instance (a subclass's included, which may +/// override the comparisons). +fn struct_seq_tuple_of(inst: &crate::types::PyInstance) -> Option { + let cls = inst.cls_raw(); + if !cls.flags.is_builtin { + return None; + } + let t @ Object::Tuple(_) = inst.native.get()? else { + return None; + }; + struct_seq_layout_of(cls).map(|_| t.clone()) +} + +/// The layout of `cls` when it's a struct sequence type itself. +fn struct_seq_layout_of(cls: &crate::types::TypeObject) -> Option<&'static StructSeqLayout> { + let at = std::ptr::from_ref(cls) as usize; + STRUCT_SEQ_TYPES.with(|types| { + types + .borrow() + .iter() + .find_map(|&(t, layout)| (t == at).then_some(layout)) + }) +} + +/// The keys of a layout's named fields in slot order (all of its slots +/// are named), made once per thread. +fn struct_seq_layout_keys(layout: &'static StructSeqLayout) -> std::rc::Rc<[DictKey]> { + thread_local! { + static KEYS: crate::gil::ReleaseUnderGil)>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(Vec::new())) }; + } + let at = std::ptr::from_ref(layout) as usize; + KEYS.with(|k| { + if let Some((_, keys)) = k.borrow().iter().find(|(a, _)| *a == at) { + return keys.clone(); + } + let keys: std::rc::Rc<[DictKey]> = layout + .slots + .iter() + .flatten() + .map(|f| static_name_key(f)) + .collect(); + k.borrow_mut().push((at, keys.clone())); + keys + }) +} + +/// `T(seq)` of a struct sequence type `ty` whose fields are all named, +/// from a tuple or list of an accepted length, made directly as +/// `struct_seq_init` would fill it: the leading items are the visible +/// fields, the rest (and `None` past them) the hidden ones. `None` for +/// anything else (a type with its own `__new__`, which refuses instances, +/// another argument, a length the full path rejects, or a value other +/// than a number, string or `None`). +pub(crate) fn struct_seq_from_sequence( + ty: &Rc, + arg: &Object, +) -> Option { + let layout = struct_seq_layout_of(ty)?; + let n_fields = layout.n_fields(); + if layout.slots.iter().any(Option::is_none) + || layout.name == "stat_result" + || ty + .dict + .borrow() + .get(&crate::object::StrKey("__new__")) + .is_some() + { + return None; + } + let mut values = match arg { + Object::Tuple(t) if (layout.n_sequence..=n_fields).contains(&t.len()) => t.to_vec(), + Object::List(l) => { + let l = l.borrow(); + if !(layout.n_sequence..=n_fields).contains(&l.len()) { + return None; + } + l.clone() + } + _ => return None, + }; + // (Only values the instance may hold untracked, as the builders'.) + if !values.iter().all(|v| { + matches!( + v, + Object::Int(_) | Object::Float(_) | Object::Str(_) | Object::Bool(_) | Object::None + ) + }) { + return None; + } + let mut hidden = values.split_off(layout.n_sequence); + hidden.resize(n_fields - layout.n_sequence, Object::None); + Some(struct_seq_instance_keyed( + ty.clone(), + &struct_seq_layout_keys(layout), + values, + &hidden, + )) +} + +/// The operands of a comparison of a struct sequence with a tuple or with +/// one of its own type, as the struct sequence's `__eq__`/`__lt__`/... +/// compare them: as tuples of the visible fields. `None` for anything else. +pub(crate) fn struct_seq_compare_operands(a: &Object, b: &Object) -> Option<(Object, Object)> { + match (a, b) { + (Object::Instance(ia), Object::Tuple(_)) => Some((struct_seq_tuple_of(ia)?, b.clone())), + (Object::Tuple(_), Object::Instance(ib)) => Some((a.clone(), struct_seq_tuple_of(ib)?)), + (Object::Instance(ia), Object::Instance(ib)) + if std::ptr::eq(ia.cls_raw(), ib.cls_raw()) => + { + Some((struct_seq_tuple_of(ia)?, struct_seq_tuple_of(ib)?)) + } + _ => None, + } +} + +/// Whether `p`, found on a class's MRO under `name`, is a struct sequence's +/// own field descriptor: a read-only property whose getter returns the +/// instance dict's entry for the name. A read through it is then the +/// instance dict's read (a missing entry is the descriptor's error, which +/// the full path raises), so the attribute caches treat the name as the +/// instance's own (`st.st_mode`, `time.localtime().tm_year`). +pub(crate) fn struct_seq_field_descr(name: &str, p: &Rc) -> bool { + if !matches!(&*p.fset.borrow(), Object::None) + || !matches!(&*p.fget.borrow(), Object::Builtin(b) if b.name == name) + { + return false; + } + crate::descr_registry::lookup(&Object::Property(p.clone())).is_some_and(|m| { + matches!(m.kind, crate::descr_registry::DescrKind::Member) + && m.name == name + && is_struct_seq_type(&m.objclass) + }) +} + /// Build (and memoise, by `name`) an all-visible, all-named struct-sequence /// type — the common shape (`os.times_result`, `os.terminal_size`, /// `sys.flags`, …). @@ -7234,6 +7646,23 @@ pub(crate) fn struct_seq_type_layout( ))) } }); + // Deletion fails the same way (`del st.st_mode` is CPython's + // "readonly attribute"). The override also keeps the fields off + // the instance-dict delete paths, which the attribute caches would + // otherwise offer them (see `struct_seq_field_descr`). + struct_seq_method(&mut dict, "__delattr__", move |args| { + let attr = match args.get(1) { + Some(Object::Str(s)) => s.to_string(), + _ => String::new(), + }; + if layout.is_named(&attr) { + Err(crate::error::attribute_error("readonly attribute")) + } else { + Err(crate::error::attribute_error(format!( + "'{name}' object has no attribute '{attr}'" + ))) + } + }); // CPython struct sequences subclass `tuple`, so `==`/`!=`/`hash()` // compare the visible fields by value (e.g. `os.stat(a) == os.stat(a)` // in `test_pathlib`, and using a `stat_result` as a dict key). Compare @@ -7317,6 +7746,10 @@ pub(crate) fn struct_seq_type_layout( }), call_kw: None, })); + // (The read is a dictionary lookup: no Python runs.) + if let Object::Builtin(b) = &fget { + crate::leaf_builtins::register(b); + } let prop = Object::Property(Rc::new(crate::object::PyProperty::new( fget, Object::None, @@ -7333,6 +7766,7 @@ pub(crate) fn struct_seq_type_layout( cls.dict.borrow_mut().insert(key, prop); } reg.borrow_mut().insert(name, (cls.clone(), layout)); + STRUCT_SEQ_TYPES.with(|t| t.borrow_mut().push((Rc::as_ptr(&cls) as usize, layout))); cls }) } @@ -7472,7 +7906,7 @@ fn struct_seq_init( let mut d = inst.dict_cell().borrow_mut(); for (i, v) in values.iter().enumerate() { if let Some(f) = layout.slots[i] { - d.insert(DictKey(Object::from_static(f)), v.clone()); + d.insert(static_name_key(f), v.clone()); } } // Hidden slots the sequence didn't reach: fill from `dict`, default @@ -7483,11 +7917,11 @@ fn struct_seq_init( let f = slot.expect("hidden struct-seq slots are named"); let v = dict_arg .as_ref() - .and_then(|d2| d2.borrow().get(&DictKey(Object::from_static(f))).cloned()); + .and_then(|d2| d2.borrow().get(&static_name_key(f)).cloned()); if v.is_some() { n_found += 1; } - d.insert(DictKey(Object::from_static(f)), v.unwrap_or(Object::None)); + d.insert(static_name_key(f), v.unwrap_or(Object::None)); } if let Some(d2) = &dict_arg { if d2.borrow().len() > n_found { @@ -7499,7 +7933,7 @@ fn struct_seq_init( } let _ = inst .native - .set(Object::new_tuple(values[..layout.n_sequence].to_vec())); + .set(Object::tuple_from_slice(&values[..layout.n_sequence])); // posixmodule's `statresult_new`: a stat_result initialized from a bare // tuple leaves the float `st_?time` members `None`; backfill them from // the integer-seconds sequence slots so `os.stat_result(range(10)).st_atime` @@ -7507,7 +7941,7 @@ fn struct_seq_init( if name == "stat_result" { let mut d = inst.dict_cell().borrow_mut(); for (slot, f) in [(7usize, "st_atime"), (8, "st_mtime"), (9, "st_ctime")] { - let key = DictKey(Object::from_static(f)); + let key = static_name_key(f); if matches!(d.get(&key), None | Some(Object::None)) { if let Some(v) = values.get(slot) { d.insert(key, v.clone()); @@ -7580,7 +8014,7 @@ fn struct_seq_replace( } let _ = new_inst .native - .set(Object::new_tuple(vals[..layout.n_sequence].to_vec())); + .set(Object::tuple_from_slice(&vals[..layout.n_sequence])); let obj = Object::Instance(Rc::new(new_inst)); // CPython allocates the copy through the GC heap, so it is tracked from // birth (test_structseq.test_replace_gc_tracked builds a cycle out of it). @@ -7622,6 +8056,17 @@ fn struct_seq_getitem( /// slots (`stat_result`'s integer times) that the named dict can't represent. /// Instances built before the native view existed fall back to the named /// visible fields, with `0` in any gap. +/// The visible fields as a tuple: the instance's own when it keeps one. +fn struct_seq_tuple( + layout: &'static StructSeqLayout, + inst: &Rc, +) -> Object { + match inst.native.get() { + Some(t @ Object::Tuple(_)) => t.clone(), + _ => Object::new_tuple(struct_seq_values(layout, inst)), + } +} + fn struct_seq_values( layout: &'static StructSeqLayout, inst: &Rc, @@ -7722,10 +8167,10 @@ fn struct_seq_richcompare( "struct sequence comparison requires an instance", )); }; - let self_tuple = Object::new_tuple(struct_seq_values(layout, inst)); + let self_tuple = struct_seq_tuple(layout, inst); let other = match args.get(1) { Some(Object::Instance(other_inst)) if Rc::ptr_eq(&inst.cls(), &other_inst.cls()) => { - Object::new_tuple(struct_seq_values(layout, other_inst)) + struct_seq_tuple(layout, other_inst) } Some(t @ Object::Tuple(_)) => t.clone(), Some(Object::List(items)) => Object::new_tuple(items.borrow().clone()), @@ -7747,8 +8192,7 @@ fn struct_seq_hash( let Some(Object::Instance(inst)) = args.first() else { return Err(type_error("struct sequence hash requires an instance")); }; - let tuple = Object::new_tuple(struct_seq_values(layout, inst)); - crate::builtins::hash_object(&tuple) + crate::builtins::hash_object(&struct_seq_tuple(layout, inst)) } /// Build an instance of a [`struct_seq_type`], binding `values` positionally to @@ -7812,8 +8256,7 @@ pub(crate) fn struct_seq_instance_keyed( /// once per instance. pub(crate) fn static_name_keys(fields: &'static [&'static str]) -> std::rc::Rc<[DictKey]> { thread_local! { - static KEYS: RefCell, crate::fasthash::FxBuildHasher>> = - RefCell::new(std::collections::HashMap::default()); + static KEYS: crate::gil::ReleaseUnderGil, crate::fasthash::FxBuildHasher>>> = crate::gil::ReleaseUnderGil::new(RefCell::new(std::collections::HashMap::default())); } let id = (fields.as_ptr() as usize, fields.len()); if let Some(keys) = KEYS.with(|k| k.borrow().get(&id).cloned()) { @@ -7830,17 +8273,21 @@ pub(crate) fn static_name_keys(fields: &'static [&'static str]) -> std::rc::Rc<[ /// their names each time. pub(crate) fn static_name_key(name: &'static str) -> DictKey { thread_local! { - static KEYS: RefCell> = - RefCell::new(std::collections::HashMap::default()); + static KEYS: crate::gil::ReleaseUnderGil>> = crate::gil::ReleaseUnderGil::new(RefCell::new(std::collections::HashMap::default())); } KEYS.with(|keys| { let mut keys = keys.borrow_mut(); let key = keys .entry((name.as_ptr() as usize, name.len())) .or_insert_with(|| { - let s = crate::shared_value::SharedStr::from(name); - crate::shared_value::SharedStr::hash_cached(&s); - Object::Str(s) + // The interned name: code that reads the field by name + // (`st.st_mode`) holds that same string, so a cached read + // matches the key by pointer. + let key = crate::stdlib::sys::intern_name(name); + if let Object::Str(s) = &key { + crate::shared_value::SharedStr::hash_cached(s); + } + key }); DictKey(key.clone()) }) @@ -7937,11 +8384,11 @@ fn path_splitroot_fast(args: &[Object]) -> Option> let (root, tail) = b.split_at(n); Object::new_tuple_array([ Object::new_bytes(Vec::new()), - Object::new_bytes(root.to_vec()), + Object::new_bytes(root), if n == 0 { p.clone() } else { - Object::new_bytes(tail.to_vec()) + Object::new_bytes(tail) }, ]) } @@ -8677,6 +9124,9 @@ fn normpath_lexical(s: &str) -> String { fn fspath_fast(args: &[Object]) -> Option> { match args { [x @ (Object::Str(_) | Object::Bytes(_))] => Some(Ok(x.clone())), + // A `pathlib` path whose string is cached (see + // `Interpreter::pathlib_fspath`). + [Object::Instance(inst)] => crate::Interpreter::pathlib_fspath(inst).map(Ok), _ => None, } } diff --git a/crates/weavepy-vm/src/stdlib/os_process.rs b/crates/weavepy-vm/src/stdlib/os_process.rs index 89af5dbdf..8c46fd47b 100644 --- a/crates/weavepy-vm/src/stdlib/os_process.rs +++ b/crates/weavepy-vm/src/stdlib/os_process.rs @@ -837,7 +837,7 @@ fn resolve_path(file: &[u8], env: &Object) -> Vec> { // A plain `dict` is str-keyed ("PATH"); `os.environ`'s `_Environ` // backing store is bytes-keyed (b"PATH"). d.get(&DictKey(Object::from_static("PATH"))) - .or_else(|| d.get(&DictKey(Object::new_bytes(b"PATH".to_vec())))) + .or_else(|| d.get(&DictKey(Object::new_bytes(b"PATH")))) .and_then(bytes_of) }) .unwrap_or_else(|| b"/usr/bin:/bin".to_vec()); diff --git a/crates/weavepy-vm/src/stdlib/pickle_accel.rs b/crates/weavepy-vm/src/stdlib/pickle_accel.rs index 9d2368545..4d8e875a2 100644 --- a/crates/weavepy-vm/src/stdlib/pickle_accel.rs +++ b/crates/weavepy-vm/src/stdlib/pickle_accel.rs @@ -29,6 +29,19 @@ struct FunctionGuard { code: Weak, } +/// Whether a guard that last proved all its functions at `proven` (a +/// [`crate::rare_events::func_edits`] count) still has them unchanged: no +/// function's code or defaults changed since. Such a guard checks only +/// which functions its classes and tables hold, not each one's code. +#[inline] +fn proven_edits(proven: &std::sync::atomic::AtomicU64) -> (bool, u64) { + let edits = crate::rare_events::func_edits(); + ( + proven.load(std::sync::atomic::Ordering::Relaxed) == edits, + edits, + ) +} + impl FunctionGuard { fn new(value: &Object) -> Option { let Object::Function(function) = value else { @@ -48,6 +61,15 @@ impl FunctionGuard { Rc::as_ptr(function) == self.function.as_ptr() && self.holds_function(function) } + /// Whether `value` is the guarded function, for a guard that proved + /// every function unchanged since the last function edit (see + /// [`proven_edits`]). (The guard's weak reference keeps the function's + /// allocation, so no other function can live at its address.) + #[inline] + fn is_same(&self, value: &Object) -> bool { + matches!(value, Object::Function(function) if Rc::as_ptr(function) == self.function.as_ptr()) + } + /// Whether the guarded function is still alive and unchanged. fn holds_live(&self) -> bool { if self.function.strong_count() == 0 { @@ -257,6 +279,10 @@ struct UnpicklerGuard { find_class: Option, dispatch: Weak>, entries: Vec<(u8, FunctionGuard)>, + /// The function-edit count at which every guarded function last held. + proven: std::sync::atomic::AtomicU64, + /// The dispatch table's mutation stamp when its entries last matched. + dispatch_stamp: std::sync::atomic::AtomicU64, } impl UnpicklerGuard { @@ -286,6 +312,8 @@ impl UnpicklerGuard { .and_then(|function| FunctionGuard::new(&function)), dispatch: Rc::downgrade(&dispatch), entries, + proven: std::sync::atomic::AtomicU64::new(u64::MAX), + dispatch_stamp: std::sync::atomic::AtomicU64::new(u64::MAX), }) } @@ -300,6 +328,69 @@ impl UnpicklerGuard { /// bases advances) proves that `__init__`, `load`, and `find_class` /// still resolve to the guarded functions. fn holds(&self, opcodes: &Opcodes) -> bool { + // (STACK_GLOBAL needs a guarded `find_class` either way.) + if opcodes.contains(STACK_GLOBAL) && self.find_class.is_none() { + return false; + } + let (proven, edits) = proven_edits(&self.proven); + // (A table whose entries changed may still hold every function + // this stream runs.) + if proven && self.same_dispatch(true, |guard, value| guard.is_same(value)) { + return true; + } + // Every function checked at once proves them all until the next + // function edit; otherwise only the ones this stream runs count. + if self.init.holds_live() + && self.load.holds_live() + && self + .find_class + .as_ref() + .is_none_or(FunctionGuard::holds_live) + && self.same_dispatch(false, FunctionGuard::holds) + { + self.proven + .store(edits, std::sync::atomic::Ordering::Relaxed); + return true; + } + self.holds_for(opcodes) + } + + /// The dispatch table still maps the guarded opcodes, in order, to + /// functions `same` accepts. With `proven`, an unchanged table (its + /// mutation stamp the one it had when its entries last matched) is + /// taken as it is. + fn same_dispatch(&self, proven: bool, same: impl Fn(&FunctionGuard, &Object) -> bool) -> bool { + let Some(dispatch) = self.dispatch.upgrade() else { + return false; + }; + let dispatch = dispatch.borrow(); + let stamp = dispatch.mutation_stamp(); + if proven + && stamp + == self + .dispatch_stamp + .load(std::sync::atomic::Ordering::Relaxed) + { + return true; + } + let holds = dispatch.len() == self.entries.len() + && dispatch + .iter() + .zip(&self.entries) + .all(|((key, value), (opcode, guard))| { + matches!(key.0, Object::Int(current) if current == i64::from(*opcode)) + && same(guard, value) + }); + if holds { + self.dispatch_stamp + .store(stamp, std::sync::atomic::Ordering::Relaxed); + } + holds + } + + /// [`Self::holds`] checked for only the functions a stream of + /// `opcodes` runs. + fn holds_for(&self, opcodes: &Opcodes) -> bool { if !self.init.holds_live() || !self.load.holds_live() { return false; } @@ -354,6 +445,14 @@ pub fn build(_cache: &ModuleCache) -> Rc { })); crate::descr_registry::register_module(&factory, "_weave_pickle"); dict.insert(DictKey(Object::from_static("make_dumps")), factory); + let factory = Object::Builtin(Rc::new(BuiltinFn { + name: "make_front", + binds_instance: false, + call: Box::new(make_front), + call_kw: None, + })); + crate::descr_registry::register_module(&factory, "_weave_pickle"); + dict.insert(DictKey(Object::from_static("make_front")), factory); Rc::new(PyModule { name: "_weave_pickle".to_owned(), filename: None, @@ -361,6 +460,161 @@ pub fn build(_cache: &ModuleCache) -> Rc { }) } +/// `make_front(kind, native, cls, full, rest)`: `_pickle.dumps` (`kind` +/// "dumps") or `_pickle.loads` ("loads") as a built-in function, as +/// CPython's are. A call the native `try_dumps`/`try_loads` (`native`, made +/// for the pickler or unpickler class `cls`) encodes or decodes returns its +/// result with no Python frame; one it declines runs the Python function +/// `rest` (the same signature, without the native attempt), and a call it +/// can't read the arguments of runs `full` (which reports them). The +/// functions are held weakly, as the guards hold theirs, so no reference +/// cycle hides in the closure; the module keeps them. +fn make_front(args: &[Object]) -> Result { + let [Object::Str(kind), Object::Builtin(native), Object::Type(cls), Object::Function(full), Object::Function(rest)] = + args + else { + return Ok(Object::None); + }; + let loads = match kind.as_ref() { + "dumps" => false, + "loads" => true, + _ => return Ok(Object::None), + }; + let front = Rc::new(Front { + loads, + ascii: Object::from_static("ASCII"), + strict: Object::from_static("strict"), + native: native.clone(), + cls: Rc::downgrade(cls), + full: Rc::downgrade(full), + rest: Rc::downgrade(rest), + }); + let kw = front.clone(); + let b = Object::Builtin(Rc::new(BuiltinFn { + name: if loads { "loads" } else { "dumps" }, + binds_instance: false, + call: Box::new(move |a: &[Object]| front.call(a, &[])), + call_kw: Some(Box::new(move |a: &[Object], k: &[(String, Object)]| { + kw.call(a, k) + })), + })); + crate::descr_registry::register_module(&b, "_pickle"); + Ok(b) +} + +struct Front { + loads: bool, + /// `loads`'s default `encoding` and `errors`, made once. + ascii: Object, + strict: Object, + native: Rc, + cls: Weak, + full: Weak, + rest: Weak, +} + +impl Front { + fn call(&self, args: &[Object], kwargs: &[(String, Object)]) -> Result { + let Some(cls) = self.cls.upgrade() else { + return self.fall_back(&self.full, args, kwargs); + }; + let result = if self.loads { + self.loads_args(args, kwargs, cls) + .map(|a| (self.native.call)(&a)) + } else { + Self::dumps_args(args, kwargs, cls).map(|a| (self.native.call)(&a)) + }; + let Some(result) = result else { + return self.fall_back(&self.full, args, kwargs); + }; + match (result?, self.loads) { + (Object::None, _) => self.fall_back(&self.rest, args, kwargs), + (Object::Tuple(t), true) if t.len() == 1 => Ok(t[0].clone()), + (Object::Tuple(_), true) => self.fall_back(&self.rest, args, kwargs), + (encoded, _) => Ok(encoded), + } + } + + /// `try_dumps`'s arguments for `dumps(obj, protocol=None, *, + /// fix_imports=True, buffer_callback=None)`: a `bool` flag and no + /// buffer callback only. + fn dumps_args( + args: &[Object], + kwargs: &[(String, Object)], + cls: Rc, + ) -> Option<[Object; 5]> { + let (obj, mut protocol) = match args { + [obj] => (obj, None), + [obj, protocol] => (obj, Some(protocol.clone())), + _ => return None, + }; + let mut fix_imports = Object::Bool(true); + for (name, value) in kwargs { + match name.as_str() { + "protocol" if protocol.is_none() => protocol = Some(value.clone()), + "fix_imports" if matches!(value, Object::Bool(_)) => fix_imports = value.clone(), + "buffer_callback" if matches!(value, Object::None) => {} + _ => return None, + } + } + Some([ + obj.clone(), + Object::Type(cls), + protocol.unwrap_or(Object::None), + fix_imports, + Object::None, + ]) + } + + /// `try_loads`'s arguments for `loads(data, /, *, fix_imports=True, + /// encoding="ASCII", errors="strict", buffers=None)`. + fn loads_args( + &self, + args: &[Object], + kwargs: &[(String, Object)], + cls: Rc, + ) -> Option<[Object; 6]> { + let [data] = args else { + return None; + }; + let mut fix_imports = Object::Bool(true); + let mut encoding = self.ascii.clone(); + let mut errors = self.strict.clone(); + for (name, value) in kwargs { + match (name.as_str(), value) { + ("fix_imports", Object::Bool(_)) => fix_imports = value.clone(), + ("encoding", Object::Str(_)) => encoding = value.clone(), + ("errors", Object::Str(_)) => errors = value.clone(), + ("buffers", Object::None) => {} + _ => return None, + } + } + Some([ + data.clone(), + Object::Type(cls), + fix_imports, + encoding, + errors, + Object::None, + ]) + } + + fn fall_back( + &self, + f: &Weak, + args: &[Object], + kwargs: &[(String, Object)], + ) -> Result { + let f = f + .upgrade() + .ok_or_else(|| crate::error::type_error("the pickle module was torn down"))?; + let ptr = crate::vm_singletons::current_interpreter_ptr() + .ok_or_else(|| crate::error::type_error("no active interpreter"))?; + // SAFETY: published by the enclosing VM frame on this thread. + unsafe { &mut *ptr }.call_object(Object::Function(f), args, kwargs) + } +} + #[allow(clippy::unnecessary_wraps)] fn make_loads(args: &[Object]) -> Result { let [Object::Type(class), modules @ ..] = args else { @@ -428,13 +682,15 @@ impl ClassFunctionsGuard { }) } - fn holds(&self) -> bool { + /// The class is unchanged; with `proven` (see [`proven_edits`]) its + /// functions' code and defaults are taken as unchanged too. + fn holds_with(&self, proven: bool) -> bool { // An unchanged version proves the class holds the same functions; // each one's code and defaults can still change in place. self.class.strong_count() > 0 // SAFETY: a live strong count keeps the class allocated. && unsafe { &*self.class.as_ptr() }.attr_version.get() == self.version - && self.functions.iter().all(FunctionGuard::holds_live) + && (proven || self.functions.iter().all(FunctionGuard::holds_live)) } } @@ -456,16 +712,20 @@ impl DumpDescriptorGuard { }) } - fn holds(&self, value: &Object) -> bool { + fn holds(&self, value: &Object, proven: bool) -> bool { let Object::Instance(instance) = value else { return false; }; Rc::as_ptr(instance) == self.instance.as_ptr() && Rc::as_ptr(&instance.class.borrow()) == self.class.class.as_ptr() - && self.class.holds() - && instance - .slot_get("_func") - .is_some_and(|f| self.function.holds(&f)) + && self.class.holds_with(proven) + && instance.slot_get("_func").is_some_and(|f| { + if proven { + self.function.is_same(&f) + } else { + self.function.holds(&f) + } + }) } } @@ -475,6 +735,10 @@ struct PicklerGuard { dump: DumpDescriptorGuard, dispatch: Weak>, entries: Vec<(Weak, FunctionGuard)>, + /// The function-edit count at which every guarded function last held. + proven: std::sync::atomic::AtomicU64, + /// The dispatch table's mutation stamp when its entries last matched. + dispatch_stamp: std::sync::atomic::AtomicU64, } impl PicklerGuard { @@ -504,30 +768,62 @@ impl PicklerGuard { dump: DumpDescriptorGuard::new(&class.lookup("dump")?)?, dispatch: Rc::downgrade(&dispatch), entries, + proven: std::sync::atomic::AtomicU64::new(u64::MAX), + dispatch_stamp: std::sync::atomic::AtomicU64::new(u64::MAX), }) } fn holds(&self, class: &Rc) -> bool { + let (proven, edits) = proven_edits(&self.proven); if Rc::as_ptr(class) != self.class.as_ptr() - || !self.hierarchy.iter().all(ClassFunctionsGuard::holds) - || !class - .lookup("dump") - .is_some_and(|value| self.dump.holds(&value)) + || !self.hierarchy.iter().all(|guard| guard.holds_with(proven)) { return false; } + // (With the whole hierarchy unchanged, `dump` resolves to the + // guarded descriptor; its `_func` can still be reassigned.) + let dump = if proven { + self.dump.instance.upgrade().map(Object::Instance) + } else { + class.lookup("dump") + }; + if !dump.is_some_and(|value| self.dump.holds(&value, proven)) { + return false; + } let Some(dispatch) = self.dispatch.upgrade() else { return false; }; let dispatch = dispatch.borrow(); - dispatch.len() == self.entries.len() + let stamp = dispatch.mutation_stamp(); + if proven + && stamp + == self + .dispatch_stamp + .load(std::sync::atomic::Ordering::Relaxed) + { + return true; + } + let holds = dispatch.len() == self.entries.len() && dispatch .iter() .zip(&self.entries) .all(|((key, value), (kind, function))| { matches!(&key.0, Object::Type(current) if Rc::as_ptr(current) == kind.as_ptr()) - && function.holds(value) - }) + && if proven { + function.is_same(value) + } else { + function.holds(value) + } + }); + if holds { + self.dispatch_stamp + .store(stamp, std::sync::atomic::Ordering::Relaxed); + if !proven { + self.proven + .store(edits, std::sync::atomic::Ordering::Relaxed); + } + } + holds } } @@ -1550,6 +1846,13 @@ impl<'c> Decoder<'c> { push_entry!(stack, value); self.memoize_next(&mut reader, stack)?; } + // BYTEARRAY8: a new bytearray of the bytes. + 0x96 => { + let size = reader.size64()?; + let value = Object::new_bytearray(reader.read(size)?); + push_entry!(stack, value); + self.memoize_next(&mut reader, stack)?; + } b']' => { self.empty_list(stack)?; self.memoize_next(&mut reader, stack)?; diff --git a/crates/weavepy-vm/src/stdlib/pickle_accel/encode.rs b/crates/weavepy-vm/src/stdlib/pickle_accel/encode.rs index 950a74645..e47db3c63 100644 --- a/crates/weavepy-vm/src/stdlib/pickle_accel/encode.rs +++ b/crates/weavepy-vm/src/stdlib/pickle_accel/encode.rs @@ -81,6 +81,22 @@ impl Framer { self.frame_start = None; } + /// Protocol 5's `BYTEARRAY8` (always the eight-byte length, as + /// CPython's pickler writes it), a large one outside the frame. + fn bytearray8(&mut self, value: &[u8]) -> Option<()> { + let mut header = [0u8; 9]; + header[0] = 0x96; + header[1..].copy_from_slice(&(value.len() as u64).to_le_bytes()); + if value.len() >= FRAME_TARGET { + self.commit(true); + extend(&mut self.output, &header)?; + extend(&mut self.output, value) + } else { + self.write(&header)?; + self.write(value) + } + } + fn data(&mut self, value: &[u8], unicode: bool) -> Option<()> { let len = value.len(); if len <= 255 { @@ -124,11 +140,13 @@ struct ClassPlan { struct Encoder<'a> { writer: Framer, + // The protocol written (4 or 5). + protocol: u8, // Memo positions by object identity. memo: MemoTable, // Pins prevent another thread's container mutation from releasing an // already memoized value and reusing its address during this operation. - // While one thread owns every object, nothing else can mutate the graph, + // While only one thread runs, nothing else can mutate the graph, // so the values stay alive and unpinned. pins: Option>, // Memo positions taken by the default state's temporary tuple and @@ -265,6 +283,7 @@ fn identity(value: &Object) -> i64 { match value { Object::Str(text) => text.as_ptr() as usize as i64, Object::Bytes(bytes) => bytes.as_ptr() as usize as i64, + Object::ByteArray(bytes) => Rc::as_ptr(bytes) as usize as i64, Object::Tuple(items) => { crate::shared_value::ThinArc::as_ptr(items).cast::<()>() as usize as i64 } @@ -424,6 +443,14 @@ impl Encoder<'_> { Object::Bytes(bytes) => self .save_memoized(value, identity(value), |writer| writer.data(bytes, false)) .map(drop), + // (Protocol 4 reduces a bytearray through `copyreg`: the Python + // pickler's.) + Object::ByteArray(bytes) if self.protocol >= 5 => { + // (A read that runs no code.) + let data = bytes.try_borrow().ok()?; + self.save_memoized(value, identity(value), |writer| writer.bytearray8(&data)) + .map(drop) + } // The empty tuple is never memoized. Object::Tuple(items) if items.is_empty() => self.writer.write(b")"), Object::Tuple(items) => { @@ -856,8 +883,9 @@ fn encode_with_context( output: Vec::new(), frame_start: None, }, + protocol, memo, - pins: (!crate::sync::bias_held()).then(Vec::new), + pins: crate::sync::threads_started().then(Vec::new), anonymous: 0, active: Vec::new(), python_headroom, diff --git a/crates/weavepy-vm/src/stdlib/pyexpat_mod.rs b/crates/weavepy-vm/src/stdlib/pyexpat_mod.rs index 916d01752..34291dcc4 100644 --- a/crates/weavepy-vm/src/stdlib/pyexpat_mod.rs +++ b/crates/weavepy-vm/src/stdlib/pyexpat_mod.rs @@ -184,8 +184,7 @@ fn state_from_ud(ud: *mut c_void) -> Option { // The last parser this thread looked up, held weakly: a parse makes // every callback ask for the same one. thread_local! { - static LAST: std::cell::RefCell<(i64, crate::sync::Weak>)> = - const { std::cell::RefCell::new((0, crate::sync::Weak::new())) }; + static LAST: crate::gil::ReleaseUnderGil>)>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new((0, crate::sync::Weak::new()))) }; } let id = ud as i64; let hit = LAST.with(|last| { @@ -2023,7 +2022,7 @@ fn get_input_context_method(args: &[Object]) -> Result { (size - offset) as usize, ) }; - Ok(Object::new_bytes(bytes.to_vec())) + Ok(Object::new_bytes(bytes)) } fn set_param_entity_parsing_method(args: &[Object]) -> Result { diff --git a/crates/weavepy-vm/src/stdlib/python/_collections.py b/crates/weavepy-vm/src/stdlib/python/_collections.py index 28c0eda9d..c6552b13f 100644 --- a/crates/weavepy-vm/src/stdlib/python/_collections.py +++ b/crates/weavepy-vm/src/stdlib/python/_collections.py @@ -41,6 +41,10 @@ ValuesView as _ValuesView, ) from _weave_collections import iterator_index as _deque_iterator_index +from _weave_collections import _extend_method as _deque_extend_method +from _weave_collections import _contains_method as _deque_contains_method +from _weave_collections import _plain_find as _deque_plain_find +from _weave_collections import _plain_count as _deque_plain_count from _weave_collections import ( install_tuplegetter as _install_tuplegetter, tuplegetter_get as _tuplegetter_get, @@ -66,6 +70,7 @@ dd_init as _dd_init, dd_missing as _dd_missing, install_defaultdict as _install_defaultdict, + install_deque as _install_deque, ) # The native `OrderedDict` operations (`stdlib/collections_odict.rs`). from _weave_collections import ( @@ -301,6 +306,11 @@ def extendleft(self, iterable): for item in iterable: self.appendleft(item) + # (Native for a list or tuple, which goes in at once; the methods + # above for anything else.) + extend = _deque_extend_method(extend, False) + extendleft = _deque_extend_method(extendleft, True) + def clear(self): self._state += 1 del self._data[:] @@ -315,6 +325,10 @@ def count(self, value): # CPython `deque_count`: per-comparison mutation trip-wire — an # `__eq__` that mutates the deque raises RuntimeError. data = self._flat() + # (Plain items and value: counted natively.) + result = _deque_plain_count(data, value) + if result is not None: + return result state = self._state n = len(data) result = 0 @@ -338,6 +352,13 @@ def index(self, value, start=0, stop=None): start = max(0, start + n) if stop < 0: stop += n + # (Plain items and value: found natively.) + if type(start) is int and type(stop) is int: + found = _deque_plain_find(data, value, start, stop) + if found is not None: + if found >= 0: + return found + raise ValueError("deque.index(x): x not in deque") for i in range(start, min(stop, n)): item = data[i] hit = item is value or item == value @@ -345,7 +366,7 @@ def index(self, value, start=0, stop=None): raise RuntimeError("deque mutated during iteration") if hit: return i - raise ValueError(f"{value!r} is not in deque") + raise ValueError("deque.index(x): x not in deque") def insert(self, i, x): if self._maxlen is not None and len(self) >= self._maxlen: @@ -378,6 +399,10 @@ def reverse(self): def __contains__(self, x): # CPython `deque_contains`: mutation during a comparison raises. data = self._flat() + # (Plain items and value: searched natively.) + found = _deque_plain_find(data, x, 0, len(data)) + if found is not None: + return found >= 0 state = self._state i = 0 while i < len(data): @@ -392,6 +417,10 @@ def __contains__(self, x): i += 1 return False + # (Native for plain items and value; the method above for anything + # else.) + __contains__ = _deque_contains_method(__contains__) + def _slot(self, idx): # Translate a logical index into a `_data` slot, honoring the # consumed prefix without flattening (`d[0]`/`d[-1]` peeks stay @@ -535,6 +564,10 @@ def __repr__(self): _repr_running.discard(k) +# (`deque()` and `deque(list_or_tuple)` build natively while its +# `__init__` is this one.) +_install_deque(deque) + _repr_running = set() @@ -637,7 +670,10 @@ class OrderedDict(dict): pop = _od_pop clear = _od_clear - def __init__(self, other=(), /, **kwds): + def __init__(self, other=_NO_ITEMS, /, **kwds): + # (Nothing to add: the order dict starts on first use.) + if other is _NO_ITEMS and not kwds: + return self.__update(other, kwds) def __update(self, other, kwds): @@ -669,6 +705,12 @@ def __update_from(self, other): if items is not None: other = items() for pair in other: + # (A 2-tuple, the common pair, unpacks as the steps below + # would; anything else goes through them for their errors.) + if type(pair) is tuple and len(pair) == 2: + key, value = pair + self[key] = value + continue it = iter(pair) try: key = next(it) @@ -740,6 +782,9 @@ def copy(self): # (gh-148660). if type(self) is OrderedDict: new = OrderedDict() + # (Plain keys: copied natively, in order, with no code run.) + if _od_update_fast(new, self): + return new for key in _od_iter(self): value = dict.get(self, key, _od_missing) if value is _od_missing: @@ -755,6 +800,17 @@ def copy(self): def fromkeys(cls, iterable, value=None): '''Create a new ordered dictionary with keys from iterable and values set to value. ''' + # WeavePy: an exact OrderedDict takes the keys of a list, tuple or + # str in one native pass (`dict.fromkeys` keeps the first + # occurrence's order, as the loop below does) and is built from + # that dict whole; a subclass may override `__setitem__`, and an + # unhashable key raises from the loop, which words the error as + # CPython's OrderedDict does. + if cls is OrderedDict and type(iterable) in (list, tuple, str): + try: + return OrderedDict(dict.fromkeys(iterable, value)) + except TypeError: + pass self = cls() for key in iterable: self[key] = value diff --git a/crates/weavepy-vm/src/stdlib/python/_decimal.py b/crates/weavepy-vm/src/stdlib/python/_decimal.py index 73c69eb53..f0a23ed10 100644 --- a/crates/weavepy-vm/src/stdlib/python/_decimal.py +++ b/crates/weavepy-vm/src/stdlib/python/_decimal.py @@ -446,7 +446,9 @@ def __ne__(self, other): def copy(self): self._check_valid() - return dict(self) + # (The mapping's own entries, as `dict(self)` reads them through + # the checked `__getitem__`, without a call a key.) + return dict.copy(self) ##### Context Functions ################################################## @@ -753,9 +755,9 @@ def _from_value(cls, value="0", context=None): digits = [] for digit in value[1]: if isinstance(digit, int) and 0 <= digit <= 9: - # skip leading zeros + # skip leading zeros (a bool digit is its int) if digits or digit != 0: - digits.append(digit) + digits.append(int(digit)) else: raise ValueError("The second value in the tuple must " "be composed of integers in the range " @@ -4151,14 +4153,14 @@ def __init__(self, /, prec=None, rounding=None, Emin=None, Emax=None, if traps is None: self.traps = dc.traps.copy() elif not isinstance(traps, dict): - self.traps = dict((s, int(s in traps)) for s in _signals + traps) + self.traps = dict((s, s in traps) for s in _signals + traps) else: self.traps = traps if flags is None: - self.flags = dict.fromkeys(_signals, 0) + self.flags = dict.fromkeys(_signals, False) elif not isinstance(flags, dict): - self.flags = dict((s, int(s in flags)) for s in _signals + flags) + self.flags = dict((s, s in flags) for s in _signals + flags) else: self.flags = flags @@ -4265,10 +4267,26 @@ def _shallow_copy(self, /): def copy(self, /): """Returns a deep copy from self.""" - nc = Context(self.prec, self.rounding, self.Emin, self.Emax, - self.capitals, self.clamp, - self.flags.copy(), self.traps.copy()) - nc._ignored_flags = self._ignored_flags + # WEAVEPY: the source's values are a context's, already checked, so + # the copy (a plain Context, as the C type's is) takes them as they + # are; its flag and trap mappings are new ones it owns. + nc = object.__new__(Context) + _set = object.__setattr__ + _set(nc, 'prec', self.prec) + _set(nc, 'rounding', self.rounding) + _set(nc, 'Emin', self.Emin) + _set(nc, 'Emax', self.Emax) + _set(nc, 'capitals', self.capitals) + _set(nc, 'clamp', self.clamp) + # (In `__init__`'s order, so the copy keeps the class's attribute + # layout.) + _set(nc, '_ignored_flags', self._ignored_flags) + owner = _weakref.ref(nc) + for name in ('traps', 'flags'): + d = SignalDict(dict.copy(getattr(self, name))) + d._owner = owner + _set(nc, name, d) + _context_changed() return nc __copy__ = copy @@ -6698,8 +6716,10 @@ def _format_number(is_negative, intpart, fracpart, exp, spec): import contextvars as _contextvars _getcontext = _install_native(Decimal, Context, SignalDict, DecimalTuple, _signals, _current_context_var, - None, _rounding_modes, + (setcontext, DefaultContext, BasicContext, + ExtendedContext), + _rounding_modes, getcontext) if _getcontext is not None: - getcontext, _context_changed = _getcontext + getcontext, _context_changed, setcontext = _getcontext del _install_native, _contextvars, _getcontext diff --git a/crates/weavepy-vm/src/stdlib/python/_pickle.py b/crates/weavepy-vm/src/stdlib/python/_pickle.py index 8ea086822..868da3d06 100644 --- a/crates/weavepy-vm/src/stdlib/python/_pickle.py +++ b/crates/weavepy-vm/src/stdlib/python/_pickle.py @@ -453,6 +453,11 @@ def dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None): encoded = _native_dumps(obj, Pickler, protocol, fix_imports, buffer_callback) if encoded is not None: return encoded + return _dumps_python(obj, protocol, fix_imports=fix_imports, + buffer_callback=buffer_callback) + + +def _dumps_python(obj, protocol=None, *, fix_imports=True, buffer_callback=None): f = _io.BytesIO() Pickler(f, protocol, fix_imports=fix_imports, buffer_callback=buffer_callback).dump(obj) @@ -477,6 +482,14 @@ def loads(s, /, *, fix_imports=True, encoding="ASCII", errors="strict", decoded = _native_loads(s, Unpickler, fix_imports, encoding, errors, buffers) if decoded is not None: return decoded[0] + return _loads_python(s, fix_imports=fix_imports, encoding=encoding, + errors=errors, buffers=buffers) + + +def _loads_python(s, /, *, fix_imports=True, encoding="ASCII", errors="strict", + buffers=None): + if isinstance(s, str): + raise TypeError("Can't load pickle from unicode string") file = _io.BytesIO(s) return Unpickler(file, fix_imports=fix_imports, buffers=buffers, encoding=encoding, errors=errors).load() @@ -500,6 +513,25 @@ def loads(s, /, *, fix_imports=True, encoding="ASCII", errors="strict", _native_dumps = _make_native_dumps( Pickler, _sys, _builtins, _pickle_py, _copyreg) del _builtins, _copyreg, _pickle_py + # Built-in `dumps` and `loads`, as CPython's are: the native engine's + # calls run no Python frame, and the rest take the functions above. + try: + from _weave_pickle import make_front as _make_front + except ImportError: + pass + else: + if _native_dumps is not None: + _front = _make_front("dumps", _native_dumps, Pickler, dumps._func, + _dumps_python) + if _front is not None: + _dumps_py, dumps = dumps, _front + if _native_loads is not None: + _front = _make_front("loads", _native_loads, Unpickler, loads._func, + _loads_python) + if _front is not None: + _loads_py, loads = loads, _front + _front = None + del _make_front, _front # Importing _pickle first initializes pickle while this module is incomplete. # Its final accelerator import then falls back. Publish the completed entry diff --git a/crates/weavepy-vm/src/stdlib/python/_seqtools.py b/crates/weavepy-vm/src/stdlib/python/_seqtools.py index 019677567..f624dc4c2 100644 --- a/crates/weavepy-vm/src/stdlib/python/_seqtools.py +++ b/crates/weavepy-vm/src/stdlib/python/_seqtools.py @@ -97,60 +97,6 @@ def __setstate__(self, state): self._index = state -class _CallableIter: - """WeavePy's equivalent of CPython's ``callable_iterator`` - (``calliterobject``): the object ``iter(callable, sentinel)`` returns. - - Each ``__next__`` calls *callable* with no arguments and yields the - result, stopping (``StopIteration``) once a result compares equal to - *sentinel*. Driving it **lazily** — one call per ``next()`` — means an - exception raised inside *callable* propagates at the right moment (so - ``for x in iter(spam, s)`` sees it mid-stream) and an unbounded source - never hangs at construction, matching CPython exactly. - """ - - __slots__ = ("_callable", "_sentinel") - - def __init__(self, callable, sentinel): - self._callable = callable - self._sentinel = sentinel - - def __iter__(self): - return self - - def __next__(self): - if self._callable is None: - raise StopIteration - # A ``StopIteration`` from the callable ends the iteration, and its - # value goes with it (CPython's ``calliter_iternext`` clears it). - stopped = False - try: - result = self._callable() - except StopIteration: - stopped = True - if stopped: - self._callable = None - raise StopIteration - # gh-101892: the call may have re-entered and exhausted us; if so, - # report exhaustion rather than yielding a post-sentinel value. - if self._callable is None: - raise StopIteration - # CPython compares ``result == sentinel`` (result's __eq__ first). - if result == self._sentinel: - self._callable = None - raise StopIteration - return result - - def __reduce__(self): - # Resolve `iter` first (it can run user code that exhausts us, - # gh-101765); an exhausted callable-iterator has dropped its - # callable and reduces to an empty `iter(())`. - _iter = _builtin_iter() - if self._callable is None: - return (_iter, ((),)) - return (_iter, (self._callable, self._sentinel)) - - class _ReversedIter: """Lazy ``reversed(seq)`` over a user sequence — CPython's ``reversedobject``. @@ -202,6 +148,13 @@ def __reduce__(self): return (reversed, (self._seq,), self._index) def __setstate__(self, state): - if state < -1: - state = -1 - self._index = state + # CPython's `reversed_setstate`: an exhausted iterator ignores the + # state; a live one clamps it to the sequence's span. + seq = self._seq + if seq is not None: + last = len(seq) - 1 + if state < -1: + state = -1 + elif state > last: + state = last + self._index = state diff --git a/crates/weavepy-vm/src/stdlib/python/_weave_envinit.py b/crates/weavepy-vm/src/stdlib/python/_weave_envinit.py index c47b4c89a..e38f2260a 100644 --- a/crates/weavepy-vm/src/stdlib/python/_weave_envinit.py +++ b/crates/weavepy-vm/src/stdlib/python/_weave_envinit.py @@ -25,6 +25,8 @@ # (test_site.test_startup_imports counts them). from _collections_abc import Mapping, MutableMapping +_MISSING = object() + class _Environ(MutableMapping): """Verbatim port of CPython's ``os._Environ``.""" @@ -47,6 +49,19 @@ def __getitem__(self, key): raise KeyError(key) from None return self.decodevalue(value) + # `Mapping.get` and `Mapping.__contains__` find a missing variable + # through `__getitem__`, raising (and catching) two `KeyError`s; a + # program asks for unset variables all the time (color and locale + # probes), so these look in the backing store directly. + def get(self, key, default=None): + value = self._data.get(self.encodekey(key), _MISSING) + if value is _MISSING: + return default + return self.decodevalue(value) + + def __contains__(self, key): + return self.encodekey(key) in self._data + def __setitem__(self, key, value): key = self.encodekey(key) value = self.encodevalue(value) diff --git a/crates/weavepy-vm/src/stdlib/python/array_mod.py b/crates/weavepy-vm/src/stdlib/python/array_mod.py index 60ca3b8b5..904b413d4 100644 --- a/crates/weavepy-vm/src/stdlib/python/array_mod.py +++ b/crates/weavepy-vm/src/stdlib/python/array_mod.py @@ -13,6 +13,8 @@ import struct as _struct import sys as _sys +import _struct as _struct_core + __all__ = ['array', 'ArrayType', 'typecodes', '_array_reconstructor'] @@ -64,19 +66,79 @@ _MISSING = object() +# What an item is, per typecode: 0 an int (within `_lo.._hi`), 1 a float, +# 2 a one-character str. The item methods test this small int instead of +# searching the typecode strings. +_KIND_INT, _KIND_FLOAT, _KIND_CHAR = 0, 1, 2 +_KINDS = {} +for _tc in _INT_TYPECODES: + _KINDS[_tc] = _KIND_INT +for _tc in _FLOAT_TYPECODES: + _KINDS[_tc] = _KIND_FLOAT +for _tc in _UNICODE_TYPECODES: + _KINDS[_tc] = _KIND_CHAR +del _tc + +_unpack_from = _struct.unpack_from +_pack_into = _struct.pack_into +_struct_pack = _struct.pack +try: + from _struct import _all_exact +except ImportError: + def _all_exact(seq, want): + for v in seq: + if type(v) is not want: + return False + return True +_struct_unpack = _struct.unpack +_struct_error = _struct.error -def _make_array(typecode): - """Internal bare constructor: no typecode re-validation and — key for - 'u' — no re-firing of the DeprecationWarning on every slice/repeat.""" - self = object.__new__(array) + +def _setup(self, typecode): fmt, size = _TYPECODES[typecode] self._typecode = typecode self._fmt = fmt self._itemsize = size + self._kind = _KINDS[typecode] + self._lo, self._hi = _INT_RANGES.get(typecode, (0, 0)) self._buf = bytearray() + + +def _make_array(typecode): + """Internal bare constructor: no typecode re-validation and — key for + 'u' — no re-firing of the DeprecationWarning on every slice/repeat.""" + self = object.__new__(array) + _setup(self, typecode) return self +def _like(src, buf): + """A new array of `src`'s type code over `buf`: its fields copied, not + looked up again (slices, sums, repeats and copies).""" + out = _object_new(array) + out._typecode = src._typecode + out._fmt = src._fmt + out._itemsize = src._itemsize + out._kind = src._kind + out._lo = src._lo + out._hi = src._hi + out._buf = buf + return out + + +_object_new = object.__new__ + + +def _values(self): + """Every stored value in one unpacking: a tuple of numbers (a unicode + array's are code points).""" + buf = self._buf + n = len(buf) // self._itemsize + if not n: + return () + return _struct_unpack('%d%s' % (n, self._fmt), buf) + + class _array_iterator: """CPython's ``arrayiterator``: index-based, so an iterator that never saw a failed ``next()`` picks up items appended later; one that raised @@ -97,9 +159,14 @@ def __next__(self): if ao is None: raise StopIteration i = self._index - if i < len(ao): + buf = ao._buf + off = i * ao._itemsize + if off < len(buf): self._index = i + 1 - return ao._unpack(i) + value = _unpack_from(ao._fmt, buf, off)[0] + if ao._kind == _KIND_CHAR: + return chr(value) + return value self._ao = None raise StopIteration @@ -125,7 +192,8 @@ class array: # CPython's array is a fixed C struct: instances have no __dict__ # (subclasses without __slots__ regain one), and typecode/itemsize # are read-only getsets. - __slots__ = ('_typecode', '_fmt', '_itemsize', '_buf', '__weakref__') + __slots__ = ('_typecode', '_fmt', '_itemsize', '_buf', '_kind', '_lo', + '_hi', '__weakref__') # The C type carries Py_TPFLAGS_SEQUENCE, so `case [..]:` patterns # match arrays (PEP 634); WeavePy's VM reads the flag off this private @@ -139,7 +207,7 @@ def __class_getitem__(cls, item): return types.GenericAlias(cls, item) - def __new__(cls, typecode=_MISSING, initializer=_MISSING, *rest, **kwargs): + def __new__(cls, typecode=_MISSING, initializer=_MISSING, /, *rest, **kwargs): if typecode is _MISSING: raise TypeError( "array() takes at least 1 argument (0 given)" @@ -151,7 +219,7 @@ def __new__(cls, typecode=_MISSING, initializer=_MISSING, *rest, **kwargs): # CPython rejects keywords only for the exact base type; subclasses # route extra keywords to their own __init__ (SF bug #1486663). if kwargs and cls is array: - raise TypeError("array() takes no keyword arguments") + raise TypeError("array.array() takes no keyword arguments") if not isinstance(typecode, str) or len(typecode) != 1: raise TypeError( "array() argument 1 must be a unicode character, not %s" @@ -171,11 +239,7 @@ def __new__(cls, typecode=_MISSING, initializer=_MISSING, *rest, **kwargs): stacklevel=2, ) self = object.__new__(cls) - fmt, size = _TYPECODES[typecode] - self._typecode = typecode - self._fmt = fmt - self._itemsize = size - self._buf = bytearray() + _setup(self, typecode) if initializer is _MISSING: return self if typecode in _UNICODE_TYPECODES: @@ -210,6 +274,9 @@ def __new__(cls, typecode=_MISSING, initializer=_MISSING, *rest, **kwargs): else: for v in initializer: self.append(v) + elif type(initializer) is list: + # (Packed at once when every item is plain.) + self.fromlist(initializer) else: for item in initializer: self.append(item) @@ -314,6 +381,22 @@ def _normalize_index(self, index): # -- mutating sequence API ------------------------------------------ def append(self, value): + # A plain int in range, or a float, packs directly; anything else + # (and any value the packing refuses) takes the full conversion, + # which raises what CPython's setters raise. + kind = self._kind + if kind == _KIND_INT: + if type(value) is int and self._lo <= value <= self._hi: + self._buf += _struct_pack(self._fmt, value) + return + elif kind == _KIND_FLOAT and type(value) is float: + try: + packed = _struct_pack(self._fmt, value) + except (OverflowError, _struct_error): + packed = None + if packed is not None: + self._buf += packed + return self._buf += self._pack(value) def extend(self, iterable): @@ -359,11 +442,16 @@ def clear(self): del self._buf[:] def reverse(self): - n = len(self) + buf = self._buf size = self._itemsize - items = [bytes(self._buf[i * size:(i + 1) * size]) for i in range(n)] - items.reverse() - self._buf[:] = b''.join(items) + if size == 1: + buf.reverse() + return + # (The items as whole chunks, last first, written back in place.) + self._buf[:] = b''.join( + [bytes(buf[off:off + size]) + for off in range(len(buf) - size, -1, -size)] + ) def byteswap(self): # Reverse the byte order of every item in place. CPython supports this @@ -382,7 +470,7 @@ def byteswap(self): # -- non-mutating queries ------------------------------------------- def count(self, value): - return sum(1 for v in self if v == value) + return self.tolist().count(value) def index(self, value, *args): # Support optional start/stop like list.index. @@ -398,13 +486,16 @@ def index(self, value, *args): if stop < 0: stop += n stop = min(stop, n) - for i in range(start, stop): - if self._unpack(i) == value: - return i - raise ValueError('array.index(x): x not in array') + try: + return self.tolist().index(value, start, max(stop, 0)) + except ValueError: + raise ValueError('array.index(x): x not in array') from None def tolist(self): - return [self._unpack(i) for i in range(len(self))] + values = _values(self) + if self._kind == _KIND_CHAR: + return [chr(v) for v in values] + return list(values) def buffer_info(self): # CPython returns the real data pointer — ctypes tests build @@ -437,6 +528,19 @@ def tobytes(self): def fromlist(self, seq): if not isinstance(seq, list): raise TypeError('arg must be list') + # Plain ints (or floats) pack in one call; an item of another type + # or out of range leaves the list to the item-by-item conversion + # below, which raises what CPython's setters raise. + n = len(seq) + want = int if self._kind == _KIND_INT else float + if n and self._kind != _KIND_CHAR and _all_exact(seq, want): + try: + packed = _struct_pack('%d%s' % (n, self._fmt), *seq) + except (OverflowError, _struct_error): + packed = None + if packed is not None: + self._buf += packed + return # All-or-nothing: pack into a scratch buffer first. scratch = bytearray() for v in seq: @@ -504,25 +608,63 @@ def __iter__(self): return _array_iterator(self) def __getitem__(self, key): + if type(key) is int: + buf = self._buf + size = self._itemsize + n = len(buf) // size + if key < 0: + key += n + if 0 <= key < n: + value = _unpack_from(self._fmt, buf, key * size)[0] + if self._kind == _KIND_CHAR: + return chr(value) + return value + raise IndexError('array index out of range') if isinstance(key, slice): - out = _make_array(self._typecode) - indices = range(*key.indices(len(self))) size = self._itemsize + buf = self._buf + start, stop, step = key.indices(len(buf) // size) + if step == 1: + # (A run of items is a run of bytes.) + return _like(self, buf[start * size:stop * size] if stop > start else bytearray()) chunks = [] - for i in indices: - chunks.append(bytes(self._buf[i * size:(i + 1) * size])) - out._buf = bytearray(b''.join(chunks)) - return out + for i in range(start, stop, step): + chunks.append(bytes(buf[i * size:(i + 1) * size])) + return _like(self, bytearray(b''.join(chunks))) return self._unpack(self._normalize_index(key)) def __setitem__(self, key, value): size = self._itemsize - if isinstance(key, slice): + if type(key) is int: + # A plain int in range, or a float, is written where it goes; + # anything else takes the full conversion below. + kind = self._kind + if (type(value) is int and kind == _KIND_INT + and self._lo <= value <= self._hi) or ( + type(value) is float and kind == _KIND_FLOAT): + buf = self._buf + n = len(buf) // size + index = key + n if key < 0 else key + if 0 <= index < n: + try: + _pack_into(self._fmt, buf, index * size, value) + return + except (OverflowError, _struct_error): + pass + elif isinstance(key, slice): start, stop, step = key.indices(len(self)) - indices = list(range(start, stop, step)) if isinstance(value, array): if value._typecode != self._typecode: raise TypeError("bad argument type for built-in operation") + if step == 1: + # (A run of items is a run of bytes; a bytearray + # stored into itself is copied first.) + lo = start * size + hi = max(stop, start) * size + self._buf[lo:hi] = value._buf + return + indices = list(range(start, stop, step)) + if isinstance(value, array): packed = [bytes(value._buf[i * size:(i + 1) * size]) for i in range(len(value))] else: @@ -551,7 +693,13 @@ def __setitem__(self, key, value): def __delitem__(self, key): size = self._itemsize if isinstance(key, slice): - indices = list(range(*key.indices(len(self)))) + start, stop, step = key.indices(len(self)) + if step == 1: + # (A run of items is a run of bytes.) + if stop > start: + del self._buf[start * size:stop * size] + return + indices = list(range(start, stop, step)) for i in sorted(indices, reverse=True): del self._buf[i * size:(i + 1) * size] return @@ -559,18 +707,13 @@ def __delitem__(self, key): del self._buf[index * size:(index + 1) * size] def __contains__(self, value): - for v in self: - if v == value: - return True - return False + return value in self.tolist() def __add__(self, other): if not isinstance(other, array) or other._typecode != self._typecode: raise TypeError("can only append array (not \"%s\") to array" % type(other).__name__) - out = _make_array(self._typecode) - out._buf = bytearray(self._buf) + other._buf - return out + return _like(self, bytearray(self._buf) + other._buf) def __iadd__(self, other): if not isinstance(other, array) or other._typecode != self._typecode: @@ -672,9 +815,7 @@ def __reduce_ex__(self, protocol): return (type(self), (self._typecode, initializer), state) def __copy__(self): - out = _make_array(self._typecode) - out._buf = bytearray(self._buf) - return out + return _like(self, bytearray(self._buf)) def __deepcopy__(self, memo): return self.__copy__() @@ -774,3 +915,12 @@ def _array_reconstructor(arraytype, typecode, mformat_code, items): del _MutableSequence except ImportError: pass + + +# The item methods and the iterator's step are served natively for plain +# indexes and values (CPython's array is a C type); each calls the method +# above that it replaces for everything else. +if hasattr(_struct_core, '_array_methods'): + for _owner, _name, _method in _struct_core._array_methods(array, _array_iterator): + setattr(_owner, _name, _method) + del _owner, _name, _method diff --git a/crates/weavepy-vm/src/stdlib/python/asyncio/events.py b/crates/weavepy-vm/src/stdlib/python/asyncio/events.py index 6347b53c5..fe67ff859 100644 --- a/crates/weavepy-vm/src/stdlib/python/asyncio/events.py +++ b/crates/weavepy-vm/src/stdlib/python/asyncio/events.py @@ -905,5 +905,5 @@ def _handle_run_failed(self, exc): except ImportError: pass else: - _weave_asyncio.install_handle(Handle, _handle_run_failed) + _weave_asyncio.install_handle(Handle, _handle_run_failed, TimerHandle) del _weave_asyncio diff --git a/crates/weavepy-vm/src/stdlib/python/codecs.py b/crates/weavepy-vm/src/stdlib/python/codecs.py index b3656c977..a2a9e36a4 100644 --- a/crates/weavepy-vm/src/stdlib/python/codecs.py +++ b/crates/weavepy-vm/src/stdlib/python/codecs.py @@ -1741,8 +1741,27 @@ def _euc_jis_2004_codecinfo(name="euc_jis_2004"): # relies on `TextIOWrapper`'s internal re-lookup seeing the change. _CODEC_CACHE = {} +# The codec each spelling of a name last resolved to (the object +# `_CODEC_CACHE` holds for its normalised name), so a repeated lookup +# skips the normalisation: `'utf-8'` and `'UTF8'` are two entries for +# one codec. Emptied with `_CODEC_CACHE`, and bounded. +_LOOKUP_MEMO = {} + def lookup(encoding): + if type(encoding) is str and not _USER_CODECS: + info = _LOOKUP_MEMO.get(encoding) + if info is not None: + return info + info = _lookup(encoding) + if type(encoding) is str and not _USER_CODECS: + if len(_LOOKUP_MEMO) >= 256: + _LOOKUP_MEMO.clear() + _LOOKUP_MEMO[encoding] = info + return info + + +def _lookup(encoding): # CPython's `_codecs.lookup` receives the name as a C string (the `s` # format code), which (1) requires ``str`` and (2) rejects an embedded NUL # with ``ValueError`` before any registry lookup — so e.g. @@ -1996,6 +2015,7 @@ def unregister(search_function): # CPython clears `interp->codec_search_cache` when the function was # registered, so a stale entry it served can't survive. _CODEC_CACHE.clear() + _LOOKUP_MEMO.clear() _SEARCH_FUNCS = [] diff --git a/crates/weavepy-vm/src/stdlib/python/collections.py b/crates/weavepy-vm/src/stdlib/python/collections.py index 157371410..58a510c48 100644 --- a/crates/weavepy-vm/src/stdlib/python/collections.py +++ b/crates/weavepy-vm/src/stdlib/python/collections.py @@ -61,6 +61,11 @@ heapq = None # Lazily imported +try: + from _weave_collections import _most_common_plain +except ImportError: + _most_common_plain = None + ################################################################################ ### OrderedDict @@ -667,6 +672,12 @@ def most_common(self, n=None): if n is None: return sorted(self.items(), key=_itemgetter(1), reverse=True) + # Plain int counts, natively (in `nlargest`'s order). + if type(self) is Counter and type(n) is int and _most_common_plain is not None: + r = _most_common_plain(self, n) + if r is not None: + return r + # Lazy import to speedup Python startup time global heapq if heapq is None: diff --git a/crates/weavepy-vm/src/stdlib/python/copy_mod.py b/crates/weavepy-vm/src/stdlib/python/copy_mod.py index 62d5e2ac8..b46bb6b9e 100644 --- a/crates/weavepy-vm/src/stdlib/python/copy_mod.py +++ b/crates/weavepy-vm/src/stdlib/python/copy_mod.py @@ -53,6 +53,11 @@ class instances). import weakref from copyreg import dispatch_table +try: + from _weave_collections import _deepcopy_plain +except ImportError: + _deepcopy_plain = None + class Error(Exception): pass error = Error # backward compatibility @@ -118,6 +123,13 @@ def deepcopy(x, memo=None, _nil=[]): if cls in _atomic_types: return x + # A tree of plain dicts, lists and tuples over atoms, copied natively + # as the table below copies it (anything else comes back None). + if memo is None and (cls is dict or cls is list or cls is tuple) and _deepcopy_plain is not None: + y = _deepcopy_plain(x) + if y is not None: + return y + d = id(x) if memo is None: memo = {} diff --git a/crates/weavepy-vm/src/stdlib/python/dataclasses.py b/crates/weavepy-vm/src/stdlib/python/dataclasses.py index 242a6d2ff..0f157435b 100644 --- a/crates/weavepy-vm/src/stdlib/python/dataclasses.py +++ b/crates/weavepy-vm/src/stdlib/python/dataclasses.py @@ -9,6 +9,11 @@ import abc from reprlib import recursive_repr +try: + from _weave_collections import _asdict_plain +except ImportError: + _asdict_plain = None + __all__ = ['dataclass', 'field', @@ -1502,6 +1507,12 @@ class C: """ if not _is_dataclass_instance(obj): raise TypeError("asdict() should be called on dataclass instances") + # (A tree of plain values copies natively; anything else, or a hook + # watching, is the Python copy's.) + if dict_factory is dict and _asdict_plain is not None: + result = _asdict_plain(obj, _FIELD) + if result is not None: + return result return _asdict_inner(obj, dict_factory) diff --git a/crates/weavepy-vm/src/stdlib/python/functools.py b/crates/weavepy-vm/src/stdlib/python/functools.py index 8afbc690f..141625094 100644 --- a/crates/weavepy-vm/src/stdlib/python/functools.py +++ b/crates/weavepy-vm/src/stdlib/python/functools.py @@ -32,6 +32,11 @@ WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__', '__annotate__', '__type_params__') WRAPPER_UPDATES = ('__dict__',) +try: + from _functools import _update_wrapper_plain +except ImportError: + def _update_wrapper_plain(wrapper, wrapped): + return None def update_wrapper(wrapper, wrapped, assigned = WRAPPER_ASSIGNMENTS, @@ -47,6 +52,11 @@ def update_wrapper(wrapper, are updated with the corresponding attribute from the wrapped function (defaults to functools.WRAPPER_UPDATES) """ + # (Two plain functions and the default lists: the same steps, native.) + if assigned is WRAPPER_ASSIGNMENTS and updated is WRAPPER_UPDATES: + done = _update_wrapper_plain(wrapper, wrapped) + if done is not None: + return done for attr in assigned: try: value = getattr(wrapped, attr) @@ -224,6 +234,46 @@ def __ge__(self, other): cmp_to_key = _cmp_to_key_py + +# WeavePy: the native `cmp_to_key` (CPython's is C) returns one of these +# instead of a class made per call: a callable `key(obj)` whose results +# compare through the wrapped `mycmp`. Making a class for every +# `sorted(xs, key=cmp_to_key(f))` cost far more than the sort. +class _CmpKey: + __slots__ = ('obj', '_mycmp') + __hash__ = None + __weave_immutable_type__ = True + + def __lt__(self, other): + return self._mycmp(self.obj, other.obj) < 0 + + def __gt__(self, other): + return self._mycmp(self.obj, other.obj) > 0 + + def __eq__(self, other): + return self._mycmp(self.obj, other.obj) == 0 + + def __le__(self, other): + return self._mycmp(self.obj, other.obj) <= 0 + + def __ge__(self, other): + return self._mycmp(self.obj, other.obj) >= 0 + + +class _CmpToKey: + __slots__ = ('_mycmp',) + __weave_immutable_type__ = True + + def __init__(self, mycmp): + self._mycmp = mycmp + + def __call__(self, obj): + key = _CmpKey.__new__(_CmpKey) + key.obj = obj + key._mycmp = self._mycmp + return key + + try: # The native version is a non-binding builtin (CPython's is a C # function); it calls back into `_cmp_to_key_py` for the K class. diff --git a/crates/weavepy-vm/src/stdlib/python/itertools.py b/crates/weavepy-vm/src/stdlib/python/itertools.py index 2103fa27c..e347b1718 100644 --- a/crates/weavepy-vm/src/stdlib/python/itertools.py +++ b/crates/weavepy-vm/src/stdlib/python/itertools.py @@ -120,6 +120,7 @@ def _is_iterator(obj): _islice_core = _n.islice_core _repeat_core = _n.repeat_core _tee_core = _n.tee_core + _tee_native = getattr(_n, "tee_native", None) _count_core = _n.count_core _cycle_core = _n.cycle_core _chain_core = _n.chain_core @@ -769,7 +770,7 @@ def __new__(cls, start=0, step=1): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -810,7 +811,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -890,7 +891,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -963,7 +964,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1019,7 +1020,7 @@ def from_iterable(cls, iterable): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1116,7 +1117,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1147,7 +1148,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1179,7 +1180,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1211,7 +1212,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1238,7 +1239,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1508,7 +1509,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1544,7 +1545,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1578,7 +1579,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1624,7 +1625,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1719,7 +1720,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1797,7 +1798,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1888,7 +1889,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -1972,7 +1973,7 @@ def __new__(cls, *args, **kwargs): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -2026,7 +2027,7 @@ def _from_data(cls, data, index): return self def __iter__(self): - return self._core + return self def __next__(self): return next(self._core) @@ -2056,9 +2057,35 @@ def __setstate__(self, state): if _HAVE_NATIVE and hasattr(_n, "_register_types"): _n._register_types(globals()) +# A native `__next__` for the classes whose own is `next(self._core)` (the +# pure-Python fallbacks keep theirs): no Python frame per step, as +# CPython's C types (`c.__next__()` of a count, as `threading` names its +# threads). +if _HAVE_NATIVE and hasattr(_n, "_core_next"): + for _name in ("count", "cycle", "repeat", "accumulate", "chain", "compress", + "dropwhile", "takewhile", "filterfalse", "starmap", "groupby", + "_grouper", "islice", "pairwise", "zip_longest", "product", + "permutations", "combinations", "combinations_with_replacement", + "batched", "_tee"): + _cls = globals().get(_name) + _f = getattr(_cls, "__dict__", {}).get("__next__") + _c = getattr(_f, "__code__", None) + if _c is not None and _c.co_names == ("next", "_core"): + _cls.__next__ = _n._core_next + del _name, _cls, _f, _c + # (`_tee` instances are their own iterators, natively.) + if hasattr(_n, "_iter_self"): + _tee.__iter__ = _n._iter_self + def tee(iterable, n=2): """tee(iterable, n=2) --> tuple of n independent iterators.""" + # (Branches over a fresh shared buffer, built natively; a tee's own + # copies and any other shape are made below.) + if _HAVE_NATIVE and _tee_native is not None: + result = _tee_native(iterable, n, _tee, _tee_dataobject) + if result is not None: + return result n = _as_int(n) if n < 0: raise ValueError("n must be >= 0") diff --git a/crates/weavepy-vm/src/stdlib/python/logging/__init__.py b/crates/weavepy-vm/src/stdlib/python/logging/__init__.py index 6e7606269..d5f235b64 100644 --- a/crates/weavepy-vm/src/stdlib/python/logging/__init__.py +++ b/crates/weavepy-vm/src/stdlib/python/logging/__init__.py @@ -2002,6 +2002,18 @@ def __repr__(self): Logger.root = root Logger.manager = Manager(Logger.root) +# Native level methods: a call a disabled level would drop returns at once +# (see `_weave_collections._log_methods`); everything else is the method +# above. +try: + from _weave_collections import _log_methods +except ImportError: + pass +else: + for _name, _method in _log_methods(Logger): + setattr(Logger, _name, _method) + del _name, _method, _log_methods + #--------------------------------------------------------------------------- # Configuration classes and functions #--------------------------------------------------------------------------- diff --git a/crates/weavepy-vm/src/stdlib/python/posix_mod.py b/crates/weavepy-vm/src/stdlib/python/posix_mod.py index 25d60693c..7b7a31412 100644 --- a/crates/weavepy-vm/src/stdlib/python/posix_mod.py +++ b/crates/weavepy-vm/src/stdlib/python/posix_mod.py @@ -17,10 +17,11 @@ # Re-export every name the underlying ``os`` module advertises so that # code written against CPython's ``posix`` finds what it expects. _names = [] +_globals = globals() for _name in dir(_os): if _name.startswith("_"): continue - globals()[_name] = getattr(_os, _name) + _globals[_name] = getattr(_os, _name) _names.append(_name) @@ -85,9 +86,10 @@ def _fail(*_a, **_kw): "execv", "execve", "execvp", "execvpe", "spawnv", "spawnvp", "spawnvpe", "spawnve", "kill", "killpg", "setsid", "setpgid", "tcgetpgrp", "tcsetpgrp"): - if _candidate not in globals(): - globals()[_candidate] = _missing(_candidate) + if _candidate not in _globals: + _globals[_candidate] = _missing(_candidate) _names.append(_candidate) +del _globals # CPython's ``posix.environ`` is a plain ``dict`` with *bytes* keys and values diff --git a/crates/weavepy-vm/src/stdlib/python/random_mod.py b/crates/weavepy-vm/src/stdlib/python/random_mod.py index 0e6a183d1..010375c85 100644 --- a/crates/weavepy-vm/src/stdlib/python/random_mod.py +++ b/crates/weavepy-vm/src/stdlib/python/random_mod.py @@ -938,6 +938,15 @@ def _notimplemented(self, *args, **kwds): # for most programs and is easier for the casual user than making them # instantiate their own Random() instance. +# Native integer methods for this class itself (see `_random._int_methods`). +try: + for _name, _method in _random._int_methods(Random): + setattr(Random, _name, _method) + _random._seal_int_methods(Random) + del _name, _method +except AttributeError: + pass + _inst = Random() seed = _inst.seed random = _inst.random diff --git a/crates/weavepy-vm/src/stdlib/python/re_parser.py b/crates/weavepy-vm/src/stdlib/python/re_parser.py index 35ab7ede2..f310a39aa 100644 --- a/crates/weavepy-vm/src/stdlib/python/re_parser.py +++ b/crates/weavepy-vm/src/stdlib/python/re_parser.py @@ -169,6 +169,9 @@ def __getitem__(self, index): if isinstance(index, slice): return SubPattern(self.state, self.data[index]) return self.data[index] + def __iter__(self): + # (The item sequence `__getitem__` reads, without a call per item.) + return iter(self.data) def __setitem__(self, index, code): self.data[index] = code def insert(self, index, code): diff --git a/crates/weavepy-vm/src/stdlib/python/struct.py b/crates/weavepy-vm/src/stdlib/python/struct.py index 6897c12a9..97918f3e5 100644 --- a/crates/weavepy-vm/src/stdlib/python/struct.py +++ b/crates/weavepy-vm/src/stdlib/python/struct.py @@ -97,8 +97,11 @@ def _readable(buffer): buffer-protocol object here, and this is the slice of that protocol we can reach from the frozen wrapper (test_struct.test_unpack_with_buffer). """ - if isinstance(buffer, (bytes, bytearray, memoryview)): + if type(buffer) in (bytes, bytearray, memoryview): return buffer + # (A subclass instance's bytes through a view, which the core reads.) + if isinstance(buffer, (bytes, bytearray, memoryview)): + return memoryview(buffer) tobytes = getattr(buffer, "tobytes", None) if callable(tobytes): return tobytes() @@ -120,18 +123,34 @@ def calcsize(format, /): raise error(str(e)) from None +def _format_error(e, buffer): + """The `struct.error` for the core's `ValueError` `e`, unless `buffer` + is a released view: that refusal is the view's own `ValueError`.""" + if isinstance(buffer, memoryview): + try: + buffer.nbytes + except ValueError: + return e + return error(str(e)) + + def unpack(format, buffer, /): try: + # (`bytes`, the common buffer, goes straight to the core.) + if type(buffer) is bytes: + return _impl.unpack(format, buffer) return _impl.unpack(format, _readable(buffer)) except ValueError as e: - raise error(str(e)) from None + raise _format_error(e, buffer) from None def unpack_from(format, /, buffer, offset=0): try: + if type(buffer) is bytes: + return _impl.unpack_from(format, buffer, offset) return _impl.unpack_from(format, _readable(buffer), offset) except ValueError as e: - raise error(str(e)) from None + raise _format_error(e, buffer) from None def pack(format, /, *v): @@ -147,6 +166,19 @@ def pack(format, /, *v): raise error(str(e)) from None +# The public `pack` packs plain values natively and calls the function +# above for anything else (coercions, and every error). +pack = _impl._native_pack(pack) + +# Likewise `unpack`: a `bytes` buffer is read natively; anything else +# (another buffer, every error) goes through the function above. +unpack = _impl._native_unpack(unpack) + +# And `unpack_from`: a `bytes`, `bytearray` or `memoryview` buffer with a +# plain offset is read where its bytes are. +unpack_from = _impl._native_unpack_from(unpack_from) + + def _writable(buffer): """Resolve `buffer` to a read-write target the Rust core can pack into. @@ -191,6 +223,11 @@ def pack_into(format, buffer, offset, /, *v): raise error(str(e)) from None +# `pack_into` writes plain numbers into a `bytearray` or a writable +# `memoryview` natively; anything else goes through the function above. +pack_into = _impl._native_pack_into(pack_into) + + class unpack_iterator: """Iterator returned by `iter_unpack` / `Struct.iter_unpack`. @@ -211,6 +248,8 @@ def __iter__(self): def __next__(self): if self._offset >= self._len: + # (The buffer's export ends with the iteration.) + self._buffer = b"" raise StopIteration result = unpack_from(self._fmt, self._buffer, self._offset) self._offset += self._size @@ -220,6 +259,14 @@ def __length_hint__(self): return (self._len - self._offset) // self._size +# The iterator's step, and its end, are native (CPython's is a C type); +# anything unusual is the method above. +if hasattr(_impl, "_unpack_iterator_methods"): + for _owner, _name, _method in _impl._unpack_iterator_methods(unpack_iterator): + setattr(_owner, _name, _method) + del _owner, _name, _method + + def _make_unpack_iterator(fmt, buffer, size): # CPython validates the buffer length up front (a `struct.error` is # raised by `iter_unpack` itself, not lazily on the first `next()`), @@ -227,11 +274,22 @@ def _make_unpack_iterator(fmt, buffer, size): if size == 0: raise error("cannot iteratively unpack with a struct of length 0") buffer = _readable(buffer) + # (A non-buffer, `str` above all, is refused here, as CPython's + # `iter_unpack` refuses it, not at the first step.) + if not isinstance(buffer, (bytes, bytearray, memoryview)): + raise TypeError( + f"a bytes-like object is required, not '{type(buffer).__name__}'" + ) if len(buffer) % size != 0: raise error( "iterative unpacking requires a buffer of a multiple of " f"{size} bytes" ) + # A `bytearray` is held through a view, an export that keeps it from + # being resized until the iteration ends, as CPython's iterator holds + # its buffer. + if type(buffer) is bytearray: + buffer = memoryview(buffer) # Bypass the guard `__new__` to build the (otherwise unconstructable) # iterator, exactly as the C type does internally. it = object.__new__(unpack_iterator) @@ -248,6 +306,12 @@ def iter_unpack(format, buffer, /): return _make_unpack_iterator(format, buffer, calcsize(format)) +# A `bytes` or `bytearray` buffer's iterator is built natively; anything +# else is the function above. +if hasattr(_impl, "_native_iter_unpack"): + iter_unpack = _impl._native_iter_unpack(iter_unpack, unpack_iterator) + + def _clearcache(): """Clear the internal format cache. diff --git a/crates/weavepy-vm/src/stdlib/python/threading.py b/crates/weavepy-vm/src/stdlib/python/threading.py index b86f57925..7ce7c0b44 100644 --- a/crates/weavepy-vm/src/stdlib/python/threading.py +++ b/crates/weavepy-vm/src/stdlib/python/threading.py @@ -147,6 +147,10 @@ def RLock(*args, **kwargs): ) if _CRLock is None: return _PyRLock(*args, **kwargs) + # WeavePy: a plain call when there's nothing to forward (forwarding an + # empty `*args, **kwargs` cost several times the lock). + if not args and not kwargs: + return _CRLock() return _CRLock(*args, **kwargs) class _RLock: diff --git a/crates/weavepy-vm/src/stdlib/python/weakref.py b/crates/weavepy-vm/src/stdlib/python/weakref.py index 94e427814..b7b0bbc0a 100644 --- a/crates/weavepy-vm/src/stdlib/python/weakref.py +++ b/crates/weavepy-vm/src/stdlib/python/weakref.py @@ -572,3 +572,17 @@ def _exitfunc(cls): finalize._shutdown = True if reenable_gc: gc.enable() + + +# The plain lookups of the weak tables (a class or a plain instance as the +# key, compared by identity) are served natively, as CPython's are dict +# and set operations on `ref` keys in C; each falls back to the Python +# method above for any other key. +try: + from _weakref import _install_weak_tables +except ImportError: + pass +else: + _install_weak_tables(WeakKeyDictionary, WeakSet, KeyedRef, + WeakValueDictionary) + del _install_weak_tables diff --git a/crates/weavepy-vm/src/stdlib/python/zoneinfo/__init__.py b/crates/weavepy-vm/src/stdlib/python/zoneinfo/__init__.py index 3f8c1edfb..f6e1613cd 100644 --- a/crates/weavepy-vm/src/stdlib/python/zoneinfo/__init__.py +++ b/crates/weavepy-vm/src/stdlib/python/zoneinfo/__init__.py @@ -1169,6 +1169,18 @@ def _parse_tz_delta(tz_delta): return total +# WeavePy: let the `datetime` natives read a zone's data in place (the +# role CPython's C `_zoneinfo` plays for an aware `datetime`). The classes +# above stay as they are; anything unusual about a zone, its class or its +# data runs their code. +try: + from _weave_zoneinfo import install as _install_native +except ImportError: + pass +else: + _install_native(globals()) + del _install_native + # CPython's `zoneinfo/__init__.py` prefers the C accelerator when it # imports (`from _zoneinfo import ZoneInfo`), keeping the pure class as # the fallback. `test.support.import_fresh_module("zoneinfo", diff --git a/crates/weavepy-vm/src/stdlib/queue_native.rs b/crates/weavepy-vm/src/stdlib/queue_native.rs index 6925b5900..48613a9da 100644 --- a/crates/weavepy-vm/src/stdlib/queue_native.rs +++ b/crates/weavepy-vm/src/stdlib/queue_native.rs @@ -30,16 +30,43 @@ use crate::stdlib::collections_native as deque; fn field( interp: &mut crate::Interpreter, recv: &Object, - name: &str, + name: &'static str, ) -> Result { if let Object::Instance(inst) = recv { - if let Some(v) = inst.attr_get_str(name) { + let found = match field_name(name) { + // (The names' hashes computed once, their positions remembered.) + Some(n) => inst.attr_get_memo(name, n.hash, &n.memo), + None => inst.attr_get_str(name), + }; + if let Some(v) = found { return Ok(v); } } interp.load_attr_public(recv, name) } +/// A queue attribute the native methods read on every call. +struct FieldName { + hash: i64, + memo: crate::inst_dict::PosMemo, +} + +/// [`FieldName`] of `_queue` or `_locked`. +fn field_name(name: &str) -> Option<&'static FieldName> { + static NAMES: std::sync::OnceLock<[FieldName; 2]> = std::sync::OnceLock::new(); + let names = NAMES.get_or_init(|| { + ["_queue", "_locked"].map(|n| FieldName { + hash: crate::object::py_str_hash(n), + memo: crate::inst_dict::PosMemo::new(), + }) + }); + match name { + "_queue" => Some(&names[0]), + "_locked" => Some(&names[1]), + _ => None, + } +} + /// `SimpleQueue.put(self, item, block=True, timeout=None)` — append to /// the deque, then open the wake gate if a `get` is parked on it /// (`simplequeue_put_locked`: `if (self->locked) { release; locked = 0 }`). diff --git a/crates/weavepy-vm/src/stdlib/random_core.rs b/crates/weavepy-vm/src/stdlib/random_core.rs index 1e5c872a7..6b1e541ea 100644 --- a/crates/weavepy-vm/src/stdlib/random_core.rs +++ b/crates/weavepy-vm/src/stdlib/random_core.rs @@ -32,6 +32,23 @@ pub fn build(_cache: &ModuleCache) -> Rc { DictKey(Object::from_static("Random")), Object::Type(random_type()), ); + for (name, f) in [ + ( + "_int_methods", + int_methods as fn(&[Object]) -> Result, + ), + ("_seal_int_methods", seal_int_methods), + ] { + d.insert( + DictKey(Object::from_static(name)), + Object::Builtin(Rc::new(BuiltinFn { + name, + binds_instance: false, + call: Box::new(f), + call_kw: None, + })), + ); + } } Rc::new(PyModule { name: "_random".to_owned(), @@ -458,6 +475,215 @@ fn random_getrandbits(args: &[Object]) -> Result { ))) } +/// The `random.Random` class whose integer methods [`int_methods`] +/// replaced, and its attribute version then. +static PY_RANDOM_CLASS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static PY_RANDOM_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// `_int_methods(Random)`: native `randint`, `randrange`, `choice` and +/// `shuffle` for +/// `random.py`'s `Random` class, as `(name, method)` pairs for the module +/// to assign. Each serves an instance of the class itself, unchanged since, +/// whose `_randbelow` and `getrandbits` are the class's, with plain int +/// arguments, by `_randbelow_with_getrandbits`'s own draws (the same +/// numbers from the same state); anything else calls the Python method it +/// replaces. +fn int_methods(args: &[Object]) -> Result { + let [Object::Type(cls)] = args else { + return Err(type_error("_int_methods() expects the Random class")); + }; + let mut out = Vec::new(); + for (name, fast) in [ + ("randint", randint_fast as crate::stdlib::struct_mod::Fast), + ("randrange", randrange_fast), + ("choice", choice_fast), + ("shuffle", shuffle_fast), + ] { + let orig = cls + .dict + .borrow() + .get(&crate::object::StrKey(name)) + .cloned() + .ok_or_else(|| type_error(format!("_int_methods(): no {name} to replace")))?; + out.push(Object::new_tuple(vec![ + Object::from_static(name), + crate::stdlib::struct_mod::fast_method(cls, name, fast, orig, false), + ])); + } + Ok(Object::new_list(out)) +} + +/// `_seal_int_methods(Random)`, once the module has assigned what +/// [`int_methods`] made: the class and its version as they now stand, +/// which the methods' native halves require. +fn seal_int_methods(args: &[Object]) -> Result { + let [Object::Type(cls)] = args else { + return Err(type_error("_seal_int_methods() expects the Random class")); + }; + PY_RANDOM_CLASS.store( + Rc::as_ptr(cls) as usize, + std::sync::atomic::Ordering::Relaxed, + ); + PY_RANDOM_VERSION.store(cls.attr_version.get(), std::sync::atomic::Ordering::Relaxed); + Ok(Object::None) +} + +/// The instance at `recv` when it is a plain `random.Random` (see +/// [`int_methods`]) and no trace or profile hook is watching. +fn plain_random(recv: &Object) -> Option<&Rc> { + let Object::Instance(inst) = recv else { + return None; + }; + let cls = inst.cls_raw(); + // (A trace or profile hook sees the Python methods' frames, as a + // debugger stepping into `randint` expects.) + if crate::trace::any_observers_active() + || std::ptr::from_ref(cls) as usize + != PY_RANDOM_CLASS.load(std::sync::atomic::Ordering::Relaxed) + || cls.attr_version.get() != PY_RANDOM_VERSION.load(std::sync::atomic::Ordering::Relaxed) + || shadowed(inst) + { + return None; + } + Some(inst) +} + +/// Whether the instance holds its own `_randbelow` or `getrandbits` (which +/// the methods would call): the names' hashes computed once, so a miss is +/// settled from the layout's filter. +fn shadowed(inst: &PyInstance) -> bool { + struct Name { + name: &'static str, + hash: i64, + memo: crate::inst_dict::PosMemo, + } + static NAMES: std::sync::OnceLock<[Name; 2]> = std::sync::OnceLock::new(); + NAMES + .get_or_init(|| { + ["_randbelow", "getrandbits"].map(|name| Name { + name, + hash: crate::object::py_str_hash(name), + memo: crate::inst_dict::PosMemo::new(), + }) + }) + .iter() + .any(|n| match inst.dict.published() { + // (A dict it can't read counts as holding the name.) + Some(d) => d.try_borrow().map_or(true, |d| { + d.get(&crate::object::StrKeyHashed { + s: n.name, + hash: n.hash, + }) + .is_some() + }), + None => inst + .dict + .split_cell() + .try_borrow() + .map_or(true, |s| s.get_memo(n.name, n.hash, &n.memo).is_some()), + }) +} + +/// `_randbelow_with_getrandbits(n)` for `0 < n < 2**63`: draws of +/// `n.bit_length()` bits, as `getrandbits` assembles them, until one is +/// below `n`. +fn randbelow(inst: &Rc, n: u64) -> u64 { + let k = 64 - n.leading_zeros(); + with_mt(inst, |mt| loop { + let r = if k <= 32 { + u64::from(mt.genrand_u32() >> (32 - k)) + } else { + let lo = u64::from(mt.genrand_u32()); + let hi = u64::from(mt.genrand_u32() >> (64 - k)); + lo | (hi << 32) + }; + if r < n { + break r; + } + }) +} + +/// A plain int argument's value (`_index` of an `int` or `bool`). +fn plain_int(o: &Object) -> Option { + match *o { + Object::Int(i) => Some(i), + Object::Bool(b) => Some(i64::from(b)), + _ => None, + } +} + +/// `randint(a, b)` of a plain `Random` (see [`int_methods`]). +fn randint_fast(args: &[Object]) -> Option> { + let [recv, a, b] = args else { + return None; + }; + let inst = plain_random(recv)?; + let (a, b) = (plain_int(a)?, plain_int(b)?); + let width = u64::try_from(b.checked_sub(a)?.checked_add(1)?).ok()?; + if width == 0 { + return None; + } + Some(Ok(Object::Int(a + randbelow(inst, width) as i64))) +} + +/// `randrange(stop)`, `randrange(start, stop)` and a step of one, of a +/// plain `Random` (see [`int_methods`]). +fn randrange_fast(args: &[Object]) -> Option> { + let (recv, start, stop) = match args { + [recv, stop] => (recv, 0, plain_int(stop)?), + [recv, start, stop] => (recv, plain_int(start)?, plain_int(stop)?), + [recv, start, stop, Object::Int(1)] => (recv, plain_int(start)?, plain_int(stop)?), + _ => return None, + }; + let inst = plain_random(recv)?; + let width = u64::try_from(stop.checked_sub(start)?).ok()?; + if width == 0 { + return None; + } + Some(Ok(Object::Int(start + randbelow(inst, width) as i64))) +} + +/// `choice(seq)` of a non-empty list or tuple, or an ASCII string, of a +/// plain `Random` (see [`int_methods`]). +fn choice_fast(args: &[Object]) -> Option> { + let [recv, seq] = args else { + return None; + }; + let inst = plain_random(recv)?; + let n = match seq { + Object::List(l) => l.try_borrow().ok()?.len(), + Object::Tuple(t) => t.len(), + Object::Str(s) if crate::shared_value::SharedStr::is_ascii(s) => s.len(), + _ => return None, + }; + if n == 0 { + return None; + } + let i = randbelow(inst, n as u64) as usize; + Some(Ok(match seq { + Object::List(l) => l.try_borrow().ok()?.get(i)?.clone(), + Object::Tuple(t) => t.get(i)?.clone(), + Object::Str(s) => Object::from_str(&s[i..=i]), + _ => return None, + })) +} + +/// `shuffle(x)` of a list, of a plain `Random` (see [`int_methods`]): +/// `random.py`'s Fisher-Yates walk from the end, each swap partner drawn as +/// `_randbelow(i + 1)` draws it. (Swapping items runs no code.) +fn shuffle_fast(args: &[Object]) -> Option> { + let [recv, Object::List(l)] = args else { + return None; + }; + let inst = plain_random(recv)?; + let mut xs = l.try_borrow_mut().ok()?; + for i in (1..xs.len()).rev() { + let j = randbelow(inst, i as u64 + 1) as usize; + xs.swap(i, j); + } + Some(Ok(Object::None)) +} + /// `getrandbits`'s leaf half: an exact `int` or `bool` count never runs /// Python code. fn getrandbits_leaf(args: &[Object]) -> Option> { diff --git a/crates/weavepy-vm/src/stdlib/select_mod.rs b/crates/weavepy-vm/src/stdlib/select_mod.rs index 707fb23bb..0794f25fe 100644 --- a/crates/weavepy-vm/src/stdlib/select_mod.rs +++ b/crates/weavepy-vm/src/stdlib/select_mod.rs @@ -629,7 +629,7 @@ static NEXT_POLL_HANDLE: std::sync::atomic::AtomicI64 = std::sync::atomic::Atomi #[cfg(unix)] thread_local! { - static POLL_CLASS: RefCell>> = const { RefCell::new(None) }; + static POLL_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } #[cfg(unix)] @@ -925,10 +925,8 @@ mod kqueue_impl { } thread_local! { - static KQUEUE_CLASS: crate::sync::RefCell>> = - const { crate::sync::RefCell::new(None) }; - static KEVENT_CLASS: crate::sync::RefCell>> = - const { crate::sync::RefCell::new(None) }; + static KQUEUE_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(crate::sync::RefCell::new(None)) }; + static KEVENT_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(crate::sync::RefCell::new(None)) }; } pub(super) fn install(d: &mut DictData) { diff --git a/crates/weavepy-vm/src/stdlib/socket_mod.rs b/crates/weavepy-vm/src/stdlib/socket_mod.rs index e002334e9..5213a7985 100644 --- a/crates/weavepy-vm/src/stdlib/socket_mod.rs +++ b/crates/weavepy-vm/src/stdlib/socket_mod.rs @@ -4894,7 +4894,7 @@ fn mod_inet_aton(args: &[Object]) -> Result { let ip: Ipv4Addr = s .parse() .map_err(|_| os_error("illegal IP address string passed to inet_aton"))?; - Ok(Object::new_bytes(ip.octets().to_vec())) + Ok(Object::new_bytes(ip.octets())) } fn mod_inet_ntoa(args: &[Object]) -> Result { @@ -4930,12 +4930,12 @@ fn mod_inet_pton(args: &[Object]) -> Result { let ip: Ipv4Addr = s .parse() .map_err(|_| os_error("illegal IP address string passed to inet_pton"))?; - Ok(Object::new_bytes(ip.octets().to_vec())) + Ok(Object::new_bytes(ip.octets())) } else if family == libc_af_inet6() as i32 { let ip: Ipv6Addr = s .parse() .map_err(|_| os_error("illegal IP address string passed to inet_pton"))?; - Ok(Object::new_bytes(ip.octets().to_vec())) + Ok(Object::new_bytes(ip.octets())) } else { Err(os_error("inet_pton: unsupported family")) } diff --git a/crates/weavepy-vm/src/stdlib/sqlite3_native/hooks.rs b/crates/weavepy-vm/src/stdlib/sqlite3_native/hooks.rs index f0fedab48..29712187e 100644 --- a/crates/weavepy-vm/src/stdlib/sqlite3_native/hooks.rs +++ b/crates/weavepy-vm/src/stdlib/sqlite3_native/hooks.rs @@ -128,7 +128,7 @@ unsafe fn build_py_params(argc: c_int, argv: *mut *mut ffi::sqlite3_value) -> Ve if p.is_null() || n == 0 { Object::new_bytes(Vec::new()) } else { - Object::new_bytes(std::slice::from_raw_parts(p, n).to_vec()) + Object::new_bytes(std::slice::from_raw_parts(p, n)) } } _ => { diff --git a/crates/weavepy-vm/src/stdlib/sre_mod.rs b/crates/weavepy-vm/src/stdlib/sre_mod.rs index 8823c6ad7..da4eeca56 100644 --- a/crates/weavepy-vm/src/stdlib/sre_mod.rs +++ b/crates/weavepy-vm/src/stdlib/sre_mod.rs @@ -778,8 +778,20 @@ fn category(chcode: u32, ch: u32) -> bool { /// A subject code unit: a byte (`bytes`, or an ASCII `str` matched over /// its UTF-8 bytes in place) or a code point. -pub(crate) trait SreChar: Copy + Into {} -impl SreChar for u8 {} +pub(crate) trait SreChar: Copy + Into { + /// Where the first unit equal to `c` is in `hay`. + #[inline] + fn find(hay: &[Self], c: u32) -> Option { + hay.iter().position(|&u| u.into() == c) + } +} +impl SreChar for u8 { + /// (Bytes: `memchr`'s word-at-a-time scan.) + #[inline] + fn find(hay: &[Self], c: u32) -> Option { + memchr::memchr(u8::try_from(c).ok()?, hay) + } +} impl SreChar for u32 {} #[inline(always)] @@ -2390,11 +2402,9 @@ impl<'a, C: SreChar> Matcher<'a, C> { let end = self.end; self.must_advance = false; while ptr < end { - while cu(self.s[ptr]) != c { - ptr += 1; - if ptr >= end { - return Ok(None); - } + match C::find(&self.s[ptr..end], c) { + Some(k) => ptr += k, + None => return Ok(None), } self.start = ptr; self.ptr = ptr + prefix_skip; @@ -2420,16 +2430,10 @@ impl<'a, C: SreChar> Matcher<'a, C> { return Ok(None); } while ptr < end { - let c = prefix[0]; - loop { - let ch = cu(self.s[ptr]); - ptr += 1; - if ch == c { - break; - } - if ptr >= end { - return Ok(None); - } + // (Past the next unit equal to the prefix's first.) + match C::find(&self.s[ptr..end], prefix[0]) { + Some(k) => ptr += k + 1, + None => return Ok(None), } if ptr >= end { return Ok(None); @@ -2653,8 +2657,7 @@ thread_local! { /// identity (and holding the source object so its pointer can't be /// reused) makes repeated matches on one immutable subject O(1) after the /// first decode. - static SUBJECT_CACHE: std::cell::RefCell>)>> = - const { std::cell::RefCell::new(None) }; + static SUBJECT_CACHE: crate::gil::ReleaseUnderGil>)>>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(None)) }; } /// Stable heap-identity key for an immutable subject. Returns `None` for @@ -2979,7 +2982,19 @@ pub fn build(_cache: &ModuleCache) -> Rc { ("_cache_get", sre_cache_get), ("_cache_put", sre_cache_put), ] { - d.insert(DictKey(Object::from_static(name)), b(name, f)); + let builtin = b(name, f); + // (`Pattern._exec`'s match, once a search: over a `str` or + // `bytes` subject it runs no Python code, and compiled code + // calls it in place.) + if name == "exec_match" { + if let Object::Builtin(bf) = &builtin { + crate::leaf_builtins::register_fast(bf, |args| { + matches!(args.get(1), Some(Object::Str(_) | Object::Bytes(_))) + .then(|| super::sre_objects::exec_match(args)) + }); + } + } + d.insert(DictKey(Object::from_static(name)), builtin); } d.insert( DictKey(Object::from_static("compile_cached")), diff --git a/crates/weavepy-vm/src/stdlib/sre_objects.rs b/crates/weavepy-vm/src/stdlib/sre_objects.rs index bab10dd82..c6145e03e 100644 --- a/crates/weavepy-vm/src/stdlib/sre_objects.rs +++ b/crates/weavepy-vm/src/stdlib/sre_objects.rs @@ -88,6 +88,8 @@ pub(crate) struct State { compile_template: Object, /// Per pattern handle, the last replacement template it expanded. templates: parking_lot::Mutex>)>>, + /// The address of the native `Pattern.__hash__` (see [`native_hash`]). + hash_fn: std::sync::OnceLock, } #[inline] @@ -126,8 +128,7 @@ fn with_interp( } fn build(cls: Rc, layout: &SharedSlice, values: Vec) -> Object { - let mut i = PyInstance::new(cls); - i.slots = RefCell::new(SlotStorage::from_layout(layout.clone(), values)); + let i = PyInstance::with_slots(cls, SlotStorage::from_layout(layout.clone(), values)); Object::Instance(Rc::new(i)) } @@ -145,9 +146,51 @@ fn fast_subject(o: &Object, cc: &CompiledCode) -> bool { } } +/// [`fast_subject`], or a `bytearray` for a bytes pattern: read in place +/// for as long as a body that runs no Python code holds it (see +/// [`with_pattern`]); its pieces are `bytes`, as CPython's are. +#[inline] +fn fast_or_buffer_subject(o: &Object, cc: &CompiledCode) -> bool { + fast_subject(o, cc) + || (cc.is_str != Some(true) + && (matches!(o, Object::ByteArray(_)) || plain_view_window(o).is_some())) +} + +/// A live, plain view of unsigned bytes (h11's and urllib3's subjects): +/// where its bytes start in its buffer, and how many it spans. +fn plain_view_window(o: &Object) -> Option<(usize, usize)> { + let Object::MemoryView(mv) = o else { + return None; + }; + (!mv.released.get() + && mv.itemsize.get() == 1 + && !mv.zero_dim.get() + && mv.shape.borrow().is_empty() + && mv.strides.borrow().is_empty() + && mv.suboffsets.borrow().is_empty() + && mv.format.borrow().as_str() == "B") + .then(|| (mv.start.get(), mv.len.get())) +} + +/// The subject a slicing body (`findall`, `split`) reads: a str +/// subclass's instance reads as its payload, its pieces exact strs as +/// CPython's slices of it are. (A body that builds match objects keeps the +/// instance, which `Match.string` returns.) +fn sliced_subject(o: &Object) -> &Object { + match o { + Object::Instance(i) => match i.native.get() { + Some(p @ Object::Str(_)) => p, + _ => o, + }, + _ => o, + } +} + fn empty_like(o: &Object) -> Object { match o { - Object::Bytes(_) => Object::new_bytes(Vec::new()), + Object::Bytes(_) | Object::ByteArray(_) | Object::MemoryView(_) => { + Object::new_bytes(Vec::new()) + } _ => Object::Str(SharedStr::from_ascii("")), } } @@ -200,6 +243,15 @@ fn subject_slice(o: &Object, a: usize, b: usize) -> Option { } Some(Object::Bytes(SharedSlice::from(&bs[a..b]))) } + // (A buffer's piece is a `bytes` of what it holds now, as + // CPython's `getslice` reads it.) + Object::ByteArray(bs) => { + let bs = bs.try_borrow().ok()?; + if b > bs.len() || a > b { + return None; + } + Some(Object::new_bytes(&bs[a..b])) + } _ => None, } } @@ -210,6 +262,12 @@ fn subject_slice(o: &Object, a: usize, b: usize) -> Option { enum Units<'a> { Narrow(&'a [u8]), Wide(Rc>), + /// A `bytearray`'s bytes (or a view's window of them, from `.1` to + /// `.2`), borrowed for the subject's life (only bodies that run no + /// Python code make one: see [`fast_or_buffer_subject`]). + Held(crate::sync::Ref<'a, Vec>, usize, usize), + /// A view's window of a `bytes` object's bytes. + Window(&'a [u8]), } /// A subject ready for matching, with cheap slicing for `str`/`bytes`. @@ -223,6 +281,27 @@ impl<'a> Subject<'a> { let units = match obj { Object::Str(s) if SharedStr::is_ascii(s) => Units::Narrow(s.as_bytes()), Object::Bytes(b) => Units::Narrow(&b[..]), + Object::ByteArray(b) => match b.try_borrow() { + Ok(held) => { + let n = held.len(); + Units::Held(held, 0, n) + } + Err(_) => Units::Wide(sre_mod::decode_subject_cached(obj)?), + }, + Object::MemoryView(mv) => match (plain_view_window(obj), &mv.buffer) { + (Some((start, n)), crate::object::MemoryViewBuffer::Bytes(b)) + if start + n <= b.len() => + { + Units::Window(&b[start..start + n]) + } + (Some((start, n)), crate::object::MemoryViewBuffer::ByteArray(b)) => { + match b.try_borrow() { + Ok(held) if start + n <= held.len() => Units::Held(held, start, start + n), + _ => Units::Wide(sre_mod::decode_subject_cached(obj)?), + } + } + _ => Units::Wide(sre_mod::decode_subject_cached(obj)?), + }, _ => Units::Wide(sre_mod::decode_subject_cached(obj)?), }; Ok(Self { obj, units }) @@ -232,6 +311,8 @@ impl<'a> Subject<'a> { match &self.units { Units::Narrow(b) => b.len(), Units::Wide(w) => w.len(), + Units::Held(_, start, end) => end - start, + Units::Window(b) => b.len(), } } @@ -248,12 +329,24 @@ impl<'a> Subject<'a> { match &self.units { Units::Narrow(b) => sre_mod::exec_found(cc, b, pos, endpos, mode, must_advance, f), Units::Wide(w) => sre_mod::exec_found(cc, &w[..], pos, endpos, mode, must_advance, f), + Units::Held(b, start, end) => { + sre_mod::exec_found(cc, &b[*start..*end], pos, endpos, mode, must_advance, f) + } + Units::Window(b) => sre_mod::exec_found(cc, b, pos, endpos, mode, must_advance, f), } } /// `[a:b]` as a new object (the subject itself for the whole range). fn slice(&self, a: usize, b: usize) -> Object { let (a, b) = (a.min(self.len()), b.min(self.len())); + // (A buffer's piece is a `bytes`, never the buffer itself.) + match &self.units { + Units::Held(held, start, _) => { + return Object::new_bytes(&held[start + a..start + b.max(a)]); + } + Units::Window(bytes) => return Object::new_bytes(&bytes[a..b.max(a)]), + _ => {} + } if a == 0 && b == self.len() { return self.obj.clone(); } @@ -306,7 +399,9 @@ enum Sink { impl Sink { fn new(subject: &Subject<'_>) -> Self { match subject.obj { - Object::Bytes(_) => Sink::Bytes(Vec::new()), + Object::Bytes(_) | Object::ByteArray(_) | Object::MemoryView(_) => { + Sink::Bytes(Vec::new()) + } _ => Sink::Str(String::new()), } } @@ -319,6 +414,10 @@ impl Sink { (Sink::Str(t), Object::Str(s), Units::Narrow(_)) => t.push_str(&s[a..b]), (Sink::Str(t), Object::Str(_), Units::Wide(w)) => push_cps(t, &w[a..b]), (Sink::Bytes(v), Object::Bytes(bs), _) => v.extend_from_slice(&bs[a..b]), + (Sink::Bytes(v), _, Units::Held(bs, start, _)) => { + v.extend_from_slice(&bs[start + a..start + b]); + } + (Sink::Bytes(v), _, Units::Window(bs)) => v.extend_from_slice(&bs[a..b]), (Sink::Parts(parts), _, _) => parts.push(subject.slice(a, b)), _ => {} } @@ -433,7 +532,7 @@ fn new_match( .match_cls .upgrade() .ok_or_else(|| type_error("re.Match is gone"))?; - let values = vec![ + let values = [ pattern.clone(), string.clone(), Object::Int(pos as i64), @@ -441,7 +540,10 @@ fn new_match( marks_tuple(found), Object::Int(found.lastindex as i64), ]; - Ok(build(cls, &st.match_layout, values)) + let slots = SlotStorage::from_layout_array(st.match_layout.clone(), values); + Ok(Object::Instance(Rc::new(PyInstance::with_slots( + cls, slots, + )))) } // --------------------------------------------------------------------- @@ -485,7 +587,7 @@ fn with_pattern( }; with_state(inst, |st| { let (cc, handle) = pattern_code(st, inst)?; - if !fast_subject(string, cc) { + if !fast_or_buffer_subject(string, cc) { return None; } Some(f(st, cc, handle)) @@ -524,6 +626,101 @@ fn pattern_exec(args: &[Object], mode: i64) -> Option Option<(Rc, Object, Object)> { + let Object::Instance(inst) = o else { + return None; + }; + with_state(inst, |st| { + let slots = inst.slots.try_borrow().ok()?; + let v = slots.values_for_layout(&st.pattern_layout)?; + Some((inst.cls(), v[1].clone(), v[2].clone())) + })? +} + +/// The hash of `inst` when it's a pattern whose class still answers +/// `__hash__` with [`pattern_hash`], computed in place: `hash((Pattern, +/// self.pattern, self.flags))` for a `str` or `bytes` pattern and `int` +/// flags. `re._compile` probes its cache with `(type(p), p, flags)` for +/// every compiled pattern a module function is handed. `None` for anything +/// else (and under free threading, whose state reads go through the class +/// cell). +pub(crate) fn native_hash(inst: &PyInstance) -> Option { + if crate::gil::free_threading_enabled() { + return None; + } + let cls = inst.cls_raw(); + let st = state_of(cls)?; + let hash_is_native = cls.memo_verdict(crate::types::Verdict::NativePatternHash, "", || { + let ours = st.hash_fn.get().copied(); + matches!( + cls.lookup("__hash__"), + Some(Object::Builtin(b)) if Some(Rc::as_ptr(&b) as usize) == ours + ) + }); + if !hash_is_native { + return None; + } + let slots = inst.slots.try_borrow().ok()?; + let v = slots.values_for_layout(&st.pattern_layout)?; + let pat = match &v[1] { + Object::Str(s) => SharedStr::hash_cached(s), + Object::Bytes(b) => { + crate::shared_value::SharedSlice::hash_cached(b, crate::object::py_hash_bytes_slice) + } + _ => return None, + }; + let Object::Int(flags) = v[2] else { + return None; + }; + let mut h = crate::object::TupleHasher::new(); + h.push(crate::object::pointer_hash(std::ptr::from_ref(cls).cast())); + h.push(pat); + h.push(crate::object::py_hash_long_i64(flags)); + Some(h.finish(3)) +} + +/// `Pattern.__hash__`: `hash((Pattern, self.pattern, self.flags))`, as the +/// Python method computes it, for a `str` or `bytes` pattern and `int` +/// flags (whose hashes run no code). +fn pattern_hash(args: &[Object]) -> Option> { + let [p] = args else { + return None; + }; + let (cls, pat, flags) = pattern_key(p)?; + if !matches!(pat, Object::Str(_) | Object::Bytes(_)) || !matches!(flags, Object::Int(_)) { + return None; + } + let key = Object::new_tuple_array([Object::Type(cls), pat, flags]); + crate::object::py_hash_value(&key).map(|h| Ok(Object::Int(h))) +} + +/// `Pattern.__eq__` of two patterns with `str` or `bytes` patterns and +/// `int` flags. +fn pattern_eq(args: &[Object]) -> Option> { + let [a, b] = args else { + return None; + }; + if a.is_same(b) { + return Some(Ok(Object::Bool(true))); + } + let ((ca, pa, fa), (cb, pb, fb)) = (pattern_key(a)?, pattern_key(b)?); + if !Rc::ptr_eq(&ca, &cb) { + return None; + } + let eq = match (&pa, &pb, &fa, &fb) { + (Object::Str(x), Object::Str(y), Object::Int(f), Object::Int(g)) => x == y && f == g, + (Object::Bytes(x), Object::Bytes(y), Object::Int(f), Object::Int(g)) => { + x[..] == y[..] && f == g + } + (Object::Str(_), Object::Bytes(_), _, _) | (Object::Bytes(_), Object::Str(_), _, _) => { + false + } + _ => return None, + }; + Some(Ok(Object::Bool(eq))) +} + fn pattern_match(args: &[Object]) -> Option> { pattern_exec(args, 1) } @@ -537,7 +734,8 @@ fn pattern_search(args: &[Object]) -> Option> { } fn pattern_findall(args: &[Object]) -> Option> { - let a = exec_args(args)?; + let mut a = exec_args(args)?; + a.string = sliced_subject(a.string); with_pattern(a.recv, a.string, |_, cc, _| { let subject = Subject::new(a.string)?; let (mut p, e) = clamp(a.pos, a.endpos, subject.len()); @@ -559,7 +757,9 @@ fn pattern_findall(args: &[Object]) -> Option> { must_advance = s == en; p = en; } - Ok(Object::new_list(out)) + let out = Object::new_list(out); + crate::gc_trace::track_built(&out); + Ok(out) }) } @@ -868,6 +1068,7 @@ fn pattern_split(args: &[Object]) -> Option> { [Object::Bool(b)] => i64::from(*b), _ => return None, }; + let string = sliced_subject(string); with_pattern(recv, string, |_, cc, _| { let subject = Subject::new(string)?; let e = subject.len(); @@ -1202,6 +1403,22 @@ struct Spec { const EXEC_PARAMS: &[&str] = &["string", "pos", "endpos"]; const SPECS: &[Spec] = &[ + Spec { + cls: 0, + name: "__hash__", + key: "Pattern.__hash__", + fast: pattern_hash, + full: None, + params: &[], + }, + Spec { + cls: 0, + name: "__eq__", + key: "Pattern.__eq__", + fast: pattern_eq, + full: None, + params: &[], + }, Spec { cls: 0, name: "match", @@ -1368,6 +1585,23 @@ fn interned(s: &str) -> SharedStr { } } +/// `cls`'s own member layout when it lays out exactly `names` in order (so +/// compiled code reads a member of an instance built natively in line, as +/// it reads one its class's `__init__` set), else a layout of `names`. +fn class_layout(cls: &TypeObject, names: &[&str]) -> SharedSlice { + if let Some(own) = cls.own_slot_layout() { + let same = own.len() == names.len() + && own + .iter() + .zip(names) + .all(|(k, n)| matches!(&k.0, Object::Str(s) if s.as_ref() == *n)); + if same { + return own.clone(); + } + } + layout(names) +} + fn layout(names: &[&str]) -> SharedSlice { names .iter() @@ -1412,12 +1646,13 @@ pub(crate) fn install(args: &[Object]) -> Result { let state = Rc::new(State { match_cls: Rc::downgrade(matchc), scanner_cls: Rc::downgrade(scanner), - pattern_layout: layout(&PATTERN_SLOTS), - match_layout: layout(&MATCH_SLOTS), - scanner_layout: layout(&SCANNER_SLOTS), + pattern_layout: class_layout(pattern, &PATTERN_SLOTS), + match_layout: class_layout(matchc, &MATCH_SLOTS), + scanner_layout: class_layout(scanner, &SCANNER_SLOTS), orig, compile_template: compile_template.clone(), templates: parking_lot::Mutex::new(HashMap::new()), + hash_fn: std::sync::OnceLock::new(), }); for cls in [pattern, matchc, scanner] { let _ = cls @@ -1444,6 +1679,9 @@ pub(crate) fn install(args: &[Object]) -> Result { call_kw, }); crate::leaf_builtins::register_fast(&b, spec.fast); + if spec.key == "Pattern.__hash__" { + let _ = state.hash_fn.set(Rc::as_ptr(&b) as usize); + } classes[spec.cls].dict.borrow_mut().insert( DictKey(Object::Str(interned(spec.name))), Object::Builtin(b), @@ -1546,6 +1784,20 @@ fn compile_cached_fast(args: &[Object]) -> Option> let [Object::Dict(cache), _, Object::Type(flag_type)] = &front[..] else { return None; }; + // A compiled pattern with no flags (`re.match(SECTCRE, key)`): `_compile` + // finds it in neither cache (they key only strings and bytes), raising + // and catching a `KeyError` on the way, and returns it as is. + if let Object::Instance(inst) = pattern { + let no_flags = match flags { + Object::Int(0) | Object::Bool(false) => true, + Object::Instance(i) if Rc::ptr_eq(&i.cls(), flag_type) => { + matches!(i.native.get(), Some(Object::Int(0))) + } + _ => false, + }; + let compiled = with_state(inst, |st| pattern_code(st, inst).is_some()) == Some(true); + return (no_flags && compiled).then(|| Ok(pattern.clone())); + } let bt = crate::builtin_types::builtin_types(); let ty = match pattern { Object::Str(_) => bt.str_.clone(), diff --git a/crates/weavepy-vm/src/stdlib/ssl_real.rs b/crates/weavepy-vm/src/stdlib/ssl_real.rs index e4ddeba4e..0e5c3fb27 100644 --- a/crates/weavepy-vm/src/stdlib/ssl_real.rs +++ b/crates/weavepy-vm/src/stdlib/ssl_real.rs @@ -2619,7 +2619,7 @@ fn ns_get_ca_certs(args: &[Object]) -> Result { .iter() .chain(c.capath_used.iter()) .filter(|c| der_is_ca(c.as_ref())) - .map(|c| Object::new_bytes(c.as_ref().to_vec())) + .map(|c| Object::new_bytes(c.as_ref())) .collect::>() })?; Ok(Object::new_list(ders)) @@ -2985,7 +2985,7 @@ fn transcript_events(stream: &[u8], direction: &str, version: i64, out: &mut Vec Object::Int(version), Object::Int(20), Object::Int(0x0101), - Object::new_bytes(body.to_vec()), + Object::new_bytes(body), ])); encrypted = true; } @@ -3003,7 +3003,7 @@ fn transcript_events(stream: &[u8], direction: &str, version: i64, out: &mut Vec Object::Int(version), Object::Int(22), Object::Int(i64::from(mtype)), - Object::new_bytes(body[j + 4..mend].to_vec()), + Object::new_bytes(&body[j + 4..mend]), ])); j = mend; } diff --git a/crates/weavepy-vm/src/stdlib/struct_mod.rs b/crates/weavepy-vm/src/stdlib/struct_mod.rs index 9432874a6..d8cc14994 100644 --- a/crates/weavepy-vm/src/stdlib/struct_mod.rs +++ b/crates/weavepy-vm/src/stdlib/struct_mod.rs @@ -79,6 +79,8 @@ struct CompiledFormat { endian: Endian, fields: Vec, size: usize, + /// How many values an unpack yields (padding none, a string one). + values: usize, } impl CompiledFormat { @@ -172,10 +174,19 @@ impl CompiledFormat { .filter(|s| *s <= MAX_STRUCT_SIZE) .ok_or_else(|| struct_error("total struct size too long"))?; } + let values = fields + .iter() + .map(|f| match f.code { + 'x' => 0, + 's' | 'p' => 1, + _ => f.count, + }) + .sum(); Ok(Self { endian, fields, size, + values, }) } @@ -278,6 +289,17 @@ impl CompiledFormat { self.unpack_from_offset(buf, 0).map(|(v, _)| v) } + /// [`Self::unpack`] as a tuple (see [`Self::unpack_tuple_at`]). + fn unpack_tuple(&self, buf: &[u8]) -> Result { + if buf.len() != self.size { + return Err(struct_error(format!( + "unpack requires a buffer of {} bytes", + self.size + ))); + } + self.unpack_tuple_at(buf, 0) + } + fn iter_unpack(&self, buf: &[u8]) -> Result>, RuntimeError> { if !buf.len().is_multiple_of(self.size) { return Err(struct_error(format!( @@ -300,16 +322,7 @@ impl CompiledFormat { buf: &[u8], start: usize, ) -> Result<(Vec, usize), RuntimeError> { - let values = self - .fields - .iter() - .map(|f| match f.code { - 'x' => 0, - 's' | 'p' => 1, - _ => f.count, - }) - .sum(); - let mut out = Vec::with_capacity(values); + let mut out = Vec::with_capacity(self.values); let mut pos = start; for f in &self.fields { match f.code { @@ -318,7 +331,7 @@ impl CompiledFormat { } 's' => { let bytes = &buf[pos..pos + f.count]; - out.push(Object::new_bytes(bytes.to_vec())); + out.push(Object::new_bytes(bytes)); pos += f.count; } 'p' => { @@ -329,7 +342,7 @@ impl CompiledFormat { let len = buf[pos] as usize; let take = len.min(f.count - 1); let bytes = &buf[pos + 1..pos + 1 + take]; - out.push(Object::new_bytes(bytes.to_vec())); + out.push(Object::new_bytes(bytes)); pos += f.count; } code => { @@ -343,6 +356,23 @@ impl CompiledFormat { } Ok((out, pos - start)) } + + /// [`Self::unpack_from_offset`]'s values as a tuple: one or two + /// numbers of a single field built in place, with no list between. + fn unpack_tuple_at(&self, buf: &[u8], start: usize) -> Result { + if let [f] = self.fields.as_slice() { + if !matches!(f.code, 'x' | 's' | 'p') && matches!(f.count, 1 | 2) { + let (a, n) = decode_one(f.code, self.endian, &buf[start..])?; + if f.count == 1 { + return Ok(Object::new_tuple_array([a])); + } + let (b, _) = decode_one(f.code, self.endian, &buf[start + n..])?; + return Ok(Object::new_tuple_array([a, b])); + } + } + self.unpack_from_offset(buf, start) + .map(|(vals, _)| Object::new_tuple(vals)) + } } /// Element size in bytes for a single repeat unit of `code`. @@ -922,6 +952,10 @@ pub fn build(_cache: &ModuleCache) -> Rc { register(&mut d, "_value_codes", b_value_codes); register(&mut d, "pack", b_pack); register(&mut d, "_pack_plain", b_pack_plain); + register(&mut d, "_native_pack", b_native_pack); + register(&mut d, "_native_unpack", b_native_unpack); + register(&mut d, "_native_unpack_from", b_native_unpack_from); + register(&mut d, "_native_pack_into", b_native_pack_into); register(&mut d, "_clearcache", b_clearcache); register(&mut d, "unpack", b_unpack); register(&mut d, "pack_into", b_pack_into); @@ -937,6 +971,10 @@ pub fn build(_cache: &ModuleCache) -> Rc { DictKey(Object::from_static("_install_struct")), Object::Builtin(install), ); + register(&mut d, "_array_methods", array_methods); + register(&mut d, "_unpack_iterator_methods", unpack_iterator_methods); + register(&mut d, "_native_iter_unpack", b_native_iter_unpack); + register(&mut d, "_all_exact", all_exact); } Rc::new(PyModule { name: "_struct".to_owned(), @@ -966,8 +1004,7 @@ fn register( thread_local! { /// Compiled formats by their text (CPython's `_struct` cache, flushed /// by `_clearcache` and bounded as CPython bounds its own). - static FORMATS: std::cell::RefCell>> = - std::cell::RefCell::new(std::collections::HashMap::new()); + static FORMATS: std::cell::RefCell>> = std::cell::RefCell::new(std::collections::HashMap::new()); } /// How many compiled formats [`FORMATS`] keeps before starting over. @@ -1004,8 +1041,7 @@ thread_local! { /// Compiled formats by the identity of a `Struct`'s format string /// (each held here, so an address names one string), most recent /// first: a `Struct` hands its methods the same string every call. - static BY_STRING: std::cell::RefCell)>> = - const { std::cell::RefCell::new(Vec::new()) }; + static BY_STRING: crate::gil::ReleaseUnderGil)>>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(Vec::new())) }; } /// How many format strings [`BY_STRING`] remembers. @@ -1045,7 +1081,17 @@ fn struct_format(recv: &Object) -> Option> { if class != STRUCT_CLASS.load(std::sync::atomic::Ordering::Relaxed) { return None; } - match inst.attr_get_str("_fmt")? { + // (The name's hash computed once, its position remembered.) + struct FmtName { + hash: i64, + memo: crate::inst_dict::PosMemo, + } + static NAME: std::sync::OnceLock = std::sync::OnceLock::new(); + let n = NAME.get_or_init(|| FmtName { + hash: crate::object::py_str_hash("_fmt"), + memo: crate::inst_dict::PosMemo::new(), + }); + match inst.attr_get_memo("_fmt", n.hash, &n.memo)? { Object::Str(fmt) => compiled_for(&fmt), _ => None, } @@ -1083,213 +1129,1892 @@ fn struct_unpack_fast(args: &[Object]) -> Option> { return None; }; let cf = struct_format(recv)?; - let vals = cf.unpack(buf).ok()?; - Some(Ok(Object::new_tuple(vals))) + Some(Ok(cf.unpack_tuple(buf).ok()?)) } -/// `_install_struct(Struct)`: serve the exact class's `pack` and -/// `unpack` natively (CPython's `Struct` is a C type), each falling back -/// to the Python method it replaces for every other shape. -fn install_struct(args: &[Object]) -> Result { - let [Object::Type(cls)] = args else { - return Err(type_error("_install_struct() expects the Struct class")); - }; - let own = |name: &str| cls.dict.borrow().get(&crate::object::StrKey(name)).cloned(); - let (Some(pack), Some(unpack)) = (own("pack"), own("unpack")) else { - return Err(type_error("_install_struct(): Struct lacks pack/unpack")); +pub(crate) type Fast = fn(&[Object]) -> Option>; + +/// A native method `name` for `cls`: it serves what `fast` takes and +/// calls the Python method `orig` (the one it replaces) for everything +/// else. With `keywords` it takes keyword arguments (for `orig`); without, +/// it is positional only, as a special method's slot is (the subscript +/// lanes take only such methods). +pub(crate) fn fast_method( + cls: &Rc, + name: &'static str, + fast: Fast, + orig: Object, + keywords: bool, +) -> Object { + // (The native keeps the class alive: its address stays its own.) + let class = cls.clone(); + let fallback = move |a: &[Object], kw: &[(String, Object)]| { + let _ = &class; + let f = orig.clone(); + let ptr = crate::vm_singletons::current_interpreter_ptr() + .ok_or_else(|| type_error("no active interpreter"))?; + // SAFETY: published by the enclosing VM frame on this thread. + unsafe { &mut *ptr }.call_object(f, a, kw) }; - type Fast = fn(&[Object]) -> Option>; - for (name, fast, orig) in [ - ("pack", struct_pack_fast as Fast, pack), - ("unpack", struct_unpack_fast as Fast, unpack), - ] { - // (The natives keep the class alive: its address stays its own.) - let class = cls.clone(); - let fallback = move |a: &[Object], kw: &[(String, Object)]| { - let _ = &class; - let f = orig.clone(); - let ptr = crate::vm_singletons::current_interpreter_ptr() - .ok_or_else(|| type_error("struct: no active interpreter"))?; - // SAFETY: published by the enclosing VM frame on this thread. - unsafe { &mut *ptr }.call_object(f, a, kw) - }; - let fallback = Rc::new(fallback); - let fallback_kw = fallback.clone(); - let b = Rc::new(BuiltinFn { - name, - binds_instance: true, - call: Box::new(move |a: &[Object]| match fast(a) { - Some(r) => r, - None => fallback(a, &[]), - }), - call_kw: Some(Box::new(move |a: &[Object], kw: &[(String, Object)]| { + let fallback = Rc::new(fallback); + let fallback_kw = fallback.clone(); + let b = Rc::new(BuiltinFn { + name, + binds_instance: true, + call: Box::new(move |a: &[Object]| match fast(a) { + Some(r) => r, + None => fallback(a, &[]), + }), + call_kw: keywords.then(|| -> KwCall { + Box::new(move |a: &[Object], kw: &[(String, Object)]| { if kw.is_empty() { if let Some(r) = fast(a) { return r; } } fallback_kw(a, kw) - })), - }); - crate::leaf_builtins::register_fast(&b, fast); + }) + }), + }); + crate::leaf_builtins::register_fast(&b, fast); + Object::Builtin(b) +} + +type KwCall = + Box Result + Send + Sync>; + +/// Put a [`fast_method`] in `cls`'s dictionary for each `(name, fast, +/// original)`. +pub(crate) fn install_fast_methods( + cls: &Rc, + methods: [(&'static str, Fast, Object); N], +) { + for (name, fast, orig) in methods { + let method = fast_method(cls, name, fast, orig, true); cls.dict .borrow_mut() - .insert(DictKey(Object::from_static(name)), Object::Builtin(b)); + .insert(DictKey(Object::from_static(name)), method); } cls.bump_attr_version(); - STRUCT_CLASS.store( - Rc::as_ptr(cls) as usize, - std::sync::atomic::Ordering::Relaxed, - ); - Ok(Object::None) } -/// `pack(fmt, *values)` when every value is one the packer reads directly -/// (a plain int, float, complex, bool, str, bytes or bytearray), else -/// `None` for the wrapper's coercing path, having done nothing. -fn b_pack_plain(args: &[Object]) -> Result { - if !args.get(1..).unwrap_or(&[]).iter().all(|v| { - matches!( - v, - Object::Int(_) - | Object::Long(_) - | Object::Bool(_) - | Object::Float(_) - | Object::Complex(_) - | Object::Str(_) - | Object::Bytes(_) - | Object::ByteArray(_) - ) - }) { - return Ok(Object::None); +// --------------------------------------------------------------------- +// `array.array` item access. The class is Python (`array_mod.py`, over a +// `bytearray` of packed items); its item methods are served here for the +// plain cases, as CPython's C type serves them, and fall back to the +// Python methods for everything else (other index and value types, every +// error). + +/// An `array.array` instance's typecode and buffer. +fn array_parts(recv: &Object) -> Option<(u8, Rc>>)> { + with_array(recv, |typecode, buf| Some((typecode, buf.clone()))) +} + +/// The slot layouts of the `array` class and its iterator class (their +/// addresses), set when `_array_methods` serves them: an instance laid out +/// over one of these has its slots at known places. +static ARRAY_LAYOUT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static ARRAY_ITER_LAYOUT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static UNPACK_ITER_LAYOUT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// The `unpack_iterator` class's address and its native `__next__`'s, set +/// when `_unpack_iterator_methods` serves them (see [`unpack_iter_items`]). +static UNPACK_ITER_CLASS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static UNPACK_ITER_NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// `inst`'s slot values when it is laid out over the layout `known` names. +fn known_slots<'a>( + inst: &crate::types::PyInstance, + slots: &'a crate::types::SlotStorage, + known: &std::sync::atomic::AtomicUsize, +) -> Option<&'a [Object]> { + let layout = inst.cls_raw().own_slot_layout()?; + if crate::shared_value::SharedSlice::word(layout) + != known.load(std::sync::atomic::Ordering::Relaxed) + { + return None; } - b_pack(args) + slots.values_for_layout(layout) } -fn fmt_arg(args: &[Object], idx: usize) -> Result { - match args.get(idx) { - Some(Object::Str(s)) => Ok(s.to_string()), - Some(Object::Bytes(b)) => Ok(String::from_utf8_lossy(b).into_owned()), - _ => Err(type_error("format must be a str or bytes-like".to_owned())), +/// `f` on an `array.array` instance's typecode and buffer, the slots read +/// in place. +fn with_array( + recv: &Object, + f: impl FnOnce(u8, &Rc>>) -> Option, +) -> Option { + let Object::Instance(inst) = recv else { + return None; + }; + let slots = inst.slots.try_borrow().ok()?; + let (code, buf) = match known_slots(inst, &slots, &ARRAY_LAYOUT) { + Some(values) => (values.first()?, values.get(3)?), + None => ( + slots.get_hinted(0, "_typecode")?, + slots.get_hinted(3, "_buf")?, + ), + }; + match (code, buf) { + (Object::Str(s), Object::ByteArray(b)) if s.len() == 1 => f(s.as_bytes()[0], b), + _ => None, } } -fn buffer_arg(o: &Object) -> Result, RuntimeError> { - o.as_bytes_view() - .ok_or_else(|| type_error("argument must be bytes-like".to_owned())) +/// The size in bytes of a numeric typecode's items (the unicode arrays, +/// whose items are characters, are the Python methods'). +fn array_item_size(typecode: u8) -> Option { + Some(match typecode { + b'b' | b'B' => 1, + b'h' | b'H' => 2, + b'i' | b'I' | b'f' => 4, + b'l' | b'L' => std::mem::size_of::(), + b'q' | b'Q' | b'd' => 8, + _ => return None, + }) } -fn b_calcsize(args: &[Object]) -> Result { - let fmt = fmt_arg(args, 0)?; - let cf = compiled(&fmt)?; - Ok(Object::Int(cf.size as i64)) +/// The item packed in `raw` (its typecode's size, native order), when it +/// is a machine int or a float. +fn array_item_read(typecode: u8, raw: &[u8]) -> Option { + let signed = |raw: &[u8]| match raw.len() { + 4 => Some(i64::from(i32::from_ne_bytes(raw.try_into().ok()?))), + 8 => Some(i64::from_ne_bytes(raw.try_into().ok()?)), + _ => None, + }; + let unsigned = |raw: &[u8]| match raw.len() { + 4 => Some(i64::from(u32::from_ne_bytes(raw.try_into().ok()?))), + // (One past the machine range is a big int: the Python method's.) + 8 => i64::try_from(u64::from_ne_bytes(raw.try_into().ok()?)).ok(), + _ => None, + }; + Some(match typecode { + b'b' => Object::Int(i64::from(raw[0] as i8)), + b'B' => Object::Int(i64::from(raw[0])), + b'h' => Object::Int(i64::from(i16::from_ne_bytes(raw.try_into().ok()?))), + b'H' => Object::Int(i64::from(u16::from_ne_bytes(raw.try_into().ok()?))), + b'i' | b'l' | b'q' => Object::Int(signed(raw)?), + b'I' | b'L' | b'Q' => Object::Int(unsigned(raw)?), + b'f' => Object::Float(f64::from(f32::from_ne_bytes(raw.try_into().ok()?))), + b'd' => Object::Float(f64::from_ne_bytes(raw.try_into().ok()?)), + _ => return None, + }) } -/// Return one format character per *value slot* the format consumes, in -/// order (`x` pad bytes contribute nothing; `s`/`p` contribute a single -/// slot; numeric codes contribute `count` slots). The frozen wrapper uses -/// this to coerce each argument through the right protocol (`__index__` -/// for integer codes, `__float__` for floats, `__bool__` for `?`) before -/// handing concrete `int`/`float`/`bool` values to the Rust packer, which -/// has no interpreter access of its own. -fn b_value_codes(args: &[Object]) -> Result { - let fmt = fmt_arg(args, 0)?; - let cf = compiled(&fmt)?; - let mut s = String::new(); - for f in &cf.fields { - match f.code { - 'x' => {} - 's' | 'p' => s.push(f.code), - c => { - for _ in 0..f.count { - s.push(c); - } +/// `value` packed as an item of `typecode` into `out`: its size, for a +/// plain `int` in the item's range or a `float` the item holds (a `float` +/// too large for an `'f'` item, like every other value, is the Python +/// method's, which converts or refuses it as CPython's setters do). +fn array_item_write(typecode: u8, value: &Object, out: &mut [u8; 8]) -> Option { + let size = array_item_size(typecode)?; + match (typecode, value) { + (b'f', Object::Float(v)) => { + let narrow = *v as f32; + if narrow.is_infinite() && v.is_finite() { + return None; + } + out[..4].copy_from_slice(&narrow.to_ne_bytes()); + } + (b'd', Object::Float(v)) => out.copy_from_slice(&v.to_ne_bytes()), + (b'b' | b'h' | b'i' | b'l' | b'q', Object::Int(v)) => { + let bits = 8 * size as u32; + if bits < 64 && !(-(1i64 << (bits - 1))..(1i64 << (bits - 1))).contains(v) { + return None; + } + out[..size].copy_from_slice(low_bytes(&v.to_ne_bytes(), size)); + } + (b'B' | b'H' | b'I' | b'L' | b'Q', Object::Int(v)) => { + let bits = 8 * size as u32; + if *v < 0 || (bits < 64 && *v >= (1i64 << bits)) { + return None; } + out[..size].copy_from_slice(low_bytes(&v.to_ne_bytes(), size)); } + _ => return None, } - Ok(Object::from_str(s)) + Some(size) } -fn b_pack(args: &[Object]) -> Result { - let fmt = fmt_arg(args, 0)?; - let cf = compiled(&fmt)?; - let bytes = cf.pack(&args[1..])?; - Ok(Object::new_bytes(bytes)) +/// The `size` low-order bytes of a native-order 64-bit value, in native +/// order. +fn low_bytes(bytes: &[u8; 8], size: usize) -> &[u8] { + if cfg!(target_endian = "big") { + &bytes[8 - size..] + } else { + &bytes[..size] + } } -fn b_unpack(args: &[Object]) -> Result { - let fmt = fmt_arg(args, 0)?; - let cf = compiled(&fmt)?; - // (A `bytes` buffer is read in place.) - let vals = match &args[1] { - Object::Bytes(b) => cf.unpack(b)?, - other => cf.unpack(&buffer_arg(other)?)?, +/// The class `_array_methods` served last (its address): slices of its own +/// instances are built natively. +static ARRAY_CLASS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The byte range `sl` names in an array of `size`-byte items holding +/// `len` bytes, for a slice with plain bounds and a step of one. +fn array_byte_run(sl: &crate::object::PySlice, len: usize, size: usize) -> Option<(usize, usize)> { + if ![&sl.start, &sl.stop, &sl.step] + .iter() + .all(|v| matches!(v, Object::None | Object::Int(_))) + { + return None; + } + let (start, stop, step, _) = crate::adjust_slice((len / size) as i64, sl).ok()?; + if step != 1 { + return None; + } + let lo = start as usize * size; + Some((lo, (stop as usize * size).max(lo))) +} + +/// The seven slot values of an instance of the `array` class itself +/// (`_typecode`, `_fmt`, `_itemsize`, `_buf`, `_kind`, `_lo`, `_hi`), read +/// in place when it is laid out over the class's layout with all of them +/// set. +fn array_values<'a>( + inst: &crate::types::PyInstance, + slots: &'a crate::types::SlotStorage, +) -> Option<&'a [Object; 7]> { + if std::ptr::from_ref(inst.cls_raw()) as usize + != ARRAY_CLASS.load(std::sync::atomic::Ordering::Relaxed) + { + return None; + } + let values: &[Object; 7] = known_slots(inst, slots, &ARRAY_LAYOUT)?.try_into().ok()?; + (!values.iter().any(|v| matches!(v, Object::Unbound))).then_some(values) +} + +/// A new instance of the `array` class with `values`' fields (see +/// [`array_values`]) over the bytes `run`, laid out as `_make_array` lays +/// one out (its slots written at once, in the class's layout). +fn array_over( + inst: &crate::types::PyInstance, + values: &[Object; 7], + run: Object, +) -> Option { + let layout = inst.cls_raw().own_slot_layout()?; + let out = [ + values[0].clone(), + values[1].clone(), + values[2].clone(), + run, + values[4].clone(), + values[5].clone(), + values[6].clone(), + ]; + Some(Object::Instance(Rc::new( + crate::types::PyInstance::with_slots( + inst.cls(), + crate::types::SlotStorage::from_layout_array(layout.clone(), out), + ), + ))) +} + +/// The numeric typecode and buffer among [`array_values`]' fields. +fn array_code_buf(values: &[Object; 7]) -> Option<(u8, &Rc>>)> { + match (&values[0], &values[3]) { + (Object::Str(code), Object::ByteArray(buf)) => match code.as_bytes() { + [typecode] if array_item_size(*typecode).is_some() => Some((*typecode, buf)), + _ => None, + }, + _ => None, + } +} + +/// `a[i:j]` of an instance of the `array` class itself: a new array over +/// a copy of the run's bytes. +fn array_slice_fast(recv: &Object, sl: &crate::object::PySlice) -> Option { + let Object::Instance(inst) = recv else { + return None; }; - Ok(Object::new_tuple(vals)) + let slots = inst.slots.try_borrow().ok()?; + let values = array_values(inst, &slots)?; + let (typecode, buf) = array_code_buf(values)?; + let size = array_item_size(typecode)?; + let run = { + let buf = buf.try_borrow().ok()?; + let (lo, hi) = array_byte_run(sl, buf.len(), size)?; + Object::new_bytearray(&buf[lo..hi]) + }; + array_over(inst, values, run) } -/// Resolve a `pack_into`/`unpack_from` byte offset, matching CPython's -/// `Py_ssize_t` coercion: ints (and `bool`) pass through, an int too big -/// for the platform word is `OverflowError`, and any non-integer is a -/// `TypeError` (test_struct.test_pack_into's bogus-offset cases). -fn ssize_offset(o: &Object) -> Result { - match o { - Object::Int(n) => Ok(*n), - Object::Bool(b) => Ok(i64::from(*b)), - Object::Long(_) => Err(overflow_error( - "Python int too large to convert to C ssize_t", - )), - other => Err(type_error(format!( - "'{}' object cannot be interpreted as an integer", - other.type_name() - ))), +/// `array(typecode)` or `array(typecode, items)` of a list of plain ints +/// or floats that the typecode holds, for a numeric typecode and the +/// `array` class itself while its `__new__` and `__init__` are the +/// module's own (a verdict kept per class version): the instance laid +/// out as `_setup` lays one out, over the packed items, as `__new__` +/// leaves it. `None` for any other call (a `'u'` or `'w'` array, which +/// may warn, another initializer, a value out of range), or while a +/// tracer or profiler would see the methods. +fn array_pure_new(cls: &Rc, args: &[Object]) -> Option { + let (code, items) = match args { + [Object::Str(code)] => (code, None), + [Object::Str(code), items @ (Object::List(_) | Object::Tuple(_))] => (code, Some(items)), + _ => return None, + }; + let [typecode] = *code.as_bytes() else { + return None; + }; + let size = array_item_size(typecode)?; + if Rc::as_ptr(cls) as usize != ARRAY_CLASS.load(std::sync::atomic::Ordering::Relaxed) + || crate::trace::any_observers_active() + { + return None; + } + let own = |name: &str| match cls.dict.borrow().get(&crate::object::StrKey(name)) { + Some(Object::Function(f)) => f.code().qualname == format!("array.{name}"), + Some(Object::StaticMethod(m)) => { + matches!(m.func(), Object::Function(f) if f.code().qualname == format!("array.{name}")) + } + _ => false, + }; + if !cls.memo_verdict(crate::types::Verdict::ArrayPlainNew, "", || { + own("__new__") && own("__init__") + }) { + return None; + } + let layout = cls.own_slot_layout()?; + if crate::shared_value::SharedSlice::word(layout) + != ARRAY_LAYOUT.load(std::sync::atomic::Ordering::Relaxed) + { + return None; + } + let mut buf = Vec::new(); + let mut pack_all = |items: &[Object]| -> Option<()> { + buf.reserve(items.len() * size); + let mut packed = [0u8; 8]; + for v in items { + let n = array_item_write(typecode, v, &mut packed)?; + buf.extend_from_slice(&packed[..n]); + } + Some(()) + }; + match items { + Some(Object::List(items)) => pack_all(&items.try_borrow().ok()?)?, + Some(Object::Tuple(items)) => pack_all(items)?, + _ => {} + } + // (`_KINDS` and `_INT_RANGES`: an int's range by width and sign.) + let (kind, lo, hi) = match typecode { + b'f' | b'd' => (1, Object::Int(0), Object::Int(0)), + _ => { + let shift = 64 - 8 * size as u32; + if typecode.is_ascii_lowercase() { + ( + 0, + Object::Int(i64::MIN >> shift), + Object::Int(i64::MAX >> shift), + ) + } else if shift == 0 { + ( + 0, + Object::Int(0), + Object::Long(Rc::new(num_bigint::BigInt::from(u64::MAX))), + ) + } else { + (0, Object::Int(0), Object::Int((1i64 << (8 * size)) - 1)) + } + } + }; + let values = [ + Object::Str(code.clone()), + Object::Str(code.clone()), + Object::Int(size as i64), + Object::new_bytearray(buf), + Object::Int(kind), + lo, + hi, + ]; + Some(Object::Instance(Rc::new( + crate::types::PyInstance::with_slots( + cls.clone(), + crate::types::SlotStorage::from_layout_array(layout.clone(), values), + ), + ))) +} + +/// `a.__copy__()` (`copy.copy(a)`) of an instance of the `array` class +/// itself with a numeric typecode: a new array over a copy of its bytes. +fn array_copy_fast(args: &[Object]) -> Option> { + let [Object::Instance(inst)] = args else { + return None; + }; + let slots = inst.slots.try_borrow().ok()?; + let values = array_values(inst, &slots)?; + let (_, buf) = array_code_buf(values)?; + let run = Object::new_bytearray(buf.try_borrow().ok()?.as_slice()); + array_over(inst, values, run).map(Ok) +} + +/// `a + b` of two instances of the `array` class itself with one numeric +/// typecode: a new array over both runs of bytes. (Anything else is the +/// Python method's, which raises for another typecode or type.) +fn array_add_fast(args: &[Object]) -> Option> { + let [Object::Instance(a), Object::Instance(b)] = args else { + return None; + }; + let (sa, sb) = (a.slots.try_borrow().ok()?, b.slots.try_borrow().ok()?); + let (va, vb) = (array_values(a, &sa)?, array_values(b, &sb)?); + let ((ca, ba), (cb, bb)) = (array_code_buf(va)?, array_code_buf(vb)?); + if ca != cb { + return None; } + let run = { + let (x, y) = (ba.try_borrow().ok()?, bb.try_borrow().ok()?); + let mut joined = Vec::with_capacity(x.len() + y.len()); + joined.extend_from_slice(&x); + joined.extend_from_slice(&y); + Object::new_bytearray(joined) + }; + array_over(a, va, run).map(Ok) } -fn b_pack_into(args: &[Object]) -> Result { - if args.len() < 3 { - return Err(type_error("pack_into() requires at least 3 arguments")); +/// The chunks still to come of an `unpack_iterator` whose class keeps its +/// own `__iter__` and native `__next__`, as stepping it to its end would +/// give them, for the containers that collect an iterable +/// (`list(struct.iter_unpack(...))`): read in one pass, the iterator left +/// at its end. `None` (the iterator untouched) for anything else. +pub(crate) fn unpack_iter_items(recv: &Object) -> Option> { + use std::sync::atomic::Ordering::Relaxed; + let Object::Instance(it) = recv else { + return None; + }; + let cls = it.cls_raw(); + if std::ptr::from_ref(cls) as usize != UNPACK_ITER_CLASS.load(Relaxed) { + return None; } - let fmt = fmt_arg(args, 0)?; - let cf = compiled(&fmt)?; - let offset = ssize_offset(&args[2])?; - let bytes = cf.pack(&args[3..])?; - match &args[1] { - Object::ByteArray(buf) => { - let mut buf = buf.borrow_mut(); - // Resolve the (possibly negative) offset against the buffer - // and bounds-check without growing it — CPython's - // `pack_into` writes in place and never resizes. - let off = resolve_buffer_offset(offset, buf.len(), cf.size, "pack_into", true)?; - buf[off..off + bytes.len()].copy_from_slice(&bytes); - Ok(Object::None) + match cls.lookup("__iter__") { + Some(Object::Function(f)) if f.code().qualname == "unpack_iterator.__iter__" => {} + _ => return None, + } + match cls.lookup("__next__") { + Some(Object::Builtin(b)) if Rc::as_ptr(&b) as usize == UNPACK_ITER_NEXT.load(Relaxed) => {} + _ => return None, + } + let layout = cls.own_slot_layout().filter(|layout| { + crate::shared_value::SharedSlice::word(layout) == UNPACK_ITER_LAYOUT.load(Relaxed) + })?; + let mut slots = it.slots.try_borrow_mut().ok()?; + let [Object::Str(fmt), buffer, _, Object::Int(offset), Object::Int(len)] = + slots.values_for_layout_mut(layout)? + else { + return None; + }; + let cf = compiled_for(fmt)?; + let (start, end) = (usize::try_from(*offset).ok()?, usize::try_from(*len).ok()?); + if cf.size == 0 { + return None; + } + let read = |buf: &[u8]| -> Option> { + if end > buf.len() { + return None; } - Object::MemoryView(mv) => { - // Writable buffer-protocol target (e.g. `memoryview(array(...))`). - if mv.readonly.get() { - return Err(type_error("cannot modify read-only memory".to_owned())); + let mut out = Vec::with_capacity(end.saturating_sub(start) / cf.size); + let mut at = start; + while at < end { + if at.checked_add(cf.size)? > buf.len() { + return None; } - let off = resolve_buffer_offset(offset, mv.len.get(), cf.size, "pack_into", true)?; - let base = mv.start.get(); - mv.buffer - .with_write(|b| b[base + off..base + off + bytes.len()].copy_from_slice(&bytes)) - .map(|()| Object::None) - .ok_or_else(|| type_error("cannot modify read-only memory".to_owned())) + out.push(cf.unpack_tuple_at(buf, at).ok()?); + at += cf.size; } - _ => Err(type_error( - "argument must be a read-write bytes-like object".to_owned(), - )), + Some(out) + }; + let items = match &*buffer { + Object::Bytes(b) => read(b)?, + Object::ByteArray(b) => read(&b.try_borrow().ok()?)?, + Object::MemoryView(mv) if !mv.released.get() && mv.is_c_contiguous() => { + mv.with_bytes(read)? + } + _ => return None, + }; + if start < end { + *offset += (items.len() * cf.size) as i64; + } + // (At its end: the buffer's export ends, as the step that finds the + // end ends it.) + if !matches!(buffer, Object::Bytes(_)) { + *buffer = Object::new_bytes(Vec::new()); } + Some(items) } -/// Resolve a `pack_into`/`unpack_from` offset against a buffer of -/// `buf_len` bytes, matching CPython's `_struct` boundary diagnostics. -/// `size` is the struct's byte size; `for_pack` toggles the -/// pack- vs unpack-flavoured messages. Returns the non-negative byte -/// offset to start at, or a `struct.error` describing the overflow. -fn resolve_buffer_offset( - offset: i64, - buf_len: usize, +/// The items of an instance of the `array` class itself (whose `__iter__` +/// is its own), as iterating it would give them, for the containers that +/// collect an iterable (`list(a)`, `tuple(a)`, `sorted(a)`). +pub(crate) fn array_items(recv: &Object) -> Option> { + if !iterates_as_array(recv) { + return None; + } + with_array(recv, |typecode, buf| { + let size = array_item_size(typecode)?; + let buf = buf.try_borrow().ok()?; + buf.chunks_exact(size) + .map(|raw| array_item_read(typecode, raw)) + .collect() + }) +} + +/// Whether `recv` is an instance of the `array` class itself whose +/// `__iter__` is its own (nothing has replaced it). +fn iterates_as_array(recv: &Object) -> bool { + let Object::Instance(inst) = recv else { + return false; + }; + if std::ptr::from_ref(inst.cls_raw()) as usize + != ARRAY_CLASS.load(std::sync::atomic::Ordering::Relaxed) + { + return false; + } + matches!( + inst.cls_raw().lookup("__iter__"), + Some(Object::Function(f)) if f.code().qualname == "array.__iter__" + ) +} + +/// `sum(a, start)` of an array of machine ints (as [`array_items`] would +/// give them) and an `int` start whose total fits a machine int: added +/// off the buffer, with no item built. `None` for anything else (a float +/// or unicode array, an item or total past the machine range). +pub(crate) fn array_int_sum(recv: &Object, start: &Object) -> Option { + let Object::Int(start) = start else { + return None; + }; + if !iterates_as_array(recv) { + return None; + } + with_array(recv, |typecode, buf| { + let size = array_item_size(typecode)?; + let buf = buf.try_borrow().ok()?; + let mut total = i128::from(*start); + for raw in buf.chunks_exact(size) { + let Object::Int(v) = array_item_read(typecode, raw)? else { + return None; + }; + total += i128::from(v); + } + Some(Object::Int(i64::try_from(total).ok()?)) + }) +} + +/// The typecode and buffer of an instance of the `array` class or of a +/// subclass of it (the methods below read the buffer itself, as +/// CPython's C methods do, whatever a subclass overrides). +fn array_instance_parts(recv: &Object) -> Option<(u8, Rc>>)> { + let Object::Instance(inst) = recv else { + return None; + }; + let array = ARRAY_CLASS.load(std::sync::atomic::Ordering::Relaxed); + let cls = inst.cls_raw(); + if std::ptr::from_ref(cls) as usize != array + && !cls + .mro + .borrow() + .iter() + .any(|t| Rc::as_ptr(t) as usize == array) + { + return None; + } + array_parts(recv) +} + +/// `on_match(i)` for each item of a numeric array equal to the plain +/// number `value`, in order, until it answers `true`. `None` (having +/// called nothing that matters) when the array or the value isn't one +/// the comparison settles natively. +fn array_matches( + recv: &Object, + value: &Object, + mut on_match: impl FnMut(usize) -> bool, +) -> Option<()> { + if !matches!(value, Object::Int(_) | Object::Float(_) | Object::Bool(_)) { + return None; + } + let (typecode, buf) = array_instance_parts(recv)?; + let size = array_item_size(typecode)?; + let buf = buf.try_borrow().ok()?; + // (A caller's answer counts only when the whole scan settles: an + // item this can't read, or compare, declines it.) + for (i, raw) in buf.chunks_exact(size).enumerate() { + let item = array_item_read(typecode, raw)?; + let equal = match (&item, value) { + (Object::Int(x), Object::Int(y)) => x == y, + (Object::Float(x), Object::Float(y)) => x == y, + _ => crate::plain_compare(&item, value, weavepy_compiler::CompareKind::Eq)?, + }; + if equal && on_match(i) { + break; + } + } + Some(()) +} + +/// The array class's native `__contains__` (its address), and the class +/// version at which the class was last found to keep it. +static ARRAY_CONTAINS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static ARRAY_CONTAINS_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// `item in a` for the membership test in compiled code: a plain number +/// in an instance of the `array` class itself, while the class keeps its +/// native `__contains__`. `None` for anything else. +pub(crate) fn array_contains_leaf( + inst: &crate::types::PyInstance, + recv: &Object, + item: &Object, +) -> Option { + use std::sync::atomic::Ordering::Relaxed; + let cls = inst.cls_raw(); + if std::ptr::from_ref(cls) as usize != ARRAY_CLASS.load(Relaxed) { + return None; + } + let ver = cls.attr_version.get(); + if ver == 0 || ver != ARRAY_CONTAINS_VER.load(Relaxed) { + let want = ARRAY_CONTAINS.load(Relaxed); + if want == 0 + || !matches!(cls.lookup("__contains__"), Some(Object::Builtin(b)) if Rc::as_ptr(&b) as usize == want) + { + return None; + } + ARRAY_CONTAINS_VER.store(ver, Relaxed); + } + let mut found = false; + array_matches(recv, item, |_| { + found = true; + true + })?; + Some(found) +} + +/// `v in a` for a plain number. +fn array_contains_fast(args: &[Object]) -> Option> { + let [recv, value] = args else { + return None; + }; + let mut found = false; + array_matches(recv, value, |_| { + found = true; + true + })?; + Some(Ok(Object::Bool(found))) +} + +/// `a.count(v)` for a plain number. +fn array_count_fast(args: &[Object]) -> Option> { + let [recv, value] = args else { + return None; + }; + let mut n = 0i64; + array_matches(recv, value, |_| { + n += 1; + false + })?; + Some(Ok(Object::Int(n))) +} + +/// The first index of the plain number `value` in `recv`. +fn array_first_index(recv: &Object, value: &Object) -> Option> { + let mut at = None; + array_matches(recv, value, |i| { + at = Some(i); + true + })?; + Some(at) +} + +/// `a.index(v)` for a plain number the array holds (a miss, and the +/// bounded forms, are the Python method's). +fn array_index_fast(args: &[Object]) -> Option> { + let [recv, value] = args else { + return None; + }; + let at = array_first_index(recv, value)??; + Some(Ok(Object::Int(at as i64))) +} + +/// The bytes `lo..hi` of an unexported array's buffer removed. +fn array_drain(buf: &Rc>>, lo: usize, hi: usize) -> Option<()> { + if crate::object::bytearray_is_exported(buf) { + return None; + } + buf.try_borrow_mut().ok()?.drain(lo..hi); + Some(()) +} + +/// `a.remove(v)` for a plain number the array holds, while no view of +/// it is exported. +fn array_remove_fast(args: &[Object]) -> Option> { + let [recv, value] = args else { + return None; + }; + let at = array_first_index(recv, value)??; + let (typecode, buf) = array_instance_parts(recv)?; + let size = array_item_size(typecode)?; + array_drain(&buf, at * size, at * size + size)?; + Some(Ok(Object::None)) +} + +/// `a.pop()` and `a.pop(i)` for a plain index in range, while no view +/// of the array is exported. +fn array_pop_fast(args: &[Object]) -> Option> { + let (recv, index) = match args { + [recv] => (recv, -1), + [recv, Object::Int(i)] => (recv, *i), + _ => return None, + }; + let (typecode, buf) = array_instance_parts(recv)?; + let size = array_item_size(typecode)?; + let (off, item) = { + let b = buf.try_borrow().ok()?; + let n = (b.len() / size) as i64; + let at = if index < 0 { index + n } else { index }; + if !(0..n).contains(&at) { + return None; + } + let off = at as usize * size; + (off, array_item_read(typecode, &b[off..off + size])?) + }; + array_drain(&buf, off, off + size)?; + Some(Ok(item)) +} + +/// `a.insert(i, v)` for a plain index and a plain value the item holds, +/// while no view of the array is exported. +fn array_insert_fast(args: &[Object]) -> Option> { + let [recv, Object::Int(index), value] = args else { + return None; + }; + let (typecode, buf) = array_instance_parts(recv)?; + let mut packed = [0u8; 8]; + let size = array_item_write(typecode, value, &mut packed)?; + if crate::object::bytearray_is_exported(&buf) { + return None; + } + let mut b = buf.try_borrow_mut().ok()?; + let n = (b.len() / size) as i64; + let at = if *index < 0 { + (*index + n).max(0) + } else { + (*index).min(n) + }; + let off = at as usize * size; + b.splice(off..off, packed[..size].iter().copied()); + Some(Ok(Object::None)) +} + +/// `del a[i]` for a plain index in range and `del a[i:j]`, while no view +/// of the array is exported. +fn array_delitem_fast(args: &[Object]) -> Option> { + let [recv, key] = args else { + return None; + }; + let (typecode, buf) = array_instance_parts(recv)?; + let size = array_item_size(typecode)?; + let len = buf.try_borrow().ok()?.len(); + let (lo, hi) = match key { + Object::Int(i) => { + let n = (len / size) as i64; + let at = if *i < 0 { *i + n } else { *i }; + if !(0..n).contains(&at) { + return None; + } + (at as usize * size, at as usize * size + size) + } + Object::Slice(sl) => array_byte_run(sl, len, size)?, + _ => return None, + }; + array_drain(&buf, lo, hi)?; + Some(Ok(Object::None)) +} + +/// `a.extend(b)` for another array of the same typecode, while no view +/// of `a` is exported. +fn array_extend_fast(args: &[Object]) -> Option> { + let [recv, other] = args else { + return None; + }; + let (typecode, buf) = array_instance_parts(recv)?; + let (other_code, source) = array_instance_parts(other)?; + if typecode != other_code || crate::object::bytearray_is_exported(&buf) { + return None; + } + // (`a.extend(a)` reads its own bytes first.) + let data = source.try_borrow().ok()?.clone(); + buf.try_borrow_mut().ok()?.extend_from_slice(&data); + Some(Ok(Object::None)) +} + +/// `a.reverse()` of a numeric array: its items swapped end for end, in +/// place. +fn array_reverse_fast(args: &[Object]) -> Option> { + let [recv] = args else { + return None; + }; + let (typecode, buf) = array_instance_parts(recv)?; + let size = array_item_size(typecode)?; + let mut b = buf.try_borrow_mut().ok()?; + let n = b.len() / size; + for i in 0..n / 2 { + let (lo, hi) = (i * size, (n - 1 - i) * size); + for k in 0..size { + b.swap(lo + k, hi + k); + } + } + Some(Ok(Object::None)) +} + +/// `a.tobytes()`: a copy of the buffer. +fn array_tobytes_fast(args: &[Object]) -> Option> { + let [recv] = args else { + return None; + }; + let (_, buf) = array_instance_parts(recv)?; + let bytes = Object::new_bytes(buf.try_borrow().ok()?.as_slice()); + Some(Ok(bytes)) +} + +/// Whether two arrays of the `array` class itself with one numeric +/// typecode hold equal items: ints by their bytes, floats by value (a +/// NaN equals nothing, the zeros equal each other). +fn array_items_equal(a: &Object, b: &Object) -> Option { + let (typecode, x) = array_instance_parts(a)?; + let (other_code, y) = array_instance_parts(b)?; + if typecode != other_code { + return None; + } + array_item_size(typecode)?; + let (x, y) = (x.try_borrow().ok()?, y.try_borrow().ok()?); + Some(match typecode { + b'f' => { + let (p, q) = (x.as_chunks::<4>().0, y.as_chunks::<4>().0); + x.len() == y.len() + && p.iter() + .zip(q) + .all(|(p, q)| f32::from_ne_bytes(*p) == f32::from_ne_bytes(*q)) + } + b'd' => { + let (p, q) = (x.as_chunks::<8>().0, y.as_chunks::<8>().0); + x.len() == y.len() + && p.iter() + .zip(q) + .all(|(p, q)| f64::from_ne_bytes(*p) == f64::from_ne_bytes(*q)) + } + _ => *x == *y, + }) +} + +/// `a == b` of two arrays (see [`array_items_equal`]). +fn array_eq_fast(args: &[Object]) -> Option> { + let [a, b] = args else { + return None; + }; + array_items_equal(a, b).map(|eq| Ok(Object::Bool(eq))) +} + +/// `a != b` of two arrays (see [`array_items_equal`]). +fn array_ne_fast(args: &[Object]) -> Option> { + let [a, b] = args else { + return None; + }; + array_items_equal(a, b).map(|eq| Ok(Object::Bool(!eq))) +} + +/// `a.tolist()` of an array of machine ints or floats: its items read +/// off the buffer into a list. (A unicode array's characters, and an +/// item past the machine range, are the Python method's.) +fn array_tolist_fast(args: &[Object]) -> Option> { + let [recv] = args else { + return None; + }; + let items: Vec = with_array(recv, |typecode, buf| { + let size = array_item_size(typecode)?; + let buf = buf.try_borrow().ok()?; + buf.chunks_exact(size) + .map(|raw| array_item_read(typecode, raw)) + .collect() + })?; + Some(Ok(Object::new_list(items))) +} + +/// The array iterator class `_array_methods` served last (its address), +/// and the native `__next__` it was given (its address). +static ARRAY_ITER_CLASS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static ARRAY_ITER_NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The version token of the array iterator class when it was last found +/// to keep its native `__next__`. +static ARRAY_NEXT_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +thread_local! { + /// The `array` class version last found to keep its own `__iter__`, + /// with the iterator class that method makes and the version at which + /// that class kept its own `__init__`. + static ARRAY_ITER_MEMO: RefCell, u64)>> = + const { RefCell::new(None) }; +} + +/// The array iterator class, when `inst`'s class (the `array` class +/// itself, at version `ver`) keeps the `__iter__` that makes one and the +/// iterator class its own `__init__` and two slots. +#[cold] +#[inline(never)] +fn array_iter_class_slow( + inst: &crate::types::PyInstance, + ver: u64, +) -> Option> { + use std::sync::atomic::Ordering::Relaxed; + let Some(Object::Function(f)) = inst.cls_raw().lookup("__iter__") else { + return None; + }; + if f.code().qualname != "array.__iter__" { + return None; + } + let it_cls = match f + .globals + .borrow() + .get(&crate::object::StrKey("_array_iterator")) + { + Some(Object::Type(t)) => t.clone(), + _ => return None, + }; + if Rc::as_ptr(&it_cls) as usize != ARRAY_ITER_CLASS.load(Relaxed) { + return None; + } + match it_cls.lookup("__init__") { + Some(Object::Function(f)) if f.code().qualname == "_array_iterator.__init__" => {} + _ => return None, + } + let layout = it_cls.own_slot_layout()?; + if layout.len() != 2 + || crate::shared_value::SharedSlice::word(layout) != ARRAY_ITER_LAYOUT.load(Relaxed) + { + return None; + } + let it_ver = it_cls.attr_version.get(); + ARRAY_ITER_MEMO.with(|m| *m.borrow_mut() = Some((ver, it_cls.clone(), it_ver))); + Some(it_cls) +} + +/// `iter(a)` of an instance of the `array` class itself, for a `for` +/// loop's `GET_ITER` in compiled code: the iterator its `__iter__` makes +/// (over `a` at index 0), built with no Python code running. `None` for +/// anything else. +pub(crate) fn array_iter_lane(v: &Object) -> Option { + use std::sync::atomic::Ordering::Relaxed; + let Object::Instance(inst) = v else { + return None; + }; + let cls = inst.cls_raw(); + if std::ptr::from_ref(cls) as usize != ARRAY_CLASS.load(Relaxed) { + return None; + } + let ver = cls.attr_version.get(); + let memo = ARRAY_ITER_MEMO.with(|m| match &*m.borrow() { + Some((v, it_cls, it_ver)) if *v == ver && it_cls.attr_version.get() == *it_ver => { + Some(it_cls.clone()) + } + _ => None, + }); + let it_cls = match memo { + Some(it_cls) => it_cls, + None => array_iter_class_slow(inst, ver)?, + }; + let layout = it_cls.own_slot_layout()?.clone(); + let slots = crate::types::SlotStorage::from_layout_array(layout, [v.clone(), Object::Int(0)]); + let obj = Object::Instance(Rc::new(crate::types::PyInstance::with_slots(it_cls, slots))); + crate::gc_trace::track(&obj); + Some(obj) +} + +/// One step of a `for` loop over an instance iterator, where it is an +/// array's. +pub(crate) enum ArrayStep { + /// The next item, the iterator stepped past it. + Item(Object), + /// The end of the array: the iterator gave up its array (handed + /// over here for the loop to release), as its `__next__` does before + /// raising `StopIteration`, so it stays exhausted. + End(Object), + /// Not an array iterator, or a step for its full `__next__` (a + /// unicode array's, an item past the machine range, a guarded cell). + Other, +} + +#[cold] +#[inline(never)] +fn array_steps_natively_slow(cls: &crate::types::TypeObject, ver: u64) -> bool { + use std::sync::atomic::Ordering::Relaxed; + let want = ARRAY_ITER_NEXT.load(Relaxed); + let ok = want != 0 + && matches!(cls.lookup("__next__"), Some(Object::Builtin(b)) if Rc::as_ptr(&b) as usize == want); + if ok { + ARRAY_NEXT_VER.store(ver, Relaxed); + } + ok +} + +/// A `for` loop's step over `it` in compiled code: an array iterator's +/// next item or its end, read in place off the array's buffer, when its +/// class keeps the native `__next__`. The array is read as it is now (an +/// item appended during the loop is reached, as the method reaches it). +/// Without `may_end`, the end is the full `__next__`'s. +#[inline] +pub(crate) fn array_for_step(it: &crate::types::PyInstance, may_end: bool) -> ArrayStep { + use std::sync::atomic::Ordering::Relaxed; + let cls = it.cls_raw(); + if std::ptr::from_ref(cls) as usize != ARRAY_ITER_CLASS.load(Relaxed) { + return ArrayStep::Other; + } + let ver = cls.attr_version.get(); + if ver != ARRAY_NEXT_VER.load(Relaxed) + && (crate::gil::free_threading_enabled() || !array_steps_natively_slow(cls, ver)) + { + return ArrayStep::Other; + } + array_step_in_place(it, may_end).unwrap_or(ArrayStep::Other) +} + +/// The `index`th item of a numeric array's buffer, as +/// [`array_item_read`] reads it, in one dispatch on the typecode: +/// `Some(None)` past the end, `None` for a typecode or an item that +/// read doesn't take. +// (A C `long` is 64 bits wide on some targets and 32 on others.) +#[allow(clippy::useless_conversion)] +#[inline(always)] +fn array_item_at(typecode: u8, buf: &[u8], index: usize) -> Option> { + macro_rules! item { + ($t:ty) => {{ + const SIZE: usize = std::mem::size_of::<$t>(); + let Some(raw) = index + .checked_mul(SIZE) + .and_then(|off| buf.get(off..)?.first_chunk::()) + else { + return Some(None); + }; + <$t>::from_ne_bytes(*raw) + }}; + } + Some(Some(match typecode { + b'b' => Object::Int(i64::from(item!(i8))), + b'B' => Object::Int(i64::from(item!(u8))), + b'h' => Object::Int(i64::from(item!(i16))), + b'H' => Object::Int(i64::from(item!(u16))), + b'i' => Object::Int(i64::from(item!(i32))), + b'I' => Object::Int(i64::from(item!(u32))), + b'l' => Object::Int(i64::from(item!(std::ffi::c_long))), + b'q' => Object::Int(item!(i64)), + // (One past the machine range is a big int: the method's.) + b'L' => Object::Int(i64::try_from(u64::from(item!(std::ffi::c_ulong))).ok()?), + b'Q' => Object::Int(i64::try_from(item!(u64)).ok()?), + b'f' => Object::Float(f64::from(item!(f32))), + b'd' => Object::Float(item!(f64)), + _ => return None, + })) +} + +#[inline(always)] +fn array_step_in_place(it: &crate::types::PyInstance, may_end: bool) -> Option { + use std::sync::atomic::Ordering::Relaxed; + let layout = it.cls_raw().own_slot_layout()?; + // SAFETY: no guard is live on the cells (`peek`/`peek_mut` check), no + // Python runs before the last use, and the iterator, its array and + // the array's buffer are distinct objects. + let its = unsafe { it.slots.peek_mut() }?; + let [held, index] = its.values_for_layout_mut(layout)? else { + return None; + }; + let (Object::Instance(array), Object::Int(i)) = (&*held, index) else { + return None; + }; + let array_layout = array.cls_raw().own_slot_layout()?; + if crate::shared_value::SharedSlice::word(array_layout) != ARRAY_LAYOUT.load(Relaxed) { + return None; + } + // SAFETY: as above. + let values = unsafe { array.slots.peek() }?.values_for_layout(array_layout)?; + let (Some(Object::Str(code)), Some(Object::ByteArray(buf))) = (values.first(), values.get(3)) + else { + return None; + }; + let [typecode] = code.as_bytes() else { + return None; + }; + // SAFETY: as above. + let buf = unsafe { buf.peek() }?; + match array_item_at(*typecode, buf, usize::try_from(*i).ok()?)? { + Some(v) => { + *i += 1; + Some(ArrayStep::Item(v)) + } + None if may_end => Some(ArrayStep::End(std::mem::replace(held, Object::None))), + None => None, + } +} + +/// `a[i]` for a plain index in range, and `a[i:j]` (see +/// [`array_slice_fast`]). +fn array_getitem_fast(args: &[Object]) -> Option> { + if let [recv, Object::Slice(sl)] = args { + return array_slice_fast(recv, sl).map(Ok); + } + let [recv, Object::Int(index)] = args else { + return None; + }; + // (The buffer borrowed where the slots hold it: no count taken.) + with_array(recv, |typecode, buf| { + let size = array_item_size(typecode)?; + let buf = buf.try_borrow().ok()?; + let n = (buf.len() / size) as i64; + let at = if *index < 0 { *index + n } else { *index }; + if !(0..n).contains(&at) { + return None; + } + let off = at as usize * size; + array_item_read(typecode, &buf[off..off + size]) + }) + .map(Ok) +} + +/// `a[i:j] = b` for another array of the same typecode: the run's bytes +/// replaced by `b`'s, in place when the lengths match, and otherwise only +/// while no view of `a` is exported. +fn array_store_run_fast(recv: &Object, sl: &crate::object::PySlice, value: &Object) -> Option<()> { + let (typecode, buf) = array_parts(recv)?; + let (other_code, other) = array_parts(value)?; + if typecode != other_code || Rc::ptr_eq(&buf, &other) { + return None; + } + let size = array_item_size(typecode)?; + let source = other.try_borrow().ok()?; + let mut target = buf.try_borrow_mut().ok()?; + let (lo, hi) = array_byte_run(sl, target.len(), size)?; + if hi - lo == source.len() { + target[lo..hi].copy_from_slice(&source); + } else { + // (The export registry doesn't read the buffer: checking under the + // borrow is safe.) + if crate::object::bytearray_is_exported(&buf) { + return None; + } + target.splice(lo..hi, source.iter().copied()); + } + Some(()) +} + +/// `a[i] = v` for a plain index in range and a plain value the item +/// holds: written where it goes. And `a[i:j] = b` (see +/// [`array_store_run_fast`]). +fn array_setitem_fast(args: &[Object]) -> Option> { + if let [recv, Object::Slice(sl), value @ Object::Instance(_)] = args { + return array_store_run_fast(recv, sl, value).map(|()| Ok(Object::None)); + } + let [recv, Object::Int(index), value] = args else { + return None; + }; + with_array(recv, |typecode, buf| { + let mut packed = [0u8; 8]; + let size = array_item_write(typecode, value, &mut packed)?; + let mut buf = buf.try_borrow_mut().ok()?; + let n = (buf.len() / size) as i64; + let at = if *index < 0 { *index + n } else { *index }; + if !(0..n).contains(&at) { + return None; + } + let off = at as usize * size; + buf[off..off + size].copy_from_slice(&packed[..size]); + Some(Ok(Object::None)) + }) +} + +/// `a.append(v)` for a plain value the item holds, while no view of the +/// array is exported (a resize under one is refused by the Python method). +fn array_append_fast(args: &[Object]) -> Option> { + let [recv, value] = args else { + return None; + }; + let (typecode, buf) = array_parts(recv)?; + let mut packed = [0u8; 8]; + let size = array_item_write(typecode, value, &mut packed)?; + if crate::object::bytearray_is_exported(&buf) { + return None; + } + buf.try_borrow_mut() + .ok()? + .extend_from_slice(&packed[..size]); + Some(Ok(Object::None)) +} + +/// `len(a)`. +fn array_len_fast(args: &[Object]) -> Option> { + let [recv] = args else { + return None; + }; + with_array(recv, |typecode, buf| { + let size = array_item_size(typecode)?; + let n = buf.try_borrow().ok()?.len() / size; + Some(Ok(Object::Int(n as i64))) + }) +} + +/// An array iterator's next item while it has one (its end, and an +/// iterator already finished, are the Python method's). +fn array_next_fast(args: &[Object]) -> Option> { + let [Object::Instance(it)] = args else { + return None; + }; + let read = |array: &Object, index: i64| { + with_array(array, |typecode, buf| { + let size = array_item_size(typecode)?; + let buf = buf.try_borrow().ok()?; + let off = usize::try_from(index).ok()?.checked_mul(size)?; + array_item_read(typecode, buf.get(off..off + size)?) + }) + }; + let mut slots = it.slots.try_borrow_mut().ok()?; + // (Laid out as the class declares them: read and advanced in place.) + let layout = it.cls_raw().own_slot_layout()?; + if crate::shared_value::SharedSlice::word(layout) + == ARRAY_ITER_LAYOUT.load(std::sync::atomic::Ordering::Relaxed) + { + let values = slots.values_for_layout_mut(layout)?; + let [array, index @ Object::Int(_), ..] = values else { + return None; + }; + let Object::Int(i) = *index else { + return None; + }; + let item = read(array, i)?; + *index = Object::Int(i + 1); + return Some(Ok(item)); + } + let Object::Int(i) = *slots.get_hinted(1, "_index")? else { + return None; + }; + let item = read(slots.get_hinted(0, "_ao")?, i)?; + *slots.get_hinted_mut(1, "_index")? = Object::Int(i + 1); + Some(Ok(item)) +} + +/// An `unpack_iterator`'s next tuple while it has one, or its end's +/// `StopIteration`: the format's fields read at the iterator's offset, +/// which then moves on by the format's size. +fn unpack_iter_next_fast(args: &[Object]) -> Option> { + let [Object::Instance(it)] = args else { + return None; + }; + match unpack_iter_step_laid(it) { + Some(Some(v)) => Some(Ok(v)), + // (The end raises natively: the Python method's raise is a frame + // and an exception unwound through it.) + Some(None) => Some(Err(crate::error::stop_iteration())), + None => unpack_iter_next_named(it), + } +} + +/// The step of the cached `__next__` version of the module's own +/// `unpack_iterator` class (see [`unpack_for_step`]). +static UNPACK_NEXT_VER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A `for` loop's step over `it` in compiled code: an `unpack_iterator`'s +/// next tuple, or `Some(None)` at its end (its buffer let go), when `it` +/// is the module's own iterator class and that class keeps the native +/// `__next__`; `None` (nothing done) otherwise. +#[inline] +pub(crate) fn unpack_for_step(it: &crate::types::PyInstance) -> Option> { + use std::sync::atomic::Ordering::Relaxed; + let cls = it.cls_raw(); + if std::ptr::from_ref(cls) as usize != UNPACK_ITER_CLASS.load(Relaxed) { + return None; + } + let ver = cls.attr_version.get(); + if ver == 0 || ver != UNPACK_NEXT_VER.load(Relaxed) { + if crate::gil::free_threading_enabled() || !unpack_steps_natively_slow(cls, ver) { + return None; + } + } + unpack_iter_step_laid(it) +} + +#[cold] +#[inline(never)] +fn unpack_steps_natively_slow(cls: &crate::types::TypeObject, ver: u64) -> bool { + use std::sync::atomic::Ordering::Relaxed; + let want = UNPACK_ITER_NEXT.load(Relaxed); + let ok = ver != 0 + && want != 0 + && matches!(cls.lookup("__next__"), Some(Object::Builtin(b)) if Rc::as_ptr(&b) as usize == want); + if ok { + UNPACK_NEXT_VER.store(ver, Relaxed); + } + ok +} + +/// [`unpack_iter_next_fast`]'s step for an iterator laid out as the +/// module's own class: the next tuple, or `Some(None)` at the end (the +/// buffer's export then let go); `None` (nothing done) for any other +/// layout or a read this doesn't take. +fn unpack_iter_step_laid(it: &crate::types::PyInstance) -> Option> { + // The class's own layout, `_fmt, _buffer, _size, _offset, _len`: the + // slots read and the offset moved in place, under one borrow (nothing + // below runs code). + let laid = it.cls_raw().own_slot_layout().filter(|layout| { + crate::shared_value::SharedSlice::word(layout) + == UNPACK_ITER_LAYOUT.load(std::sync::atomic::Ordering::Relaxed) + }); + let layout = laid?; + let mut slots = it.slots.try_borrow_mut().ok()?; + let [Object::Str(fmt), buffer, _, Object::Int(offset), Object::Int(len)] = + slots.values_for_layout_mut(layout)? + else { + return None; + }; + if *offset >= *len { + // The buffer's export ends with the iteration, as CPython's + // iterator releases it. + if !matches!(buffer, Object::Bytes(_)) { + *buffer = Object::new_bytes(Vec::new()); + } + return Some(None); + } + let cf = compiled_for(fmt)?; + let off = usize::try_from(*offset).ok()?; + let read = |buf: &[u8]| { + if off.checked_add(cf.size)? > buf.len() { + return None; + } + cf.unpack_tuple_at(buf, off).ok() + }; + let vals = match &*buffer { + Object::Bytes(b) => read(b)?, + Object::ByteArray(b) => read(&b.try_borrow().ok()?)?, + Object::MemoryView(mv) if !mv.released.get() && mv.is_c_contiguous() => { + mv.with_bytes(read)? + } + _ => return None, + }; + *offset += cf.size as i64; + Some(Some(vals)) +} + +/// [`unpack_iter_next_fast`] for an iterator whose class isn't laid out as +/// the module's own: its slots by name. +fn unpack_iter_next_named(it: &crate::types::PyInstance) -> Option> { + // (The class's own layout, `_fmt, _buffer, _size, _offset, _len`, is + // read at its places; anything else by name.) + let (fmt, buffer, offset) = { + let slots = it.slots.try_borrow().ok()?; + let laid = known_slots(it, &slots, &UNPACK_ITER_LAYOUT); + let (fmt, offset, len) = match laid { + Some([f, _, _, o, l]) => (f, o, l), + _ => ( + slots.get_hinted(0, "_fmt")?, + slots.get_hinted(3, "_offset")?, + slots.get_hinted(4, "_len")?, + ), + }; + let (Object::Str(fmt), Object::Int(offset), Object::Int(len)) = (fmt, offset, len) else { + return None; + }; + if offset >= len { + return Some(Err(crate::error::stop_iteration())); + } + let buffer = match laid { + Some([_, b, ..]) => b, + _ => slots.get_hinted(1, "_buffer")?, + }; + (fmt.clone(), buffer.clone(), *offset) + }; + let cf = compiled_for(&fmt)?; + let read = |buf: &[u8]| { + let off = usize::try_from(offset).ok()?; + if off.checked_add(cf.size)? > buf.len() { + return None; + } + cf.unpack_tuple_at(buf, off).ok() + }; + let vals = match &buffer { + Object::Bytes(b) => read(b)?, + Object::ByteArray(b) => read(&b.try_borrow().ok()?)?, + Object::MemoryView(mv) if !mv.released.get() && mv.is_c_contiguous() => { + mv.with_bytes(read)? + } + _ => return None, + }; + let next = Object::Int(offset + cf.size as i64); + let mut slots = it.slots.try_borrow_mut().ok()?; + let laid = it.cls_raw().own_slot_layout().filter(|layout| { + crate::shared_value::SharedSlice::word(layout) + == UNPACK_ITER_LAYOUT.load(std::sync::atomic::Ordering::Relaxed) + }); + let at = match laid { + Some(layout) => slots.values_for_layout_mut(layout)?.get_mut(3)?, + None => slots.get_hinted_mut(3, "_offset")?, + }; + *at = next; + drop(slots); + Some(Ok(vals)) +} + +/// `_all_exact(items, cls)`: whether every item of the list is exactly of +/// the builtin class `cls` (`int` or `float`: `array.fromlist` packs such +/// a list in one call). `False` for any other class or argument. +fn all_exact(args: &[Object]) -> Result { + let [Object::List(items), Object::Type(cls)] = args else { + return Ok(Object::Bool(false)); + }; + let bt = crate::builtin_types::builtin_types(); + let items = items.borrow(); + let all = if Rc::ptr_eq(cls, &bt.int_) { + items + .iter() + .all(|v| matches!(v, Object::Int(_) | Object::Long(_))) + } else if Rc::ptr_eq(cls, &bt.float_) { + items.iter().all(|v| matches!(v, Object::Float(_))) + } else { + false + }; + Ok(Object::Bool(all)) +} + +/// `_unpack_iterator_methods(unpack_iterator)`: the iterator's native +/// step, as `(class, name, method)` triples for the module to assign. +fn unpack_iterator_methods(args: &[Object]) -> Result { + let [Object::Type(cls)] = args else { + return Err(type_error( + "_unpack_iterator_methods() expects the iterator class", + )); + }; + let orig = cls + .dict + .borrow() + .get(&crate::object::StrKey("__next__")) + .cloned() + .ok_or_else(|| type_error("_unpack_iterator_methods(): no __next__ to replace"))?; + if let Some(layout) = cls.own_slot_layout() { + UNPACK_ITER_LAYOUT.store( + crate::shared_value::SharedSlice::word(layout), + std::sync::atomic::Ordering::Relaxed, + ); + } + let next = fast_method(cls, "__next__", unpack_iter_next_fast, orig, false); + if let Object::Builtin(b) = &next { + UNPACK_ITER_NEXT.store(Rc::as_ptr(b) as usize, std::sync::atomic::Ordering::Relaxed); + UNPACK_ITER_CLASS.store( + Rc::as_ptr(cls) as usize, + std::sync::atomic::Ordering::Relaxed, + ); + } + let mut out = vec![Object::new_tuple(vec![ + Object::Type(cls.clone()), + Object::from_static("__next__"), + next, + ])]; + let hint = cls + .dict + .borrow() + .get(&crate::object::StrKey("__length_hint__")) + .cloned(); + if let Some(hint) = hint { + out.push(Object::new_tuple(vec![ + Object::Type(cls.clone()), + Object::from_static("__length_hint__"), + fast_method( + cls, + "__length_hint__", + unpack_iter_length_hint_fast, + hint, + false, + ), + ])); + } + Ok(Object::new_list(out)) +} + +/// An `unpack_iterator`'s `__length_hint__`, the chunks still to come, from +/// its own layout's slots (anything else is the Python method's). +fn unpack_iter_length_hint_fast(args: &[Object]) -> Option> { + let [Object::Instance(it)] = args else { + return None; + }; + let layout = it.cls_raw().own_slot_layout().filter(|layout| { + crate::shared_value::SharedSlice::word(layout) + == UNPACK_ITER_LAYOUT.load(std::sync::atomic::Ordering::Relaxed) + })?; + let slots = it.slots.try_borrow().ok()?; + let [_, _, Object::Int(size), Object::Int(offset), Object::Int(len)] = + slots.values_for_layout(layout)? + else { + return None; + }; + if *size <= 0 { + return None; + } + Some(Ok(Object::Int((len - offset).div_euclid(*size)))) +} + +/// `_array_methods(array, array_iterator)`: the native item methods of +/// the `array` class and its iterator's native step, as `(class, name, +/// method)` triples for the module to assign (a class attribute +/// assignment keeps the special-method caches right). +fn array_methods(args: &[Object]) -> Result { + let [Object::Type(cls), Object::Type(iter_cls)] = args else { + return Err(type_error( + "_array_methods() expects the array class and its iterator's", + )); + }; + let table: [(&Rc, &'static str, Fast); 20] = [ + (cls, "pop", array_pop_fast), + (cls, "insert", array_insert_fast), + (cls, "remove", array_remove_fast), + (cls, "extend", array_extend_fast), + (cls, "reverse", array_reverse_fast), + (cls, "count", array_count_fast), + (cls, "index", array_index_fast), + (cls, "tobytes", array_tobytes_fast), + (cls, "__contains__", array_contains_fast), + (cls, "__delitem__", array_delitem_fast), + (cls, "__eq__", array_eq_fast), + (cls, "__ne__", array_ne_fast), + (cls, "tolist", array_tolist_fast), + (cls, "__getitem__", array_getitem_fast), + (cls, "__add__", array_add_fast), + (cls, "__copy__", array_copy_fast), + (cls, "__setitem__", array_setitem_fast), + (cls, "__len__", array_len_fast), + (cls, "append", array_append_fast), + (iter_cls, "__next__", array_next_fast), + ]; + ARRAY_CLASS.store( + Rc::as_ptr(cls) as usize, + std::sync::atomic::Ordering::Relaxed, + ); + ARRAY_ITER_CLASS.store( + Rc::as_ptr(iter_cls) as usize, + std::sync::atomic::Ordering::Relaxed, + ); + // (Plain constructions build in place: see `array_pure_new`.) + cls.pure_new.set(Some(array_pure_new)); + for (owner, known) in [(cls, &ARRAY_LAYOUT), (iter_cls, &ARRAY_ITER_LAYOUT)] { + if let Some(layout) = owner.own_slot_layout() { + known.store( + crate::shared_value::SharedSlice::word(layout), + std::sync::atomic::Ordering::Relaxed, + ); + } + } + let mut out = Vec::with_capacity(table.len()); + for (owner, name, fast) in table { + let orig = owner + .dict + .borrow() + .get(&crate::object::StrKey(name)) + .cloned() + .ok_or_else(|| type_error(format!("_array_methods(): no {name} to replace")))?; + let method = fast_method(owner, name, fast, orig, false); + if let ("__next__", Object::Builtin(b)) = (name, &method) { + ARRAY_ITER_NEXT.store(Rc::as_ptr(b) as usize, std::sync::atomic::Ordering::Relaxed); + } + if let ("__contains__", Object::Builtin(b)) = (name, &method) { + ARRAY_CONTAINS.store(Rc::as_ptr(b) as usize, std::sync::atomic::Ordering::Relaxed); + } + out.push(Object::new_tuple(vec![ + Object::Type(owner.clone()), + Object::from_static(name), + method, + ])); + } + Ok(Object::new_list(out)) +} + +/// `_install_struct(Struct)`: serve the exact class's `pack` and +/// `unpack` natively (CPython's `Struct` is a C type), each falling back +/// to the Python method it replaces for every other shape. +fn install_struct(args: &[Object]) -> Result { + let [Object::Type(cls)] = args else { + return Err(type_error("_install_struct() expects the Struct class")); + }; + let own = |name: &str| cls.dict.borrow().get(&crate::object::StrKey(name)).cloned(); + let (Some(pack), Some(unpack)) = (own("pack"), own("unpack")) else { + return Err(type_error("_install_struct(): Struct lacks pack/unpack")); + }; + install_fast_methods( + cls, + [ + ("pack", struct_pack_fast as Fast, pack), + ("unpack", struct_unpack_fast as Fast, unpack), + ], + ); + cls.bump_attr_version(); + STRUCT_CLASS.store( + Rc::as_ptr(cls) as usize, + std::sync::atomic::Ordering::Relaxed, + ); + Ok(Object::None) +} + +/// `pack(fmt, *values)` when every value is one the packer reads directly +/// (a plain int, float, complex, bool, str, bytes or bytearray), else +/// `None` for the wrapper's coercing path, having done nothing. +fn b_pack_plain(args: &[Object]) -> Result { + if !args.get(1..).unwrap_or(&[]).iter().all(|v| { + matches!( + v, + Object::Int(_) + | Object::Long(_) + | Object::Bool(_) + | Object::Float(_) + | Object::Complex(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::ByteArray(_) + ) + }) { + return Ok(Object::None); + } + b_pack(args) +} + +fn fmt_arg(args: &[Object], idx: usize) -> Result { + match args.get(idx) { + Some(Object::Str(s)) => Ok(s.to_string()), + Some(Object::Bytes(b)) => Ok(String::from_utf8_lossy(b).into_owned()), + _ => Err(type_error("format must be a str or bytes-like".to_owned())), + } +} + +/// `f` on the bytes of the bytes-like argument `o`, read where they are +/// (unpacking a few bytes of a large buffer copies none of it). +fn with_buffer(o: &Object, f: impl FnOnce(&[u8]) -> R) -> Result { + // (CPython asks for a C-contiguous buffer: a strided view is refused, + // not gathered.) + if let Object::MemoryView(mv) = o { + if mv.released.get() { + return Err(value_error( + "operation forbidden on released memoryview object", + )); + } + if !mv.is_c_contiguous() { + return Err(crate::error::buffer_error( + "memoryview: underlying buffer is not C-contiguous", + )); + } + } + o.with_bytes_view(f) + .ok_or_else(|| type_error("argument must be bytes-like".to_owned())) +} + +fn b_calcsize(args: &[Object]) -> Result { + let fmt = fmt_arg(args, 0)?; + let cf = compiled(&fmt)?; + Ok(Object::Int(cf.size as i64)) +} + +/// Return one format character per *value slot* the format consumes, in +/// order (`x` pad bytes contribute nothing; `s`/`p` contribute a single +/// slot; numeric codes contribute `count` slots). The frozen wrapper uses +/// this to coerce each argument through the right protocol (`__index__` +/// for integer codes, `__float__` for floats, `__bool__` for `?`) before +/// handing concrete `int`/`float`/`bool` values to the Rust packer, which +/// has no interpreter access of its own. +fn b_value_codes(args: &[Object]) -> Result { + let fmt = fmt_arg(args, 0)?; + let cf = compiled(&fmt)?; + let mut s = String::new(); + for f in &cf.fields { + match f.code { + 'x' => {} + 's' | 'p' => s.push(f.code), + c => { + for _ in 0..f.count { + s.push(c); + } + } + } + } + Ok(Object::from_str(s)) +} + +fn b_pack(args: &[Object]) -> Result { + let cf = format_of(args)?; + let bytes = cf.pack(&args[1..])?; + Ok(Object::new_bytes(bytes)) +} + +/// The compiled format `args[0]` names: a `str` by its identity (a call +/// site's literal is one string every call), a bytes-like one by text. +fn format_of(args: &[Object]) -> Result, RuntimeError> { + if let Some(Object::Str(s)) = args.first() { + if let Some(cf) = compiled_for(s) { + return Ok(cf); + } + } + compiled(&fmt_arg(args, 0)?) +} + +/// `struct.pack(format, *v)`'s fast half: a `str` format and plain values +/// packed at once; `None` (nothing done) for anything else or any error, +/// which the Python function raises as `struct.error`. +fn pack_fast(args: &[Object]) -> Option> { + let (Some(Object::Str(fmt)), Some(values)) = (args.first(), args.get(1..)) else { + return None; + }; + let plain = values.iter().all(|v| { + matches!( + v, + Object::Int(_) + | Object::Long(_) + | Object::Bool(_) + | Object::Float(_) + | Object::Complex(_) + | Object::Str(_) + | Object::Bytes(_) + | Object::ByteArray(_) + ) + }); + if !plain { + return None; + } + let bytes = compiled_for(fmt)?.pack(values).ok()?; + Some(Ok(Object::new_bytes(bytes))) +} + +/// `_native_pack(python_pack)`: the public `struct.pack`, which packs +/// plain values in place (see [`pack_fast`]) and calls the Python +/// function `python_pack` for anything else. +fn b_native_pack(args: &[Object]) -> Result { + let [fallback] = args else { + return Err(type_error("_native_pack() takes the Python pack")); + }; + let fallback = fallback.clone(); + let b = Rc::new(BuiltinFn { + name: "pack", + binds_instance: false, + call: Box::new(move |a: &[Object]| match pack_fast(a) { + Some(r) => r, + None => { + let interp = crate::builtins::reentrant_interp()?; + let globals = interp.builtins_dict(); + interp.call(&fallback, a, &[], &globals) + } + }), + call_kw: None, + }); + crate::leaf_builtins::register_fast(&b, pack_fast); + Ok(Object::Builtin(b)) +} + +/// `struct.unpack(format, buffer)`'s fast half: a `str` format over a +/// `bytes` or `bytearray` buffer, read at once; `None` (nothing done) for anything else +/// or any error, which the Python function raises as `struct.error`. +fn unpack_fast(args: &[Object]) -> Option> { + let [Object::Str(fmt), buffer] = args else { + return None; + }; + let vals = match buffer { + Object::Bytes(b) => compiled_for(fmt)?.unpack_tuple(b).ok()?, + Object::ByteArray(b) => compiled_for(fmt)? + .unpack_tuple(&b.try_borrow().ok()?) + .ok()?, + _ => return None, + }; + Some(Ok(vals)) +} + +/// `_native_unpack(python_unpack)`: the public `struct.unpack`, which +/// reads a `bytes` buffer in place (see [`unpack_fast`]) and calls the +/// Python function `python_unpack` for anything else. +fn b_native_unpack(args: &[Object]) -> Result { + let [fallback] = args else { + return Err(type_error("_native_unpack() takes the Python unpack")); + }; + let fallback = fallback.clone(); + let b = Rc::new(BuiltinFn { + name: "unpack", + binds_instance: false, + call: Box::new(move |a: &[Object]| match unpack_fast(a) { + Some(r) => r, + None => { + let interp = crate::builtins::reentrant_interp()?; + let globals = interp.builtins_dict(); + interp.call(&fallback, a, &[], &globals) + } + }), + call_kw: None, + }); + crate::leaf_builtins::register_fast(&b, unpack_fast); + let obj = Object::Builtin(b); + crate::descr_registry::register_text_signature(&obj, "(format, buffer, /)"); + Ok(obj) +} + +fn b_unpack(args: &[Object]) -> Result { + let cf = format_of(args)?; + // (A `bytes` buffer is read in place.) + let vals = match &args[1] { + Object::Bytes(b) => cf.unpack(b)?, + other => with_buffer(other, |buf| cf.unpack(buf))??, + }; + Ok(Object::new_tuple(vals)) +} + +/// Resolve a `pack_into`/`unpack_from` byte offset, matching CPython's +/// `Py_ssize_t` coercion: ints (and `bool`) pass through, an int too big +/// for the platform word is `OverflowError`, and any non-integer is a +/// `TypeError` (test_struct.test_pack_into's bogus-offset cases). +fn ssize_offset(o: &Object) -> Result { + match o { + Object::Int(n) => Ok(*n), + Object::Bool(b) => Ok(i64::from(*b)), + Object::Long(_) => Err(overflow_error( + "Python int too large to convert to C ssize_t", + )), + // (Anything else through `__index__`, as CPython's `n` converter + // takes it; an object without one is a `TypeError`.) + other => crate::builtins::coerce_index_i64(other), + } +} + +fn b_pack_into(args: &[Object]) -> Result { + if args.len() < 3 { + return Err(type_error("pack_into() requires at least 3 arguments")); + } + let fmt = fmt_arg(args, 0)?; + let cf = compiled(&fmt)?; + let offset = ssize_offset(&args[2])?; + let bytes = cf.pack(&args[3..])?; + match &args[1] { + Object::ByteArray(buf) => { + let mut buf = buf.borrow_mut(); + // Resolve the (possibly negative) offset against the buffer + // and bounds-check without growing it — CPython's + // `pack_into` writes in place and never resizes. + let off = resolve_buffer_offset(offset, buf.len(), cf.size, "pack_into", true)?; + buf[off..off + bytes.len()].copy_from_slice(&bytes); + Ok(Object::None) + } + Object::MemoryView(mv) => { + // Writable buffer-protocol target (e.g. `memoryview(array(...))`). + if mv.readonly.get() { + return Err(type_error("cannot modify read-only memory".to_owned())); + } + let off = resolve_buffer_offset(offset, mv.len.get(), cf.size, "pack_into", true)?; + let base = mv.start.get(); + mv.buffer + .with_write(|b| b[base + off..base + off + bytes.len()].copy_from_slice(&bytes)) + .map(|()| Object::None) + .ok_or_else(|| type_error("cannot modify read-only memory".to_owned())) + } + _ => Err(type_error( + "argument must be a read-write bytes-like object".to_owned(), + )), + } +} + +/// Resolve a `pack_into`/`unpack_from` offset against a buffer of +/// `buf_len` bytes, matching CPython's `_struct` boundary diagnostics. +/// `size` is the struct's byte size; `for_pack` toggles the +/// pack- vs unpack-flavoured messages. Returns the non-negative byte +/// offset to start at, or a `struct.error` describing the overflow. +fn resolve_buffer_offset( + offset: i64, + buf_len: usize, size: usize, op: &str, for_pack: bool, @@ -1337,18 +3062,217 @@ fn b_unpack_from(args: &[Object]) -> Result { } let fmt = fmt_arg(args, 0)?; let cf = compiled(&fmt)?; - let buf = buffer_arg(&args[1])?; - let offset = args.get(2).and_then(|o| o.as_i64()).unwrap_or(0); - let off = resolve_buffer_offset(offset, buf.len(), cf.size, "unpack_from", false)?; - let (vals, _) = cf.unpack_from_offset(&buf, off)?; + let offset = match args.get(2) { + Some(o) => ssize_offset(o)?, + None => 0, + }; + let vals = with_buffer(&args[1], |buf| { + let off = resolve_buffer_offset(offset, buf.len(), cf.size, "unpack_from", false)?; + cf.unpack_from_offset(buf, off).map(|(vals, _)| vals) + })??; Ok(Object::new_tuple(vals)) } +/// `struct.unpack_from(format, buffer, offset=0)`'s fast half: a `str` +/// format over a `bytes`, `bytearray` or live contiguous `memoryview` +/// with a plain `int` offset, read where the bytes are; `None` (nothing +/// done) for anything else or any error, which the Python function raises +/// as `struct.error`. +fn unpack_from_fast(args: &[Object]) -> Option> { + let (fmt, buffer, offset) = match args { + [Object::Str(fmt), buffer] => (fmt, buffer, 0), + [Object::Str(fmt), buffer, Object::Int(offset)] => (fmt, buffer, *offset), + _ => return None, + }; + let read = |buf: &[u8]| { + let cf = compiled_for(fmt)?; + let off = resolve_buffer_offset(offset, buf.len(), cf.size, "unpack_from", false).ok()?; + cf.unpack_tuple_at(buf, off).ok() + }; + let vals = match buffer { + Object::Bytes(b) => read(b)?, + Object::ByteArray(b) => read(&b.try_borrow().ok()?)?, + Object::MemoryView(mv) if !mv.released.get() && mv.is_c_contiguous() => { + mv.with_bytes(read)? + } + _ => return None, + }; + Some(Ok(vals)) +} + +/// `struct.pack_into(format, buffer, offset, *v)`'s fast half: a `str` +/// format and plain values written into a `bytearray` or a live, writable, +/// contiguous `memoryview` at a plain `int` offset; `None` (nothing done) +/// for anything else or any error. +fn pack_into_fast(args: &[Object]) -> Option> { + let [Object::Str(fmt), target, Object::Int(offset), values @ ..] = args else { + return None; + }; + if !values + .iter() + .all(|v| matches!(v, Object::Int(_) | Object::Bool(_) | Object::Float(_))) + { + return None; + } + let cf = compiled_for(fmt)?; + let bytes = cf.pack(values).ok()?; + let write = |buf: &mut [u8]| { + let off = resolve_buffer_offset(*offset, buf.len(), cf.size, "pack_into", true).ok()?; + buf[off..off + bytes.len()].copy_from_slice(&bytes); + Some(()) + }; + match target { + Object::ByteArray(b) => write(&mut b.try_borrow_mut().ok()?)?, + Object::MemoryView(mv) + if !mv.released.get() && !mv.readonly.get() && mv.is_c_contiguous() => + { + let (start, len) = (mv.start.get(), mv.len.get()); + mv.buffer + .with_write(|all| write(all.get_mut(start..start + len)?))??; + } + _ => return None, + } + Some(Ok(Object::None)) +} + +/// A module function `name` that tries `fast` and calls the Python +/// function `fallback` (with the same arguments) for anything `fast` +/// leaves: the public `struct.unpack_from` and `struct.pack_into`. +fn native_with_fallback( + name: &'static str, + fast: fn(&[Object]) -> Option>, + fallback: &Object, +) -> Object { + let (plain, keyed) = (fallback.clone(), fallback.clone()); + let b = Rc::new(BuiltinFn { + name, + binds_instance: false, + call: Box::new(move |a: &[Object]| match fast(a) { + Some(r) => r, + None => { + let interp = crate::builtins::reentrant_interp()?; + let globals = interp.builtins_dict(); + interp.call(&plain, a, &[], &globals) + } + }), + call_kw: Some(Box::new(move |a: &[Object], kw: &[(String, Object)]| { + if kw.is_empty() { + if let Some(r) = fast(a) { + return r; + } + } + let interp = crate::builtins::reentrant_interp()?; + let globals = interp.builtins_dict(); + interp.call(&keyed, a, kw, &globals) + })), + }); + crate::leaf_builtins::register_fast(&b, fast); + Object::Builtin(b) +} + +/// `_native_unpack_from(python_unpack_from)`: the public +/// `struct.unpack_from` (see [`unpack_from_fast`]). +fn b_native_unpack_from(args: &[Object]) -> Result { + let [fallback] = args else { + return Err(type_error( + "_native_unpack_from() takes the Python unpack_from", + )); + }; + let obj = native_with_fallback("unpack_from", unpack_from_fast, fallback); + crate::descr_registry::register_text_signature(&obj, "(format, /, buffer, offset=0)"); + Ok(obj) +} + +/// `_native_pack_into(python_pack_into)`: the public `struct.pack_into` +/// (see [`pack_into_fast`]). +fn b_native_pack_into(args: &[Object]) -> Result { + let [fallback] = args else { + return Err(type_error("_native_pack_into() takes the Python pack_into")); + }; + let obj = native_with_fallback("pack_into", pack_into_fast, fallback); + crate::descr_registry::register_text_signature(&obj, "(format, buffer, offset, /, *v)"); + Ok(obj) +} + +thread_local! { + /// Each interpreter's `unpack_iterator` class and its slot layout, by + /// the interpreter's address (see [`b_native_iter_unpack`]); the class + /// held weakly, so a torn-down interpreter's entry never answers. + static UNPACK_ITER_CLASSES: std::cell::RefCell< + Vec<( + usize, + crate::sync::Weak, + crate::shared_value::SharedSlice, + )>, + > = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// `_native_iter_unpack(python_iter_unpack, unpack_iterator)`: the public +/// `struct.iter_unpack` (see [`iter_unpack_fast`]), with the running +/// interpreter's iterator class noted for it. +fn b_native_iter_unpack(args: &[Object]) -> Result { + let [fallback, Object::Type(cls)] = args else { + return Err(type_error( + "_native_iter_unpack() takes the Python iter_unpack and the iterator class", + )); + }; + let (Some(layout), Some(interp)) = ( + cls.own_slot_layout().cloned(), + crate::vm_singletons::current_interpreter_ptr(), + ) else { + return Ok(fallback.clone()); + }; + UNPACK_ITER_CLASSES.with(|c| { + let mut c = c.borrow_mut(); + c.retain(|(p, w, _)| *p != interp as usize && w.strong_count() > 0); + c.push((interp as usize, Rc::downgrade(cls), layout)); + }); + let obj = native_with_fallback("iter_unpack", iter_unpack_fast, fallback); + crate::descr_registry::register_text_signature(&obj, "(format, buffer, /)"); + Ok(obj) +} + +/// `iter_unpack(format, buffer)` over an exact `bytes` or `bytearray` +/// whose length the format's size divides: the iterator built in place, as +/// the Python function's `_make_unpack_iterator` builds it. Anything else +/// (a view, another buffer, an error to raise) is the Python function's. +fn iter_unpack_fast(a: &[Object]) -> Option> { + // (A `bytearray` is the Python constructor's: it holds the buffer + // through a view, an export that keeps it from being resized.) + let [Object::Str(fmt), buffer @ Object::Bytes(b)] = a else { + return None; + }; + let len = b.len(); + let size = compiled_for(fmt)?.size; + if size == 0 || len % size != 0 { + return None; + } + let interp = crate::vm_singletons::current_interpreter_ptr()? as usize; + let (cls, layout) = UNPACK_ITER_CLASSES.with(|c| { + let c = c.try_borrow().ok()?; + let (_, w, layout) = c.iter().find(|(p, _, _)| *p == interp)?; + Some((w.upgrade()?, layout.clone())) + })?; + if layout.len() != 5 { + return None; + } + let values = vec![ + Object::Str(fmt.clone()), + buffer.clone(), + Object::Int(i64::try_from(size).ok()?), + Object::Int(0), + Object::Int(i64::try_from(len).ok()?), + ]; + let slots = crate::types::SlotStorage::from_layout(layout, values); + Some(Ok(Object::Instance(Rc::new( + crate::types::PyInstance::with_slots(cls, slots), + )))) +} + fn b_iter_unpack(args: &[Object]) -> Result { let fmt = fmt_arg(args, 0)?; let cf = compiled(&fmt)?; - let buf = buffer_arg(&args[1])?; - let groups = cf.iter_unpack(&buf)?; + let groups = with_buffer(&args[1], |buf| cf.iter_unpack(buf))??; let items: Vec = groups.into_iter().map(Object::new_tuple).collect(); // Frozen wrapper turns this into an iterator; for now we hand // back a list so the Python side can `iter(...)` over it. diff --git a/crates/weavepy-vm/src/stdlib/sys.rs b/crates/weavepy-vm/src/stdlib/sys.rs index 9376614ed..3713a3e60 100644 --- a/crates/weavepy-vm/src/stdlib/sys.rs +++ b/crates/weavepy-vm/src/stdlib/sys.rs @@ -1305,9 +1305,10 @@ thread_local! { // limit on conversion, but `sys.get/set_int_max_str_digits` must round-trip // (test_int reads/sets it; many modules query it at import). static INT_MAX_STR_DIGITS: std::cell::Cell = const { std::cell::Cell::new(4300) }; - // `sys.setswitchinterval` value: advisory for WeavePy's GIL (the - // holder yields on bytecode-count boundaries, not a timer), but the - // set/get pair must round-trip (test_sys test_switchinterval). + // `sys.setswitchinterval` value as it was given, for the set/get + // pair's round trip (test_sys test_switchinterval). The GIL's own + // copy (`EvalBreaker::switch_interval`) is what a busy holder's + // checkpoints time a hand-off against. static SWITCH_INTERVAL: std::cell::Cell = const { std::cell::Cell::new(0.005) }; } @@ -1335,6 +1336,13 @@ fn sys_setswitchinterval(args: &[Object]) -> Result { )); } SWITCH_INTERVAL.with(|c| c.set(interval)); + // (At least a microsecond, CPython's unit; at most what a duration + // holds.) + crate::gil::global_gil_ref() + .breaker + .set_switch_interval(std::time::Duration::from_secs_f64( + interval.clamp(1e-6, 1e9), + )); Ok(Object::None) } @@ -1418,8 +1426,24 @@ fn sys_setrecursionlimit(args: &[Object]) -> Result { thread_local! { // (Fx-hashed: interning runs for every name of every code object a // module loads, and SipHash showed in import profiles.) - static INTERN_POOL: RefCell> = - const { RefCell::new(std::collections::HashSet::with_hasher(crate::fasthash::FxBuildHasher)) }; + // (Released under the GIL at its thread's exit: it holds strings.) + static INTERN_POOL: crate::gil::ReleaseUnderGil< + RefCell>, + > = const { + crate::gil::ReleaseUnderGil::new(RefCell::new(std::collections::HashSet::with_hasher( + crate::fasthash::FxBuildHasher, + ))) + }; +} + +/// Empty the calling thread's intern pool: a worker's last act while it +/// still holds the GIL (see [`crate::vm_singletons::clear_thread_python_tls`]). +pub(crate) fn forget_thread_interns() { + let _ = INTERN_POOL.try_with(|pool| { + if let Ok(mut pool) = pool.try_borrow_mut() { + pool.clear(); + } + }); } /// Canonicalize `name` through the interpreter's intern pool, seeding it @@ -1440,6 +1464,46 @@ pub(crate) fn intern_name(name: &str) -> Object { }) } +/// [`intern_name`] for a code object's name, through a per-thread memo +/// of recent names by the pooled name's address: the names a module's +/// code objects share (`self`, `append`) skip the pool's hash and probe. +/// Each entry holds its name, so no other text comes to sit at its +/// address. +pub(crate) fn intern_code_name(name: &weavepy_compiler::Name) -> Object { + const N: usize = 512; + thread_local! { + static MEMO: crate::gil::ReleaseUnderGil< + RefCell<[Option<(weavepy_compiler::Name, SharedStr)>; N]>, + > = const { crate::gil::ReleaseUnderGil::new(RefCell::new([const { None }; N])) }; + } + let addr = name.addr(); + let slot = (addr >> 4 ^ addr >> 13) % N; + let hit = MEMO + .try_with(|m| { + let m = m.try_borrow().ok()?; + match &m[slot] { + Some((n, pooled)) if weavepy_compiler::Name::ptr_eq(n, name) => { + Some(pooled.clone()) + } + _ => None, + } + }) + .ok() + .flatten(); + if let Some(pooled) = hit { + return Object::Str(pooled); + } + let obj = intern_name(name); + if let Object::Str(pooled) = &obj { + let _ = MEMO.try_with(|m| { + if let Ok(mut m) = m.try_borrow_mut() { + m[slot] = Some((name.clone(), pooled.clone())); + } + }); + } + obj +} + /// `sys.intern` for an existing string: the pooled object for its value, /// which becomes `text` itself on first sight. The native unpickler interns /// attribute names this way, exactly as `load_build` does. @@ -1455,6 +1519,39 @@ pub(crate) fn intern_shared(text: &SharedStr) -> SharedStr { }) } +/// [`intern_shared`] through a per-thread memo of recent names by +/// identity: a setter called with the same name object again (a frozen +/// dataclass's `object.__setattr__(self, 'x', x)`, a `setattr` in a loop) +/// skips the pool's hash and probe. Each entry holds the name it was +/// asked for, so no other string can come to sit at its address. +pub(crate) fn intern_shared_memo(text: &SharedStr) -> SharedStr { + const N: usize = 64; + thread_local! { + static MEMO: crate::gil::ReleaseUnderGil; N]>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new([const { None }; N])) }; + } + let slot = (text.as_ptr() as usize >> 4) % N; + let hit = MEMO + .try_with(|m| { + let m = m.try_borrow().ok()?; + match &m[slot] { + Some((asked, pooled)) if SharedStr::ptr_eq(asked, text) => Some(pooled.clone()), + _ => None, + } + }) + .ok() + .flatten(); + if let Some(pooled) = hit { + return pooled; + } + let pooled = intern_shared(text); + let _ = MEMO.try_with(|m| { + if let Ok(mut m) = m.try_borrow_mut() { + m[slot] = Some((text.clone(), pooled.clone())); + } + }); + pooled +} + /// CPython's `intern_string_constants` rule (codeobject.c): a str /// constant is interned when it is ASCII and every character is a name /// character (`Py_ISALNUM` or `_`); the empty string and every @@ -1466,7 +1563,9 @@ pub(crate) fn cpython_interns_constant(s: &str) -> bool { (Some(c), None) if (c as u32) < 256 => return true, _ => {} } - s.is_ascii() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') + // (Every name character is ASCII, so one pass that stops at the first + // other character, a docstring's first space, decides.) + s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') } /// Is `o` the pooled (`sys.intern`) instance for its value? `marshal` @@ -1855,7 +1954,7 @@ pub fn audit_event(event: &str, args: &[Object]) -> Result<(), RuntimeError> { // interpreter mutably. Mutation from this thread is exclusive // because the VM holds the GIL across the whole audit event. let interp = unsafe { &mut *ptr }; - let arg_tuple = Object::new_tuple(args.to_vec()); + let arg_tuple = Object::tuple_from_slice(args); let outer = interp.builtins_dict(); // `PyThreadState_EnterTracing`: hooks run untraced by default. let _suppress = crate::trace::TracingSuppressGuard::enter(); @@ -2878,8 +2977,7 @@ fn sys_set_coroutine_origin_tracking_depth(args: &[Object]) -> Result = - const { std::cell::RefCell::new((Object::None, Object::None)) }; + static ASYNCGEN_HOOKS: crate::gil::ReleaseUnderGil> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new((Object::None, Object::None))) }; } /// The currently-installed `(firstiter, finalizer)` asyncgen hooks. diff --git a/crates/weavepy-vm/src/stdlib/testcapi_call.rs b/crates/weavepy-vm/src/stdlib/testcapi_call.rs index 95c158df1..92d8c61c0 100644 --- a/crates/weavepy-vm/src/stdlib/testcapi_call.rs +++ b/crates/weavepy-vm/src/stdlib/testcapi_call.rs @@ -146,7 +146,7 @@ fn desc2_call(_args: &[Object]) -> Result { /// a fresh tuple of the positional arguments after `self`. The /// identity-preserving splat path lives in `CALL_FUNCTION_EX`. fn nopget_call(args: &[Object]) -> Result { - Ok(Object::new_tuple(args[1..].to_vec())) + Ok(Object::tuple_from_slice(&args[1..])) } const VECTORCALL_SET_KEY: &str = "_weave_vectorcall_set"; diff --git a/crates/weavepy-vm/src/stdlib/thread_real.rs b/crates/weavepy-vm/src/stdlib/thread_real.rs index 6de17dd94..a125fcdc4 100644 --- a/crates/weavepy-vm/src/stdlib/thread_real.rs +++ b/crates/weavepy-vm/src/stdlib/thread_real.rs @@ -32,7 +32,7 @@ use crate::sync::Rc; use crate::sync::RefCell; use std::collections::HashMap; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; @@ -46,14 +46,14 @@ use crate::types::{PyInstance, TypeFlags, TypeObject}; thread_local! { /// Cached "lock" type built once per interpreter so /// `type(lock).__name__` returns `"lock"` consistently. - static LOCK_TYPE: RefCell>> = const { RefCell::new(None) }; + static LOCK_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; /// Cached "RLock" type. - static RLOCK_TYPE: RefCell>> = const { RefCell::new(None) }; + static RLOCK_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; /// Per-thread "sentinel" lock returned by `_set_sentinel`. /// Auto-released on thread exit so `Thread.join` works. - static SENTINEL_LOCK: RefCell>> = const { RefCell::new(None) }; + static SENTINEL_LOCK: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; /// Cached `_ThreadHandle` type (RFC 0039). - static THREAD_HANDLE_TYPE: RefCell>> = const { RefCell::new(None) }; + static THREAD_HANDLE_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } /// Process-wide counter for synthesised thread idents (used by @@ -381,12 +381,22 @@ fn held<'a, T: 'static>(obj: &'a Object, name: &'static str) -> Option<&'a T> { let Object::Instance(inst) = obj else { return None; }; - let addr = |s: &crate::types::SlotStorage| match s.get_hinted(0, LOCK_SLOT) { - Some(Object::Builtin(b)) if std::ptr::eq(b.name, name) => match (b.call)(&[]) { + // The first slot's value, its key unread: a builtin named by the + // keeper's static is a keeper wherever it sits (only `keeper` builds + // one, and only a lock's hidden slot holds it), and a lock lays its + // slot out first. + let addr = |s: &crate::types::SlotStorage| { + let b = match s.get_index(0) { + Some((_, Object::Builtin(b))) if std::ptr::eq(b.name, name) => b, + _ => match s.get(LOCK_SLOT) { + Some(Object::Builtin(b)) if std::ptr::eq(b.name, name) => b, + _ => return None, + }, + }; + match (b.call)(&[]) { Ok(Object::Int(addr)) => Some(addr as usize), _ => None, - }, - _ => None, + } }; // SAFETY: a read of one slot that runs no code (the keeper's call // only answers an address). @@ -499,8 +509,11 @@ fn lock_enter(args: &[Object]) -> Result { } fn lock_exit(args: &[Object]) -> Result { - let _ = lock_of(args, "__exit__")?.release(); - Ok(Object::Bool(false)) + // As CPython's: `release()`, an unheld lock's error included, and `None`. + lock_of(args, "__exit__")? + .release() + .map_err(runtime_error)?; + Ok(Object::None) } fn lock_at_fork_reinit(args: &[Object]) -> Result { @@ -582,6 +595,8 @@ fn lock_type() -> Rc { }, ) .expect("lock type"); + t.pure_new + .set(Some(|_, args| args.is_empty().then(new_lock_object))); *cell.borrow_mut() = Some(t.clone()); t }) @@ -698,8 +713,9 @@ fn rlock_enter(args: &[Object]) -> Result { fn rlock_exit(args: &[Object]) -> Result { let lock = rlock_of(args, "__exit__")?; - let _ = lock.release(crate::gil::current_thread_id()); - Ok(Object::Bool(false)) + lock.release(crate::gil::current_thread_id()) + .map_err(runtime_error)?; + Ok(Object::None) } fn rlock_at_fork_reinit(args: &[Object]) -> Result { @@ -787,6 +803,8 @@ fn rlock_type() -> Rc { }, ) .expect("rlock type"); + t.pure_new + .set(Some(|_, args| args.is_empty().then(new_rlock_object))); *cell.borrow_mut() = Some(t.clone()); t }) @@ -881,7 +899,108 @@ fn lock_acquire_blocking(lock: &RealLock, me: u64) { if lock.try_acquire(me) { return; } - crate::gil::allow_threads_then(|| lock.acquire(me)); + let _ = acquire_contended( + || lock.try_acquire(me), + |w| lock.wait_free(w), + |w| take_lock(lock, me, w), + None, + false, + ); +} + +/// A contended acquire, as CPython's lock takes it: the GIL is released +/// only to wait for the lock to come free, and the lock is taken once the +/// GIL is back. A waiter that took the lock while the GIL holder ran on +/// would make that holder block at its next acquire of the same lock (a +/// `queue.Queue`'s mutex between a producer and a consumer), handing the +/// GIL over at every operation. With the GIL back first, the running +/// thread retakes a lock it released, and a woken waiter that finds it +/// taken waits again. A waiter that has waited [`HANDOFF_AFTER`] takes the +/// lock as soon as it comes free instead (`take_waiting`, with the GIL +/// released), as CPython's lock hands itself to a waiter of over a +/// millisecond: a holder that always has the lock when it yields the GIL +/// can't starve it, because a release with such a waiter keeps the lock +/// for it (see `RealLock::release`). `deadline` bounds the whole acquire (`false` when it +/// passes); `signals` waits in slices on the main thread, running pending +/// signal handlers between them (CPython's `EINTR` retry loop), and a +/// handler that raises abandons the acquire. +fn acquire_contended( + try_take: impl Fn() -> bool, + wait_free: impl Fn(Option), + take_waiting: impl Fn(Option) -> bool, + deadline: Option, + signals: bool, +) -> Result { + let start = Instant::now(); + loop { + let mut wait = match deadline { + Some(dl) => { + let now = Instant::now(); + if now >= dl { + return Ok(false); + } + Some(dl - now) + } + None => None, + }; + if signals { + wait = Some(wait.map_or(SIGNAL_POLL_SLICE, |w| w.min(SIGNAL_POLL_SLICE))); + } + if start.elapsed() >= HANDOFF_AFTER { + if crate::gil::allow_threads_then(|| take_waiting(wait)) { + return Ok(true); + } + } else { + let turn = Some(wait.map_or(HANDOFF_AFTER, |w| w.min(HANDOFF_AFTER))); + // (A turn that runs out goes on to take the lock in the same + // wait: coming back for the GIL in between cost the waiter a + // switch interval behind a busy holder.) + let taken = crate::gil::allow_threads_then(|| { + wait_free(turn); + if start.elapsed() < HANDOFF_AFTER { + return false; + } + let mut left = deadline.map(|dl| dl.saturating_duration_since(Instant::now())); + if signals { + left = Some(left.map_or(SIGNAL_POLL_SLICE, |w| w.min(SIGNAL_POLL_SLICE))); + } + take_waiting(left) + }); + if taken || try_take() { + return Ok(true); + } + } + if signals { + service_pending_signals()?; + } + } +} + +/// How long a contended acquire waits for its turn before it takes the +/// lock as soon as it comes free (see [`acquire_contended`]). +const HANDOFF_AFTER: Duration = Duration::from_millis(5); + +/// `lock`'s blocking acquire for `me`, bounded by `wait` (the waiting half +/// of a contended acquire past its hand-off point). +fn take_lock(lock: &RealLock, me: u64, wait: Option) -> bool { + match wait { + Some(d) => lock.acquire_timeout(me, d), + None => { + lock.acquire(me); + true + } + } +} + +/// [`take_lock`] for a reentrant lock. +fn take_rlock(lock: &RealRLock, me: u64, wait: Option) -> bool { + match wait { + Some(d) => lock.acquire_timeout(me, d), + None => { + lock.acquire(me); + true + } + } } /// Slice length for the main thread's signal-interruptible wait. Short @@ -919,32 +1038,13 @@ fn lock_acquire_interruptible( if lock.try_acquire(me) { return Ok(true); } - if !crate::gil::is_main_thread() { - return Ok(match timeout { - Some(d) => crate::gil::allow_threads_then(|| lock.acquire_timeout(me, d)), - None => { - crate::gil::allow_threads_then(|| lock.acquire(me)); - true - } - }); - } - let deadline = timeout.map(|d| Instant::now() + d); - loop { - let wait = match deadline { - Some(dl) => { - let now = Instant::now(); - if now >= dl { - return Ok(false); - } - (dl - now).min(SIGNAL_POLL_SLICE) - } - None => SIGNAL_POLL_SLICE, - }; - if crate::gil::allow_threads_then(|| lock.acquire_timeout(me, wait)) { - return Ok(true); - } - service_pending_signals()?; - } + acquire_contended( + || lock.try_acquire(me), + |w| lock.wait_free(w), + |w| take_lock(lock, me, w), + timeout.map(|d| Instant::now() + d), + crate::gil::is_main_thread(), + ) } /// Reentrant counterpart to [`lock_acquire_interruptible`]. @@ -956,32 +1056,13 @@ fn rlock_acquire_interruptible( if lock.try_acquire(me) { return Ok(true); } - if !crate::gil::is_main_thread() { - return Ok(match timeout { - Some(d) => crate::gil::allow_threads_then(|| lock.acquire_timeout(me, d)), - None => { - crate::gil::allow_threads_then(|| lock.acquire(me)); - true - } - }); - } - let deadline = timeout.map(|d| Instant::now() + d); - loop { - let wait = match deadline { - Some(dl) => { - let now = Instant::now(); - if now >= dl { - return Ok(false); - } - (dl - now).min(SIGNAL_POLL_SLICE) - } - None => SIGNAL_POLL_SLICE, - }; - if crate::gil::allow_threads_then(|| lock.acquire_timeout(me, wait)) { - return Ok(true); - } - service_pending_signals()?; - } + acquire_contended( + || lock.try_acquire(me), + |w| lock.wait_free(me, w), + |w| take_rlock(lock, me, w), + timeout.map(|d| Instant::now() + d), + crate::gil::is_main_thread(), + ) } /// Grace period a `join()` blocks normally before it begins running @@ -1084,7 +1165,13 @@ fn rlock_acquire_blocking(lock: &RealRLock, me: u64) { if lock.try_acquire(me) { return; } - crate::gil::allow_threads_then(|| lock.acquire(me)); + let _ = acquire_contended( + || lock.try_acquire(me), + |w| lock.wait_free(me, w), + |w| take_rlock(lock, me, w), + None, + false, + ); } fn get_ident(_args: &[Object]) -> Result { @@ -1205,6 +1292,33 @@ fn start_new_thread(args: &[Object]) -> Result { Ok(Object::Int(synth_id as i64)) } +/// Workers spawned whose OS threads haven't been joined yet (see +/// [`reap_workers`]). +static UNREAPED_WORKERS: AtomicUsize = AtomicUsize::new(0); + +/// After a `join()` saw worker `ident` finish: join the OS threads of it +/// and of every other worker that has finished (each is past its last +/// touch of an object, and its thread-local destructors run before the OS +/// join returns), with the GIL released. Once no worker is left, the +/// joining thread is the only one, and the single-thread bias comes back +/// (see [`crate::sync::restore_bias`]): a program that ran threads for a +/// while runs as fast afterwards as one that never did. +fn reap_workers(ident: u64) { + let handles = thread_registry().take_finished_handles(ident); + if handles.is_empty() { + return; + } + let n = handles.len(); + crate::gil::allow_threads_then(|| { + for h in handles { + let _ = h.join(); + } + }); + if UNREAPED_WORKERS.fetch_sub(n, Ordering::SeqCst) == n { + crate::sync::restore_bias(crate::gil::current_thread_id()); + } +} + /// Spawn one Python worker on a real OS thread. Shared by /// `_thread.start_new_thread` (fire-and-forget) and /// `_thread.start_joinable_thread` (RFC 0039 — returns a handle the @@ -1283,12 +1397,20 @@ fn spawn_python_worker( // deep recursion. A 64 MiB starting reserve keeps early-startup // segment churn low while letting hundreds of workers coexist. const WORKER_STACK_BYTES: usize = 64 * 1024 * 1024; // 64 MiB - // The worker clones and drops objects before it first takes the GIL. - crate::rc::revoke_refcount_bias(); - let handle = std::thread::Builder::new() + + // The worker takes the GIL before its first touch of an object and + // keeps it through its last (its thread-local destructors included), + // so reference counts stay plain when the spawner holds it as well. + crate::sync::note_worker_spawn(crate::gil::current_thread_holds_gil()); + UNREAPED_WORKERS.fetch_add(1, Ordering::SeqCst); + let spawned = std::thread::Builder::new() .name(format!("weavepy-worker-{}", synth_id)) .stack_size(WORKER_STACK_BYTES) .spawn(move || { + // (First, so that it is this thread's last thread-local to + // go: see the end of this body.) + crate::gil::arm_guard_stack(); + crate::sync::note_vm_worker(); crate::vm_singletons::install_worker_thread_id(synth_id); // RFC 0040 WS4: record this worker's pthread_t so // `signal.pthread_kill(ident, sig)` can target it. @@ -1407,14 +1529,14 @@ fn spawn_python_worker( // (test_threading.test_foreign_thread's `wait_threads_exit`). drop(worker_interp); crate::vm_singletons::clear_thread_python_tls(); - // Drop the guard before marking finished so the parent's - // join (which blocks on the released join lock) sees the - // released GIL — without this the parent could re-acquire - // the GIL and find the worker still "running" even though - // its target has returned. Mark the handle done *before* - // releasing the lock so a thread waking from `join()` - // immediately observes `is_done()`. - let _ = crate::gil::pop_gil_guard(); + // The guard stays on this thread's stack, and the GIL with + // it, until the thread's last thread-local is destroyed (the + // stack itself, armed first above): the caches its other + // thread-locals hold are objects, and their destructors run + // after this body returns. A joiner waits on the join lock + // with the GIL released and takes the GIL back once this + // thread is gone, so it finds the handle done either way: + // it is marked *before* the lock is released below. // A daemon thread that reaches this point during interpreter // finalization was forced out by the dispatch loop (CPython's // `tstate_must_exit`: it would hang forever in `take_gil` and @@ -1432,8 +1554,11 @@ fn spawn_python_worker( #[cfg(unix)] super::signal_mod::unregister_thread_pthread(synth_id); crate::vm_singletons::clear_worker_thread_id(); - }) - .map_err(|e| runtime_error(format!("failed to spawn thread: {}", e)))?; + }); + let handle = spawned.map_err(|e| { + UNREAPED_WORKERS.fetch_sub(1, Ordering::SeqCst); + runtime_error(format!("failed to spawn thread: {}", e)) + })?; let entry = Arc::new(ThreadEntry::new(synth_id, thread_name, daemon, handle)); entry.attach_join_lock(join_lock); @@ -1585,7 +1710,11 @@ fn get_main_thread_ident(_args: &[Object]) -> Result { pub fn after_fork_in_child() { let surviving = main_thread_ident_now(); MAIN_THREAD_IDENT.store(surviving, Ordering::Release); - for state in handle_registry().lock().values() { + for state in handle_registry() + .lock() + .values() + .filter_map(std::sync::Weak::upgrade) + { let id = state.ident.load(Ordering::Acquire); // ident 0 = an unstarted handle; leave it. The surviving thread's own // handle stays alive; everything else is now dead. @@ -1617,12 +1746,29 @@ struct ThreadHandleState { /// instance dict as `_wp_hid`) to its shared state, so /// `start_joinable_thread` can wire a worker to a pre-constructed /// handle. -fn handle_registry() -> &'static parking_lot::Mutex>> { - static REG: OnceLock>>> = +/// Every live handle's state by its `_wp_hid`. The handle object's own +/// methods hold the state; the registry holds it weakly, so a handle that +/// dies (with its `threading.Thread`) leaves nothing behind but an entry +/// the next registration's sweep drops. +fn handle_registry() -> &'static parking_lot::Mutex>> +{ + static REG: OnceLock>>> = OnceLock::new(); REG.get_or_init(|| parking_lot::Mutex::new(HashMap::new())) } +/// Register `state` under `hid`, first sweeping out the entries of dead +/// handles once the registry has doubled since the last sweep. +fn register_handle(hid: u64, state: &Arc) { + static SWEEP_AT: AtomicUsize = AtomicUsize::new(64); + let mut reg = handle_registry().lock(); + if reg.len() >= SWEEP_AT.load(Ordering::Relaxed) { + reg.retain(|_, w| w.strong_count() > 0); + SWEEP_AT.store((reg.len() * 2).max(64), Ordering::Relaxed); + } + reg.insert(hid, Arc::downgrade(state)); +} + static NEXT_HANDLE_ID: AtomicU64 = AtomicU64::new(1); fn thread_handle_type() -> Rc { @@ -1651,7 +1797,7 @@ fn thread_handle_type() -> Rc { /// from a handle the caller pre-created. fn make_thread_handle_object(state: Arc, ident: Object) -> Object { let hid = NEXT_HANDLE_ID.fetch_add(1, Ordering::AcqRel); - handle_registry().lock().insert(hid, state.clone()); + register_handle(hid, &state); let dict = Rc::new(RefCell::new(DictData::default())); @@ -1669,6 +1815,7 @@ fn make_thread_handle_object(state: Arc, ident: Object) -> Ob return Err(runtime_error("thread not started")); } if join_state.done.load(Ordering::Acquire) { + reap_workers(ident); return Ok(Object::None); } // Joining a thread from itself would deadlock; CPython's handle @@ -1718,6 +1865,9 @@ fn make_thread_handle_object(state: Arc, ident: Object) -> Ob } }, } + if join_state.done.load(Ordering::Acquire) { + reap_workers(ident); + } Ok(Object::None) }; @@ -1775,7 +1925,10 @@ fn handle_state_of(obj: &Object) -> Option> { _ => return None, } }; - handle_registry().lock().get(&hid).cloned() + handle_registry() + .lock() + .get(&hid) + .and_then(std::sync::Weak::upgrade) } /// `_thread._ThreadHandle()` — a fresh, unstarted handle. diff --git a/crates/weavepy-vm/src/stdlib/time.rs b/crates/weavepy-vm/src/stdlib/time.rs index 5226bc01e..24abd4260 100644 --- a/crates/weavepy-vm/src/stdlib/time.rs +++ b/crates/weavepy-vm/src/stdlib/time.rs @@ -293,8 +293,7 @@ fn struct_time_type() -> Rc { // (The registry memoises the type per thread too; this skips building // the layout and the name lookup for every `localtime`.) thread_local! { - static TYPE: std::cell::OnceCell> = - const { std::cell::OnceCell::new() }; + static TYPE: crate::gil::ReleaseUnderGil>> = const { crate::gil::ReleaseUnderGil::new(std::cell::OnceCell::new()) }; } TYPE.with(|t| { t.get_or_init(|| { @@ -321,8 +320,7 @@ fn make_struct_time(values: Vec) -> Object { /// `tm_gmtoff` and `tm_zone` (the order `with_tz_extras` stores them in). fn struct_time_keys() -> std::rc::Rc<[DictKey]> { thread_local! { - static KEYS: std::cell::OnceCell> = - const { std::cell::OnceCell::new() }; + static KEYS: crate::gil::ReleaseUnderGil>> = const { crate::gil::ReleaseUnderGil::new(std::cell::OnceCell::new()) }; } KEYS.with(|k| { k.get_or_init(|| { @@ -353,8 +351,7 @@ fn make_struct_time_tz(values: Vec, gmtoff: i64, zone: Object) -> Object #[cfg(unix)] fn zone_str(bytes: &[u8]) -> Object { thread_local! { - static LAST: std::cell::RefCell, Object)>> = - const { std::cell::RefCell::new(None) }; + static LAST: crate::gil::ReleaseUnderGil, Object)>>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(None)) }; } LAST.with(|last| { if let Some((b, z)) = &*last.borrow() { @@ -429,8 +426,7 @@ fn time_get_clock_info(args: &[Object]) -> Result { other => return Err(crate::error::value_error(format!("unknown clock: {other}"))), }; thread_local! { - static CLOCK_INFO_TYPE: RefCell>> = - const { RefCell::new(None) }; + static CLOCK_INFO_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } let cls = CLOCK_INFO_TYPE.with(|slot| { if let Some(c) = slot.borrow().as_ref() { diff --git a/crates/weavepy-vm/src/stdlib/ucd/mod.rs b/crates/weavepy-vm/src/stdlib/ucd/mod.rs index d53e4a088..2323b92dd 100644 --- a/crates/weavepy-vm/src/stdlib/ucd/mod.rs +++ b/crates/weavepy-vm/src/stdlib/ucd/mod.rs @@ -429,6 +429,11 @@ const NORM_CORRECTIONS_32: &[(u32, u32)] = &[ ]; fn decompose_cp(cp: u32, compat: bool, old: bool, out: &mut Vec) { + // Nothing below U+00A0 decomposes, canonically or otherwise. + if cp < 0xA0 { + out.push(cp); + return; + } if old { if let Ok(i) = NORM_CORRECTIONS_32.binary_search_by_key(&cp, |&(c, _)| c) { decompose_cp(NORM_CORRECTIONS_32[i].1, compat, old, out); @@ -454,6 +459,10 @@ fn decompose_cp(cp: u32, compat: bool, old: bool, out: &mut Vec) { } fn combining_of(cp: u32, old: bool) -> u8 { + // The first nonzero combining class is U+0300's. + if cp < 0x300 { + return 0; + } if cp < 0x0011_0000 { record(cp, old).combining() } else { @@ -549,6 +558,98 @@ fn compose(cps: &mut Vec, old: bool) { *cps = out; } +/// Code points that some composition pair takes as its second element, +/// including the Hangul vowel and trailing jamo. +fn is_composition_second(cp: u32) -> bool { + static SECONDS: OnceLock> = OnceLock::new(); + if (V_BASE..V_BASE + V_COUNT).contains(&cp) || (T_BASE + 1..T_BASE + T_COUNT).contains(&cp) { + return true; + } + SECONDS + .get_or_init(|| comp_index().keys().map(|&(_, b)| b).collect()) + .contains(&cp) +} + +/// Whether the current-version `form` leaves `cp` as is wherever it sits in +/// a run of such code points: a starter that maps to itself, and for the +/// composing forms one whose decomposition starts with a starter and which +/// can't join the code point before it. +fn quick_yes_one(form: usize, cp: u32) -> bool { + let (compat, compose_after) = (form & 1 == 1, form < 2); + if combining_of(cp, false) != 0 { + return false; + } + let mut d = Vec::with_capacity(4); + decompose_cp(cp, compat, false, &mut d); + if !compose_after { + return d.len() == 1 && d[0] == cp; + } + if is_composition_second(cp) || is_composition_second(d[0]) || combining_of(d[0], false) != 0 { + return false; + } + canonical_order(&mut d, false); + compose(&mut d, false); + d.len() == 1 && d[0] == cp +} + +/// Per-form bitsets over the Basic Multilingual Plane, filled 256 code +/// points at a time on first use. +struct QuickTable { + words: [[std::sync::atomic::AtomicU64; 4]; 256], + ready: [std::sync::atomic::AtomicBool; 256], +} + +impl QuickTable { + const fn new() -> Self { + QuickTable { + words: [const { [const { std::sync::atomic::AtomicU64::new(0) }; 4] }; 256], + ready: [const { std::sync::atomic::AtomicBool::new(false) }; 256], + } + } +} + +static QUICK: [QuickTable; 4] = [const { QuickTable::new() }; 4]; + +fn quick_yes_bmp(form: usize, cp: u32) -> bool { + use std::sync::atomic::Ordering; + let t = &QUICK[form]; + let block = (cp >> 8) as usize; + if !t.ready[block].load(Ordering::Acquire) { + for w in 0..4u32 { + let mut bits = 0u64; + for k in 0..64u32 { + if quick_yes_one(form, ((block as u32) << 8) | (w << 6) | k) { + bits |= 1 << k; + } + } + t.words[block][w as usize].store(bits, Ordering::Relaxed); + } + t.ready[block].store(true, Ordering::Release); + } + let low = cp & 0xFF; + t.words[block][(low >> 6) as usize].load(Ordering::Relaxed) >> (low & 63) & 1 == 1 +} + +/// CPython's `is_normalized_quickcheck` answering "yes": the current +/// version's `form` (NFC/NFD/NFKC/NFKD) leaves `s` unchanged. `false` +/// means "maybe". +pub fn quick_normalized(form: &str, s: &str) -> bool { + let form = match form { + "NFC" => 0, + "NFKC" => 1, + "NFD" => 2, + "NFKD" => 3, + _ => return false, + }; + if s.is_ascii() { + return true; + } + s.chars().all(|c| { + let cp = c as u32; + cp < 0x80 || (cp < 0x1_0000 && quick_yes_bmp(form, cp)) + }) +} + /// Normalize a code-point sequence. `form` must be one of /// NFC/NFD/NFKC/NFKD (validated by the caller). pub fn normalize(form: &str, cps: &[u32], old: bool) -> Vec { diff --git a/crates/weavepy-vm/src/stdlib/unicodedata_mod.rs b/crates/weavepy-vm/src/stdlib/unicodedata_mod.rs index 40dfea2b6..baa3a06a8 100644 --- a/crates/weavepy-vm/src/stdlib/unicodedata_mod.rs +++ b/crates/weavepy-vm/src/stdlib/unicodedata_mod.rs @@ -124,12 +124,16 @@ fn build_inner_ucd() -> Rc { } fn builtin(name: &'static str, body: fn(&[Object]) -> Result) -> Object { - Object::Builtin(Rc::new(BuiltinFn { + let b = Rc::new(BuiltinFn { name, binds_instance: false, call: Box::new(body), call_kw: None, - })) + }); + // Every body reads the character database and runs no Python code: a + // call site runs it in place. + crate::leaf_builtins::register(&b); + Object::Builtin(b) } /// The single code point of a one-character string argument, accepting both @@ -139,18 +143,26 @@ fn builtin(name: &'static str, body: fn(&[Object]) -> Result Result { + // (CPython numbers the argument of the functions that also take a + // default.) + let arg = if matches!(fn_name, "name" | "decimal" | "digit" | "numeric") { + "argument 1" + } else { + "argument" + }; match args.first() { Some(obj) if obj.is_str() => { let cps = obj.str_codepoints().unwrap_or_default(); match cps.as_slice() { [cp] => Ok(*cp), _ => Err(type_error(format!( - "{fn_name}() argument must be a unicode character" + "{fn_name}(): {arg} must be a unicode character, not a string of length {}", + cps.len() ))), } } Some(other) => Err(type_error(format!( - "{fn_name}() argument 1 must be str, not '{}'", + "{fn_name}() {arg} must be a unicode character, not {}", other.type_name() ))), None => Err(type_error(format!("{fn_name}() takes at least 1 argument"))), @@ -280,7 +292,11 @@ fn arg_unistr_codepoints(args: &[Object], fname: &str) -> Result, Runti // anywhere str is (RFC 0076 WS1). fn cps(o: &Object) -> Option> { match o { - Object::Str(s) => Some(s.chars().map(|c| c as u32).collect()), + Object::Str(s) => { + let mut v = Vec::with_capacity(s.len()); + v.extend(s.chars().map(|c| c as u32)); + Some(v) + } Object::WStr(cps) => Some(cps.to_vec()), Object::Instance(inst) => inst.native.get().and_then(cps), _ => None, @@ -291,6 +307,17 @@ fn arg_unistr_codepoints(args: &[Object], fname: &str) -> Result, Runti .ok_or_else(|| type_error(format!("{fname}() unistr must be str"))) } +/// The quick check over a `str` (or a `str` subclass's text) argument. +fn quick_normalized_arg(form: &str, o: Option<&Object>) -> bool { + match o { + Some(Object::Str(s)) => ucd::quick_normalized(form, s), + Some(Object::Instance(inst)) => { + matches!(inst.native.get(), Some(Object::Str(s)) if ucd::quick_normalized(form, s)) + } + _ => false, + } +} + fn arg_form<'a>(args: &'a [Object], fname: &str) -> Result<&'a str, RuntimeError> { match args.first() { Some(Object::Str(s)) => Ok(s), @@ -310,6 +337,18 @@ fn impl_normalize(args: &[Object], old: bool) -> Result { if !matches!(form, "NFC" | "NFD" | "NFKC" | "NFKD") { return Err(value_error("invalid normalization form")); } + // CPython returns the input itself (a subclass's as a plain `str`) when + // the quick check says it's already in the current version's form. + if !old && quick_normalized_arg(form, args.get(1)) { + return Ok(match &args[1] { + Object::Instance(inst) => inst + .native + .get() + .cloned() + .unwrap_or_else(|| args[1].clone()), + o => o.clone(), + }); + } let cps = arg_unistr_codepoints(args, "normalize")?; let out = ucd::normalize(form, &cps, old); Ok(Object::str_from_codepoints(out)) @@ -320,6 +359,9 @@ fn impl_is_normalized(args: &[Object], old: bool) -> Result>> = const { RefCell::new(None) }; - static PROXY_TYPE: RefCell>> = const { RefCell::new(None) }; - static CALLABLE_PROXY_TYPE: RefCell>> = const { RefCell::new(None) }; + static REF_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; + /// [`REF_TYPE`]'s address once built (`0` before): a type call's one + /// compare (see [`is_ref_type`]). + static REF_TYPE_ADDR: std::cell::Cell = const { std::cell::Cell::new(0) }; + static PROXY_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; + static CALLABLE_PROXY_TYPE: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } pub fn build(_cache: &ModuleCache) -> Rc { @@ -84,6 +87,10 @@ pub fn build(_cache: &ModuleCache) -> Rc { DictKey(Object::from_static("ReferenceType")), Object::Type(ref_type()), ); + d.insert( + DictKey(Object::from_static("_install_weak_tables")), + b("_install_weak_tables", install_weak_tables), + ); d.insert( DictKey(Object::from_static("ProxyType")), Object::Type(proxy_type()), @@ -166,6 +173,12 @@ fn ref_type_call(args: &[Object]) -> Result { let me = args .first() .ok_or_else(|| type_error("__call__() missing self"))?; + if args.len() > 1 { + return Err(type_error(format!( + "weakref expected 0 arguments, got {}", + args.len() - 1 + ))); + } if let Object::Instance(inst) = me { let getter = reg::wrapper_value(inst, WrapperKey::Get); if let Some(Object::Builtin(b)) = getter { @@ -175,6 +188,18 @@ fn ref_type_call(args: &[Object]) -> Result { Err(type_error("__call__() requires a weakref instance")) } +/// [`ref_type_call`]'s leaf half: a weakref instance's referent, or +/// `None` once it died; anything else declines to the full call. +fn ref_call_fast(args: &[Object]) -> Option> { + let [me @ Object::Instance(inst)] = args else { + return None; + }; + if let Some(r) = reg::wrapper_deref_in_place(inst) { + return r.ok().map(Ok); + } + ref_type_call(std::slice::from_ref(me)).ok().map(Ok) +} + /// C-API bridge (`PyWeakref_NewRef`): mint a plain weakref to `target`, /// exactly like `_weakref.ref(target, callback)`. pub fn c_new_ref(target: Object, callback: Option) -> Result { @@ -228,6 +253,480 @@ pub fn c_referent(obj: &Object) -> Option> { /// Referent of a ref/proxy wrapper through its per-instance deref /// closure. `Some(Some(target))` while live, `Some(None)` once dead, /// `None` when `obj` isn't a weakref wrapper at all. +/// `_install_weak_tables(WeakKeyDictionary, WeakSet)`: serve the plain +/// lookups of the two classes natively for keys that compare by identity +/// (see [`identity_keyed`]), each falling back to the Python method it +/// replaces for anything else. +fn install_weak_tables(args: &[Object]) -> Result { + let (wkd, ws) = match args { + [Object::Type(wkd), Object::Type(ws)] => (wkd, ws), + [Object::Type(wkd), Object::Type(ws), Object::Type(keyed), rest @ ..] => { + // (A `WeakValueDictionary` store builds a `KeyedRef` in place.) + keyed.pure_new.set(Some(keyedref_pure_new)); + if let [Object::Type(wvd)] = rest { + note_removal_twin(TWIN_WVD, wvd, "remove"); + } + (wkd, ws) + } + _ => { + return Err(type_error( + "_install_weak_tables() expects the weak classes", + )) + } + }; + note_removal_twin(TWIN_WKD, wkd, "remove"); + note_removal_twin(TWIN_SET, ws, "_remove"); + let own = |cls: &Rc, name: &str| cls.dict.borrow().get(&StrKey(name)).cloned(); + if let (Some(getitem), Some(get), Some(contains), Some(setitem)) = ( + own(wkd, "__getitem__"), + own(wkd, "get"), + own(wkd, "__contains__"), + own(wkd, "__setitem__"), + ) { + crate::stdlib::struct_mod::install_fast_methods( + wkd, + [ + ( + "__getitem__", + wkd_getitem_fast as crate::leaf_builtins::Fast, + getitem, + ), + ("get", wkd_get_fast, get), + ("__contains__", wkd_contains_fast, contains), + ("__setitem__", wkd_setitem_fast, setitem), + ], + ); + } + if let (Some(add), Some(contains)) = (own(ws, "add"), own(ws, "__contains__")) { + crate::stdlib::struct_mod::install_fast_methods( + ws, + [ + ("add", weakset_add_fast as crate::leaf_builtins::Fast, add), + ("__contains__", weakset_contains_fast, contains), + ], + ); + } + Ok(Object::None) +} + +/// `KeyedRef(ob, callback, key)` while the class keeps `weakref`'s own +/// `__new__` and `__init__` (a verdict kept per class version): the ref +/// `ref.__new__(cls, ob, callback)` makes, its `key` slot set, as those +/// methods leave it. `None` for any other call (an object that can't be +/// weakly referenced, whose error the full call raises). +fn keyedref_pure_new(cls: &Rc, args: &[Object]) -> Option { + let [ob, callback, key] = args else { + return None; + }; + let own = |name: &str| match cls.dict.borrow().get(&StrKey(name)) { + Some(Object::Function(f)) => f.code().qualname == format!("KeyedRef.{name}"), + Some(Object::StaticMethod(m)) => matches!( + m.func(), + Object::Function(f) if f.code().qualname == format!("KeyedRef.{name}") + ), + _ => false, + }; + if crate::trace::any_observers_active() + || !cls.memo_verdict(crate::types::Verdict::KeyedRefPlainNew, "", || { + own("__new__") && own("__init__") + }) + || !supports_weakref(ob) + { + return None; + } + let obj = make_ref_object_with_class( + ob.clone(), + extract_callback(Some(callback)), + kind::REF, + Some(cls.clone()), + ); + let Object::Instance(inst) = &obj else { + return None; + }; + inst.slots.try_borrow_mut().ok()?.insert("key", key.clone()); + Some(obj) +} + +/// Whether `key` compares and hashes by identity, so the stored weak +/// reference equal to `ref(key)` is the one whose referent is `key` +/// itself: a function, a class whose metaclass keeps `type`'s `__eq__` +/// and `__hash__`, or a plain instance (weakly referenceable) whose class +/// keeps `object`'s. +fn identity_keyed(key: &Object) -> bool { + match key { + Object::Function(_) => true, + Object::Type(t) => crate::object::type_hash_is_identity(t), + Object::Instance(i) => { + let cls = i.cls_raw(); + i.native.get().is_none() + && cls.native_kind.get() == 0 + && cls.c_ext_ptr.get() == 0 + && cls.dunder(crate::types::Dunder::Eq).object_owner() + && cls.dunder(crate::types::Dunder::Hash).object_owner() + && supports_weakref(key) + } + _ => false, + } +} + +/// A probe for a weak table's entry for `key` (see [`identity_keyed`]): +/// the stored live weak reference whose referent is `key`. +struct ReferentProbe<'a> { + key: &'a Object, + hash: i64, +} + +impl crate::dictmap::Probe for ReferentProbe<'_> { + fn probe_hash(&self) -> i64 { + self.hash + } + + fn probe_eq(&self, stored: &DictKey) -> bool { + match &stored.0 { + Object::Instance(inst) => matches!( + reg::wrapper_deref_in_place(inst), + Some(Ok(r)) if r.is_same(self.key) + ), + _ => false, + } + } +} + +/// The probe for `key` and the weak table's `data` attribute of `recv`, +/// when the lookup is one the fast halves settle. +fn weak_table_parts(recv: &Object, key: &Object) -> Option<(Object, i64)> { + if !identity_keyed(key) || crate::trace::any_observers_active() { + return None; + } + let Object::Instance(inst) = recv else { + return None; + }; + let data = match inst.dict.published() { + Some(d) => d.try_borrow().ok()?.get(&StrKey("data")).cloned(), + None => inst + .dict + .split_cell() + .try_borrow() + .ok()? + .get_str("data") + .cloned(), + }?; + // (As a `ref`'s hash is its referent's, see `weakref_native_hash`.) + let hash = + crate::object::py_hash_value(key).unwrap_or_else(|| crate::object::identity_hash(key)); + Some((data, hash)) +} + +/// `WeakKeyDictionary` lookups: the value of the entry for `key`, or +/// `None` for a miss (`Some(None)`) or a shape the Python method takes. +fn wkd_lookup(recv: &Object, key: &Object) -> Option> { + let (Object::Dict(d), hash) = weak_table_parts(recv, key)? else { + return None; + }; + let d = d.try_borrow().ok()?; + Some( + d.get_full(&ReferentProbe { key, hash }) + .map(|(_, _, v)| v.clone()), + ) +} + +/// `wkd[key]` (a miss raises through the Python method). +fn wkd_getitem_fast(args: &[Object]) -> Option> { + let [recv, key] = args else { + return None; + }; + wkd_lookup(recv, key)?.map(Ok) +} + +/// `wkd.get(key[, default])`. +fn wkd_get_fast(args: &[Object]) -> Option> { + let (recv, key, default) = match args { + [recv, key] => (recv, key, Object::None), + [recv, key, default] => (recv, key, default.clone()), + _ => return None, + }; + Some(Ok(wkd_lookup(recv, key)?.unwrap_or(default))) +} + +/// `key in wkd`. +fn wkd_contains_fast(args: &[Object]) -> Option> { + let [recv, key] = args else { + return None; + }; + Some(Ok(Object::Bool(wkd_lookup(recv, key)?.is_some()))) +} + +/// `wkd[key] = value`: for a key already present, the value replaced and +/// the stored reference kept (as a dict store under an equal key keeps +/// it); for a new key, the entry under the reference +/// `ref(key, self._remove)` makes ([`new_member_ref`]). +fn wkd_setitem_fast(args: &[Object]) -> Option> { + let [recv, key, value] = args else { + return None; + }; + let (Object::Dict(d), hash) = weak_table_parts(recv, key)? else { + return None; + }; + let found = d + .try_borrow() + .ok()? + .get_full(&ReferentProbe { key, hash }) + .map(|(i, _, _)| i); + let Some(i) = found else { + let Object::Instance(inst) = recv else { + return None; + }; + let r = new_member_ref(key, &own_attr(inst, "_remove")?, hash)?; + d.try_borrow_mut() + .ok()? + .insert_unique_hashed(hash, DictKey(r), value.clone()); + return Some(Ok(Object::None)); + }; + let old = { + let mut d = d.try_borrow_mut().ok()?; + let (_, slot) = d.get_index_mut(i)?; + std::mem::replace(slot, value.clone()) + }; + drop(old); + Some(Ok(Object::None)) +} + +/// The attribute `name` of the weak table `inst`, from its own dictionary. +fn own_attr(inst: &PyInstance, name: &'static str) -> Option { + match inst.dict.published() { + Some(d) => d.try_borrow().ok()?.get(&StrKey(name)).cloned(), + None => inst + .dict + .split_cell() + .try_borrow() + .ok()? + .get_str(name) + .cloned(), + } +} + +/// `ref(target, callback)` for a weak table's new entry, `target` hashing +/// to `hash` by identity (see [`identity_keyed`]): an exact `ref` with its +/// callback, its hash remembered as `ref.__hash__` remembers it (the entry +/// stays discardable once the target is gone). +fn new_member_ref(target: &Object, callback: &Object, hash: i64) -> Option { + if !supports_weakref(target) { + return None; + } + let r = make_ref_object_with_class( + target.clone(), + extract_callback(Some(callback)), + kind::REF, + None, + ); + let Object::Instance(ri) = &r else { + return None; + }; + ri.hash_cache.store(hash); + Some(r) +} + +/// The weak tables' removal closures a callback may be (see +/// [`removal_twin`]): `WeakSet.__init__`'s `_remove`, and +/// `WeakKeyDictionary.__init__`'s and `WeakValueDictionary.__init__`'s +/// `remove`. +const TWIN_SET: usize = 0; +const TWIN_WKD: usize = 1; +const TWIN_WVD: usize = 2; + +/// Each twin's closure code and class, by address (`0` before +/// [`install_weak_tables`] notes them). The code is kept alive, so its +/// address stays its own. +static TWIN_CODE: [std::sync::atomic::AtomicUsize; 3] = [ + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), +]; +static TWIN_CLASS: [std::sync::atomic::AtomicUsize; 3] = [ + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), +]; + +/// Note `cls`'s removal closure, the function `name` its `__init__` +/// defines, as twin `which`. +fn note_removal_twin(which: usize, cls: &Rc, name: &str) { + use std::sync::atomic::Ordering::Relaxed; + let init = cls.dict.borrow().get(&StrKey("__init__")).cloned(); + let Some(Object::Function(init)) = init else { + return; + }; + let code = init.code(); + let inner = code.constants.iter().find_map(|c| match c { + weavepy_compiler::Constant::Code(inner) if inner.name == name => Some(inner.clone()), + _ => None, + }); + let Some(inner) = inner else { + return; + }; + TWIN_CODE[which].store(std::sync::Arc::as_ptr(&inner) as usize, Relaxed); + TWIN_CLASS[which].store(Rc::as_ptr(cls) as usize, Relaxed); + // (Kept for good: a freed code object's address could become another + // function's.) + std::mem::forget(inner); +} + +/// The callback `cb` of the dead weak reference `wr` when it is one of the +/// weak tables' own removal closures (see [`TWIN_CODE`]), still closed over +/// a table of the class it was written for: what the closure's body does, +/// done here with no frame. A `WeakSet`'s discards `wr` from its `data`; a +/// `WeakKeyDictionary`'s deletes `data[wr]`, a missing key being fine; a +/// `WeakValueDictionary`'s removes `data[wr.key]` if that entry's +/// reference is dead (`_remove_dead_weakref`). `true` when done (a table +/// already gone has nothing to remove), `false`, nothing touched, for any +/// other callback or a table in a shape the closure itself should see. +pub(crate) fn removal_twin(cb: &Object, wr: &Object) -> bool { + use std::sync::atomic::Ordering::Relaxed; + let Object::Function(f) = cb else { + return false; + }; + // SAFETY: a GIL-serialized read of the function's code cell. + let code = Rc::as_ptr(unsafe { &*f.code.as_ptr() }) as usize; + let Some(which) = TWIN_CODE.iter().position(|t| t.load(Relaxed) == code) else { + return false; + }; + if code == 0 || crate::trace::any_observers_active() { + return false; + } + // `self = selfref()`: the table, or gone. + let Some(selfref) = f.defaults.first() else { + return false; + }; + let table = match wrapper_referent(selfref) { + Some(Some(table)) => table, + Some(None) => return true, + None => return false, + }; + let Object::Instance(inst) = &table else { + return false; + }; + if std::ptr::from_ref(inst.cls_raw()) as usize != TWIN_CLASS[which].load(Relaxed) { + return false; + } + let Some(data) = own_attr(inst, "data") else { + return false; + }; + let Object::Instance(dead) = wr else { + return false; + }; + // The stored entry is `wr` itself: a dead reference equals only + // itself. (Anything else under its hash that isn't an exact `ref` + // could answer `==` its own way: the closure's to ask.) + let is_ref = |k: &Object| matches!(k, Object::Instance(i) if is_ref_type(&i.cls())); + match (which, &data) { + (TWIN_SET, Object::Set(s)) => { + let Some(hash) = dead.hash_cache.get() else { + return false; + }; + let Ok(mut s) = s.try_borrow_mut() else { + return false; + }; + let mut odd = false; + let at = s.find_by_hash(hash, |k| { + odd |= !is_ref(&k.0); + k.0.is_same(wr) + }); + if odd { + return false; + } + let removed = at.and_then(|i| s.swap_remove_index(i)); + drop(s); + drop(removed); + true + } + (TWIN_WKD, Object::Dict(d)) => { + let Some(hash) = dead.hash_cache.get() else { + return false; + }; + let Ok(mut d) = d.try_borrow_mut() else { + return false; + }; + let mut odd = false; + let at = d.find_by_hash(hash, |k| { + odd |= !is_ref(&k.0); + k.0.is_same(wr) + }); + if odd { + return false; + } + let removed = at.and_then(|i| d.lazy_remove_index(i)); + drop(d); + drop(removed); + true + } + (TWIN_WVD, Object::Dict(_)) => { + // `wr.key`, a key whose hash and equality run no code. + let key = dead + .slots + .try_borrow() + .ok() + .and_then(|s| s.get("key").cloned()); + let Some(key) = key else { + return false; + }; + if !matches!( + key, + Object::Str(_) | Object::Int(_) | Object::Bytes(_) | Object::Bool(_) | Object::None + ) { + return false; + } + remove_dead_weakref(&[data, key]).is_ok() + } + _ => false, + } +} + +/// `WeakSet` membership of `item`, or `None` for a shape the Python +/// method takes. +fn weakset_has(recv: &Object, item: &Object) -> Option { + let (Object::Set(s), hash) = weak_table_parts(recv, item)? else { + return None; + }; + let s = s.try_borrow().ok()?; + Some(s.get_full(&ReferentProbe { key: item, hash }).is_some()) +} + +/// `item in weakset`. +fn weakset_contains_fast(args: &[Object]) -> Option> { + let [recv, item] = args else { + return None; + }; + Some(Ok(Object::Bool(weakset_has(recv, item)?))) +} + +/// `weakset.add(item)`: nothing to do for an item already present (the +/// Python method's new reference would compare equal and be dropped); a +/// new one's reference, `ref(item, self._remove)` ([`new_member_ref`]), +/// joins the set. +fn weakset_add_fast(args: &[Object]) -> Option> { + let [recv, item] = args else { + return None; + }; + let (Object::Set(s), hash) = weak_table_parts(recv, item)? else { + return None; + }; + let present = s + .try_borrow() + .ok()? + .get_full(&ReferentProbe { key: item, hash }) + .is_some(); + if !present { + let Object::Instance(inst) = recv else { + return None; + }; + let r = new_member_ref(item, &own_attr(inst, "_remove")?, hash)?; + s.try_borrow_mut() + .ok()? + .insert_unique_hashed(hash, DictKey(r)); + } + Some(Ok(Object::None)) +} + fn wrapper_referent(obj: &Object) -> Option> { let Object::Instance(inst) = obj else { return None; @@ -447,10 +946,13 @@ fn ref_type() -> Rc { return t; } let mut type_dict = DictData::default(); - type_dict.insert( - DictKey(Object::from_static("__call__")), - m("__call__", ref_type_call), - ); + let call = m("__call__", ref_type_call); + // `r()` runs no Python code (the referent, or `None` once it + // died): a leaf half, so call sites take the leaf lanes. + if let Object::Builtin(b) = &call { + crate::leaf_builtins::register_fast(b, ref_call_fast); + } + type_dict.insert(DictKey(Object::from_static("__call__")), call); type_dict.insert( DictKey(Object::from_static("__eq__")), m("__eq__", ref_type_eq), @@ -485,25 +987,34 @@ fn ref_type() -> Rc { // `MyRef` call `ref.__new__(cls, ob, callback)` and expect an // instance of `cls` wired to a live slot. The base type's own // call path stays on the VM's `construct_ref` special-case. + let new = Rc::new(BuiltinFn { + name: "weakref.__new__", + binds_instance: false, + call: Box::new(|args| ref_subclass_new(args, &[])), + call_kw: Some(Box::new(ref_subclass_new)), + }); + // (It runs no Python code: `KeyedRef.__new__`'s `ref.__new__(type, + // ob, callback)`, one for every `WeakValueDictionary` entry, is + // called in place.) + crate::leaf_builtins::register(&new); type_dict.insert( DictKey(Object::from_static("__new__")), - Object::StaticMethod(crate::object::MethodWrapper::new(Object::Builtin(Rc::new( - BuiltinFn { - name: "weakref.__new__", - binds_instance: false, - call: Box::new(|args| ref_subclass_new(args, &[])), - call_kw: Some(Box::new(ref_subclass_new)), - }, - )))), + Object::StaticMethod(crate::object::MethodWrapper::new(Object::Builtin(new))), ); + let init = Rc::new(BuiltinFn { + name: "__init__", + binds_instance: true, + call: Box::new(|args| ref_init(args, &[])), + call_kw: Some(Box::new(ref_init)), + }); + // (A subclass's `super().__init__(ob, callback)`, as `KeyedRef` + // makes for every `WeakValueDictionary` entry, checks its count.) + crate::leaf_builtins::register_fast(&init, |args| { + (2..=3).contains(&args.len()).then_some(Ok(Object::None)) + }); type_dict.insert( DictKey(Object::from_static("__init__")), - Object::Builtin(Rc::new(BuiltinFn { - name: "__init__", - binds_instance: true, - call: Box::new(|args| ref_init(args, &[])), - call_kw: Some(Box::new(ref_init)), - })), + Object::Builtin(init), ); // CPython 3.13's `tp_name` is `"weakref.ReferenceType"`, so // `weakref.ref.__name__ == 'ReferenceType'` and @@ -519,10 +1030,34 @@ fn ref_type() -> Rc { ) .expect("ref type"); *cell.borrow_mut() = Some(t.clone()); + REF_TYPE_ADDR.with(|a| a.set(Rc::as_ptr(&t) as usize)); + t.pure_new.set(Some(crate::seqiter::builtin_ctor_arms)); t }) } +/// Whether `cls` is this thread's `weakref.ref` type itself. +#[inline] +pub(crate) fn is_ref_type(cls: &Rc) -> bool { + REF_TYPE_ADDR.with(|a| a.get() == Rc::as_ptr(cls) as usize) +} + +/// `weakref.ref(target)` with no callback, for a type call that runs no +/// code (see `seqiter::builtin_ctor_pure`): `None` for a target that +/// can't be weakly referenced (the full call raises). +pub(crate) fn ref_pure(target: &Object, callback: Option<&Object>) -> Option { + if !supports_weakref(target) { + return None; + } + let callback = extract_callback(callback); + if callback.is_none() { + if let Some(cached) = find_cached_wrapper(id_of(target), kind::REF) { + return Some(cached); + } + } + Some(make_ref_object(target.clone(), callback, kind::REF)) +} + /// If `obj` is a weakproxy (either flavour), dereference it: CPython's /// proxy forwards `tp_getattro` wholesale, so attribute reads such as /// `proxy.__class__` must report the *referent*, never the proxy type. @@ -1032,7 +1567,7 @@ pub(crate) fn construct_ref( /// (test_ref_reuse / test_proxy_reuse). Only exact native-type wrappers /// are shared; subclass instances never are. fn find_cached_wrapper(target_id: ObjectId, kind_tag: u8) -> Option { - let base = match kind_tag { + let base = || match kind_tag { kind::PROXY => proxy_type(), kind::CALLABLE_PROXY => callable_proxy_type(), _ => ref_type(), @@ -1040,7 +1575,7 @@ fn find_cached_wrapper(target_id: ObjectId, kind_tag: u8) -> Option { for slot in reg::collect_for(target_id) { if slot.kind == kind_tag && !slot.is_dead() && !slot.has_callback { if let Some(inst) = slot.py_ref.borrow().as_ref().and_then(|w| w.upgrade()) { - if Rc::ptr_eq(&inst.cls(), &base) { + if Rc::ptr_eq(&inst.cls(), &base()) { return Some(Object::Instance(inst)); } } @@ -1089,19 +1624,19 @@ fn new_proxy(args: &[Object]) -> Result { Ok(make_ref_object(target, callback, k)) } -thread_local! { - /// How many weak references this thread has made (see - /// [`weakref_epoch`]). - static WEAKREF_EPOCH: std::cell::Cell = const { std::cell::Cell::new(0) }; -} +/// How many weak references the process has made (see [`weakref_epoch`]). +/// One count for every thread: a plain load where a thread-local costs a +/// runtime call on some platforms (macOS), and another thread's weak +/// reference only makes a comparison here see a move it needn't have. +static WEAKREF_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -/// A count of the weak references this thread has made, which moves with -/// each one: compiled code that keeps objects alive past their last use -/// (tier 2's pins) leaves for the interpreter after a call that made one, -/// so the referent dies when CPython's would. +/// A count of the weak references made, which moves with each one: +/// compiled code that keeps objects alive past their last use (tier 2's +/// pins) leaves for the interpreter after a call that made one, so the +/// referent dies when CPython's would. #[inline] pub(crate) fn weakref_epoch() -> u64 { - WEAKREF_EPOCH.with(std::cell::Cell::get) + WEAKREF_EPOCH.load(std::sync::atomic::Ordering::Relaxed) } fn make_ref_object(target: Object, callback: Option, kind_tag: u8) -> Object { @@ -1118,7 +1653,12 @@ fn make_ref_object_with_class( kind_tag: u8, class_override: Option>, ) -> Object { - WEAKREF_EPOCH.with(|e| e.set(e.get().wrapping_add(1))); + // (A plain read and write, no locked add: two threads' racing bumps + // still move the count, which is all a comparison asks.) + WEAKREF_EPOCH.store( + weakref_epoch().wrapping_add(1), + std::sync::atomic::Ordering::Relaxed, + ); let target_id = id_of(&target); // A weakly referenced instance may die in a cycle, and only a // collection can find that, so a deferred instance is tracked from @@ -1131,10 +1671,14 @@ fn make_ref_object_with_class( kind::CALLABLE_PROXY => callable_proxy_type(), _ => ref_type(), }); - // Only exact refs share methods and native storage. Foreign classes, - // proxies, and subclasses preserve their dictionary representation. - let shared_methods = kind_tag == kind::REF && Rc::ptr_eq(&class, &ref_type()); - let fixed_wrapper = shared_methods && cfg!(target_pointer_width = "64"); + // Only exact refs keep native storage; foreign classes, proxies and + // subclasses keep their dictionary representation. A subclass of `ref` + // shares the class's `__call__` and `__repr__` too (they read the + // stored getter, and both are looked up on the type), so its instances + // skip two closures each (a `KeyedRef` per `WeakValueDictionary` item). + let exact = kind_tag == kind::REF && is_ref_type(&class); + let shared_methods = exact || (kind_tag == kind::REF && class.is_subclass_of(&ref_type())); + let fixed_wrapper = exact && cfg!(target_pointer_width = "64"); let mut slot = WeakRefSlot::new(target_id, target.clone(), callback.is_some(), kind_tag); slot.fixed_wrapper = fixed_wrapper; let slot = Arc::new(slot); @@ -1155,6 +1699,24 @@ fn make_ref_object_with_class( callback.clone().unwrap_or(Object::None), ), ) + } else if shared_methods { + // A subclass's ref (a `WeakValueDictionary`'s `KeyedRef`): its + // three entries laid down in one piece. + let mut values = [ + b_dyn("__weakref_get__", get_target), + callback.clone().unwrap_or(Object::None), + Object::Int(i64::from(kind_tag)), + ] + .into_iter(); + let map = crate::dictmap::DictMap::from_unique_hashed(3, |i| { + let key = [WrapperKey::Get, WrapperKey::Callback, WrapperKey::Kind][i].owned(); + let hash = crate::object::dict_key_hash(&key.0); + (hash, key, values.next().expect("three values")) + }); + ( + Rc::new(RefCell::new(DictData::from(map))).into(), + crate::types::SlotStorage::default(), + ) } else { let dict = Rc::new(RefCell::new(DictData::default())); let mut d = dict.borrow_mut(); @@ -1280,6 +1842,21 @@ pub(crate) fn supports_weakref(target: &Object) -> bool { // slots-free (or weakref-slotted) class on the MRO is enough — // `__slots__ = ["__dict__"]` grants a dict but *not* weakrefs. let cls = inst.cls(); + // (The common case first: a class of its own with no `__slots__`.) + if !cls.flags.is_builtin && !cls.declares_slots.get() { + return true; + } + // The MRO walk below, in place: a heap class without `__slots__`, or + // listing `"__weakref__"` in them, grants weak references (every later + // test only grants them too). + for ty in cls.mro.borrow().iter() { + if ty.flags.is_builtin { + continue; + } + if !ty.declares_slots.get() || ty.slot_names.borrow().iter().any(|s| s == "__weakref__") { + return true; + } + } // CPython's `module` type carries `tp_weaklistoffset`, so every module // object is weakly referenceable — including `types.ModuleType(...)` // doubles and the fresh extension-module re-imports @@ -1314,18 +1891,6 @@ pub(crate) fn supports_weakref(target: &Object) -> bool { }) { return true; } - let mro = cls.mro.borrow().clone(); - for ty in mro { - if ty.flags.is_builtin { - continue; - } - if !ty.declares_slots.get() { - return true; - } - if ty.slot_names.borrow().iter().any(|s| s == "__weakref__") { - return true; - } - } false } @@ -1424,7 +1989,7 @@ fn remove_dead_weakref(args: &[Object]) -> Result { // is CPython's `is_dead_weakref` predicate. if matches!(wrapper_referent(&value), Some(None)) { crate::object::key_cmp_scope(|| { - d.borrow_mut().shift_remove(&dk); + d.borrow_mut().lazy_remove(&dk); })?; } Ok(Object::None) diff --git a/crates/weavepy-vm/src/stdlib/win_console.rs b/crates/weavepy-vm/src/stdlib/win_console.rs index eb1d0d9a5..460c97016 100644 --- a/crates/weavepy-vm/src/stdlib/win_console.rs +++ b/crates/weavepy-vm/src/stdlib/win_console.rs @@ -608,7 +608,7 @@ fn wcio_write(args: &[Object]) -> Result { pub(crate) fn windows_console_io_type() -> Rc { use crate::object::MethodWrapper; thread_local! { - static CLS: RefCell>> = const { RefCell::new(None) }; + static CLS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } CLS.with(|slot| { if let Some(c) = slot.borrow().as_ref() { diff --git a/crates/weavepy-vm/src/stdlib/winapi_mod.rs b/crates/weavepy-vm/src/stdlib/winapi_mod.rs index 16c3ba26d..4d15ef7ae 100644 --- a/crates/weavepy-vm/src/stdlib/winapi_mod.rs +++ b/crates/weavepy-vm/src/stdlib/winapi_mod.rs @@ -1497,8 +1497,7 @@ fn overlapped_registry() -> &'static Mutex> { static NEXT_OVERLAPPED_ID: AtomicI64 = AtomicI64::new(1); thread_local! { - static OVERLAPPED_CLASS: RefCell>> = - const { RefCell::new(None) }; + static OVERLAPPED_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } /// A live handle to a registry entry, used only during construction of diff --git a/crates/weavepy-vm/src/stdlib/winreg_mod.rs b/crates/weavepy-vm/src/stdlib/winreg_mod.rs index 09eb5732d..03ccc52f4 100644 --- a/crates/weavepy-vm/src/stdlib/winreg_mod.rs +++ b/crates/weavepy-vm/src/stdlib/winreg_mod.rs @@ -468,7 +468,7 @@ fn opt_ptr(buf: Option<&Vec>) -> *const u16 { // --------------------------------------------------------------------------- thread_local! { - static HKEY_CLASS: RefCell>> = const { RefCell::new(None) }; + static HKEY_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; } /// The `PyHKEY` type object, built once per thread (poll-object diff --git a/crates/weavepy-vm/src/stdlib/zlib_mod.rs b/crates/weavepy-vm/src/stdlib/zlib_mod.rs index 39b8d7517..40e3381ae 100644 --- a/crates/weavepy-vm/src/stdlib/zlib_mod.rs +++ b/crates/weavepy-vm/src/stdlib/zlib_mod.rs @@ -14,7 +14,6 @@ use crate::sync::Rc; use crate::sync::RefCell; -use std::collections::HashMap; use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; @@ -187,9 +186,13 @@ fn b_kw( /// Coerce a zlib data argument. Unlike a plain `str`, zlib requires a /// *bytes-like* object (buffer protocol); `str` and numbers raise /// `TypeError`, which `test_badargs` checks explicitly. -fn bytes_of(arg: Option<&Object>) -> Result, RuntimeError> { +fn bytes_of(arg: Option<&Object>) -> Result, RuntimeError> { + if let Some(o) = arg { + o.check_simple_buffer()?; + } match arg { - Some(o) => o.as_bytes_view().ok_or_else(|| { + // (A `bytes` object's bytes are read where they are.) + Some(o) => o.bytes_cow().ok_or_else(|| { type_error(format!( "a bytes-like object is required, not '{}'", o.type_name() @@ -364,16 +367,33 @@ struct ZlibDecompressorState { } thread_local! { - static COMPRESS_REG: RefCell>>> = - RefCell::new(HashMap::new()); - static DECOMPRESS_REG: RefCell>>> = - RefCell::new(HashMap::new()); - static ZDECOMP_REG: RefCell>>> = - RefCell::new(HashMap::new()); + static COMPRESS_REG: crate::gil::ReleaseUnderGil>> = crate::gil::ReleaseUnderGil::new(RefCell::new(super::handle_table::HandleTable::default())); + static DECOMPRESS_REG: crate::gil::ReleaseUnderGil>> = crate::gil::ReleaseUnderGil::new(RefCell::new(super::handle_table::HandleTable::default())); + static ZDECOMP_REG: crate::gil::ReleaseUnderGil>> = crate::gil::ReleaseUnderGil::new(RefCell::new(super::handle_table::HandleTable::default())); static NEXT_ID: RefCell = const { RefCell::new(1) }; - static COMPRESS_CLASS: RefCell>> = const { RefCell::new(None) }; - static DECOMPRESS_CLASS: RefCell>> = const { RefCell::new(None) }; - static ZDECOMP_CLASS: RefCell>> = const { RefCell::new(None) }; + static COMPRESS_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; + static DECOMPRESS_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; + static ZDECOMP_CLASS: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; +} + +/// A streaming object's state goes with it (see `handle_table`); one that +/// dies on another thread than its table's leaves it to the table's sweep. +fn compress_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + let _ = COMPRESS_REG.try_with(|r| r.try_borrow_mut().map(|mut r| r.remove(id))); + } +} + +fn decompress_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + let _ = DECOMPRESS_REG.try_with(|r| r.try_borrow_mut().map(|mut r| r.remove(id))); + } +} + +fn zdecomp_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + let _ = ZDECOMP_REG.try_with(|r| r.try_borrow_mut().map(|mut r| r.remove(id))); + } } fn next_id() -> i64 { @@ -589,20 +609,21 @@ fn zlib_compressobj(args: &[Object], kwargs: &[(String, Object)]) -> Result Result { @@ -667,6 +689,7 @@ fn compress_class() -> Rc { method_into(&mut dict, "compress", compress_compress); method_into(&mut dict, "flush", compress_flush); let cls = TypeObject::new_user("zlib.Compress", vec![bt.object_.clone()], dict) + .inspect(|cls| super::handle_table::watch_owner_class(cls, compress_died)) .expect("zlib.Compress must linearise"); *slot.borrow_mut() = Some(cls.clone()); cls @@ -683,6 +706,7 @@ fn decompress_class() -> Rc { method_into_kw(&mut dict, "decompress", decompress_decompress); method_into(&mut dict, "flush", decompress_flush); let cls = TypeObject::new_user("zlib.Decompress", vec![bt.object_.clone()], dict) + .inspect(|cls| super::handle_table::watch_owner_class(cls, decompress_died)) .expect("zlib.Decompress must linearise"); *slot.borrow_mut() = Some(cls.clone()); cls @@ -727,7 +751,7 @@ fn method_into_kw( fn compress_compress(args: &[Object]) -> Result { let id = handle_of(args)?; let data = bytes_of(args.get(1))?; - let state = COMPRESS_REG.with(|r| r.borrow().get(&id).cloned()); + let state = COMPRESS_REG.with(|r| r.borrow().get(id)); let state = state.ok_or_else(|| value_error("zlib: stale compressor"))?; let mut st = state.borrow_mut(); if st.done { @@ -740,7 +764,7 @@ fn compress_compress(args: &[Object]) -> Result { fn compress_flush(args: &[Object]) -> Result { let id = handle_of(args)?; let mode = args.get(1).and_then(Object::as_i64).unwrap_or(4); // Z_FINISH - let state = COMPRESS_REG.with(|r| r.borrow().get(&id).cloned()); + let state = COMPRESS_REG.with(|r| r.borrow().get(id)); let state = state.ok_or_else(|| value_error("zlib: stale compressor"))?; let mut st = state.borrow_mut(); if st.done { @@ -770,11 +794,11 @@ fn store_decompress_attrs(args: &[Object], unused: &[u8], unconsumed: &[u8], eof let mut d = inst.dict_cell().borrow_mut(); d.insert( DictKey(Object::from_static("unused_data")), - Object::new_bytes(unused.to_vec()), + Object::new_bytes(unused), ); d.insert( DictKey(Object::from_static("unconsumed_tail")), - Object::new_bytes(unconsumed.to_vec()), + Object::new_bytes(unconsumed), ); d.insert(DictKey(Object::from_static("eof")), Object::Bool(eof)); } @@ -805,7 +829,7 @@ fn decompress_decompress( } else { Some(max_length as usize) }; - let state = DECOMPRESS_REG.with(|r| r.borrow().get(&id).cloned()); + let state = DECOMPRESS_REG.with(|r| r.borrow().get(id)); let state = state.ok_or_else(|| value_error("zlib: stale decompressor"))?; let mut st = state.borrow_mut(); if st.eof { @@ -843,7 +867,7 @@ fn decompress_flush(args: &[Object]) -> Result { return Err(value_error("length must be greater than zero")); } } - let state = DECOMPRESS_REG.with(|r| r.borrow().get(&id).cloned()); + let state = DECOMPRESS_REG.with(|r| r.borrow().get(id)); let state = state.ok_or_else(|| value_error("zlib: stale decompressor"))?; let mut st = state.borrow_mut(); // Once the stream has ended, `flush()` has nothing left to do and must @@ -880,32 +904,58 @@ fn read_bytes_attr(args: &[Object], name: &str) -> Vec { Vec::new() } +/// `f` on a checksum's data: a `bytes`, `bytearray` or live `memoryview` +/// read where it is (a checksum runs no code while it reads), anything +/// else through [`bytes_of`] (its copy, or its error). +fn with_data(arg: Option<&Object>, f: impl FnOnce(&[u8]) -> R) -> Result { + let mut f = Some(f); + if let Some(o) = arg { + o.check_simple_buffer()?; + if let Some(r) = o.with_bytes_view(|d| (f.take().expect("called once"))(d)) { + return Ok(r); + } + } + let data = bytes_of(arg)?; + Ok((f.take().expect("called once"))(&data)) +} + fn zlib_crc32(args: &[Object]) -> Result { - let data = bytes_of(args.first())?; let init = match args.get(1) { Some(Object::Int(n)) => *n as u32, _ => 0, }; - let mut hasher = crc32fast::Hasher::new_with_initial(init); - hasher.update(&data); - Ok(Object::Int(i64::from(hasher.finalize()))) + let crc = with_data(args.first(), |data| { + let mut hasher = crc32fast::Hasher::new_with_initial(init); + hasher.update(data); + hasher.finalize() + })?; + Ok(Object::Int(i64::from(crc))) } fn zlib_adler32(args: &[Object]) -> Result { - let data = bytes_of(args.first())?; let init = match args.get(1) { Some(Object::Int(n)) => *n as u32, _ => 1, }; - // Classic Adler-32 from RFC 1950. - let mut a = init & 0xFFFF; - let mut b = (init >> 16) & 0xFFFF; + // Adler-32 from RFC 1950, reduced once per block of 5,552 bytes (zlib's + // NMAX: the most a block can add before `b` overflows 32 bits). const MOD_ADLER: u32 = 65521; - for &byte in &data { - a = (a + u32::from(byte)) % MOD_ADLER; - b = (b + a) % MOD_ADLER; - } - Ok(Object::Int(i64::from((b << 16) | a))) + const NMAX: usize = 5552; + let sum = with_data(args.first(), |data| { + let mut a = init & 0xFFFF; + let mut b = (init >> 16) & 0xFFFF; + for block in data.chunks(NMAX) { + for &byte in block { + a += u32::from(byte); + b += a; + } + a %= MOD_ADLER; + b %= MOD_ADLER; + } + // (zlib reduces the starting value even for no data.) + (b % MOD_ADLER) << 16 | (a % MOD_ADLER) + })?; + Ok(Object::Int(i64::from(sum))) } // ---- zlib._ZlibDecompressor ------------------------------------------- @@ -931,6 +981,7 @@ fn zlibdecompressor_class() -> Rc { method_into(&mut dict, "__reduce__", zlibdecompressor_no_pickle); method_into(&mut dict, "__reduce_ex__", zlibdecompressor_no_pickle); let cls = TypeObject::new_user("_ZlibDecompressor", vec![bt.object_.clone()], dict) + .inspect(|cls| super::handle_table::watch_owner_class(cls, zdecomp_died)) .expect("zlib._ZlibDecompressor must linearise"); *slot.borrow_mut() = Some(cls.clone()); cls @@ -946,7 +997,7 @@ fn store_zd_attrs(args: &[Object], unused: &[u8], eof: bool, needs_input: bool) let mut d = inst.dict_cell().borrow_mut(); d.insert( DictKey(Object::from_static("unused_data")), - Object::new_bytes(unused.to_vec()), + Object::new_bytes(unused), ); d.insert(DictKey(Object::from_static("eof")), Object::Bool(eof)); d.insert( @@ -992,10 +1043,12 @@ fn zlib_zlibdecompressor( } } let id = next_id(); + let inst = Rc::new(PyInstance::new(zlibdecompressor_class())); ZDECOMP_REG.with(|r| { r.borrow_mut().insert( id, - Rc::new(RefCell::new(ZlibDecompressorState { + &inst, + ZlibDecompressorState { d: None, wbits, zdict, @@ -1004,10 +1057,9 @@ fn zlib_zlibdecompressor( needs_input: true, unused_data: Vec::new(), broken: false, - })), + }, ); }); - let inst = PyInstance::new(zlibdecompressor_class()); { let mut d = inst.dict_cell().borrow_mut(); d.insert(DictKey(Object::from_static("_handle")), Object::Int(id)); @@ -1021,7 +1073,7 @@ fn zlib_zlibdecompressor( Object::Bool(true), ); } - Ok(Object::Instance(Rc::new(inst))) + Ok(Object::Instance(inst)) } fn zlibdecompressor_decompress( @@ -1048,7 +1100,7 @@ fn zlibdecompressor_decompress( } else { Some(max_length as usize) }; - let state = ZDECOMP_REG.with(|r| r.borrow().get(&id).cloned()); + let state = ZDECOMP_REG.with(|r| r.borrow().get(id)); let state = state.ok_or_else(|| value_error("zlib: stale decompressor"))?; let mut st = state.borrow_mut(); if st.eof { diff --git a/crates/weavepy-vm/src/stdlib/zoneinfo_native.rs b/crates/weavepy-vm/src/stdlib/zoneinfo_native.rs new file mode 100644 index 000000000..4082845ae --- /dev/null +++ b/crates/weavepy-vm/src/stdlib/zoneinfo_native.rs @@ -0,0 +1,822 @@ +//! `_weave_zoneinfo`: native zone lookups over `zoneinfo`'s Python data. +//! +//! WeavePy runs `zoneinfo.ZoneInfo` as Python code (CPython has the +//! `_zoneinfo` C accelerator), so every offset an aware `datetime` asks +//! its zone for was thousands of interpreted instructions: the local +//! timestamp, a bisection of the transition list and, past the last +//! transition, the POSIX rule's two transition days for the year. +//! +//! [`install`] (called at the end of the `zoneinfo` module body) records +//! the module's classes and the methods the lookups go through. The +//! `datetime` natives then ask [`local_info`] and [`utc_info`] for what +//! `ZoneInfo._find_trans` and `ZoneInfo.fromutc` compute, with no Python +//! code run. The zone's data stays where the Python code keeps it and is +//! read from there on every lookup, so both always agree. The zone's own +//! `utcoffset`, `dst`, `tzname` and `fromutc` get native bodies over the +//! same lookups, for an exact `datetime` argument; they call the Python +//! methods they replaced for anything else. +//! +//! A lookup serves an instance only while its class resolves the zone +//! methods to the functions [`install`] found on the base class (a +//! subclass that overrides `utcoffset` isn't served), the helper classes +//! are as they were, and the instance's dictionary holds only the +//! attributes the module itself sets (so none shadows a method). Anything +//! else, and any value of an unexpected type, declines: the caller runs +//! the Python code. + +use std::sync::atomic::{AtomicPtr, AtomicU64, AtomicUsize, Ordering}; + +use crate::error::{type_error, RuntimeError}; +use crate::import::ModuleCache; +use crate::object::{BuiltinFn, DictData, DictKey, Object, PyModule, StrKey}; +use crate::shared_value::SharedStr; +use crate::sync::{Rc, RefCell, Weak}; +use crate::types::{PyInstance, TypeObject}; + +/// `datetime(1970, 1, 1).toordinal()`. +const EPOCH_ORDINAL: i64 = 719_163; + +/// The methods a lookup stands in for, which a served class must resolve +/// to the base class's own. +const METHODS: [&str; 6] = [ + "utcoffset", + "dst", + "tzname", + "fromutc", + "_find_trans", + "_get_local_timestamp", +]; + +/// The attributes the module sets on a zone; the first five are the ones +/// the lookups read. +const FIELDS: [&str; 11] = [ + "_trans_utc", + "_trans_local", + "_ttinfos", + "_tti_before", + "_tz_after", + "_key", + "_file_path", + "_file_repr", + "_from_cache", + "_fixed_offset", + "__reduce__", +]; +const F_TRANS_UTC: usize = 0; +const F_TRANS_LOCAL: usize = 1; +const F_TTINFOS: usize = 2; +const F_TTI_BEFORE: usize = 3; +const F_TZ_AFTER: usize = 4; + +// The helper classes, in `State::aux` order. +const TTINFO: usize = 0; +const TZSTR: usize = 1; +const DAY_OFFSET: usize = 2; +const CALENDAR_OFFSET: usize = 3; + +/// One `zoneinfo` module's classes and the functions its lookups run. +struct State { + /// `_ZoneInfoBase`. + base: Weak, + /// `_ttinfo`, `_TZStr`, `_DayOffset` and `_CalendarOffset`, with the + /// class versions [`install`] saw (a later edit turns the lookups + /// off). + aux: [Weak; 4], + aux_ver: [u64; 4], + /// [`METHODS`] as the base class holds them once [`install`] is done + /// (the natives, and the two Python helpers). + methods: Vec, + /// `_TZStr._get_trans_info` and `_TZStr._get_trans_info_fromutc`. + rule_fns: [Object; 2], + fields: Vec, + /// Which of [`FIELDS`] each of a zone class's shared attribute names + /// is (see [`KeyMap`]). + keymap: KeyMap, + /// The versions of the zone classes last verified (see + /// [`State::serves`]). + verified: [AtomicU64; 4], + next: AtomicU64, +} + +/// Which of [`FIELDS`] each shared attribute name of a zone class is +/// (see `crate::inst_dict`), for instances whose values are laid out over +/// them: names never move, so the map stays valid as the table grows. +#[derive(Default)] +struct KeyMap { + /// The `SharedKeys` described (0 = none yet). + keys: AtomicUsize, + /// How many of its names are described. + len: AtomicUsize, + /// Four bits per name: the field index plus one (0 = not a field). + map: AtomicU64, +} + +impl KeyMap { + #[inline] + fn field_at(&self, pos: usize) -> usize { + ((self.map.load(Ordering::Relaxed) >> (pos * 4)) & 15) as usize + } + + #[cold] + #[inline(never)] + fn refresh(&self, keys: &crate::inst_dict::SharedKeys, fields: &[SharedStr]) { + let n = keys.len().min(16); + let mut m = 0u64; + for pos in 0..n { + if let Some(DictKey(Object::Str(s))) = keys.get(pos) { + let j = fields + .iter() + .position(|f| SharedStr::ptr_eq(s, f) || **f == **s); + if let Some(j) = j { + m |= (j as u64 + 1) << (pos * 4); + } + } + } + self.keys.store(0, Ordering::Relaxed); + self.map.store(m, Ordering::Relaxed); + self.len.store(n, Ordering::Relaxed); + self.keys + .store(std::ptr::from_ref(keys) as usize, Ordering::Relaxed); + } +} + +/// Every installed module's state (a fresh import of `zoneinfo` installs +/// its own), and the one that last served a lookup. +static STATES: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); +static LAST: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); + +fn interned(s: &str) -> SharedStr { + match crate::stdlib::sys::intern_name(s) { + Object::Str(s) => s, + _ => SharedStr::from(s), + } +} + +#[inline] +fn class_of(i: &PyInstance) -> &TypeObject { + i.cls_raw() +} + +impl State { + /// Whether `cls` (at version `ver`) was verified since it last + /// changed. + #[inline] + fn knows(&self, ver: u64) -> bool { + self.verified + .iter() + .any(|v| v.load(Ordering::Relaxed) == ver) + } + + /// Whether this module's lookups serve instances of `cls`: a subclass + /// of its base class that resolves every zone method to the base's + /// own, while the helper classes are unchanged. + #[cold] + #[inline(never)] + fn serves(&self, cls: &TypeObject, ver: u64) -> bool { + let Some(base) = self.base.upgrade() else { + return false; + }; + let in_mro = cls + .mro + .try_borrow() + .is_ok_and(|mro| mro.iter().any(|t| Rc::ptr_eq(t, &base))); + let ok = in_mro + && self + .aux + .iter() + .zip(self.aux_ver) + .all(|(c, v)| c.upgrade().is_some_and(|c| c.attr_version.get() == v)) + && METHODS + .iter() + .zip(&self.methods) + .all(|(name, want)| cls.lookup(name).is_some_and(|got| got.is_same(want))); + if ok { + let at = self.next.fetch_add(1, Ordering::Relaxed) as usize % self.verified.len(); + self.verified[at].store(ver, Ordering::Relaxed); + } + ok + } + + /// `o` when it is an instance of helper class `k` (exact). + #[inline] + fn aux<'a>(&self, k: usize, o: &'a Object) -> Option<&'a PyInstance> { + match o { + Object::Instance(i) if std::ptr::eq(class_of(i), self.aux[k].as_ptr()) => Some(i), + _ => None, + } + } + + /// Which of [`FIELDS`] the attribute name `s` is. + #[inline] + fn field(&self, s: &SharedStr) -> Option { + self.fields + .iter() + .position(|f| SharedStr::ptr_eq(s, f)) + .or_else(|| self.fields.iter().position(|f| **f == **s)) + } +} + +/// The state whose lookups serve the zone `tz`, when one does. +#[inline] +fn state_for(tz: &PyInstance) -> Option<&'static State> { + let cls = class_of(tz); + let ver = cls.attr_version.get(); + let last = LAST.load(Ordering::Relaxed); + // SAFETY: states are leaked when installed, never freed. + if let Some(st) = unsafe { last.as_ref() } { + if st.knows(ver) { + return Some(st); + } + } + state_for_slow(cls, ver) +} + +#[cold] +#[inline(never)] +fn state_for_slow(cls: &TypeObject, ver: u64) -> Option<&'static State> { + let states = STATES.read().ok()?; + let st = states + .iter() + .copied() + .find(|st| st.knows(ver) || st.serves(cls, ver))?; + LAST.store(std::ptr::from_ref(st).cast_mut(), Ordering::Relaxed); + Some(st) +} + +/// Whether `tz` is a zone the native lookups serve (its class only: the +/// instance is checked by each lookup). +#[inline] +pub(crate) fn is_zone(tz: &Object) -> bool { + matches!(tz, Object::Instance(i) if state_for(i).is_some()) +} + +/// The zone data a lookup reads off an instance. +#[derive(Default)] +struct Zone { + trans_utc: Option, + trans_local: Option, + ttinfos: Option, + tti_before: Option, + tz_after: Option, +} + +/// The data of `tz`, when its dictionary holds only attributes the +/// module sets. +fn zone_of(st: &State, tz: &PyInstance) -> Option { + if let Some(z) = zone_split(st, tz) { + return z; + } + let mut z = Zone::default(); + let mut plain = true; + let mut visit = |k: &DictKey, v: &Object| match &k.0 { + Object::Str(s) => match st.field(s) { + Some(F_TRANS_UTC) => z.trans_utc = Some(v.clone()), + Some(F_TRANS_LOCAL) => z.trans_local = Some(v.clone()), + Some(F_TTINFOS) => z.ttinfos = Some(v.clone()), + Some(F_TTI_BEFORE) => z.tti_before = Some(v.clone()), + Some(F_TZ_AFTER) => z.tz_after = Some(v.clone()), + Some(_) => {} + None => plain = false, + }, + _ => plain = false, + }; + match tz.dict.published() { + Some(d) => { + let d = d.try_borrow().ok()?; + for (k, v) in d.iter() { + visit(k, v); + } + } + None => { + let s = tz.dict.split_cell().try_borrow().ok()?; + for (k, v) in s.iter() { + visit(k, v); + } + } + } + plain.then_some(z) +} + +/// [`zone_of`] for an instance whose values lie over its class's shared +/// names, by position through the state's [`KeyMap`]; the outer `None` +/// for any other layout. +#[inline] +fn zone_split(st: &State, tz: &PyInstance) -> Option> { + let keys = class_of(tz).shared_keys.get()?; + let kp: *const crate::inst_dict::SharedKeys = keys; + // SAFETY: nothing below runs code, so nothing stores an attribute + // while the view is held. + let split = unsafe { tz.dict.split_peek() }?; + let vals = split.values(); + split.get_over(kp, 0)?; + let km = &st.keymap; + if km.keys.load(Ordering::Relaxed) != kp as usize || km.len.load(Ordering::Relaxed) < vals.len() + { + km.refresh(keys, &st.fields); + if km.len.load(Ordering::Relaxed) < vals.len() { + return None; + } + } + let mut z = Zone::default(); + for (pos, v) in vals.iter().enumerate() { + match km.field_at(pos) { + 0 => return Some(None), + 1 => z.trans_utc = Some(v.clone()), + 2 => z.trans_local = Some(v.clone()), + 3 => z.ttinfos = Some(v.clone()), + 4 => z.tti_before = Some(v.clone()), + 5 => z.tz_after = Some(v.clone()), + _ => {} + } + } + Some(Some(z)) +} + +/// A `_ttinfo` a lookup settled on; its fields are read when asked for. +pub(crate) struct Info(Object); + +impl Info { + /// `tti.utcoff`. + #[inline] + pub(crate) fn utcoff(&self) -> Option { + self.slot(0, "utcoff") + } + + /// `tti.dstoff`. + #[inline] + pub(crate) fn dstoff(&self) -> Option { + self.slot(1, "dstoff") + } + + /// `tti.tzname`. + #[inline] + pub(crate) fn tzname(&self) -> Option { + self.slot(2, "tzname") + } + + #[inline] + fn slot(&self, hint: usize, name: &str) -> Option { + match &self.0 { + Object::Instance(i) => slot(i, hint, name), + _ => None, + } + } +} + +fn info_of(st: &State, tti: &Object) -> Option { + st.aux(TTINFO, tti)?; + Some(Info(tti.clone())) +} + +/// Slot `name` (declared at `hint`) of `i`, an `int`. +#[inline] +fn int_slot(i: &PyInstance, hint: usize, name: &str) -> Option { + match i.slots.try_borrow().ok()?.get_hinted(hint, name)? { + Object::Int(v) => Some(*v), + Object::Bool(b) => Some(i64::from(*b)), + _ => None, + } +} + +#[inline] +fn slot(i: &PyInstance, hint: usize, name: &str) -> Option { + i.slots.try_borrow().ok()?.get_hinted(hint, name).cloned() +} + +/// A `list` or `tuple` of `int`s read in place. +fn with_ints(seq: &Object, f: impl FnOnce(&[Object]) -> Option) -> Option { + match seq { + Object::List(l) => f(&l.try_borrow().ok()?), + Object::Tuple(t) => f(t), + _ => None, + } +} + +#[inline] +fn int_at(v: &[Object], i: usize) -> Option { + match v.get(i)? { + Object::Int(x) => Some(*x), + _ => None, + } +} + +/// `bisect.bisect_right(v, ts)` over `int`s. +fn bisect_right(v: &[Object], ts: i64) -> Option { + let (mut lo, mut hi) = (0, v.len()); + while lo < hi { + let mid = usize::midpoint(lo, hi); + if ts < int_at(v, mid)? { + hi = mid; + } else { + lo = mid + 1; + } + } + Some(lo) +} + +fn is_leap(y: i64) -> bool { + y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) +} + +/// `_post_epoch_days_before_year(year)`. +fn days_before_year(year: i64) -> i64 { + let y = year - 1; + y * 365 + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400) - EPOCH_ORDINAL +} + +/// `rule.year_to_epoch(year)` for a `_DayOffset` or `_CalendarOffset`. +fn year_to_epoch(st: &State, rule: &Object, year: i64) -> Option { + if let Some(r) = st.aux(CALENDAR_OFFSET, rule) { + let (m, w, d) = ( + int_slot(r, 0, "m")?, + int_slot(r, 1, "w")?, + int_slot(r, 2, "d")?, + ); + let time = int_slot(r, 3, "hour")? + .checked_mul(3600)? + .checked_add(int_slot(r, 4, "minute")?.checked_mul(60)?)? + .checked_add(int_slot(r, 5, "second")?)?; + if !(1..=12).contains(&m) || !(1..=5).contains(&w) || !(0..=6).contains(&d) { + return None; + } + // (`calendar.monthrange`: the first day's weekday, Monday 0, and + // the month's length.) + const BEFORE: [i64; 13] = [-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + const LENGTH: [i64; 13] = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + let leap = is_leap(year); + let late = i64::from(m > 2 && leap); + let first = days_before_year(year) + BEFORE[m as usize] + late + 1; + // (1970-01-01 was a Thursday; ordinals here count from it, day 1 + // of a month being `first`.) + let first_day = (first + EPOCH_ORDINAL + 6).rem_euclid(7); + let in_month = LENGTH[m as usize] + i64::from(m == 2 && leap); + let mut month_day = (d - (first_day + 1)).rem_euclid(7) + 1 + (w - 1) * 7; + if month_day > in_month { + month_day -= 7; + } + let ordinal = days_before_year(year) + BEFORE[m as usize] + late + month_day; + return ordinal.checked_mul(86_400)?.checked_add(time); + } + let r = st.aux(DAY_OFFSET, rule)?; + let mut d = int_slot(r, 0, "d")?; + let julian = match slot(r, 1, "julian")? { + Object::Bool(b) => b, + Object::Int(v) => v != 0, + _ => return None, + }; + let time = int_slot(r, 2, "hour")? + .checked_mul(3600)? + .checked_add(int_slot(r, 3, "minute")?.checked_mul(60)?)? + .checked_add(int_slot(r, 4, "second")?)?; + if julian && d >= 59 && is_leap(year) { + d += 1; + } + days_before_year(year) + .checked_add(d)? + .checked_mul(86_400)? + .checked_add(time) +} + +/// A `_TZStr`'s rule for one year, read off its slots: the standard and +/// daylight `_ttinfo`s, the year's two transitions, and `dst_diff`. +struct Rule { + std: Object, + dst: Object, + start: i64, + end: i64, + diff: i64, +} + +/// The rule of `tzstr` for `year`, when its slot `which` still holds the +/// method [`install`] found (`get_trans_info` or +/// `get_trans_info_fromutc`, which `_TZStr.__init__` binds). +fn rule_of(st: &State, tzstr: &Object, year: i64, which: usize) -> Option { + let r = st.aux(TZSTR, tzstr)?; + let (name, hint) = [("get_trans_info", 4), ("get_trans_info_fromutc", 5)][which]; + match slot(r, hint, name)? { + Object::BoundMethod(bm) + if bm.function.is_same(&st.rule_fns[which]) && bm.receiver.is_same(tzstr) => {} + _ => return None, + } + Some(Rule { + std: slot(r, 0, "std")?, + dst: slot(r, 1, "dst")?, + start: year_to_epoch(st, &slot(r, 2, "start")?, year)?, + end: year_to_epoch(st, &slot(r, 3, "end")?, year)?, + diff: int_slot(r, 6, "dst_diff")?, + }) +} + +/// The zone `tz`, its state and its data, when the lookups serve it. +#[inline] +fn zone(tz: &Object) -> Option<(&'static State, Zone)> { + let Object::Instance(i) = tz else { + return None; + }; + let st = state_for(i)?; + Some((st, zone_of(st, i)?)) +} + +/// `tz._find_trans(dt)` for the local time `dt` holds: day `ordinal` +/// (`dt.toordinal()`), `secs` into it, in `year`, with `fold`. `None` +/// when the Python code must run (it isn't a zone the lookups serve, or +/// its data is unusual). +pub(crate) fn local_info( + tz: &Object, + ordinal: i64, + secs: i64, + year: i64, + fold: i64, +) -> Option { + let (st, z) = zone(tz)?; + let ts = (ordinal - EPOCH_ORDINAL) * 86_400 + secs; + let Object::List(sides) = z.trans_local.as_ref()? else { + return None; + }; + let lt = sides.try_borrow().ok()?.get(fold as usize)?.clone(); + // (`None`: past the last transition; `Some(None)`: before the first.) + let at = with_ints(<, |v| { + let n = v.len(); + if n > 0 && ts < int_at(v, 0)? { + Some(Some(None)) + } else if n == 0 || ts > int_at(v, n - 1)? { + Some(None) + } else { + Some(Some(Some(bisect_right(v, ts)?.checked_sub(1)?))) + } + })?; + let tti = match at { + Some(None) => z.tti_before?, + Some(Some(idx)) => { + let Object::List(infos) = z.ttinfos.as_ref()? else { + return None; + }; + let tti = infos.try_borrow().ok()?.get(idx)?.clone(); + tti + } + None => { + let after = z.tz_after?; + if st.aux(TTINFO, &after).is_some() { + after + } else { + // `_TZStr._get_trans_info(ts, year, fold)`. + let r = rule_of(st, &after, year, 0)?; + let (mut start, mut end) = (r.start, r.end); + if (fold == 1) == (r.diff >= 0) { + end -= r.diff; + } else { + start += r.diff; + } + let isdst = if start < end { + start <= ts && ts < end + } else { + !(end <= ts && ts < start) + }; + if isdst { + r.dst + } else { + r.std + } + } + } + }; + info_of(st, &tti) +} + +/// What `tz.fromutc(dt)` settles for the UTC time `dt` holds (as +/// [`local_info`] takes a local one): the `_ttinfo` in force, and whether +/// the local time it gives is the second of two (`fold`). `offset_us` +/// reads a `_ttinfo`'s `utcoff` as microseconds. +pub(crate) fn utc_info( + tz: &Object, + ordinal: i64, + secs: i64, + year: i64, + offset_us: impl Fn(&Object) -> Option, +) -> Option<(Info, bool)> { + let (st, z) = zone(tz)?; + let ts = (ordinal - EPOCH_ORDINAL) * 86_400 + secs; + let after = z.tz_after?; + let after_is_info = st.aux(TTINFO, &after).is_some(); + let trans = z.trans_utc.as_ref()?; + let n = with_ints(trans, |v| Some(v.len()))?; + let first = if n > 0 { + Some(with_ints(trans, |v| int_at(v, 0))?) + } else { + None + }; + let last = if n > 0 { + Some(with_ints(trans, |v| int_at(v, n - 1))?) + } else { + None + }; + let us = |tti: &Object| offset_us(&info_of(st, tti)?.utcoff()?); + let (tti, fold) = if first.is_some_and(|t| ts < t) { + (z.tti_before?, false) + } else if last.is_none_or(|t| ts > t) && !after_is_info { + // `_TZStr._get_trans_info_fromutc(ts, year)`, in microseconds. + let r = rule_of(st, &after, year, 1)?; + let m = 1_000_000_i128; + let (ts, diff) = (i128::from(ts) * m, i128::from(r.diff) * m); + let start = i128::from(r.start) * m - us(&r.std)?; + let end = i128::from(r.end) * m - us(&r.dst)?; + let isdst = if start < end { + start <= ts && ts < end + } else { + !(end <= ts && ts < start) + }; + let (ambig_start, ambig_end) = if diff > 0 { + (end, end + diff) + } else { + (start, start - diff) + }; + let fold = ambig_start <= ts && ts < ambig_end; + (if isdst { r.dst } else { r.std }, fold) + } else if n == 0 { + (after, false) + } else { + let Object::List(infos) = z.ttinfos.as_ref()? else { + return None; + }; + let infos = infos.try_borrow().ok()?; + let idx = with_ints(trans, |v| bisect_right(v, ts))?; + let second = with_ints(trans, |v| { + if n > 1 { + int_at(v, 1).map(Some) + } else { + Some(None) + } + })?; + let (prev, tti) = if second.is_some_and(|t| ts >= t) { + ( + infos.get(idx.checked_sub(2)?)?.clone(), + infos.get(idx - 1)?.clone(), + ) + } else if last.is_some_and(|t| ts > t) { + (infos.last()?.clone(), after) + } else { + (z.tti_before?, infos.first()?.clone()) + }; + let at = with_ints(trans, |v| int_at(v, idx.checked_sub(1)?))?; + let shift = us(&prev)? - us(&tti)?; + (tti, shift > i128::from(ts - at) * 1_000_000) + }; + Some((info_of(st, &tti)?, fold)) +} + +fn with_interp( + f: impl FnOnce(&mut crate::Interpreter) -> Result, +) -> Result { + let ptr = crate::vm_singletons::current_interpreter_ptr() + .ok_or_else(|| type_error("zoneinfo: no active interpreter"))?; + // SAFETY: published by the enclosing VM frame on this thread. + f(unsafe { &mut *ptr }) +} + +type Fast = fn(&[Object]) -> Option>; + +/// `tz.utcoffset(dt)` (`which` 0), `tz.dst(dt)` (1) and `tz.tzname(dt)` +/// (2) for an exact `datetime`: `tz._find_trans(dt)`'s field. +fn zone_part(a: &[Object], which: u8) -> Option> { + let [tz, dt] = a else { return None }; + let (ordinal, secs, year, fold) = crate::stdlib::datetime_native::local_parts(dt)?; + let info = local_info(tz, ordinal, secs, year, fold)?; + match which { + 0 => info.utcoff(), + 1 => info.dstoff(), + _ => info.tzname(), + } + .map(Ok) +} + +fn zone_utcoffset(a: &[Object]) -> Option> { + zone_part(a, 0) +} + +fn zone_dst(a: &[Object]) -> Option> { + zone_part(a, 1) +} + +fn zone_tzname(a: &[Object]) -> Option> { + zone_part(a, 2) +} + +/// `tz.fromutc(dt)` for an exact `datetime` whose `tzinfo` is `tz`. +fn zone_fromutc(a: &[Object]) -> Option> { + let [tz, dt] = a else { return None }; + crate::stdlib::datetime_native::zone_fromutc(tz, dt).map(Ok) +} + +/// The zone methods with native bodies. +const NATIVES: [(&str, Fast); 4] = [ + ("utcoffset", zone_utcoffset), + ("dst", zone_dst), + ("tzname", zone_tzname), + ("fromutc", zone_fromutc), +]; + +/// The builtin standing in for the Python method `orig`: `fast` when it +/// answers, else `orig` itself. +fn native_method(name: &'static str, fast: Fast, orig: Object) -> Object { + let (o1, o2) = (orig.clone(), orig); + let b = Rc::new(BuiltinFn { + name, + binds_instance: true, + call: Box::new(move |a: &[Object]| match fast(a) { + Some(r) => r, + None => with_interp(|i| i.call_object(o1.clone(), a, &[])), + }), + call_kw: Some(Box::new(move |a: &[Object], kw: &[(String, Object)]| { + if kw.is_empty() { + if let Some(r) = fast(a) { + return r; + } + } + with_interp(|i| i.call_object(o2.clone(), a, kw)) + })), + }); + crate::leaf_builtins::register_fast(&b, fast); + let f = Object::Builtin(b); + crate::descr_registry::register_module(&f, "zoneinfo"); + f +} + +/// `install(namespace)`: take note of the `zoneinfo` module's classes, +/// and give the zone methods their native bodies. +fn install(a: &[Object]) -> Result { + let [Object::Dict(ns)] = a else { + return Err(type_error("install() takes the zoneinfo namespace")); + }; + let class = |name: &str| match ns.borrow().get(&StrKey(name)) { + Some(Object::Type(t)) => Ok(t.clone()), + _ => Err(type_error(format!("install(): no class {name}"))), + }; + let base = class("_ZoneInfoBase")?; + let aux = [ + class("_ttinfo")?, + class("_TZStr")?, + class("_DayOffset")?, + class("_CalendarOffset")?, + ]; + let own = |cls: &TypeObject, name: &str| { + cls.dict + .borrow() + .get(&StrKey(name)) + .cloned() + .ok_or_else(|| type_error(format!("install(): {} has no {name}", cls.name))) + }; + for (name, fast) in NATIVES { + let native = native_method(name, fast, own(&base, name)?); + base.dict + .borrow_mut() + .insert(DictKey(Object::Str(interned(name))), native); + } + base.bump_attr_version(); + let mut methods = Vec::new(); + for name in METHODS { + methods.push(own(&base, name)?); + } + let rule_fns = [ + own(&aux[TZSTR], "_get_trans_info")?, + own(&aux[TZSTR], "_get_trans_info_fromutc")?, + ]; + let state: &'static State = Box::leak(Box::new(State { + base: Rc::downgrade(&base), + aux_ver: std::array::from_fn(|k| aux[k].attr_version.get()), + aux: std::array::from_fn(|k| Rc::downgrade(&aux[k])), + methods, + rule_fns, + fields: FIELDS.iter().map(|n| interned(n)).collect(), + keymap: KeyMap::default(), + verified: Default::default(), + next: AtomicU64::new(0), + })); + if let Ok(mut states) = STATES.write() { + // (A module that is gone leaves its state unused.) + states.retain(|st| st.base.strong_count() > 0); + states.push(state); + } + Ok(Object::None) +} + +pub(crate) fn build(_cache: &ModuleCache) -> Rc { + let mut dict = DictData::default(); + dict.insert( + DictKey(Object::from_static("__name__")), + Object::from_static("_weave_zoneinfo"), + ); + dict.insert( + DictKey(Object::from_static("install")), + Object::Builtin(Rc::new(BuiltinFn { + name: "install", + binds_instance: false, + call: Box::new(install), + call_kw: None, + })), + ); + Rc::new(PyModule { + name: "_weave_zoneinfo".to_owned(), + filename: None, + dict: Rc::new(RefCell::new(dict)), + }) +} diff --git a/crates/weavepy-vm/src/stdlib/zstd_mod.rs b/crates/weavepy-vm/src/stdlib/zstd_mod.rs index cb9fd4235..02abf13c1 100644 --- a/crates/weavepy-vm/src/stdlib/zstd_mod.rs +++ b/crates/weavepy-vm/src/stdlib/zstd_mod.rs @@ -19,7 +19,6 @@ use crate::sync::Rc; use crate::sync::RefCell; -use std::collections::HashMap; use std::os::raw::{c_int, c_uint, c_void}; use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::{Mutex, OnceLock}; @@ -138,17 +137,35 @@ impl Drop for DState { unsafe impl Send for CState {} unsafe impl Send for DState {} -type CompReg = Mutex>>>; -type DecompReg = Mutex>>>; +type CompReg = Mutex>; +type DecompReg = Mutex>; fn comp_reg() -> &'static CompReg { static REG: OnceLock = OnceLock::new(); - REG.get_or_init(|| Mutex::new(HashMap::new())) + REG.get_or_init(Mutex::default) +} + +/// A compressor's state goes with it (see `handle_table`). +fn comp_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + if let Ok(mut reg) = comp_reg().try_lock() { + reg.remove(id); + } + } +} + +/// A decompressor's state goes with it (see `handle_table`). +fn decomp_died(inst: &PyInstance) { + if let Some(id) = super::handle_table::handle_of(inst) { + if let Ok(mut reg) = decomp_reg().try_lock() { + reg.remove(id); + } + } } fn decomp_reg() -> &'static DecompReg { static REG: OnceLock = OnceLock::new(); - REG.get_or_init(|| Mutex::new(HashMap::new())) + REG.get_or_init(Mutex::default) } fn next_id() -> i64 { @@ -830,7 +847,7 @@ fn compressor_init(args: &[Object], kwargs: &[(String, Object)]) -> Result Result>, RuntimeError> { comp_reg() .lock() .ok() - .and_then(|reg| reg.get(&id).cloned()) + .and_then(|reg| reg.get(id)) .ok_or_else(|| value_error("stale ZstdCompressor")) } @@ -1068,6 +1085,7 @@ fn compressor_class() -> Rc { is_builtin: true, }, ) + .inspect(|cls| super::handle_table::watch_owner_class(cls, comp_died)) .expect("ZstdCompressor must linearise") }) .clone() @@ -1131,7 +1149,7 @@ fn decompressor_init(args: &[Object], kwargs: &[(String, Object)]) -> Result Rc { is_builtin: true, }, ) + .inspect(|cls| super::handle_table::watch_owner_class(cls, decomp_died)) .expect("ZstdDecompressor must linearise") }) .clone() diff --git a/crates/weavepy-vm/src/sync.rs b/crates/weavepy-vm/src/sync.rs index 3c4185715..15e0d6ce3 100644 --- a/crates/weavepy-vm/src/sync.rs +++ b/crates/weavepy-vm/src/sync.rs @@ -287,6 +287,7 @@ std::thread_local! { thread_id: std::cell::Cell::new(0), cell_id: std::cell::Cell::new(0), live_guards: std::cell::Cell::new(0), + parked_guards: std::cell::Cell::new(0), } }; } @@ -324,6 +325,9 @@ pub(crate) struct CellTls { cell_id: std::cell::Cell, /// Live [`Ref`]/[`RefMut`] guards on this thread. live_guards: std::cell::Cell, + /// This thread's lock-free guards while it is without the GIL (see + /// [`gil_given_up`]). + parked_guards: std::cell::Cell, } impl CellTls { @@ -365,16 +369,20 @@ impl CellTls { } } -/// Whether more than one OS thread has ever run VM code (a second -/// thread acquired the GIL, or free-threading is on). Until then every -/// cell is touched by exactly one thread, and a borrow skips the lock +/// Whether a borrow must take the cell's lock word: some thread may +/// touch a cell without the GIL (free-threading, a thread the VM didn't +/// start, a watcher, a thread outside its outermost GIL scope beside +/// others; see [`gil_orders_counts`]). Until then a borrow skips the lock /// word: no compare-exchange to take it, no release store to drop it. -/// Set by [`note_vm_thread`] *before* the second thread touches any -/// cell; the first thread cannot hold a borrow across a GIL release -/// (the hand-off refuses while guards are live), so no guard taken -/// lock-free is ever live once another thread runs. A guard remembers -/// whether it took the lock, so a flip while one is live (impossible -/// per the invariant) still releases correctly. +/// With one thread nothing else reaches a cell. With several under the +/// GIL, the GIL orders every borrow and release, and the borrow counter +/// alone keeps a shared and an exclusive borrow apart, across threads as +/// within one (a thread can hold a borrow across a blocking call; the +/// lock word made another thread's borrow of that cell spin with the GIL +/// held, where the counter makes it fail like a nested borrow). Set by +/// [`share_all`], under the GIL or before a second thread exists; a guard +/// remembers whether it took the lock, so a flip while one is live still +/// releases correctly. static CELLS_SHARED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); #[inline] @@ -470,9 +478,9 @@ pub(crate) fn release_gates_ptr() -> *const u32 { /// but the reference-count bias's `rc_shared`). pub(crate) const RELEASE_OBSERVER_GATES: u32 = u32::from_ne_bytes([0, 0xff, 0xff, 0xff]); -/// Whether reference counts must be updated atomically: set whenever the -/// cell bias is revoked, and also before spawning a thread that may touch -/// objects before it registers (see [`crate::rc`]). Never cleared. +/// Whether reference counts must be updated atomically: set once a thread +/// may touch a count without the GIL (see [`gil_orders_counts`], and +/// [`crate::rc`]). Cleared again only by [`restore_bias`]. static RC_SHARED: &std::sync::atomic::AtomicBool = &RELEASE_GATES.rc_shared; /// The flag [`bias_held`] reads (native code that takes references in @@ -481,35 +489,199 @@ pub(crate) fn rc_shared_flag() -> &'static std::sync::atomic::AtomicBool { RC_SHARED } -/// True while one thread owns every reference count (see [`crate::rc`]). +/// True while reference counts are updated with plain loads and stores: +/// one thread owns every count, or the GIL orders every update (see +/// [`crate::rc`]). #[cfg_attr(debug_assertions, allow(dead_code))] #[inline(always)] pub(crate) fn bias_held() -> bool { // A plain read (one compare with memory, where a relaxed load is a load, - // a test and an address computation): the flag changes before a second - // thread touches an object, and that thread's GIL acquire orders the - // change before this thread's next read. Nothing can hold the value - // across a GIL release, which is a synchronizing call. + // a test and an address computation): the flag is set by a thread that + // holds the GIL (or before a second thread exists), and every other + // thread's GIL acquire orders the change before its next read. Nothing + // can hold the value across a GIL release, which is a synchronizing + // call. // SAFETY: a `bool` in a live static (see above for the ordering). !unsafe { RC_SHARED.as_ptr().read() } } -/// Make reference counting atomic before spawning a thread that will run -/// VM code. Cell borrows keep their bias until the thread registers: the -/// spawner may hold a lock-free guard now, and it can't hand the GIL to the -/// new thread until that guard is released. +/// Whether a thread other than the first runs VM code, or was spawned to: +/// set with the first worker's spawn or a second thread's first GIL +/// acquire, cleared by [`restore_bias`]. Another thread can then look at +/// this one's frames and mutate what it reads whenever it gives up the +/// GIL, whether or not reference counts are atomic (see +/// [`gil_orders_counts`]). +static VM_THREADS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Whether more than one thread runs VM code (see [`VM_THREADS`]). +#[inline] +pub(crate) fn threads_started() -> bool { + VM_THREADS.load(Ordering::Relaxed) +} + +/// Whether the GIL alone orders reference-count updates, so that counts +/// stay plain with several threads: every thread that touches an object +/// holds the GIL while it does, and a hand-off of the GIL orders one +/// thread's updates before the next one's. +/// +/// That holds for the threads the VM starts and for the first thread +/// while it stays inside the VM (see [`counts_leave_gil`]). It doesn't +/// with free-threading, with a watcher that reads state from outside the +/// GIL, or after a thread the VM didn't start appeared, whose discipline +/// is its own; counts are atomic then, as they are on Windows (whose +/// blocking paths haven't been checked against the rule) and under +/// `WEAVEPY_ATOMIC_COUNTS=1`. Cell borrows follow the same rule (see +/// [`CELLS_SHARED`]). Once counts are atomic the answer stays no until +/// [`restore_bias`]. +fn gil_orders_counts() -> bool { + static ALLOWED: std::sync::OnceLock = std::sync::OnceLock::new(); + // (Not in a debug or test build: the unit-test binary's threads run + // interpreters with no GIL between them.) + *ALLOWED.get_or_init(|| { + !cfg!(any(windows, debug_assertions, test)) + && std::env::var_os("WEAVEPY_ATOMIC_COUNTS").is_none_or(|v| v == "0") + }) && !RC_SHARED.load(Ordering::SeqCst) + && !CELLS_UNGUARDED.load(Ordering::SeqCst) + && !FOREIGN_SEEN.load(Ordering::SeqCst) + && !crate::gil::free_threading_enabled() +} + +/// Make reference counting atomic before spawning a thread that may touch +/// objects without the GIL. Cell borrows keep their bias until the thread +/// registers: the spawner may hold a lock-free guard now, and it can't +/// hand the GIL to the new thread until that guard is released. pub(crate) fn revoke_bias_for_spawn() { + VM_THREADS.store(true, Ordering::SeqCst); RC_SHARED.store(true, Ordering::SeqCst); } +/// Before spawning a worker that takes the GIL ahead of its first touch +/// of an object, and keeps it through its last: counts stay plain when +/// the spawner holds the GIL too (see [`gil_orders_counts`]). +pub(crate) fn note_worker_spawn(spawner_holds_gil: bool) { + VM_THREADS.store(true, Ordering::SeqCst); + if !spawner_holds_gil || !gil_orders_counts() { + RC_SHARED.store(true, Ordering::SeqCst); + } +} + +/// The calling thread, holding the GIL, is about to give it up outside a +/// blocking call's bracket (its outermost scope ends) and may touch +/// objects afterwards: an embedder reading a result, the command line +/// reporting an exception. With other threads running, counts are atomic +/// and borrows locked from here on. Every other thread is parked outside +/// the VM or in a blocking call now, and takes the GIL, which orders +/// these stores, before its next update. +pub(crate) fn counts_leave_gil() { + if VM_THREADS.load(Ordering::Relaxed) + && !(RC_SHARED.load(Ordering::Relaxed) && CELLS_SHARED.load(Ordering::Relaxed)) + { + share_all(); + } +} + +/// The calling thread is about to give up the GIL for real (its last +/// guard goes): [`SOLE_GUARDS`] counts the GIL holder's lock-free +/// guards, so the ones this thread still holds (a borrow kept across a +/// blocking call) leave the count with it and come back in +/// [`gil_taken`]. Left in, they'd make every other thread refuse the +/// cooperative hand-off (see [`cell_guards_live`]) until this one ran +/// again, which it couldn't. +#[inline] +pub(crate) fn gil_given_up() { + let n = SOLE_GUARDS.load(Ordering::Relaxed); + if n != 0 { + park_sole_guards(n); + } +} + +#[cold] +fn park_sole_guards(n: usize) { + let _ = CELL_TLS.try_with(|t| { + // (A debug or test build's threads run without a GIL between + // them, and only the first takes lock-free guards: the count is + // that thread's alone.) + if cfg!(any(debug_assertions, test)) && FIRST.load(Ordering::Relaxed) != t.thread_id() { + return; + } + t.parked_guards.set(t.parked_guards.get() + n); + SOLE_GUARDS.store(0, Ordering::Release); + PARKED_GUARDS.fetch_add(n, Ordering::SeqCst); + }); +} + +/// Lock-free guards held by threads that are without the GIL (see +/// [`gil_given_up`]): blocked in a call with a borrow live, or waiting to +/// take the GIL back after one. +static PARKED_GUARDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// How long [`retry_past_parked`] waits when the caller holds borrows of +/// its own, so that its failure may be a nested borrow and not another +/// thread's. +const PARKED_WAIT_UNSURE: Duration = Duration::from_millis(2); + +/// `attempt` again, for as long as it fails and a borrow held by a +/// thread blocked without the GIL may be why: the GIL goes to that +/// thread between tries, so that it can finish and release. `None` once +/// no other thread holds a borrow (the failure is this thread's own +/// nested borrow, the caller's to handle as before), and at once in any +/// mode but GIL-ordered lock-free borrows. +/// +/// For a caller at a point where other threads may run: it holds no +/// guardless view of any cell, as around any blocking call. (CPython +/// lets the second thread's operation through at once; here it waits +/// for the first's, as it would for a per-object lock. With the lock +/// word, it spun for that thread with the GIL held, a deadlock.) +pub(crate) fn retry_past_parked(mut attempt: impl FnMut() -> Option) -> Option { + if cells_shared() || PARKED_GUARDS.load(Ordering::Relaxed) == 0 { + return None; + } + if !crate::gil::try_current_thread_holds_gil() { + return None; + } + // With no borrow of its own the caller can only have met another + // thread's, and waits it out. + let unsure = SOLE_GUARDS.load(Ordering::Relaxed) != 0; + let start = Instant::now(); + let mut pause = Duration::from_micros(20); + loop { + crate::gil::allow_threads_then(|| std::thread::sleep(pause)); + pause = (pause * 2).min(Duration::from_millis(2)); + if let Some(v) = attempt() { + return Some(v); + } + if cells_shared() + || PARKED_GUARDS.load(Ordering::Relaxed) == 0 + || (unsure && start.elapsed() >= PARKED_WAIT_UNSURE) + { + return None; + } + } +} + +/// The calling thread has just taken the GIL for real (see +/// [`gil_given_up`]). +#[inline] +pub(crate) fn gil_taken() { + let _ = CELL_TLS.try_with(|t| { + let n = t.parked_guards.get(); + if n != 0 { + t.parked_guards.set(0); + SOLE_GUARDS.store(SOLE_GUARDS.load(Ordering::Relaxed) + n, Ordering::Release); + PARKED_GUARDS.fetch_sub(n, Ordering::SeqCst); + } + }); +} + /// The first thread to run VM code (see [`note_vm_thread`]). static FIRST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -/// Live borrow guards taken lock-free (while the bias held). Only the -/// biased thread takes such guards, but [`revoke_bias`] reads the count -/// from another thread, so both sides are sequentially consistent: the -/// drain below and the re-check in the borrow fast paths must not miss -/// each other. +/// Live borrow guards taken lock-free (while [`CELLS_SHARED`] was clear) +/// by the thread that holds the GIL: a thread's own leave the count while +/// it is without the GIL (see [`gil_given_up`]). Plain updates, ordered by +/// the GIL; [`share_all`] may read the count from a thread that has none, +/// so its drain and the re-check in the borrow fast paths are +/// sequentially consistent and can't miss each other. static SOLE_GUARDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// The `tls` tag of a guard counted in [`SOLE_GUARDS`]. @@ -545,7 +717,7 @@ fn biased_here() -> bool { // invariant above does not hold there, and only the first registered // thread may take the lock-free path. (Without it, two threads' plain // updates of `SOLE_GUARDS` can lose one, and the next thread to - // register spins in `revoke_bias` forever, holding the GIL.) A release + // register spins in `share_all` forever, holding the GIL.) A release // build has one VM thread under the GIL and pays nothing. #[cfg(any(debug_assertions, test))] { @@ -559,7 +731,7 @@ fn biased_here() -> bool { } /// Publish a lock-free guard and re-check that the bias still holds. -/// Both accesses are `SeqCst`, so this and [`revoke_bias`] linearise: +/// Both accesses are `SeqCst`, so this and [`share_all`] linearise: /// whichever runs second observes the other's write, and a borrow is /// therefore never held lock-free once a revoker has moved on. #[inline] @@ -568,7 +740,7 @@ fn publish_sole_guard() { // whole cost. It needs no barrier: a revoker that can race this // thread is one that touches cells without the GIL, which is outside // the contract `biased_here` documents -- and for the backstop in - // `try_borrow_locked` that catches such a thread anyway, `revoke_bias` + // `try_borrow_locked` that catches such a thread anyway, `share_all` // runs a barrier on *every* thread first, which makes this store // visible to its drain. let n = SOLE_GUARDS.load(Ordering::Relaxed); @@ -636,7 +808,7 @@ fn heavy_barrier() { // cannot fail with EPERM; on any other outcome fall back to a // local fence *and* keep the flag, because readers may already be // relying on it -- the fence below then orders this side, and the - // spin in `revoke_bias` still waits for every published guard. + // spin in `share_all` still waits for every published guard. let rc = unsafe { libc::syscall( libc::SYS_membarrier, @@ -674,18 +846,37 @@ fn retract_sole_guard() { SOLE_GUARDS.store(n.saturating_sub(1), Ordering::Release); } -/// Take every cell off the biased path, then wait for the biased -/// thread's lock-free guards to drain. Only the thread that performs -/// the transition drains, so a thread that already sees cells shared — -/// including the biased thread backing out of its own fast path — never -/// waits on a guard it is itself holding. -fn revoke_bias() { +/// A second thread runs VM code. Under the GIL nothing else changes: +/// counts stay plain and borrows lock-free (see [`gil_orders_counts`]). +#[cold] +fn second_thread(thread_id: u64) { + if !VM_THREADS.load(Ordering::Relaxed) { + if std::env::var_os("WEAVEPY_CELLS_TRACE").is_some() { + eprintln!( + "[cells] thread {thread_id:#x} joins {:#x}", + FIRST.load(Ordering::Relaxed) + ); + } + VM_THREADS.store(true, Ordering::SeqCst); + } + if !gil_orders_counts() { + share_all(); + } +} + +/// Make counts atomic and take every cell off the lock-free path: some +/// thread will touch objects without the GIL. Only the thread that +/// performs the transition drains, so a thread that already sees cells +/// shared, including one backing out of its own fast path, never waits +/// on a guard it is itself holding. +fn share_all() { + VM_THREADS.store(true, Ordering::SeqCst); RC_SHARED.store(true, Ordering::SeqCst); if CELLS_SHARED.swap(true, Ordering::SeqCst) { return; } if std::env::var_os("WEAVEPY_CELLS_TRACE").is_some() { - eprintln!("[cells] shared: bias revoked"); + eprintln!("[cells] shared: borrows take the lock word from here on"); } // After this every thread has executed a full barrier: a borrow that // read the flag as clear did so before it, and its guard store -- @@ -694,28 +885,130 @@ fn revoke_bias() { // first time a barrier is due.) enable_asymmetric_barrier(); heavy_barrier(); + // A caller that holds the GIL has nothing to wait for: the counted + // guards are its own (every other thread's left the count when it + // gave the GIL up), and none of them can go while it waits here. + // (Waiting was a hang whenever one was live: a thread registering + // beside a main thread blocked in a call with a borrow held.) + if crate::gil::holds_gil_lock() { + return; + } + // Without the GIL (free-threading starting up, a thread that runs + // the VM with no GIL at all) the drain is what makes the transition + // safe. With cells touched outside the GIL it waits for good; while + // the GIL guards every cell a count that stays up can only be a lost + // update, and past a bound the caller goes on. + let bounded = !CELLS_UNGUARDED.load(Ordering::SeqCst) && !crate::gil::free_threading_enabled(); + let start = std::time::Instant::now(); + let mut spins = 0u32; while SOLE_GUARDS.load(Ordering::SeqCst) > 0 { std::hint::spin_loop(); + spins = spins.wrapping_add(1); + if bounded && spins.is_multiple_of(1024) && start.elapsed() >= DRAIN_BOUND { + if std::env::var_os("WEAVEPY_CELLS_TRACE").is_some() { + eprintln!( + "[cells] drain gave up after {:?}: {} guard(s) outstanding", + start.elapsed(), + SOLE_GUARDS.load(Ordering::SeqCst) + ); + } + break; + } } } +/// How long [`share_all`] waits for lock-free guards while the GIL guards +/// every cell. +const DRAIN_BOUND: std::time::Duration = std::time::Duration::from_millis(50); + /// Record that `thread_id` is about to run VM code. Called from the GIL /// acquire path (and free-threading start-up); the first thread to -/// register is the sole owner of every cell until a second one appears. +/// register is the only one until a second appears (see +/// [`second_thread`]). +#[inline] pub fn note_vm_thread(thread_id: u64) { if CELLS_SHARED.load(Ordering::Relaxed) { return; } - match FIRST.compare_exchange(0, thread_id, Ordering::AcqRel, Ordering::Acquire) { - Ok(_) => {} - Err(first) if first == thread_id => {} - Err(first) => { - if std::env::var_os("WEAVEPY_CELLS_TRACE").is_some() { - eprintln!("[cells] shared: thread {thread_id:#x} joins {first:#x}"); + let first = FIRST.load(Ordering::Relaxed); + if first == thread_id { + return; + } + if first == 0 { + match FIRST.compare_exchange(0, thread_id, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return, + Err(first) if first == thread_id => return, + Err(_) => {} + } + } + second_thread(thread_id); +} + +/// Set once a thread the VM didn't start (a C thread entering through +/// `PyGILState_Ensure`, say) takes the GIL: nothing says when it's gone, so +/// the bias is never restored (see [`restore_bias`]). +static FOREIGN_SEEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +std::thread_local! { + /// Whether this thread is known to the VM: the first to register, or a + /// worker it started (see [`note_vm_worker`]). Checked at its first + /// GIL acquire ([`note_gil_thread`]). + static KNOWN_THREAD: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Mark the calling thread as a worker the VM started, before it first +/// takes the GIL. +pub(crate) fn note_vm_worker() { + KNOWN_THREAD.with(|k| k.set(1)); +} + +/// Called with the GIL just taken (after [`note_vm_thread`]): a thread +/// that is neither the first to register nor a worker the VM started is +/// foreign (see [`FOREIGN_SEEN`]). +#[inline] +pub(crate) fn note_gil_thread(thread_id: u64) { + let _ = KNOWN_THREAD.try_with(|k| { + if k.get() == 0 { + k.set(1); + if FIRST.load(Ordering::Acquire) != thread_id { + // (Under the GIL just taken: counts are atomic and + // borrows locked before this thread, whose discipline + // is its own, touches an object.) + FOREIGN_SEEN.store(true, Ordering::SeqCst); + share_all(); } - revoke_bias(); } + }); +} + +/// Back to one thread: the caller, `thread_id`, has joined every worker's +/// OS thread, so nothing else can touch an object until a new thread +/// registers or is spawned. Counts go back to plain and borrows to +/// lock-free if they had left (a spawn made without the GIL, a thread +/// that left its outermost scope beside workers). Declined (`false`) +/// after a foreign thread or a thread that touches objects without the +/// GIL appeared, or while this thread holds a cell borrow taken on the +/// locked path. +pub(crate) fn restore_bias(thread_id: u64) -> bool { + if !VM_THREADS.load(Ordering::SeqCst) + || CELLS_UNGUARDED.load(Ordering::SeqCst) + || FOREIGN_SEEN.load(Ordering::SeqCst) + || FIRST.load(Ordering::SeqCst) != thread_id + { + return false; + } + if CELLS_SHARED.load(Ordering::SeqCst) + && (cell_guards_live() || SOLE_GUARDS.load(Ordering::SeqCst) != 0) + { + return false; } + if std::env::var_os("WEAVEPY_CELLS_TRACE").is_some() { + eprintln!("[cells] thread {thread_id:#x} is the only one again"); + } + CELLS_SHARED.store(false, Ordering::SeqCst); + RC_SHARED.store(false, Ordering::SeqCst); + VM_THREADS.store(false, Ordering::SeqCst); + true } /// Every cell is shared from now on (free-threading, a foreign thread @@ -728,14 +1021,15 @@ pub fn note_vm_thread(thread_id: u64) { /// tier-2 attribute tests would then report as deopts. #[cfg(test)] pub(crate) fn revoke_bias_for_test() { - revoke_bias(); + share_all(); } pub fn mark_cells_shared() { // Ordered before the revocation: a thread that observes the bias - // gone must also observe that guardless reads are off. + // gone must also observe that guardless reads are off. (With the + // flag set, the revocation makes counts atomic too.) CELLS_UNGUARDED.store(true, Ordering::SeqCst); - revoke_bias(); + share_all(); } // `try_with`, not `with`, throughout: guards can be dropped from TLS @@ -765,8 +1059,12 @@ fn note_cell_guard_released(tls: *const CellTls) { /// this is true (see [`CELL_TLS`]). #[inline] pub fn cell_guards_live() -> bool { + // (The count is the GIL holder's, so the caller's; in a debug or test + // build, whose threads run without a GIL between them, the first + // thread's.) if SOLE_GUARDS.load(Ordering::Relaxed) > 0 - && FIRST.load(Ordering::Relaxed) == crate::gil::current_thread_id() + && (cfg!(not(any(debug_assertions, test))) + || FIRST.load(Ordering::Relaxed) == crate::gil::current_thread_id()) { return true; } @@ -965,7 +1263,7 @@ impl GilCell { pub fn try_borrow(&self) -> Result, BorrowError> { if biased_here() { // Publish the guard *before* claiming the counter, so a - // revoker's drain (see `revoke_bias`) covers the claim. + // revoker's drain (see `share_all`) covers the claim. publish_sole_guard(); if self.borrow_shared(false) { // SAFETY: the counter is `>= 1`, so no `&mut T` to the @@ -1475,6 +1773,16 @@ pub struct RealLock { struct LockState { held: bool, owner: Option, + /// Threads blocked in [`RealLock::acquire`] or + /// [`RealLock::acquire_timeout`]: waiters past their turn (see + /// `thread_real::acquire_contended`), whom a release hands the lock. + starving: u32, + /// Released while a waiter was starving: free, and kept for one of + /// them. [`RealLock::try_acquire`] fails meanwhile, so the releasing + /// thread can't take the lock back before the waiter it woke has run + /// (it did every time once that thread's code got fast enough, and a + /// waiter's acquire took a third of a second). + reserved: bool, } impl Default for RealLock { @@ -1494,7 +1802,7 @@ impl RealLock { /// Try once without blocking. Returns `true` if acquired. pub fn try_acquire(&self, owner: u64) -> bool { let mut state = self.state.lock(); - if state.held { + if state.held || state.reserved { false } else { state.held = true; @@ -1503,12 +1811,16 @@ impl RealLock { } } - /// Acquire, blocking forever if necessary. + /// Acquire, blocking forever if necessary. A release while this + /// waits keeps the lock for it (see [`LockState::reserved`]). pub fn acquire(&self, owner: u64) { let mut state = self.state.lock(); + state.starving += 1; while state.held { self.cv.wait(&mut state); } + state.starving -= 1; + state.reserved = false; state.held = true; state.owner = Some(owner); } @@ -1518,24 +1830,44 @@ impl RealLock { pub fn acquire_timeout(&self, owner: u64, timeout: Duration) -> bool { let deadline = Instant::now() + timeout; let mut state = self.state.lock(); + state.starving += 1; while state.held { let now = Instant::now(); - if now >= deadline { - return false; - } - let remaining = deadline - now; - let result = self.cv.wait_for(&mut state, remaining); - if result.timed_out() && state.held { + let gone = now >= deadline + || (self.cv.wait_for(&mut state, deadline - now).timed_out() && state.held); + if gone { + state.starving -= 1; return false; } } + state.starving -= 1; + state.reserved = false; state.held = true; state.owner = Some(owner); true } + /// Block until the lock is free (without taking it) or `timeout` + /// runs out: the GIL-released half of a contended acquire (see + /// `thread_real::acquire_contended`). + pub fn wait_free(&self, timeout: Option) { + let deadline = timeout.map(|d| Instant::now() + d); + let mut state = self.state.lock(); + while state.held || state.reserved { + match deadline { + None => self.cv.wait(&mut state), + Some(dl) => { + if self.cv.wait_until(&mut state, dl).timed_out() { + return; + } + } + } + } + } + /// Release the lock. Returns `Ok(())` on success, `Err` if - /// the lock isn't held. + /// the lock isn't held. With a waiter starving, the lock is kept + /// for it (see [`LockState::reserved`]). pub fn release(&self) -> Result<(), &'static str> { let mut state = self.state.lock(); if !state.held { @@ -1543,13 +1875,22 @@ impl RealLock { } state.held = false; state.owner = None; + let handed = state.starving > 0; + state.reserved = handed; drop(state); - self.cv.notify_one(); + if handed { + // (Every waiter: one that only watches for the lock to come + // free must not swallow the starving one's wake-up.) + self.cv.notify_all(); + } else { + self.cv.notify_one(); + } Ok(()) } pub fn is_locked(&self) -> bool { - self.state.lock().held + let state = self.state.lock(); + state.held || state.reserved } /// Forcibly return the lock to the fresh, unlocked state, ignoring any @@ -1604,6 +1945,9 @@ pub struct RealRLock { struct RLockState { owner: Option, depth: usize, + /// As [`LockState::starving`] and [`LockState::reserved`]. + starving: u32, + reserved: bool, } impl Default for RealRLock { @@ -1627,7 +1971,7 @@ impl RealRLock { state.depth += 1; true } - None => { + None if !state.reserved => { state.owner = Some(owner); state.depth = 1; true @@ -1638,44 +1982,57 @@ impl RealRLock { pub fn acquire(&self, owner: u64) { let mut state = self.state.lock(); - loop { - match state.owner { - Some(o) if o == owner => { - state.depth += 1; - return; - } - None => { - state.owner = Some(owner); - state.depth = 1; - return; - } - _ => self.cv.wait(&mut state), - } + if state.owner == Some(owner) { + state.depth += 1; + return; + } + state.starving += 1; + while state.owner.is_some() { + self.cv.wait(&mut state); } + state.starving -= 1; + state.reserved = false; + state.owner = Some(owner); + state.depth = 1; } pub fn acquire_timeout(&self, owner: u64, timeout: Duration) -> bool { let deadline = Instant::now() + timeout; let mut state = self.state.lock(); - loop { - match state.owner { - Some(o) if o == owner => { - state.depth += 1; - return true; - } - None => { - state.owner = Some(owner); - state.depth = 1; - return true; - } - _ => { - let now = Instant::now(); - if now >= deadline { - return false; - } - let result = self.cv.wait_for(&mut state, deadline - now); - if result.timed_out() && state.owner.is_some() && state.owner != Some(owner) { - return false; + if state.owner == Some(owner) { + state.depth += 1; + return true; + } + state.starving += 1; + while state.owner.is_some() { + let now = Instant::now(); + let gone = now >= deadline + || (self.cv.wait_for(&mut state, deadline - now).timed_out() + && state.owner.is_some()); + if gone { + state.starving -= 1; + return false; + } + } + state.starving -= 1; + state.reserved = false; + state.owner = Some(owner); + state.depth = 1; + true + } + + /// Block until `owner` could take the lock (it is free, or already + /// `owner`'s) without taking it, or until `timeout` runs out (see + /// [`RealLock::wait_free`]). + pub fn wait_free(&self, owner: u64, timeout: Option) { + let deadline = timeout.map(|d| Instant::now() + d); + let mut state = self.state.lock(); + while state.owner.is_some_and(|o| o != owner) || (state.owner.is_none() && state.reserved) { + match deadline { + None => self.cv.wait(&mut state), + Some(dl) => { + if self.cv.wait_until(&mut state, dl).timed_out() { + return; } } } @@ -1690,8 +2047,14 @@ impl RealRLock { state.depth -= 1; if state.depth == 0 { state.owner = None; + let handed = state.starving > 0; + state.reserved = handed; drop(state); - self.cv.notify_one(); + if handed { + self.cv.notify_all(); + } else { + self.cv.notify_one(); + } Ok(0) } else { Ok(state.depth) diff --git a/crates/weavepy-vm/src/thread_registry.rs b/crates/weavepy-vm/src/thread_registry.rs index 790eefe95..116fbfb5f 100644 --- a/crates/weavepy-vm/src/thread_registry.rs +++ b/crates/weavepy-vm/src/thread_registry.rs @@ -163,6 +163,26 @@ impl ThreadRegistry { g.remove(&native_id); } + /// The join handles of `ident`'s thread and of every finished one, + /// taken, with the finished entries dropped: nothing reads an entry + /// once its thread has finished and been joined (a late `join()` waits + /// on the thread handle's own state), and a program that starts + /// thousands of threads would otherwise scan them all at every reap. + pub fn take_finished_handles(&self, ident: u64) -> Vec> { + let mut handles = Vec::new(); + let mut g = self.entries.write(); + g.retain(|_, e| { + let finished = !e.is_alive(); + if finished || e.native_id == ident { + if let Some(h) = e.take_handle() { + handles.push(h); + } + } + !finished + }); + handles + } + pub fn get(&self, native_id: u64) -> Option> { let g = self.entries.read(); g.get(&native_id).cloned() diff --git a/crates/weavepy-vm/src/tier2.rs b/crates/weavepy-vm/src/tier2.rs index 939c340d8..2f6b51761 100644 --- a/crates/weavepy-vm/src/tier2.rs +++ b/crates/weavepy-vm/src/tier2.rs @@ -203,6 +203,10 @@ struct InlineUpdate { /// pointer it must equal. code_at: Cell, code: Cell, + /// For a field that is a `__slots__` member (its [`Self::idx`] then + /// carries [`weavepy_jit::SLOT_FIELD`]): the class's slot layout's + /// word, as [`AttrGuard::slot_layout`]. `0` for a split field. + layout: Cell, } impl InlineUpdate { @@ -214,6 +218,7 @@ impl InlineUpdate { inc: Cell::new(0), code_at: Cell::new(0), code: Cell::new(0), + layout: Cell::new(0), } } } @@ -244,6 +249,23 @@ enum MethodCallee { /// One slot per method token (parallel to `cf.method_sites`). type MethodTable = Vec; +/// Whether a method site's callee is a pure leaf small enough for the +/// frame JIT to put in line (its inlining limit): tier 2 calls one through +/// the leaf evaluator, so it doesn't repay a loop's element steps (see +/// `weavepy_jit::analyze::MethodResolution::leaf`). +fn method_callee_is_small_leaf(callee: &MethodCallee) -> bool { + match callee { + MethodCallee::Py { code, .. } => code_is_small_leaf(code), + MethodCallee::Native { .. } => false, + } +} + +/// Whether `code` is a pure leaf small enough for the frame JIT to put in +/// line (its inlining limit). +fn code_is_small_leaf(code: &CodeObject) -> bool { + code.instructions.len() <= 64 && crate::code_is_pure_leaf_pub(code) +} + /// The widest positional arity a native method site admits (receiver /// included). The builtin validates its own arity, so this only bounds /// the marshal buffer. @@ -443,6 +465,11 @@ struct DirectEntry { /// `true` = receiver-in-slot-0 shape ([`native_method_callable`]); /// `false` = all-scalar parameters ([`native_callable`]). method_shape: bool, + /// The leading locals a caller fills: the positional parameters, and + /// the keyword-only ones too when the body reads them at entry (a + /// caller that bound every parameter enters such a body; the + /// native-to-native lanes, which pass positionals only, never do). + nparams: usize, } /// Everything one successful compile produced (RFC 0069 — the pieces @@ -479,6 +506,9 @@ struct Artifacts { /// Whether the body works on floats in their lanes (a float local, /// field or return, or a `math` intrinsic): see [`float_work`]. float_work: bool, + /// The loops the analysis carved out for an opcode tier 2 never + /// compiles (see [`carved_loop_for_code`]). + carved_for_code: Vec, } /// Whether `cf` keeps floats unboxed: a float local, field site or @@ -564,6 +594,13 @@ struct CacheEntry { /// Framed native entries of this code (saturating), the /// denominator of the generic-call retirement ratio below. native_entries: u32, + /// Compile attempts that failed (saturating): see [`gave_up_often`]. + failed_compiles: u8, + /// The analysis work the attempts on this code have done, and the + /// least budget its next attempt needs: twice that of one that ran + /// out, for code that waits (see [`analysis_due_at`]). + analysis_spent: u64, + analysis_floor: u64, /// OSR entries this code made (saturating), and requests at its region /// roots turned down as too short (see [`note_short_region`]). osr_runs: u32, @@ -617,12 +654,15 @@ impl CacheEntry { CacheEntry { counter: 0, tier: Tier::Cold, + analysis_spent: 0, + analysis_floor: 0, defer_osr: false, osr_failures: 0, backedges: 0, calls: 0, deopts: 0, native_entries: 0, + failed_compiles: 0, osr_runs: 0, short_regions: 0, guard_failures: 0, @@ -962,14 +1002,15 @@ pub(crate) fn note_frameless_calls(code: &CodeObject, n: u32) -> Option { return None; } let threshold = st.threshold; - let sized = if st.range_budget { - size_budget(code) - } else { - 0 - }; + let range_budget = st.range_budget; match st.cache.get_mut(&std::ptr::from_ref(code)) { None => Some(true), Some(entry) if matches!(entry.tier, Tier::Cold) => { + let sized = if range_budget { + size_budget(code).max(analysis_due_at(entry, code)) + } else { + 0 + }; entry.counter = entry.counter.saturating_add(n); let next = entry.counter.saturating_add(1); let due = next >= threshold.max(sized) && compile_allowed(next, threshold); @@ -1125,6 +1166,87 @@ fn size_budget(code: &CodeObject) -> u32 { .saturating_mul(WORK_PER_INSTRUCTION) } +/// A tuning knob of the analysis budget, read once from the environment. +fn analysis_knob(cell: &'static std::sync::OnceLock, var: &str, default: u64) -> u64 { + *cell.get_or_init(|| { + std::env::var(var) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) + }) +} + +/// Analysis work (see [`weavepy_jit::with_work_budget`]) a code object of +/// `len` instructions may have done on it before its own work has paid +/// for any: a base, which covers the callees a short driver types, and a +/// number of passes over the code itself. +fn analysis_free(len: usize) -> u64 { + static BASE: std::sync::OnceLock = std::sync::OnceLock::new(); + static PASSES: std::sync::OnceLock = std::sync::OnceLock::new(); + analysis_knob(&BASE, "WEAVEPY_T2_FREE", 1024) + .saturating_add(analysis_knob(&PASSES, "WEAVEPY_T2_PASSES", 8).saturating_mul(len as u64)) +} + +/// The work (calls and loop iterations) of a code object that pays for +/// one unit of analysis work on it. +fn work_per_analysis_unit() -> u64 { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + analysis_knob(&V, "WEAVEPY_T2_WPP", 8).max(1) +} + +/// The analysis work an attempt on `entry`'s code may do: the free +/// allowance, and what the code's own work has paid for beyond the work +/// already done on it. +fn analysis_allowance(entry: &CacheEntry, code: &CodeObject) -> u64 { + analysis_free(code.instructions.len()).saturating_add( + (u64::from(entry.counter) / work_per_analysis_unit()).saturating_sub(entry.analysis_spent), + ) +} + +/// The counter `entry`'s code needs before tier 2 analyzes it again, for +/// code waiting on an attempt that ran out of budget (zero otherwise). +/// An analysis costs time in proportion to the code's length and to the +/// passes it takes (one for each loop it carves out, each retry with +/// other assumptions, each callee it types), all of it on the thread +/// that runs the program, and most code is rejected: `argparse` building +/// and running a parser 180 times spent 44 of its 200 ms analyzing 104 +/// functions to compile 12 trivial ones, 11 of them on two 160-pass +/// attempts at one function. A kernel compiles in a few passes (the +/// costliest among the benchmark fixtures takes seven, and a +/// 29-instruction driver 950 units with its callees), so every attempt +/// gets that much (see [`analysis_free`]) and what the code's own work +/// has paid for. An attempt that runs out stands as a rejection, unless +/// the code's calls run long loops (see [`BUDGET_WAIT_ITERATIONS`]): that +/// waits, interpreted, until its work pays for twice the budget. +fn analysis_due_at(entry: &CacheEntry, code: &CodeObject) -> u32 { + if entry.analysis_floor == 0 { + return 0; + } + let need = entry + .analysis_spent + .saturating_add(entry.analysis_floor) + .saturating_sub(analysis_free(code.instructions.len())); + u32::try_from(need.saturating_mul(work_per_analysis_unit())).unwrap_or(u32::MAX) +} + +/// Loop iterations a call of a code object runs, on average, from which +/// the code waits, interpreted, for its work to pay for another analysis +/// after one ran out of budget (see [`analysis_due_at`]): a loop long +/// enough to matter soon does. For any other the verdict stands, as it +/// would for a shape tier 2 doesn't compile: waiting would keep the code +/// from the frame JIT meanwhile. +const BUDGET_WAIT_ITERATIONS: u32 = 16; + +/// Whether `entry`'s calls of `code` run loops long enough to wait for an +/// analysis budget (see [`BUDGET_WAIT_ITERATIONS`]). +fn waits_for_budget(entry: &CacheEntry, code: &CodeObject) -> bool { + let calls = entry + .calls + .wrapping_add(code.jit_hint.lean_entries()) + .max(1); + entry.backedges / calls >= BUDGET_WAIT_ITERATIONS +} + /// [`compile_allowed`] for the frame compiler (see `frame_jit`), which /// keeps tier 2's start-up and import budgets. pub(crate) fn frame_compile_allowed(counter: u32, threshold: u32) -> bool { @@ -1284,7 +1406,12 @@ impl JitState { // a native entry to pay for the general call, and how many. let long_calls; let iters_per_call; + // The analysis work this attempt may do (see [`analysis_due_at`]). + let budget; let mut carved = weavepy_jit::Carved::default(); + // A recompile's predecessor, put back if the recompile fails: the + // frame it compiled still serves the entries it has. + let mut predecessor: Option = None; { let entry = cache_entry(&mut self.cache, &mut self.sweep_at, code); if entry_pc == 0 { @@ -1297,7 +1424,10 @@ impl JitState { // here (see `CacheEntry::recompile_at_osr`). // A loop carved out for its code alone stays interpreted; one // carved out for want of live values recompiles from inside. + // (An entry pc that missed its probes already would miss them + // again: it observes the same frame state.) let recompile = entry_pc != 0 + && !entry.probe_misses.contains(&entry_pc) && matches!(&entry.tier, Tier::Compiled(a) if !a.cf.osr_entries.iter().any(|e| e.pc == entry_pc) && ((entry.recompile_at_osr && !a.cf.stayed_heads.contains(&entry_pc)) @@ -1308,7 +1438,7 @@ impl JitState { entry.cold_recompiles = entry.cold_recompiles.saturating_add(1); entry.osr_failures = 0; entry.osr_absent.clear(); - entry.tier = Tier::Cold; + predecessor = Some(std::mem::replace(&mut entry.tier, Tier::Cold)); entry.counter = entry.counter.max(self.threshold); } match &entry.tier { @@ -1344,7 +1474,8 @@ impl JitState { if entry.counter < self.threshold || !compile_allowed(entry.counter, self.threshold) || entry.counter < import_size_budget(code, admit_at(self.threshold)) - || (self.range_budget && entry.counter < size_budget(code)) + || (self.range_budget + && entry.counter < size_budget(code).max(analysis_due_at(entry, code))) { return None; } @@ -1373,6 +1504,13 @@ impl JitState { .max(1); iters_per_call = entry.backedges / calls; long_calls = iters_per_call >= LOOP_CALL_ITERATIONS; + // (A recompile comes with a frame that works: it gets at least + // what a first attempt needs.) + budget = if self.range_budget { + analysis_allowance(entry, code).max(entry.analysis_floor) + } else { + u64::MAX + }; } // Threshold reached: compile (engine + cache borrowed disjointly). // The engine is built once an analysis admits some code (see @@ -1392,6 +1530,7 @@ impl JitState { ctor_field, cell, obj_live, + py_callee, stack_iter, pairs, } = probes; @@ -1516,11 +1655,18 @@ impl JitState { // A `RefCell` because the direct-method lookup below reads the // table while `probe_method` (a sibling `&mut` closure) grows it. let methods: std::cell::RefCell = std::cell::RefCell::new(Vec::new()); - let mut method_tokens: HashMap<(u32, Vec, String), u32> = HashMap::new(); + // A triple that didn't resolve is remembered too: the probe + // reads the requesting frame and the receiver's class, which + // an analysis doesn't change, and resolving one types the + // method's body, a whole analysis of its own, which the + // analyzer would repeat for every pass over every such site. + let mut method_tokens: HashMap<(u32, Vec, String), Option> = + HashMap::new(); let mut probe_method = |slot: u32, path: &[String], name: &str| -> Option { - if let Some(&token) = method_tokens.get(&(slot, path.to_vec(), name.to_owned())) - { + let key = (slot, path.to_vec(), name.to_owned()); + if let Some(&known) = method_tokens.get(&key) { + let token = known?; let methods = methods.borrow(); let e = &methods[token as usize]; return Some(MethodResolution { @@ -1531,12 +1677,20 @@ impl JitState { native: matches!(e.callee, MethodCallee::Native { .. }), elem: matches!(e.callee, MethodCallee::Native { op, .. } if crate::stdlib::collections_native::op_returns_element(op)), + leaf: method_callee_is_small_leaf(&e.callee), }); } - let e = method(slot, path, name)?; + let Some(e) = method(slot, path, name) else { + // (Not one cut short by the work budget, which + // ends the attempt anyway.) + if !weavepy_jit::work_short() { + method_tokens.insert(key, None); + } + return None; + }; let mut methods = methods.borrow_mut(); let token = methods.len() as u32; - method_tokens.insert((slot, path.to_vec(), name.to_owned()), token); + method_tokens.insert(key, Some(token)); let res = MethodResolution { token, arg_count: e.arg_count, @@ -1545,6 +1699,7 @@ impl JitState { native: matches!(e.callee, MethodCallee::Native { .. }), elem: matches!(e.callee, MethodCallee::Native { op, .. } if crate::stdlib::collections_native::op_returns_element(op)), + leaf: method_callee_is_small_leaf(&e.callee), }; methods.push(e); Some(res) @@ -1621,6 +1776,41 @@ impl JitState { obj_global: &mut probe_obj_global, cell: &mut **cell, obj: &mut **obj_live, + py_callee: &mut |slot| { + if slot & weavepy_jit::PY_CALLEE_GLOBAL == 0 { + return (py_callee)(slot); + } + let frameless = slot & weavepy_jit::PY_CALLEE_FRAMELESS != 0; + let Some(name) = code.names.get( + (slot & !(weavepy_jit::PY_CALLEE_GLOBAL | weavepy_jit::PY_CALLEE_FRAMELESS)) + as usize, + ) else { + return false; + }; + (resolve_cell.borrow_mut())(name).is_some_and(|f| { + if !frameless { + return small_py_callee(&f); + } + // (A callee compiled as a scalar leaf is entered + // natively, see `direct` below.) + let Object::Function(func) = &f else { + return false; + }; + let fcode = func.code.borrow(); + let k = Rc::as_ptr(&fcode).cast::(); + let direct = cache_ref.get(&k).is_some_and(|e| match &e.tier { + Tier::Compiled(a) => a.cf.direct_leaf(fcode.arg_count).is_some(), + _ => false, + }); + !direct && frameless_py_callee(&f) + }) + }, + py_operator: &mut |pc| { + crate::code_vm_ext(code).is_some_and(|ext| { + crate::dunder_known(ext, pc as usize) + || crate::instance_site(ext, pc as usize) + }) + }, local: &mut probe_local, stack_iter: &mut **stack_iter, pairs: &mut **pairs, @@ -1698,9 +1888,26 @@ impl JitState { }; // An attribute site whose receiver keeps the attribute in a // laid-out member slot reads and writes it there in line. - let mut slot_member = - |site: &AttrSiteMeta| attr_guard_of(site).is_some_and(|g| g.slot_layout != 0); + // (And whether compiled code has a position to read or write + // the attribute at in line: a scalar lane's only.) ensure_obj_layout(); + let layout = weavepy_jit::obj_layout_published(); + let mut slot_member = |site: &AttrSiteMeta| { + let guard = attr_guard_of(site); + let member = guard.as_ref().is_some_and(|g| g.slot_layout != 0); + let position = guard + .as_ref() + .filter(|g| g.split_idx != u32::MAX) + .map(|g| (g.ver, g.split_idx, g.slot_layout)); + let in_line = matches!(layout, Some(slots_ok) if slots_ok || !member) + && matches!(site.lane, JitType::Int | JitType::Float | JitType::Bool) + && position.is_some(); + weavepy_jit::SiteLayout { + slot_member: member, + in_line, + position, + } + }; let r = JitEngine::compile_frame_lazily( engine, code, @@ -1717,17 +1924,62 @@ impl JitState { let obj_names = obj_names.into_inner().into_iter().map(|(n, _)| n).collect(); (r, callees.into_inner(), methods.into_inner(), obj_names) }; - let (res, callees, methods, obj_names) = { - let first = run(false); - if matches!( - first.0, - Err(weavepy_jit::JitVerdict::TypeUnknown | weavepy_jit::JitVerdict::ProbeMiss(_)) - ) { - run(true) - } else { - first + let ((res, callees, methods, obj_names), spent, short) = + weavepy_jit::with_work_budget(budget, || { + let first = run(false); + if matches!( + first.0, + Err(weavepy_jit::JitVerdict::TypeUnknown + | weavepy_jit::JitVerdict::ProbeMiss(_)) + ) { + run(true) + } else { + first + } + }); + if crate::hot_gates::env_flags::jit_trace() { + eprintln!( + "jit analysis {:?}: {spent} of {budget} work units over {} instructions{}", + code.name, + code.instructions.len(), + if short { ", ran out" } else { "" } + ); + } + if let Some(e) = self.cache.get_mut(&key) { + e.analysis_spent = e.analysis_spent.saturating_add(spent); + // Out of budget: code whose calls run long loops waits until + // its work pays for twice as much (the carving found so far + // is kept); for any other the verdict stands (see + // `analysis_due_at`). + if short && res.is_err() && waits_for_budget(e, code) { + e.analysis_floor = budget.saturating_mul(2); + e.carved = carved; + if let Some(prev) = predecessor { + e.tier = prev; + } + return None; } + } + let res = if short && res.is_err() { + Err(weavepy_jit::JitVerdict::UnsupportedOpcode( + weavepy_jit::OVER_BUDGET, + )) + } else { + res }; + if res.is_err() { + if let Some(e) = self.cache.get_mut(&key) { + e.failed_compiles = e.failed_compiles.saturating_add(1); + // Handed over (see `gave_up_often`): its back edges stop + // asking, so the loops each failing in turn don't analyze + // it again and again; the frame JIT takes them. + if e.failed_compiles >= FAILED_COMPILES_HANDOVER + && !matches!(e.tier, Tier::Compiled(_)) + { + code.jit_hint.set_backedge_quiet(); + } + } + } if matches!( res, Err(weavepy_jit::JitVerdict::UnsupportedOpcode(why)) if why == weavepy_jit::NO_HOST_ENGINE @@ -1815,7 +2067,14 @@ impl JitState { // scanner's `while s[i] in chars`) stays interpreted, // entering its native form from the back edge when a // call runs long. + // (A body the interpreter never enters natively, see + // `CompiledFrame::interp_entry`, has no native self to + // reach from its calls: an `__init__` that names its + // own class lists itself as a callee without calling + // anything, and a claim would only keep its calls off + // the lean paths and the frame JIT's direct ones.) let recursive = entry_pc == 0 + && cf.interp_entry && callees .iter() .any(|(_, c)| std::ptr::eq(Rc::as_ptr(c), std::ptr::from_ref(&**code))); @@ -1823,16 +2082,20 @@ impl JitState { && cf.interp_entry && !(code.is_generator || code.is_coroutine || code.is_async_generator); // A loop that calls no Python function or method - // natively: a compiled caller's direct call of the - // frame JIT's body serves it better than this one's + // natively, or only small pure leaves (which the frame + // JIT puts in line): a compiled caller's direct call of + // the frame JIT's body serves it better than this one's // framed entry when it runs a few iterations a call - // (see `crate::SHORT_LOOP_ITERS`). One that does - // (`raytrace`'s `first_hit`) runs its calls better - // here. - if callees.is_empty() - && methods - .iter() - .all(|m| !matches!(m.callee, MethodCallee::Py { .. })) + // (see `crate::SHORT_LOOP_ITERS`). One that calls more + // (`raytrace`'s `first_hit`, whose callee calls Python) + // runs its calls better here. + if callees + .iter() + .all(|(f, c)| matches!(f, Object::Function(_)) && code_is_small_leaf(c)) + && methods.iter().all(|m| { + !matches!(m.callee, MethodCallee::Py { .. }) + || method_callee_is_small_leaf(&m.callee) + }) { super::note_loop_iters(code, iters_per_call); } @@ -1877,6 +2140,7 @@ impl JitState { callee_entries: Cell::new(0), callee_roundtrips: Cell::new(0), float_work, + carved_for_code: carved.code_heads().to_vec(), }); // RFC 0067 WS1 — a fresh compile can flip a // `None` native-callee slot in *other* frames' @@ -1916,6 +2180,9 @@ impl JitState { if loop_headers(code).all(|pc| entry.probe_misses.contains(&pc)) { code.jit_hint.set_backedge_quiet(); } + if let Some(prev) = predecessor { + entry.tier = prev; + } } return None; } @@ -1923,6 +2190,13 @@ impl JitState { (Tier::NotJitable, None) } }; + if let (Tier::NotJitable, Some(prev)) = (&tier, predecessor) { + // The new entry is out of reach; the old frame isn't. + if let Some(entry) = self.cache.get_mut(&key) { + entry.tier = prev; + } + return None; + } if matches!(tier, Tier::NotJitable) { // RFC 0067 — denormalize the rejection onto the code // object so every later activation skips tier-up on one @@ -2051,19 +2325,26 @@ impl JitState { }; (a.clone(), a.code.clone()) }; + let argc = code.arg_count as usize; + let bound = argc + code.kwonly_count as usize; let method_shape = if native_callable(&art.cf, &code) { - Some(false) + Some((false, argc)) } else if native_method_callable(&art.cf, &code) { - Some(true) + Some((true, argc)) + } else if bound > argc && native_callable_n(&art.cf, &code, bound) { + // (Keyword-only parameters the body reads: a caller that + // bound them all fills their slots too.) + Some((false, bound)) } else { None }; - let out = method_shape.map(|method_shape| { + let out = method_shape.map(|(method_shape, nparams)| { StdRc::new(DirectEntry { native: self.native_table_for(key), method_native: self.method_native_table_for(key), art, method_shape, + nparams, }) }); if let Some(ce) = self.cache.get_mut(&key) { @@ -2164,7 +2445,8 @@ impl JitState { } entry.counter = entry.counter.saturating_add(stride); entry.counter >= self.threshold - && (!self.range_budget || entry.counter >= size_budget(code)) + && (!self.range_budget + || entry.counter >= size_budget(code).max(analysis_due_at(entry, code))) } Tier::Compiled(..) => { if entry.osr_failures < OSR_FAILURE_BUDGET { @@ -2257,6 +2539,9 @@ struct VmProbes<'a> { /// the requesting activation (no grading), for the analyzer's /// generic-attribute probe-miss fallback. obj_live: &'a mut dyn FnMut(u32) -> bool, + /// Whether local `slot` holds a Python function or a method bound to + /// one (see [`probe_py_callee`]). + py_callee: &'a mut dyn FnMut(u32) -> bool, /// The lane of the live loop iterator at an interpreter-stack index /// of the requesting activation (see [`probe_stack_iter_lane`]). stack_iter: &'a mut dyn FnMut(u32) -> Option, @@ -2489,12 +2774,18 @@ fn marshalable_lane_ty(t: JitType) -> bool { /// - no cells (the analyzer rejects cell opcodes, so this is /// defensive). fn native_callable(cf: &CompiledFrame, code: &CodeObject) -> bool { + native_callable_n(cf, code, code.arg_count as usize) +} + +/// [`native_callable`] with the first `argc` locals as the parameters a +/// caller fills (the positional ones, or those and the keyword-only ones +/// after them). +fn native_callable_n(cf: &CompiledFrame, code: &CodeObject, argc: usize) -> bool { // RFC 0070 WS2 — a compiled *generator* body is OSR-only: a call // must create the generator object, never run the body. if code.is_generator { return false; } - let argc = code.arg_count as usize; for j in 0..argc { match cf.local_types.get(j).copied().flatten() { Some(t) if marshalable_lane_ty(t) => {} @@ -2552,9 +2843,9 @@ thread_local! { /// result at runtime — so staleness (e.g. the callee's own globals /// changing what its analysis would say) costs a deopt, never /// correctness. - static RET_LANE_CACHE: RefCell< + static RET_LANE_CACHE: crate::gil::ReleaseUnderGil, bool, crate::sync::Weak)>, - > = RefCell::new(CodeMap::default()); + >> = crate::gil::ReleaseUnderGil::new(RefCell::new(CodeMap::default())); } /// Infer a candidate callee's return typing — its stable scalar return @@ -2610,10 +2901,13 @@ fn callee_ret_info( (None, weavepy_jit::returns_none_syntactically(fcode)) } }; - RET_LANE_CACHE.with(|c| { - c.borrow_mut() - .insert(key, (lane, ret_none, Rc::downgrade(fcode))) - }); + // (An analysis that ran out of work budget says nothing of the code.) + if !weavepy_jit::work_short() { + RET_LANE_CACHE.with(|c| { + c.borrow_mut() + .insert(key, (lane, ret_none, Rc::downgrade(fcode))) + }); + } (lane, ret_none) } @@ -2717,6 +3011,8 @@ fn method_ret_info( cell: &mut |_| None, // Depth bound: no live locals to observe in the nested view. obj: &mut |_| false, + py_callee: &mut |_| false, + py_operator: &mut |_| false, local: &mut |_| None, stack_iter: &mut |_| None, pairs: &mut |_| None, @@ -3088,6 +3384,51 @@ fn probe_obj_live(frame: &super::Frame, slot: u32) -> bool { .is_some_and(|o| !matches!(o, Object::Unbound)) } +/// Whether local `slot` holds a small plain Python function, or a method +/// bound to one, in the requesting activation (see `Probes::py_callee`). +fn probe_py_callee(frame: &super::Frame, slot: u32) -> bool { + let locals = frame.locals.borrow(); + locals.get(slot as usize).is_some_and(small_py_callee) +} + +/// The most instructions a callee may have for [`small_py_callee`]. +const SMALL_PY_CALLEE: usize = 64; + +/// Whether `f` is a Python function, or a method bound to one, short +/// enough that a generic call's cost (about 800 instructions more than the +/// frame JIT's entry) is a large part of calling it. A longer body, which +/// tier 2 likely compiles itself, repays the call. +fn small_py_callee(f: &Object) -> bool { + let func = match f { + Object::Function(func) => func, + Object::BoundMethod(bm) => match &bm.function { + Object::Function(func) => func, + _ => return false, + }, + _ => return false, + }; + func.code.borrow().instructions.len() <= SMALL_PY_CALLEE +} + +/// Whether a guarded call of `f` (a `CallPy`) evaluates it frameless (see +/// `wpjit_call_py`), given that tier 2 hasn't compiled it as a scalar leaf +/// (which native code enters directly): a loop-free plain function short +/// enough for [`small_py_callee`] that the frameless evaluator takes. +/// Such a call costs several hundred instructions from native code, its +/// tiny shapes (an argument's field, a constant) included, where the frame +/// JIT lowers a short callee in line. (A callee with loops runs as tier +/// 2's own native code.) +fn frameless_py_callee(f: &Object) -> bool { + let Object::Function(func) = f else { + return false; + }; + if !small_py_callee(f) { + return false; + } + let code = func.code.borrow(); + code.jit_hint.loop_free(&code) && crate::code_is_pure_leaf_pub(&code) +} + /// RFC 0073 WS2 — the dict-lane probe: `(key lane, value lane)` of /// local `slot` when it currently holds an *exact* `dict` whose /// sampled keys are uniformly exact-`str` (never `WStr` — surrogate- @@ -3664,11 +4005,14 @@ fn obj_layout(obj: &Object, inst: &Rc) -> Option) -> Option>>>>, + /// The state of the activation's method calls on builtin values (see + /// [`BoundLane`]). + bound: BoundLane, /// A frameless activation's frame object, made for its activation /// shell while a call ran (`sys._getframe()`): the interpreter /// continuation adopts it (see [`call_with_activation_shell`]). @@ -4803,6 +5155,67 @@ pub(crate) fn sync_native_locals(locals: &Rc>>) { }); } +/// One method-form load of a builtin value's method (`d.pop` of +/// `d.pop(k)`) that tier 2 answers without building the bound method. +/// +/// Tier 2 runs such a call as two operations, the load and the call. A +/// builtin value's method table never changes and its lookup runs no +/// code, so when the method is one the core loop's leaf lane runs in +/// place, the load leaves the receiver where the bound method would go +/// and arms this record, and the call at `call_pc` runs the builtin on +/// the receiver and its arguments. An exit between the two rebuilds the +/// bound method the interpreter expects there (see `rebuild_stack`). +struct BoundSite { + /// The load's pc and its call's. + load_pc: u32, + call_pc: u32, + /// Whether the load's last run left its receiver for the call. Every + /// run of the load sets it, so it is exact whenever the call (which + /// only that load reaches) or an exit inside the pair reads it. + armed: bool, + /// The receiver kind (`builtins::method_memo_tag`) the rest is for. + tag: u8, + /// The leaf registry's generation `kind` was read at. + gen: u64, + builtin: Rc, + kind: super::LeafKind, +} + +/// What an activation keeps for its method calls on builtin values. +struct BoundLane { + /// The activation's deferred method loads (a handful at most). + sites: Vec, + /// The builtin the last bound-method call ran as a leaf, with the + /// leaf registry's generation and its kind. + kind: Option<(Rc, u64, super::LeafKind)>, +} + +impl BoundLane { + fn new() -> Self { + Self { + sites: Vec::new(), + kind: None, + } + } + + /// The armed record of the load whose call is at `call_pc`. + #[inline(always)] + fn armed_call(&self, call_pc: u32) -> Option<&BoundSite> { + if self.sites.is_empty() { + return None; + } + self.sites.iter().find(|s| s.call_pc == call_pc && s.armed) + } + + /// The armed record of the load at `load_pc`. + fn armed_load(&self, load_pc: u32) -> Option<&BoundSite> { + self.sites.iter().find(|s| s.load_pc == load_pc && s.armed) + } +} + +/// The most deferred method loads an activation records. +const BOUND_SITES_MAX: usize = 16; + /// The size of [`CallCtx::pin_memo`]: sets of [`PIN_MEMO_WAYS`] slots. const PIN_MEMO: usize = 64; @@ -4823,7 +5236,8 @@ fn pin_identity(v: &Object) -> usize { } /// The [`CallCtx::pin_memo`] home entry for an object identity, whose set -/// (`s ^ w` for each of [`PIN_MEMO_WAYS`]) it may sit in. The address is mixed multiplicatively: allocations a +/// (`s ^ w` for each of [`PIN_MEMO_WAYS`], four entries that lie together) +/// it may sit in. The address is mixed multiplicatively: allocations a /// fixed stride apart (a loop's few instances) would otherwise share /// entries, and each would evict the other on every read. #[inline] @@ -4832,33 +5246,65 @@ fn pin_memo_slot(id: usize) -> usize { >> (usize::BITS - PIN_MEMO.trailing_zeros()) } -/// The identity of the object `pins[ix]` holds (`0` for none). +/// Pin indices recently handed out, each beside a tag of the identity it +/// was handed out for (see [`pin_memo_tag`]). A tag only screens: a match +/// is checked against the pin it names, so a stale or colliding entry is a +/// miss, and a miss compares the set's tags without reading any pin. An +/// entry holds its tag beside its index, and a set's entries lie together +/// (32 bytes): a lookup reads one stretch of memory, not one per field. +#[derive(Clone, Copy)] +struct PinMemo { + entries: [PinMemoEntry; PIN_MEMO], +} + +#[derive(Clone, Copy)] +#[repr(C)] +struct PinMemoEntry { + tag: u32, + ix: u32, +} + +impl PinMemo { + const EMPTY: PinMemo = PinMemo { + entries: [PinMemoEntry { + tag: 0, + ix: u32::MAX, + }; PIN_MEMO], + }; +} + +/// An identity's [`PinMemo`] tag (never `0`, which marks an unused entry). #[inline] -fn pin_memo_holds(pins: &PinTable, ix: u32) -> usize { - match pins.get(ix as usize) { - Some(Pin::Obj(p)) => pin_identity(p), - Some(Pin::List(l, _)) => Rc::as_ptr(l) as usize, - None => 0, - } +fn pin_memo_tag(id: usize) -> u32 { + ((id >> 3) as u32) | 1 +} + +/// The pin index in the entry of `id`'s set whose tag is its own, if one +/// is (the identity's own entry first). +#[inline] +fn pin_memo_find(id: usize, memo: &PinMemo) -> Option { + let s = pin_memo_slot(id); + let tag = pin_memo_tag(id); + (0..PIN_MEMO_WAYS) + .map(|w| &memo.entries[s ^ w]) + .find(|e| e.tag == tag) + .map(|e| e.ix as usize) } /// The pin that already holds this very object, when `memo` remembers /// one. A pin only owns its object, so two sites that pin the same object /// can share one. #[inline] -fn pin_memo_hit(v: &Object, pins: &PinTable, memo: &[u32; PIN_MEMO]) -> Option { +fn pin_memo_hit(v: &Object, pins: &PinTable, memo: &PinMemo) -> Option { let id = pin_identity(v); if id == 0 { return None; } - let s = pin_memo_slot(id); - (0..PIN_MEMO_WAYS).map(|w| s ^ w).find_map(|k| { - let hint = memo[k] as usize; - match pins.get(hint) { - Some(Pin::Obj(p)) if pin_identity(p) == id => Some(hint as u64), - _ => None, - } - }) + let hint = pin_memo_find(id, memo)?; + match pins.get(hint) { + Some(Pin::Obj(p)) if pin_identity(p) == id => Some(hint as u64), + _ => None, + } } /// The pin that already holds this very list (a row of a nested list @@ -4867,22 +5313,21 @@ fn pin_memo_hit(v: &Object, pins: &PinTable, memo: &[u32; PIN_MEMO]) -> Option>>, pins: &PinTable, - memo: &[u32; PIN_MEMO], + memo: &PinMemo, ) -> Option { - let s = pin_memo_slot(Rc::as_ptr(l) as usize); - (0..PIN_MEMO_WAYS).map(|w| s ^ w).find_map(|k| { - let hint = memo[k] as usize; - match pins.get(hint) { - Some(Pin::List(p, _)) if Rc::ptr_eq(p, l) => Some(hint as u64), - _ => None, - } - }) + let hint = pin_memo_find(Rc::as_ptr(l) as usize, memo)?; + match pins.get(hint) { + Some(Pin::List(p, _)) if Rc::ptr_eq(p, l) => Some(hint as u64), + _ => None, + } } -/// Remember that pin `ix` will hold `p`'s object: in its first entry, -/// unless that one remembers another live object, then in its second. +/// Remember that pin `ix` (the table's next) will hold `p`'s object: in +/// this identity's own entry or a free one of its set (unused, or naming a +/// pin past the table's end, which a cleared table left), else in one by +/// the pin's index, so that a set's entries take turns. #[inline] -fn pin_memo_note(p: &Pin, ix: usize, pins: &PinTable, memo: &mut [u32; PIN_MEMO]) { +fn pin_memo_note(p: &Pin, ix: usize, memo: &mut PinMemo) { let id = match p { Pin::Obj(v) => pin_identity(v), Pin::List(l, _) => Rc::as_ptr(l) as usize, @@ -4891,21 +5336,21 @@ fn pin_memo_note(p: &Pin, ix: usize, pins: &PinTable, memo: &mut [u32; PIN_MEMO] return; } let s = pin_memo_slot(id); - // A free entry of the set, or this identity's own; else one by the - // pin's index, so that a set's entries take turns. + let tag = pin_memo_tag(id); let k = (0..PIN_MEMO_WAYS) .map(|w| s ^ w) .find(|&k| { - matches!(pin_memo_holds(pins, memo[k]), 0) || pin_memo_holds(pins, memo[k]) == id + let e = &memo.entries[k]; + e.tag == tag || e.tag == 0 || e.ix as usize >= ix }) .unwrap_or(s ^ (ix % PIN_MEMO_WAYS)); - memo[k] = ix as u32; + memo.entries[k] = PinMemoEntry { tag, ix: ix as u32 }; } /// Pin `v` in `pins`, reusing the pin that already holds this very object /// (see [`pin_memo_hit`]); `None` at the pin cap. #[inline] -fn pin_reusing(v: &Object, pins: &mut PinTable, memo: &mut [u32; PIN_MEMO]) -> Option { +fn pin_reusing(v: &Object, pins: &mut PinTable, memo: &mut PinMemo) -> Option { if let Some(bits) = pin_memo_hit(v, pins, memo) { return Some(bits); } @@ -4913,7 +5358,7 @@ fn pin_reusing(v: &Object, pins: &mut PinTable, memo: &mut [u32; PIN_MEMO]) -> O return None; } let p = Pin::Obj(v.clone()); - pin_memo_note(&p, pins.len(), pins, memo); + pin_memo_note(&p, pins.len(), memo); pins.push(p); Some((pins.len() - 1) as u64) } @@ -4973,7 +5418,7 @@ fn guards_hold( // A rebinding in place leaves the stamps alone (see `STORE_GLOBAL`). crate::object::global_value_epoch(), ); - if (guard_snapshot.last_ok.get() != key || interp.globals_missing_any.get()) + if (guard_snapshot.last_ok.get() != key || interp.globals_missing_gate()) && !global_guards_hold(interp, globals, builtins, guard_snapshot, key) { return false; @@ -5384,7 +5829,7 @@ fn lane_tag(t: JitType) -> u32 { /// `None` singleton is the nullable lane's `-1`; an instance pins into /// the caller's table (capped), reusing the pin that already holds it /// (a method returning `self`). Anything else can't ride the lane. -fn obj_ret_bits(v: &Object, pins: &mut PinTable, memo: &mut [u32; PIN_MEMO]) -> Option { +fn obj_ret_bits(v: &Object, pins: &mut PinTable, memo: &mut PinMemo) -> Option { match v { Object::None => Some(u64::MAX), Object::Instance(_) => pin_reusing(v, pins, memo), @@ -5766,7 +6211,9 @@ unsafe fn native_scalar_field_update( /// have just held, so what compiled code still checks per call (the /// receiver's class version and split names, the shadow bound, the code /// identity, the observer and key gates) is all that can change. A split -/// field and the plain increments only; anything else stays unarmed. +/// field, or a `__slots__` member of a class whose instances have no +/// dictionary (so none can shadow the method's name), and the plain +/// increments only; anything else stays unarmed. fn arm_update(entry: &MethodEntry, nc: &NativeCallee, receiver: &Object, argc: u32) { let Some(plan) = nc.scalar_update.as_deref() else { return; @@ -5782,24 +6229,36 @@ fn arm_update(entry: &MethodEntry, nc: &NativeCallee, receiver: &Object, argc: u return; }; let cls = inst.cls_raw(); - let Some(keys) = cls.shared_keys.get() else { - return; - }; let (from_arg, inc) = match (plan.increment, argc) { (Some(inc), 0) => (0, inc), (None, 1) => (1, 0), _ => return, }; - if guard.split_idx == u32::MAX - || guard.ver != entry.ver - || cls.attr_version.get() != entry.ver - || !matches!(guard.storage, AttrStorage::Indexed(i) if i == guard.split_idx) + if guard.split_idx == u32::MAX || guard.ver != entry.ver || cls.attr_version.get() != entry.ver { return; } - let shadow = keys.names_before(&entry.name, entry.name_hash); let u = &entry.update; - u.shadow.set(u32::try_from(shadow).unwrap_or(0)); + if guard.split_idx & weavepy_jit::SLOT_FIELD != 0 { + // A member slot, at its position in the class's layout. + if guard.slot_layout == 0 + || !entry.no_dict + || !cls.forbids_dict + || !matches!(guard.storage, AttrStorage::Slot(_)) + { + return; + } + u.layout.set(guard.slot_layout); + } else { + let Some(keys) = cls.shared_keys.get() else { + return; + }; + if !matches!(guard.storage, AttrStorage::Indexed(i) if i == guard.split_idx) { + return; + } + let shadow = keys.names_before(&entry.name, entry.name_hash); + u.shadow.set(u32::try_from(shadow).unwrap_or(0)); + } u.from_arg.set(from_arg); u.inc.set(inc); u.code_at.set(func.code.as_ptr() as usize); @@ -6266,6 +6725,10 @@ unsafe fn try_native_call( }; } child.entry_pin_count = child.pins.len(); + // (Another code object's pcs.) + if !child.bound.sites.is_empty() { + child.bound.sites.clear(); + } child.interp = ctx.interp; let nctx: &mut CallCtx = &mut child; let mut njf = JitFrame { @@ -6527,9 +6990,10 @@ fn fresh_child(ctx: &CallCtx, nc: &NativeCallee, callee_key: *const CodeObject) // callee — keep it observable to callee-side stack walkers. frameless_code: Some(nc.code.clone()), dyn_callee: None, - pin_memo: [u32::MAX; PIN_MEMO], + pin_memo: PinMemo::EMPTY, introspected: Cell::new(false), inspected_locals: std::cell::RefCell::new(None), + bound: BoundLane::new(), inspected_frame: std::cell::RefCell::new(None), cell_list_pins: Vec::new(), }) @@ -6989,7 +7453,16 @@ fn finish_deopted( nctx.parked.take() }; rebuild_stack( - interp, &mut frame, entry, locals_buf, spill, tags, njf, &nctx.pins, parked, + interp, + &mut frame, + entry, + locals_buf, + spill, + tags, + njf, + &nctx.pins, + &nctx.bound, + parked, ); if raised.is_some() { // As though the raising CALL just executed: pc points past it @@ -7068,6 +7541,12 @@ fn call_with_activation_shell( tb_refs: std::sync::atomic::AtomicU32::new(0), departed: crate::object::Departed::default(), }); + // The callers still waiting on the pending list (a lean activation + // whose builtin, `map` or a sort, called this one) are older than this + // activation: their shells go on the spine first, or a walk from the + // call below would find them above it (`sys._getframe()` answered the + // caller's frame, and the pop below took the caller's shell). + interp.flush_pending_callers(); interp.frame_stack.borrow_mut().push(shell.clone()); // Inspection of the shell's frame finds this activation's locals. let out = with_native_frame(&shell_locals, jf, || { @@ -7208,6 +7687,31 @@ unsafe fn wpjit_call_py_inner(frame: *mut JitFrame, token: u32, argc: u32, expec native_table = ctx.native.clone(); } + // A class whose `__init__` only stores its parameters, which the + // interpreter or the frame JIT proved: the instance built with its + // fields in place, as they build it, with no `__init__` frame. No + // Python code runs, so no guard can have moved. + if expect_tag == SlotTag::ObjPin as u32 { + if let Some((Object::Type(ty), _)) = ctx.callees.get(token as usize) { + let pins = &ctx.pins; + let inst = interp.store_init_call(ty, argc as usize, ctx.depth_cell, |j| { + // SAFETY: native code wrote `argc` entries (`j` counts + // from 1). + let (bits, tag) = unsafe { (*jf.call_args.add(j - 1), *jf.call_tags.add(j - 1)) }; + unpack_pins(bits, tag, pins) + }); + if let Some(inst) = inst { + if let Some(bits) = obj_ret_bits(&inst, &mut ctx.pins, &mut ctx.pin_memo) { + jf.ret_bits = bits; + jf.ret_tag = expect_tag; + return CallStatus::Ok as i64; + } + ctx.parked = Some(inst); + return CallStatus::Boxed as i64; + } + } + } + // Interpreter path: arbitrary Python runs on behalf of this // activation, so burned-in resolutions must be revalidated after // the call (RFC 0067 WS1's dirtiness discipline). @@ -7807,6 +8311,22 @@ thread_local! { static KEEP_CALL_DENSE: std::cell::Cell = const { std::cell::Cell::new(false) }; } +/// Whether tier 2 enters code whose loops measured short (see +/// [`crate::short_loops`]): only under `force_enable_for_test`, whose +/// threshold has a compile measure a couple of back edges a call, so every +/// test kernel would read as short. +#[inline(always)] +fn keeps_short_loops() -> bool { + #[cfg(test)] + { + KEEP_CALL_DENSE.with(std::cell::Cell::get) + } + #[cfg(not(test))] + { + false + } +} + /// Recompiles one code object may take after cold exits (see /// `CacheEntry::recompile_at_osr`): one per later loop is the common /// shape (a function running several loops over containers it builds in @@ -7966,6 +8486,11 @@ unsafe fn wpjit_call_method_inner( // here exactly as the interpreter's `LOAD_ATTR` would. native_stat(|s| s.method_guard_misses.set(s.method_guard_misses.get() + 1)); ctx.dirty = true; + // A generic resolution and call: a loop whose receivers keep + // missing the burned class (a site seeing two classes in turn) + // is judged like any other driver around generic calls, and + // handed back to tier 1's per-site method caches. + ctx.dyn_py_calls = ctx.dyn_py_calls.saturating_add(1); let bound = match interp.load_attr_public(&recv, &entry.name) { Err(err) => { ctx.raised = Some(err); @@ -8878,7 +9403,7 @@ unsafe extern "C" fn wpjit_list_get(frame: *mut JitFrame, pin: i64, idx: i64) -> return 1; } jf.ret_bits = ctx.pins.len() as u64; - pin_memo_note(&p, ctx.pins.len(), &ctx.pins, &mut ctx.pin_memo); + pin_memo_note(&p, ctx.pins.len(), &mut ctx.pin_memo); ctx.pins.push(p); 0 } @@ -9624,14 +10149,43 @@ unsafe extern "C" fn wpjit_tuple_len(frame: *mut JitFrame, pin: i64) -> i64 { // (`deque.__len__`): its body runs no Python and has no effects, // so anything but a plain length deopts for the interpreter to // call it again. - Some(Pin::Obj(obj @ Object::Instance(_))) if !crate::gil::free_threading_enabled() => { + Some(Pin::Obj(obj @ Object::Instance(inst))) if !crate::gil::free_threading_enabled() => { // SAFETY: the `&mut Interpreter` is dormant while the helper runs. let interp = unsafe { &*ctx.interp }; - match interp - .leaf_instance_dunder(obj, "__len__") - .map(|b| (b.call)(std::slice::from_ref(obj))) + // (`Interpreter::leaf_instance_dunder`'s lookup, with a deque's + // own `__len__` read by its direct operation.) + if !crate::Interpreter::default_getattribute(inst.cls_raw()) + || crate::object::exotic_str_keys_possible() + { + return -1; + } + let Some(b) = crate::Interpreter::instance_native_dunder( + inst, + crate::types::AttrKey::vm(crate::types::vm_key::LEAF_LEN), + "__len__", + false, + ) else { + return -1; + }; + if crate::stdlib::collections_native::is_deque_len(&b) { + if let Some(Object::Int(n)) = crate::stdlib::collections_native::fast_op( + crate::stdlib::collections_native::OP_LEN, + obj, + None, + ) { + if n >= 0 { + return n; + } + } + } + if !(b.binds_instance + && b.call_kw.is_none() + && interp.leaf_call_kind(&b) == Some(crate::LeafKind::Opaque)) { - Some(Ok(Object::Int(n))) if n >= 0 => n, + return -1; + } + match (b.call)(std::slice::from_ref(obj)) { + Ok(Object::Int(n)) if n >= 0 => n, _ => -1, } } @@ -9824,7 +10378,7 @@ unsafe extern "C" fn wpjit_list_next(frame: *mut JitFrame, pin: i64, idx: i64) - let pinned = match outcome { Ok(bits) => Some(bits), Err(p) => (ctx.pins.len() < RUNTIME_PIN_CAP).then(|| { - pin_memo_note(&p, ctx.pins.len(), &ctx.pins, &mut ctx.pin_memo); + pin_memo_note(&p, ctx.pins.len(), &mut ctx.pin_memo); ctx.pins.push(p); (ctx.pins.len() - 1) as u64 }), @@ -9873,17 +10427,38 @@ unsafe extern "C" fn wpjit_get_iter(frame: *mut JitFrame, pin: i64) -> i64 { #[inline] fn builtin_seq_step(cell: &Rc>) -> Option> { use crate::object::PyIterator; - let mut it = cell.try_borrow_mut().ok()?; - match &*it { - PyIterator::List { .. } | PyIterator::Tuple { .. } | PyIterator::Range { .. } => { - Some(it.next_value()) - } - PyIterator::DictKeys { .. } => { - match super::Interpreter::core_dict_next(&mut it, false, false) { - crate::DictStep::Item(v, _) => Some(Some(v)), - crate::DictStep::Exhausted | crate::DictStep::Decline => None, + // SAFETY: the view ends with the step, which runs no code. + let it = unsafe { cell.peek_mut() }?; + match it { + PyIterator::List { .. } + | PyIterator::Tuple { .. } + | PyIterator::Range { .. } + | PyIterator::Reversed { .. } + | PyIterator::Bytes { .. } => Some(it.next_value()), + // A buffer's next byte while it has one (its end detaches the + // iterator, which is the general step's). + PyIterator::ByteArray { data, index } => { + // SAFETY: a read of a distinct cell, ended before anything runs. + let b = *unsafe { data.peek() }?.get(*index)?; + *index += 1; + Some(Some(Object::Int(i64::from(b)))) + } + // A set's next element while it keeps its size (a change, and the + // end, are the general step's to report). + PyIterator::Set { set, len, index } => { + // SAFETY: a read of a distinct cell, ended before anything runs. + let items = unsafe { set.peek() }?; + if items.len() != *len { + return None; } + let v = crate::clone_hot(&items.get_index(*index)?.0); + *index += 1; + Some(Some(v)) } + PyIterator::DictKeys { .. } => match super::Interpreter::core_dict_next(it, false, false) { + crate::DictStep::Item(v, _) => Some(Some(v)), + crate::DictStep::Exhausted | crate::DictStep::Decline => None, + }, _ => None, } } @@ -9894,16 +10469,39 @@ fn builtin_seq_step(cell: &Rc>) -> Option< /// the lane, any other iterator, or one already borrowed. #[inline] fn seq_scalar_step(cell: &Rc>, elem_tag: i64) -> Option { - let lane = match u32::try_from(elem_tag).ok().map(SlotTag::from_raw) { - Some(SlotTag::Int) => JitType::Int, - Some(SlotTag::Float) => JitType::Float, - Some(SlotTag::Bool) => JitType::Bool, + // (The tag's discriminants compared directly: a conversion first + // cost a tenth of a step.) + const INT: i64 = SlotTag::Int as i64; + const FLOAT: i64 = SlotTag::Float as i64; + const BOOL: i64 = SlotTag::Bool as i64; + let lane = match elem_tag { + INT => JitType::Int, + FLOAT => JitType::Float, + BOOL => JitType::Bool, _ => return None, }; // SAFETY: the views end before anything that could borrow either cell // runs (reading an element and packing its bits run no code). let it = unsafe { cell.peek_mut()? }; match it { + // A range's next int either way (a counted loop the compiler left + // opaque: `range(n, -1, -1)`, `reversed(range(n))`); its end is the + // general step's. + PyIterator::Range { + current, + stop, + step, + } if lane == JitType::Int + && (if *step > 0 { + *current < *stop + } else { + *step < 0 && *current > *stop + }) => + { + let v = *current; + *current = current.wrapping_add(*step); + pack(&Object::Int(v), lane) + } PyIterator::Tuple { items, index } => { let bits = pack(items.get(*index)?, lane)?; *index += 1; @@ -9915,6 +10513,58 @@ fn seq_scalar_step(cell: &Rc>, elem_tag: i64) -> Option { + let b = *data.get(*index)?; + *index += 1; + pack(&Object::Int(i64::from(b)), lane) + } + PyIterator::ByteArray { data, index } if lane == JitType::Int => { + // SAFETY: as above. + let b = *unsafe { data.peek()? }.get(*index)?; + *index += 1; + pack(&Object::Int(i64::from(b)), lane) + } + // A reversed list's (its end, and a list that shrank under it, are + // the general step's). + PyIterator::Reversed { items, index, .. } => { + let at = usize::try_from(*index).ok()?; + // SAFETY: as above. + let bits = pack(unsafe { items.peek()? }.get(at)?, lane)?; + *index -= 1; + Some(bits) + } + // A plain dict's next key or value, after the first step set its + // watch, while the dict keeps its size and keys (see + // `Interpreter::core_dict_next`, whose step this is; its end, and + // an `OrderedDict`'s values, are the general step's). + PyIterator::DictKeys { + kind, + index, + dict: Some(d), + len, + watch: Some(watch), + reverse: false, + odict, + .. + } => { + use crate::object::DictViewKind; + let take_value = match kind { + DictViewKind::Keys => false, + DictViewKind::Values if odict.is_none() => true, + _ => return None, + }; + // SAFETY: as above. + let data = unsafe { d.peek()? }; + if data.len() != *len || watch.changed() { + return None; + } + let (k, v) = data.get_index(*index)?; + let bits = pack(if take_value { v } else { &k.0 }, lane)?; + *index += 1; + Some(bits) + } _ => None, } } @@ -9948,6 +10598,63 @@ unsafe extern "C" fn wpjit_iter_next(frame: *mut JitFrame, pin: i64, elem_tag: i return 0; } } + // (The rest in a frame of its own, so this step's stays small.) + // SAFETY: the caller's contract. + unsafe { iter_next_rest(frame, pin, elem_tag) } +} + +/// [`wpjit_iter_next`] past its scalar list-or-tuple step. +/// +/// # Safety +/// +/// Same contract as [`wpjit_call_py`]. +#[inline(never)] +unsafe fn iter_next_rest(frame: *mut JitFrame, pin: i64, elem_tag: i64) -> i64 { + // SAFETY: see wpjit_call_py — same live-buffer contract. + let jf = unsafe { &mut *frame }; + #[allow(clippy::cast_ptr_alignment)] + let ctx = unsafe { &*jf.ctx.cast::() }; + // A list, tuple, range, set or dict iterator's next element for any + // lane it packs into (a dict's keys, a set's strings): stepped in place, + // no Python run. Its end, and an element outside the lane, take the + // general step. + let step = match ctx.pins.get(pin as usize) { + Some(Pin::Obj(Object::Iter(cell))) => builtin_seq_step(cell), + // `islice`'s, `chain`'s, `count`'s and `cycle`'s commonest steps, + // which run no code either (their ends are the general step's). + Some(Pin::Obj(Object::LazyIter(l))) => crate::seqiter::lazy_hot_next(l).map(Some), + _ => None, + }; + if let Some(Some(v)) = step { + #[allow(clippy::cast_ptr_alignment)] + let ctx = unsafe { &mut *jf.ctx.cast::() }; + // (A string for the `str` lane is pinned itself, with room checked + // first.) + if elem_tag == weavepy_jit::ITER_ELEM_STR + && matches!(v, Object::Str(_)) + && ctx.pins.len() < RUNTIME_PIN_CAP + { + ctx.pins.push(Pin::Obj(v)); + jf.ret_bits = (ctx.pins.len() - 1) as u64; + return 0; + } + if let Some(bits) = pack_iter_elem(&v, elem_tag, &mut ctx.pins, &mut ctx.pin_memo) { + jf.ret_bits = bits; + return 0; + } + // Consumed but outside the lane: pinned raw (`None` rides the + // nullable `-1`), resumed interpreted at the fused store. + jf.ret_bits = if matches!(v, Object::None) { + u64::MAX + } else { + ctx.pins.push(Pin::Obj(v)); + (ctx.pins.len() - 1) as u64 + }; + return 3; + } + if let Some(None) = step { + return 1; + } // SAFETY: the caller's contract. unsafe { iter_next_general(frame, pin, elem_tag) } } @@ -10241,8 +10948,10 @@ unsafe extern "C" fn wpjit_build_list( // RFC 0073 WS1 — the interpreter tracks *every* list it builds // (`gc.is_tracked([])` is True and any list can close a cycle by // later mutation); a natively built list is no different, and a - // comprehension accumulator in particular always escapes. - crate::gc_trace::track(&Object::List(list.clone())); + // comprehension accumulator in particular always escapes. (Deferred + // as a built list is, a collection promoting it once it can anchor a + // cycle.) + crate::gc_trace::track_built(&Object::List(list.clone())); let idx = ctx.pins.len() as i64; ctx.pins.push(Pin::List(list, elem)); idx @@ -10280,15 +10989,25 @@ unsafe extern "C" fn wpjit_build_tuple(frame: *mut JitFrame, n: i64) -> i64 { }) { return -1; } - let tuple = if n == 0 { - Object::new_tuple(Vec::new()) - } else { - Object::Tuple(crate::tuple_storage::TupleStorage::from_exact_iter( - (0..n).map(|j| { - let (bits, tag) = entry(j); - boxed_element(ctx, bits, tag).unwrap_or(Object::None) - }), - )) + let boxed = |j: usize| { + let (bits, tag) = entry(j); + boxed_element(ctx, bits, tag).unwrap_or(Object::None) + }; + // (A pair or a triple in a fixed-size allocation.) + let tuple = match n { + 0 => Object::new_tuple(Vec::new()), + 2 => Object::Tuple(crate::tuple_storage::TupleStorage::from_array([ + boxed(0), + boxed(1), + ])), + 3 => Object::Tuple(crate::tuple_storage::TupleStorage::from_array([ + boxed(0), + boxed(1), + boxed(2), + ])), + _ => Object::Tuple(crate::tuple_storage::TupleStorage::from_exact_iter( + (0..n).map(boxed), + )), }; let idx = ctx.pins.len() as i64; ctx.pins.push(Pin::Obj(tuple)); @@ -10430,6 +11149,9 @@ unsafe extern "C" fn wpjit_build_map(frame: *mut JitFrame, n: i64) -> i64 { } let n = n as usize; let mut d = DictData::with_capacity_and_hasher(n, crate::fasthash::FxBuildHasher); + // (Keys whose hashes differ from every earlier key's go in without the + // probe for an equal one; a repeated key replaces, as the literal's.) + let mut seen = [0i64; 8]; for p in 0..n { // SAFETY: per the function contract, `2n` marshaled entries // and tags are live. @@ -10438,18 +11160,29 @@ unsafe extern "C" fn wpjit_build_map(frame: *mut JitFrame, n: i64) -> i64 { let Some(k) = boxed_element(ctx, kbits, ktag) else { return -1; }; - if !matches!(k, Object::Str(_) | Object::Int(_)) { - return -1; - } + let h = match &k { + Object::Str(s) => crate::shared_value::SharedStr::hash_cached(s), + Object::Int(i) => crate::object::py_hash_long_i64(*i), + _ => return -1, + }; let Some(v) = boxed_element(ctx, vbits, vtag) else { return -1; }; - d.insert(DictKey(k), v); + if p < seen.len() && !seen[..p].contains(&h) { + seen[p] = h; + d.insert_unique_hashed(h, DictKey(k), v); + } else { + if p < seen.len() { + seen[p] = h; + } + d.insert(DictKey(k), v); + } } let obj = Object::Dict(Rc::new(GilRefCell::new(d))); - // The interpreter tracks every dict it builds; a natively built - // dict is no different. - crate::gc_trace::track(&obj); + // The interpreter tracks every dict it builds; a natively built one + // is deferred as a built dict is, a collection promoting it once it + // can anchor a cycle. + crate::gc_trace::track_built(&obj); let idx = ctx.pins.len() as i64; ctx.pins.push(Pin::Obj(obj)); idx @@ -10486,14 +11219,16 @@ unsafe extern "C" fn wpjit_list_repeat(frame: *mut JitFrame, pin: i64, count: i6 if total > (isize::MAX as usize) / size_of::() { return -1; } - let mut out = Vec::with_capacity(total); - for _ in 0..reps { - out.extend(items.iter().cloned()); - } + let mut out = Vec::new(); + crate::repeat_objects(&items, reps, &mut out); drop(items); - let fresh = Rc::new(crate::sync::RefCell::new(out)); - // See `wpjit_build_list`: every built list is GC-tracked. - crate::gc_trace::track(&Object::List(fresh.clone())); + let fresh = Object::List(Rc::new(crate::sync::RefCell::new(out))); + // See `wpjit_build_list`: deferred without scanning its elements (each + // collection promotes the deferred lists that could close a cycle). + crate::gc_trace::track_built(&fresh); + let Object::List(fresh) = fresh else { + unreachable!("built above") + }; let idx = ctx.pins.len() as i64; ctx.pins.push(Pin::List(fresh, elem)); idx @@ -10585,9 +11320,13 @@ unsafe extern "C" fn wpjit_list_slice( Vec::new() }; drop(items); - let fresh = Rc::new(crate::sync::RefCell::new(out)); - // See `wpjit_build_list`: every built list is GC-tracked. - crate::gc_trace::track(&Object::List(fresh.clone())); + let fresh = Object::List(Rc::new(crate::sync::RefCell::new(out))); + // See `wpjit_build_list`: deferred without scanning its elements (each + // collection promotes the deferred lists that could close a cycle). + crate::gc_trace::track_built(&fresh); + let Object::List(fresh) = fresh else { + unreachable!("built above") + }; let idx = ctx.pins.len() as i64; ctx.pins.push(Pin::List(fresh, elem)); idx @@ -12059,7 +12798,68 @@ unsafe fn call_dyn_impl( // SAFETY: the `&mut Interpreter` that entered native code is // dormant while the helper runs. let interp = unsafe { &mut *ctx.interp }; - let retry_python = if kwc == 0 { + // A builtin value's method whose load left the receiver in the bound + // method's place (see `BoundSite`): the builtin runs on the receiver + // and the arguments as the core loop's leaf lane runs it. A call the + // lane declines (keywords, an argument that needs Python) goes on + // below with the bound method the load would have made. + let mut deferred = None; + if let Some(site) = ctx.bound.armed_call(jf.deopt_pc) { + let (b, kind) = (Rc::as_ptr(&site.builtin), site.kind); + // SAFETY: the record keeps the builtin alive, and nothing changes + // the records before the leaf call below returns (it runs no + // Python and enters no helper). + let b = unsafe { &*b }; + let Some(recv) = ctx.pins.get(callee_pin as usize).map(Pin::to_object) else { + return CallStatus::Reject as i64; + }; + let mut staged = [const { Object::None }; 4]; + staged[0] = recv; + if kwc == 0 && argc < 4 { + for j in 0..argc as usize { + // SAFETY: native code wrote `argc` entries. + let (bits, tag) = unsafe { (*jf.call_args.add(j), *jf.call_tags.add(j)) }; + staged[j + 1] = unpack_pins(bits, tag, &ctx.pins); + } + match interp.leaf_builtin_call(kind, b, &staged[..=(argc as usize)]) { + Some(Ok(v)) => return dyn_leaf_result(jf, ctx, v, int_result), + Some(Err(e)) => { + ctx.raised = Some(e); + return CallStatus::Raised as i64; + } + None => {} + } + } + let [recv, ..] = staged; + let builtin = ctx + .bound + .armed_call(jf.deopt_pc) + .map(|site| site.builtin.clone()); + deferred = builtin.map(|b| { + Object::BoundMethod(Rc::new(crate::object::BoundMethod::new( + recv, + Object::Builtin(b), + ))) + }); + } + // `type(x)`: the argument's class, read off the borrowed pins (no + // callee clone or staged arguments), as `builtin_ctor_arms` answers it. + if deferred.is_none() && kwc == 0 && argc == 1 { + if let Some(Pin::Obj(Object::Type(t))) = ctx.pins.get(callee_pin as usize) { + if Rc::ptr_eq(t, &crate::builtin_types::builtin_types().type_) { + // SAFETY: native code wrote the one entry. + let (bits, tag) = unsafe { (*jf.call_args, *jf.call_tags) }; + let mut tmp = None; + if let Some(x) = staged_ref(bits, tag, &ctx.pins, &mut tmp) { + let v = Object::Type(crate::builtins::class_of(x)); + return dyn_leaf_result(jf, ctx, v, int_result); + } + } + } + } + let retry_python = if deferred.is_some() { + false + } else if kwc == 0 { // SAFETY: the same live buffers; the borrowed path releases every // borrow before this code updates the result or enters Python. match unsafe { try_borrowed_dyn_scalar(jf, ctx, interp, callee_pin, argc) } { @@ -12086,19 +12886,30 @@ unsafe fn call_dyn_impl( }; // The callee rode a pinned lane; `-1` is the nullable `None` // (calling `None` raises) — both misses re-execute generically. - let callee = match ctx.pins.get(callee_pin as usize) { - Some(p) => p.to_object(), - None => return CallStatus::Reject as i64, + let was_deferred = deferred.is_some(); + let callee = match deferred { + Some(bound) => bound, + None => match ctx.pins.get(callee_pin as usize) { + Some(p) => p.to_object(), + None => return CallStatus::Reject as i64, + }, }; // A native method bound to its exact builtin receiver whose call the // core loop's leaf lane runs (`groups[k].append(x)`, `s.strip()`): // run as the lane runs it, with no bound-method call or activation // shell. (Only the kinds whose releases can't finalize anything.) - if kwc == 0 && argc < 4 { - if let Object::BoundMethod(bm) = &callee { - if let Some(status) = dyn_bound_leaf(jf, ctx, interp, bm, argc, int_result) { - return status; + if kwc == 0 && argc < 4 && !was_deferred { + let ran = match &callee { + Object::BoundMethod(bm) => dyn_bound_leaf(jf, ctx, interp, bm, argc), + _ => None, + }; + match ran { + Some(Ok(v)) => return dyn_leaf_result(jf, ctx, v, int_result), + Some(Err(e)) => { + ctx.raised = Some(e); + return CallStatus::Raised as i64; } + None => {} } } // RFC 0076 WS7 — the per-kind fast path: a compiled Python callee @@ -12131,6 +12942,35 @@ unsafe fn call_dyn_impl( return status; } } + // `dict(k=v, ...)`: the keywords' own name objects are the keys. + // (Ahead of the function binders below, which all decline a class.) + if kwc > 0 && argc == 0 { + if let Object::Type(t) = &callee { + if Rc::ptr_eq(t, &crate::builtin_types::builtin_types().dict_) { + // SAFETY: per the function contract, the activation keeps + // its code object alive. + let code = unsafe { &*ctx.code_ptr }; + if let Some(Object::Tuple(name_items)) = + crate::code_const_objects(code).get(names as usize) + { + let mut vals = [const { Object::None }; 8]; + if name_items.len() == kwc as usize && kwc as usize <= vals.len() { + for (j, slot) in vals.iter_mut().enumerate().take(kwc as usize) { + // SAFETY: native code wrote `kwc` entries. + let (bits, tag) = + unsafe { (*jf.call_args.add(j), *jf.call_tags.add(j)) }; + *slot = unpack_pins(bits, tag, &ctx.pins); + } + if let Some(d) = + crate::Interpreter::dict_of_keywords(name_items, &vals[..kwc as usize]) + { + return dyn_leaf_result(jf, ctx, d, int_result); + } + } + } + } + } + } // A keyword call of a warm pure leaf evaluates frameless on its // marshaled values (no Python runs, so nothing needs revalidating). // It isn't counted against the native driver, though the frame JIT @@ -12187,34 +13027,6 @@ unsafe fn call_dyn_impl( // SAFETY: as above. return unsafe { dyn_call_result(jf, ctx, called, false, true, int_result) }; } - // `dict(k=v, ...)`: the keywords' own name objects are the keys. - if kwc > 0 && argc == 0 { - if let Object::Type(t) = &callee { - if Rc::ptr_eq(t, &crate::builtin_types::builtin_types().dict_) { - // SAFETY: per the function contract, the activation keeps - // its code object alive. - let code = unsafe { &*ctx.code_ptr }; - if let Some(Object::Tuple(name_items)) = - crate::code_const_objects(code).get(names as usize) - { - let mut vals = [const { Object::None }; 8]; - if name_items.len() == kwc as usize && kwc as usize <= vals.len() { - for (j, slot) in vals.iter_mut().enumerate().take(kwc as usize) { - // SAFETY: native code wrote `kwc` entries. - let (bits, tag) = - unsafe { (*jf.call_args.add(j), *jf.call_tags.add(j)) }; - *slot = unpack_pins(bits, tag, &ctx.pins); - } - if let Some(d) = - crate::Interpreter::dict_of_keywords(name_items, &vals[..kwc as usize]) - { - return dyn_leaf_result(jf, ctx, d, int_result); - } - } - } - } - } - } let n = (argc + kwc) as usize; let mut args: Vec = Vec::with_capacity(n); for j in 0..n { @@ -12451,15 +13263,14 @@ unsafe fn dyn_kw_pure_leaf( /// [`call_dyn_impl`]'s call of a native method `bm` bound to its exact /// builtin receiver, over the `argc` marshaled arguments, when the core /// loop's leaf lane runs it in place (see `LeafKind::runs_in_core`): the -/// call's status, or `None` (nothing done) for the general call. +/// call's outcome, or `None` (nothing done) for the general call. fn dyn_bound_leaf( - jf: &mut JitFrame, + jf: &JitFrame, ctx: &mut CallCtx, interp: &super::Interpreter, bm: &crate::object::BoundMethod, argc: u32, - int_result: bool, -) -> Option { +) -> Option> { let Object::Builtin(b) = &bm.function else { return None; }; @@ -12469,7 +13280,17 @@ fn dyn_bound_leaf( { return None; } - let kind = interp.leaf_call_kind(b).filter(|k| k.runs_in_core())?; + // The builtin's kind, remembered from the site's last call (the + // remembered builtin is kept alive, so its address is its identity). + let gen = super::leaf_builtins::generation(); + let kind = match &ctx.bound.kind { + Some((last, g, kind)) if Rc::ptr_eq(last, b) && *g == gen => *kind, + _ => { + let kind = interp.leaf_call_kind(b).filter(|k| k.runs_in_core())?; + ctx.bound.kind = Some((b.clone(), gen, kind)); + kind + } + }; let mut staged = [const { Object::None }; 4]; staged[0] = bm.receiver.clone(); for j in 0..argc as usize { @@ -12477,13 +13298,7 @@ fn dyn_bound_leaf( let (bits, tag) = unsafe { (*jf.call_args.add(j), *jf.call_tags.add(j)) }; staged[j + 1] = unpack_pins(bits, tag, &ctx.pins); } - match interp.leaf_builtin_call(kind, b, &staged[..=(argc as usize)])? { - Ok(v) => Some(dyn_leaf_result(jf, ctx, v, int_result)), - Err(e) => { - ctx.raised = Some(e); - Some(CallStatus::Raised as i64) - } - } + interp.leaf_builtin_call(kind, b, &staged[..=(argc as usize)]) } fn dyn_leaf_result(jf: &mut JitFrame, ctx: &mut CallCtx, v: Object, int_result: bool) -> i64 { @@ -12703,6 +13518,32 @@ unsafe extern "C" fn wpjit_dyn_attr_get(frame: *mut JitFrame, pin: i64, name: i6 }; // SAFETY: the activation retains the code object until native return. let code = unsafe { &*ctx.code_ptr }; + // This run of the load decides anew whether its call finds the + // receiver in the bound method's place (see `BoundSite`): at once + // for a receiver of the kind the site saw last. + let site = if ctx.bound.sites.is_empty() { + None + } else { + ctx.bound + .sites + .iter() + .position(|s| s.load_pc == jf.deopt_pc) + }; + if let Some(at) = site { + let s = &mut ctx.bound.sites[at]; + s.armed = crate::builtins::method_memo_tag(receiver) == Some(s.tag) + && s.gen == super::leaf_builtins::generation(); + if s.armed { + jf.ret_bits = pin as u64; + #[cfg(test)] + DYN_ATTR_NATIVE_READS.with(|reads| { + let mut counts = reads.get(); + counts[3] += 1; + reads.set(counts); + }); + return 0; + } + } let (value, kind) = match receiver { Object::Instance(inst) if inst.cls_raw().native_kind.get() == 0 => { // The site's split-layout shortcut first (the interpreter's @@ -12773,10 +13614,46 @@ unsafe extern "C" fn wpjit_dyn_attr_get(frame: *mut JitFrame, pin: i64, name: i6 | Object::Bool(_) | Object::Float(_) | Object::Complex(_) => { + // A method the call can run on the receiver directly: the + // receiver stays where it is (see `BoundSite`). + let tag = crate::builtins::method_memo_tag(receiver); + let gen = super::leaf_builtins::generation(); let Some(name) = code.names.get(name_idx as usize) else { return 3; }; - let method = crate::builtins::lookup_method(receiver, name).map(|method| { + let method = crate::builtins::lookup_method(receiver, name); + if let (Some(tag), Some(Object::Builtin(b))) = (tag, &method) { + // SAFETY: the entering interpreter is dormant, and the + // lookup below neither calls Python nor changes it. + let interp = unsafe { &*ctx.interp }; + let deferred = (site.is_some() || ctx.bound.sites.len() < BOUND_SITES_MAX) + .then(|| defer_method_load(ctx, interp, code, jf.deopt_pc, b)) + .flatten(); + if let Some((call_pc, kind)) = deferred { + let record = BoundSite { + load_pc: jf.deopt_pc, + call_pc, + armed: true, + tag, + gen, + builtin: b.clone(), + kind, + }; + match site { + Some(at) => ctx.bound.sites[at] = record, + None => ctx.bound.sites.push(record), + } + jf.ret_bits = pin as u64; + #[cfg(test)] + DYN_ATTR_NATIVE_READS.with(|reads| { + let mut counts = reads.get(); + counts[3] += 1; + reads.set(counts); + }); + return 0; + } + } + let method = method.map(|method| { if matches!(&method, Object::Builtin(b) if !b.binds_instance) { method } else { @@ -12812,11 +13689,13 @@ unsafe extern "C" fn wpjit_dyn_attr_get(frame: *mut JitFrame, pin: i64, name: i6 ctx.parked = Some(value); return 2; } - // Consume the completed value once. On cap pressure retain that same - // value for the interpreter; None still uses its allocation-free sentinel. + // Consume the completed value once. On cap pressure, or for a value no + // pin may hold (an instance whose release runs a finalizer, which + // `pin_any` refuses whatever the table's size), retain that same value + // for the interpreter; None still uses its allocation-free sentinel. let bits = match value { - value if ctx.pins.len() < RUNTIME_PIN_CAP => { - pin_any(value, &mut ctx.pins).expect("below the cap") + value if ctx.pins.len() < RUNTIME_PIN_CAP && !finalizes_on_release(&value) => { + pin_any(value, &mut ctx.pins).expect("pinnable, below the cap") } value => { ctx.parked = Some(value); @@ -12835,6 +13714,37 @@ unsafe extern "C" fn wpjit_dyn_attr_get(frame: *mut JitFrame, pin: i64, name: i6 0 } +/// Whether the method-form load at `load_pc` of the builtin value's +/// method `b` can leave its receiver for the call (see [`BoundSite`]): +/// the call's pc and the kind of leaf `b` is, when the load is the +/// method form, its call is a dynamic call this activation compiled (the +/// one whose marker span opens at the load), and `b` binds its receiver +/// and runs as a leaf in place. +fn defer_method_load( + ctx: &CallCtx, + interp: &super::Interpreter, + code: &CodeObject, + load_pc: u32, + b: &Rc, +) -> Option<(u32, super::LeafKind)> { + if !b.binds_instance || ctx.cf.is_null() { + return None; + } + let method_form = code + .instructions + .get(load_pc as usize) + .is_some_and(|i| i.op == weavepy_compiler::OpCode::LoadMethodAttr); + if !method_form { + return None; + } + // SAFETY: the activation's compiled frame outlives it (see the field). + let cf = unsafe { &*ctx.cf }; + let span = cf.null_spans.iter().find(|s| s.live_from == load_pc)?; + let call_pc = span.live_to.checked_sub(1)?; + let kind = interp.leaf_call_kind(b).filter(|k| k.runs_in_core())?; + Some((call_pc, kind)) +} + /// The `wpjit_dyn_attr_set` helper (RFC 0074 WS4): the interpreter's /// exact attribute store on a pinned receiver (`__setattr__` dispatch /// included — arbitrary Python; the dirtiness discipline applies). @@ -13162,6 +14072,14 @@ unsafe fn dyn_leaf_getitem(jf: &JitFrame, ctx: &CallCtx) -> Option { let i = if i < 0 { i + n as i64 } else { i }; usize::try_from(i).ok().filter(|&i| i < n) }; + // A plain class's native `__getitem__` with a leaf half (an `array`'s + // item): the half's answer (an error is the full path's to raise + // again). + if let Object::Instance(inst) = container { + if let Some(fast) = super::Interpreter::instance_getitem_leaf(inst) { + return fast(&[container.clone(), key.clone()])?.ok(); + } + } match (container, key) { (Object::List(l), Object::Int(i)) => { // SAFETY: nothing runs code while the items are viewed. @@ -13169,6 +14087,7 @@ unsafe fn dyn_leaf_getitem(jf: &JitFrame, ctx: &CallCtx) -> Option { xs.get(at(*i, xs.len())?).map(super::clone_hot) } (Object::Tuple(t), Object::Int(i)) => t.get(at(*i, t.len())?).map(super::clone_hot), + // A `dict` subclass's instance that keeps `dict.__getitem__` (a // `defaultdict`, a `Counter`) by a present key, as compiled code's // `h_inst_dict_get` reads it (a miss may run `__missing__`). @@ -13179,6 +14098,24 @@ unsafe fn dyn_leaf_getitem(jf: &JitFrame, ctx: &CallCtx) -> Option { // SAFETY: written on success. .then(|| unsafe { out.assume_init() }) } + // Likewise by any other key that compares natively (a tuple). + (Object::Instance(inst), _) => { + let Some(Object::Dict(d)) = inst.native.get() else { + return None; + }; + if !inst + .class_dunder(crate::types::Dunder::GetItem) + .dict_owner() + { + return None; + } + let probe = crate::object::LeafProbe::new(key)?; + // SAFETY: nothing runs code while the table is viewed. + match unsafe { d.peek() }?.get(&probe) { + Some(v) => Some(super::clone_hot(v)), + None => crate::stdlib::collections_native::dd_missing_pure(inst, d, key), + } + } // A key whose Python `__hash__` is a pure leaf, found as itself (a // miss is the full path's to raise). (Object::Dict(d), Object::Instance(_)) if crate::object::LeafProbe::new(key).is_none() => { @@ -13239,6 +14176,71 @@ fn deliver_dyn_result( 2 } +/// `a b` of the two staged operands when it runs no Python code, +/// by the helpers compiled frames use (`frame_jit::h_binop`): two exact +/// lists' or tuples' concatenation, two dicts' union and two sets' +/// algebra over keys that hash and compare natively, two `bytes`' +/// concatenation. `None` leaves the operation to the interpreter. +/// +/// # Safety +/// +/// As [`dyn_operands`]. +unsafe fn dyn_leaf_binop( + jf: &JitFrame, + ctx: &CallCtx, + kind: weavepy_compiler::BinOpKind, +) -> Option { + use weavepy_compiler::BinOpKind as K; + // SAFETY: per the function contract. + let (a_bits, a_tag, b_bits, b_tag) = unsafe { + ( + *jf.call_args, + *jf.call_tags, + *jf.call_args.add(1), + *jf.call_tags.add(1), + ) + }; + // (A pinned list is its real list, whatever element lane the compile + // assumed for it.) + fn operand<'a>( + bits: u64, + tag: u32, + pins: &'a PinTable, + tmp: &'a mut Option, + ) -> Option<&'a Object> { + match SlotTag::from_raw(tag) { + SlotTag::ListPin | SlotTag::ObjPin => match pins.get(bits as usize)? { + Pin::Obj(o) => Some(o), + Pin::List(l, _) => Some(tmp.insert(Object::List(l.clone()))), + }, + _ => staged_ref(bits, tag, pins, tmp), + } + } + let (mut a_tmp, mut b_tmp) = (None, None); + let a = operand(a_bits, a_tag, &ctx.pins, &mut a_tmp)?; + let b = operand(b_bits, b_tag, &ctx.pins, &mut b_tmp)?; + match (a, b) { + (Object::List(_), Object::List(_)) | (Object::Tuple(_), Object::Tuple(_)) + if kind == K::Add => + { + super::Interpreter::core_seq_concat(a, b) + } + (Object::Dict(_), Object::Dict(_)) if kind == K::BitOr => super::dict_union_plain(a, b), + (Object::Set(_) | Object::FrozenSet(_), Object::Set(_) | Object::FrozenSet(_)) + if matches!(kind, K::BitOr | K::BitAnd | K::Sub | K::BitXor) => + { + super::set_algebra_fast(a, b, kind) + } + (Object::Bytes(x), Object::Bytes(y)) if kind == K::Add => { + let mut out = Vec::with_capacity(x.len() + y.len()); + out.extend_from_slice(x); + out.extend_from_slice(y); + Some(Object::new_bytes(out)) + } + _ => None, + } +} + /// The `wpjit_dyn_binop` helper (`weavepy_jit::TOp::DynBinary`): run the /// interpreter's own `BINARY_OP` dispatch for `arg` (the operator and the /// in-place flag) on the two staged operands — the full `__op__` / @@ -13256,12 +14258,30 @@ unsafe extern "C" fn wpjit_dyn_binop(frame: *mut JitFrame, arg: i64, _unused: i6 let ctx = unsafe { &mut *jf.ctx.cast::() }; // SAFETY: the `&mut Interpreter` is dormant while the helper runs. let interp = unsafe { &mut *ctx.interp }; - // SAFETY: native code staged both operands. - let (a, b) = unsafe { dyn_operands(jf, ctx) }; let arg = arg as u32; // SAFETY: `BinOpKind` is `repr(u8)` and the compiler only emits valid // kinds (the interpreter's `binary_op_step` decodes it the same way). let kind: weavepy_compiler::BinOpKind = unsafe { std::mem::transmute(arg as u8) }; + // A result no Python code computes, built off the borrowed operands + // (as `wpjit_dyn_getitem` reads one): no guard can have changed, so + // none is rechecked. + if arg & weavepy_compiler::BINARY_OP_INPLACE_FLAG == 0 { + // SAFETY: native code staged both operands. + if let Some(v) = unsafe { dyn_leaf_binop(jf, ctx, kind) } { + if !ctx.temporary_pin_limit_reached() { + if let Some(bits) = pin_any(v.clone(), &mut ctx.pins) { + jf.ret_bits = bits; + return 0; + } + } else { + ctx.pin_pressure_exit = true; + } + ctx.parked = Some(v); + return 2; + } + } + // SAFETY: native code staged both operands. + let (a, b) = unsafe { dyn_operands(jf, ctx) }; let globals = ctx.globals.clone(); ctx.dirty = true; let r = if arg & weavepy_compiler::BINARY_OP_INPLACE_FLAG != 0 { @@ -13343,6 +14363,31 @@ unsafe extern "C" fn wpjit_dyn_setitem(frame: *mut JitFrame, _arg: i64, _unused: unpack_pins(*jf.call_args.add(k), *jf.call_tags.add(k), &ctx.pins) }); ctx.dirty = true; + // A built-in base's own `__setitem__` with a leaf half (an + // `OrderedDict`'s): the half stores it, running no code, so no guard can + // have broken. + if let Object::Instance(inst) = &container { + if let Some(fast) = super::Interpreter::instance_setitem_leaf(inst) { + let args = [container, index, value]; + match fast(&args) { + Some(Ok(_)) => { + if finalizer_queued() { + ctx.parked = None; + return 2; + } + return 0; + } + Some(Err(err)) => { + ctx.raised = Some(err); + return 1; + } + None => { + let [c, i, v] = args; + return dyn_setitem_full(interp, ctx, &c, &i, v); + } + } + } + } // A `dict` subclass's instance that keeps `dict.__setitem__`, by a key // that compares natively: stored as compiled code's `h_inst_dict_set` // stores it (the store runs no code, so no guard can have broken). @@ -13360,7 +14405,70 @@ unsafe extern "C" fn wpjit_dyn_setitem(frame: *mut JitFrame, _arg: i64, _unused: return 0; } } - match interp.subscr_set_public(&container, &index, value) { + // An exact dict by a key that hashes and compares natively: stored as + // the core loop's `STORE_SUBSCR` arm stores it (no code runs, so no + // guard can have broken; a displaced value's release may queue a + // finalizer). Likewise the payload of a `dict` subclass's instance + // that keeps `dict.__setitem__`, by a key the lane above left (a + // tuple). + let payload = match &container { + Object::Dict(cell) => Some(cell), + Object::Instance(inst) => match inst.native.get() { + Some(Object::Dict(cell)) + if inst + .class_dunder(crate::types::Dunder::SetItem) + .dict_owner() => + { + Some(cell) + } + _ => None, + }, + _ => None, + }; + if let Some(cell) = payload { + if !crate::capi_watchers::dicts_active() { + if let Some(probe) = crate::object::LeafProbe::new(&index) { + if let Ok(mut d) = cell.try_borrow_mut() { + let stored = match d.probe_entry(&probe) { + crate::dictmap::ProbeEntry::Occupied(e) => { + let slot = e.into_mut(); + let old = std::mem::replace(slot, value.clone()); + Some((!old.is_same(slot), old)) + } + crate::dictmap::ProbeEntry::Vacant(e) if probe.miss_is_exact() => { + e.insert(DictKey(index.clone()), value.clone()); + Some((true, Object::None)) + } + crate::dictmap::ProbeEntry::Vacant(_) => None, + }; + drop(d); + if let Some((changed, old)) = stored { + if changed { + crate::object::dict_mutation_event(cell); + } + drop(old); + if finalizer_queued() { + ctx.parked = None; + return 2; + } + return 0; + } + } + } + } + } + dyn_setitem_full(interp, ctx, &container, &index, value) +} + +/// [`wpjit_dyn_setitem`]'s general store. +fn dyn_setitem_full( + interp: &mut super::Interpreter, + ctx: &mut CallCtx, + container: &Object, + index: &Object, + value: Object, +) -> i64 { + match interp.subscr_set_public(container, index, value) { Err(err) => { ctx.raised = Some(err); 1 @@ -13430,14 +14538,33 @@ unsafe extern "C" fn wpjit_dyn_compare(frame: *mut JitFrame, arg: i64, _unused: let ctx = unsafe { &mut *jf.ctx.cast::() }; // SAFETY: the `&mut Interpreter` is dormant while the helper runs. let interp = unsafe { &mut *ctx.interp }; - // SAFETY: native code staged both operands. - let (a, b) = unsafe { dyn_operands(jf, ctx) }; let arg = arg as u32; let to_bool = arg & weavepy_compiler::COMPARE_OP_TO_BOOL_FLAG != 0; // SAFETY: `CompareKind` is `repr(u8)`; decoded as `compare_op_step` // decodes it. let kind: weavepy_compiler::CompareKind = unsafe { std::mem::transmute((arg & !weavepy_compiler::COMPARE_OP_TO_BOOL_FLAG) as u8) }; + // An answer no Python code computes (see `plain_compare`: numbers, + // strings, tuples of them), or a plain instance's comparison method + // that is a warm pure leaf, off the borrowed operands, as + // `wpjit_dyn_binop`'s leaf results: no guard can have changed, so + // none is rechecked. + // SAFETY: native code staged both operands. + if let Some(t) = unsafe { dyn_leaf_compare(jf, ctx, interp, kind) } { + if to_bool { + jf.ret_bits = u64::from(t); + return 0; + } + // (Pin pressure, and a full table, are the general path's.) + if !ctx.temporary_pin_limit_reached() { + if let Some(bits) = pin_any(Object::Bool(t), &mut ctx.pins) { + jf.ret_bits = bits; + return 0; + } + } + } + // SAFETY: native code staged both operands. + let (a, b) = unsafe { dyn_operands(jf, ctx) }; let globals = ctx.globals.clone(); ctx.dirty = true; let r = interp.rich_compare_obj(&a, &b, kind, &globals); @@ -13476,6 +14603,57 @@ unsafe extern "C" fn wpjit_dyn_compare(frame: *mut JitFrame, arg: i64, _unused: } } +/// `a b` of the two staged operands when no Python code answers it +/// (see [`crate::plain_compare`]). `None` leaves it to the interpreter. +/// +/// # Safety +/// +/// As [`dyn_operands`]. +unsafe fn dyn_leaf_compare( + jf: &JitFrame, + ctx: &CallCtx, + interp: &mut crate::Interpreter, + kind: weavepy_compiler::CompareKind, +) -> Option { + // SAFETY: per the function contract. + let (a_bits, a_tag, b_bits, b_tag) = unsafe { + ( + *jf.call_args, + *jf.call_tags, + *jf.call_args.add(1), + *jf.call_tags.add(1), + ) + }; + let (mut ta, mut tb) = (None, None); + let a = staged_ref(a_bits, a_tag, &ctx.pins, &mut ta)?; + let b = staged_ref(b_bits, b_tag, &ctx.pins, &mut tb)?; + // A plain instance's own method (see + // `Interpreter::compare_instance_dunder`), a warm pure leaf, evaluated + // on the operands where they are, as the frame JIT's `compare_leaf` + // evaluates it: only a `bool` answer is taken (anything else, + // `NotImplemented` among them, is the full protocol's, which may run + // the method again: a pure leaf has no effects). + if let Object::Instance(_) = a { + if let Some(f) = crate::Interpreter::compare_instance_dunder(a, b, kind) { + // SAFETY: GIL-serialized raw read of the function's code cell. + let code = unsafe { &*f.code.as_ptr() }; + if code.arg_count != 2 + || !crate::code_is_pure_leaf(code) + || !crate::pure_leaf_warm(code) + || crate::recursion::current_depth() >= crate::recursion::recursion_limit() + { + return None; + } + let ptrs: [*const Object; 2] = [a, b]; + return match interp.pure_leaf_eval::(code, &f, &ptrs)? { + Object::Bool(r) => Some(r), + _ => None, + }; + } + } + crate::plain_compare(a, b, kind) +} + /// The `wpjit_build_set` helper (RFC 0076 WS8): build a fresh set from /// `n` per-element-tagged entries staged in the marshal buffer, pin /// it, and answer the pin index — negative deopts (cap pressure, or @@ -13549,6 +14727,28 @@ unsafe extern "C" fn wpjit_iter_new(frame: *mut JitFrame, pin: i64) -> i64 { if ctx.pins.len() >= RUNTIME_PIN_CAP { return -1; } + // A list's or tuple's cursor (an opaque loop's commonest iterable) + // directly, without the general dispatch. + let direct = match ctx.pins.get(pin as usize) { + Some(Pin::Obj(Object::List(l)) | Pin::List(l, _)) => Some(PyIterator::List { + items: l.clone(), + index: 0, + owner: None, + }), + Some(Pin::Obj(Object::Tuple(t))) => Some(PyIterator::Tuple { + items: t.clone(), + index: 0, + }), + _ => None, + }; + if let Some(it) = direct { + let idx = ctx.pins.len() as i64; + ctx.pins + .push(Pin::Obj(Object::Iter(Rc::new(crate::sync::RefCell::new( + it, + ))))); + return idx; + } let recv = match ctx.pins.get(pin as usize) { Some(Pin::Obj(o)) => o.clone(), Some(Pin::List(l, _)) => Object::List(l.clone()), @@ -13592,12 +14792,7 @@ unsafe extern "C" fn wpjit_iter_new(frame: *mut JitFrame, pin: i64) -> i64 { /// Pack one yielded element into a compiled loop-variable lane /// (RFC 0074 WS3 — the [`weavepy_jit::ITER_ELEM_STR`]-aware sibling /// of `wpjit_iter_next`'s packing). `None` = outside the lane. -fn pack_iter_elem( - v: &Object, - tag: i64, - pins: &mut PinTable, - memo: &mut [u32; PIN_MEMO], -) -> Option { +fn pack_iter_elem(v: &Object, tag: i64, pins: &mut PinTable, memo: &mut PinMemo) -> Option { if tag == weavepy_jit::ITER_ELEM_STR { return match v { Object::Str(_) if pins.len() < RUNTIME_PIN_CAP => { @@ -13641,6 +14836,48 @@ enum NativeBytePair { Value(i64, u8), } +/// `enumerate` over a list or tuple iterator whose next item packs into the +/// scalar lane `lane` (`for i, x in enumerate(xs)` over a list of ints): the +/// count and the item's bits, both cursors advanced. `None` consumes +/// nothing: any other shape, an item outside the lane, the source's end +/// (the general step reports it), or a counter that would overflow. +#[inline] +fn next_enumerated_scalar(it: &Object, lane: JitType) -> Option<(i64, u64)> { + let Object::Iter(it) = it else { + return None; + }; + // SAFETY: the views end before anything that could borrow either cell + // runs (reading an item and packing its bits run no code). + let state = unsafe { it.peek_mut()? }; + let PyIterator::Enumerate { + inner, + count, + count_big: None, + } = state + else { + return None; + }; + let next_count = count.checked_add(1)?; + // SAFETY: as above (the source is a cell of its own). + let bits = match unsafe { inner.peek_mut()? } { + PyIterator::Tuple { items, index } => { + let bits = pack(items.get(*index)?, lane)?; + *index += 1; + bits + } + PyIterator::List { items, index, .. } => { + // SAFETY: as above. + let bits = pack(unsafe { items.peek()? }.get(*index)?, lane)?; + *index += 1; + bits + } + _ => return None, + }; + let current = *count; + *count = next_count; + Some((current, bits)) +} + /// Read exact native byte enumeration without constructing a Python tuple. /// Keep both shared cursors current so an interpreter continuation sees the /// same state. Unsupported shapes and counter overflow consume nothing. @@ -13792,8 +15029,8 @@ unsafe extern "C" fn wpjit_iter_next_pair( let ctx = unsafe { &mut *jf.ctx.cast::() }; // SAFETY: the `&mut Interpreter` is dormant while the helper runs. let interp = unsafe { &mut *ctx.interp }; - // `enumerate` over bytes or tuples into typed lanes first: one peek - // tells any other iterator apart, where the list, tuple and + // `enumerate` over bytes into two int lanes first (a byte loop's + // every step): one peek tells any other iterator apart, where the list, tuple and // `dict.items()` steps below would each borrow and inspect it (an // `enumerate(bytes)` step cost a third more behind them). if tag1 == SlotTag::Int as i64 && tag2 == SlotTag::Int as i64 { @@ -13812,7 +15049,66 @@ unsafe extern "C" fn wpjit_iter_next_pair( NativeBytePair::Exhausted => return 1, NativeBytePair::Unsupported => {} } - } else if tag1 == SlotTag::Int as i64 && tag2 == SlotTag::ObjPin as i64 { + } + // A list's or tuple's next element that is a pair whose halves pack + // into the two lanes (`for a, b in pairs`): read where it sits, the + // cursor advanced once both packed. (The views are guard-free: nothing + // below runs code, and packing touches only the pin table.) + let at: Option<(*const Object, *mut usize)> = match ctx.pins.get(pin as usize) { + // SAFETY: as above. + Some(Pin::Obj(Object::Iter(cell))) => match unsafe { cell.peek_mut() } { + Some(PyIterator::List { + items, + index, + owner: None, + }) => unsafe { items.peek() } + .and_then(|xs| xs.get(*index)) + .map(|v| (std::ptr::from_ref(v), std::ptr::from_mut(index))), + Some(PyIterator::Tuple { items, index }) => items + .get(*index) + .map(|v| (std::ptr::from_ref(v), std::ptr::from_mut(index))), + _ => None, + }, + _ => None, + }; + if let Some((v, index)) = at { + // SAFETY: the element and the cursor live in the source's and the + // iterator's own allocations, which the pinned iterator keeps, and + // packing pushes only onto the pin table. + if let Object::Tuple(t) = unsafe { &*v } { + if let [a, b] = &t[..] { + let packed1 = pack_iter_elem(a, tag1, &mut ctx.pins, &mut ctx.pin_memo); + let packed2 = + packed1.and_then(|_| pack_iter_elem(b, tag2, &mut ctx.pins, &mut ctx.pin_memo)); + if let (Some(b1), Some(b2)) = (packed1, packed2) { + // SAFETY: as above. + unsafe { *index += 1 }; + jf.ret_bits = b1; + // SAFETY: the marshal buffer is at least one slot wide. + unsafe { *jf.call_args = b2 }; + return 0; + } + } + } + } + // `enumerate` over a list or tuple into an int lane and a scalar one. + if tag1 == SlotTag::Int as i64 { + let lane = match u32::try_from(tag2).ok().map(SlotTag::from_raw) { + Some(SlotTag::Int) => Some(JitType::Int), + Some(SlotTag::Float) => Some(JitType::Float), + Some(SlotTag::Bool) => Some(JitType::Bool), + _ => None, + }; + if let (Some(lane), Some(Pin::Obj(it))) = (lane, ctx.pins.get(pin as usize)) { + if let Some((index, bits)) = next_enumerated_scalar(it, lane) { + jf.ret_bits = index as u64; + // SAFETY: the marshal buffer has at least one slot. + unsafe { *jf.call_args = bits }; + return 0; + } + } + } + if tag1 == SlotTag::Int as i64 && tag2 == SlotTag::ObjPin as i64 { let pair = match ctx.pins.get(pin as usize) { Some(Pin::Obj(it)) => next_enumerated_tuple(it, ctx.pins.len() < RUNTIME_PIN_CAP), _ => NativeObjectPair::Unsupported, @@ -14058,6 +15354,16 @@ unsafe extern "C" fn wpjit_str_mod( _ => return 3, }; let rhs = unpack_pins(rhs_bits as u64, rhs_tag as u32, &ctx.pins); + // `"%s" % SomeStrEnum.A`: payloads, formatted without running Python. + if let Object::Str(t) = &lhs { + if let Some(out) = crate::percent_format_payloads_checked(t, &rhs) { + if ctx.pins.len() < RUNTIME_PIN_CAP { + jf.ret_bits = ctx.pins.len() as u64; + ctx.pins.push(Pin::Obj(Object::from_str(out))); + return 0; + } + } + } // Scalar and exact-`str`/tuple-of-scalar operands format without // running Python; anything else may dispatch `__str__`/`__repr__`. let may_run_python = !matches!( @@ -14152,7 +15458,6 @@ pub(crate) fn try_call_native_bound( ) -> Option> { if code.has_varargs || code.has_varkeywords - || code.kwonly_count != 0 || !f.closure.is_empty() || code.is_generator || code.is_coroutine @@ -14160,7 +15465,9 @@ pub(crate) fn try_call_native_bound( { return None; } - let args = bound.get(..code.arg_count as usize)?; + // (Every parameter is bound: the keyword-only ones follow the + // positional ones.) + let args = bound.get(..code.arg_count as usize + code.kwonly_count as usize)?; try_call_native_direct(interp, f, code, args) } @@ -14200,7 +15507,10 @@ pub(crate) fn try_call_native_direct( if crate::hot_gates::load() != 0 || crate::trace::any_observers_active() { return None; } - if args.len() != code.arg_count as usize { + // (The positional parameters, or every parameter: the keyword-only + // ones too, from a caller that bound them.) + let argc = code.arg_count as usize; + if args.len() != argc && args.len() != argc + code.kwonly_count as usize { return None; } let key = Rc::as_ptr(code).cast::(); @@ -14215,6 +15525,9 @@ pub(crate) fn try_call_native_direct( if !cf.interp_entry { return None; } + // The slots the body takes from its caller (a keyword-only parameter + // it reads at entry must come bound). + let args = args.get(..entry.nparams)?; let method_shape = entry.method_shape; if method_shape && !matches!(args[0], Object::Instance(_)) { return None; @@ -14331,9 +15644,10 @@ pub(crate) fn try_call_native_direct( // keep the activation observable to callee-side stack walkers. frameless_code: Some(code.clone()), dyn_callee: None, - pin_memo: [u32::MAX; PIN_MEMO], + pin_memo: PinMemo::EMPTY, introspected: Cell::new(false), inspected_locals: std::cell::RefCell::new(None), + bound: BoundLane::new(), inspected_frame: std::cell::RefCell::new(None), cell_list_pins: Vec::new(), }; @@ -14444,6 +15758,13 @@ pub(crate) fn try_enter(interp: &mut super::Interpreter, frame: &mut super::Fram if frame.code.is_generator { return JitEntry::Skip; } + // Code whose loops run a few iterations a call: the frame JIT's body, + // which the core loop warms and enters next, as compiled callers call + // it (see `crate::SHORT_LOOP_ITERS`), costs a fraction of the framed + // entry here. + if crate::short_loops(&frame.code) && !keeps_short_loops() { + return JitEntry::Skip; + } // Phase 1: counter + compilation, holding the state borrow briefly. let entry = JIT.with(|cell| { let mut st = cell.borrow_mut(); @@ -14472,6 +15793,7 @@ pub(crate) fn try_enter(interp: &mut super::Interpreter, frame: &mut super::Fram |cls: &str, attr: &str| probe_ctor_field(interp_ref, frame_ref, cls, attr); let mut probe_cell = |idx: u32| probe_cell_lane(frame_ref, idx); let mut probe_obj = |slot: u32| probe_obj_live(frame_ref, slot); + let mut probe_py = |slot: u32| probe_py_callee(frame_ref, slot); let mut probe_iter = |depth: u32| probe_stack_iter_lane(frame_ref, depth); let mut probe_pairs = |slot: u32| probe_pair_lanes(frame_ref, slot); st.get_compiled( @@ -14491,6 +15813,7 @@ pub(crate) fn try_enter(interp: &mut super::Interpreter, frame: &mut super::Fram ctor_field: &mut probe_ctor_fld, cell: &mut probe_cell, obj_live: &mut probe_obj, + py_callee: &mut probe_py, stack_iter: &mut probe_iter, pairs: &mut probe_pairs, }, @@ -14575,6 +15898,15 @@ fn note_entry_guard_failure(code: &Rc) { return; }; ce.guard_failures = ce.guard_failures.saturating_add(1); + if matches!(ce.tier, Tier::Compiled(_)) && chronically_missed(ce) { + ce.tier = Tier::NotJitable; + code.jit_hint.mark_not_jitable(); + code.jit_hint.unmark_compiled(); + if crate::hot_gates::env_flags::jit_trace() { + eprintln!("jit miss retire {:?}", code.qualname); + } + return; + } if !ce.no_interp_entry && ce.guard_failures >= GUARD_FAILURE_BUDGET && ce.guard_failures / ce.native_entries.max(1) >= GUARD_FAILURES_PER_ENTRY @@ -14728,6 +16060,7 @@ pub(crate) fn try_enter_osr(interp: &mut super::Interpreter, frame: &mut super:: |cls: &str, attr: &str| probe_ctor_field(interp_ref, frame_ref, cls, attr); let mut probe_cell = |idx: u32| probe_cell_lane(frame_ref, idx); let mut probe_obj = |slot: u32| probe_obj_live(frame_ref, slot); + let mut probe_py = |slot: u32| probe_py_callee(frame_ref, slot); let mut probe_iter = |depth: u32| probe_stack_iter_lane(frame_ref, depth); let mut probe_pairs = |slot: u32| probe_pair_lanes(frame_ref, slot); st.get_compiled( @@ -14747,6 +16080,7 @@ pub(crate) fn try_enter_osr(interp: &mut super::Interpreter, frame: &mut super:: ctor_field: &mut probe_ctor_fld, cell: &mut probe_cell, obj_live: &mut probe_obj, + py_callee: &mut probe_py, stack_iter: &mut probe_iter, pairs: &mut probe_pairs, }, @@ -14881,10 +16215,13 @@ const OSR_VERDICT_ENTRIES: u32 = 16; /// The fewest loop iterations an OSR entry's runs must average: an entry /// and its exit (the frame rebuilt for the interpreter) cost several -/// interpreted iterations, though a float kernel's iteration gains enough -/// natively for a short loop to pay (`scimark`'s `lu` runs 16 a pass in -/// its last rows). -const OSR_MIN_TRIPS: u64 = 8; +/// interpreted iterations, and a loop given up goes to the frame JIT, +/// which runs it and the loops around it with no hand-off at all +/// (`difflib`'s `find_longest_match` entered its inner loop about nine +/// times a pass, its outer loop interpreted: `ratio()` ran 2.4 times +/// slower). A float kernel's iteration gains enough natively for a short +/// loop to pay (`scimark`'s `lu` runs 16 a pass in its last rows). +const OSR_MIN_TRIPS: u64 = 16; /// [`OSR_MIN_TRIPS`] for compiled code of `stmts` statements. Small code /// gains little an iteration over the frame JIT's loop, while the @@ -15137,6 +16474,7 @@ pub(crate) fn try_enter_resume( |cls: &str, attr: &str| probe_ctor_field(interp_ref, frame_ref, cls, attr); let mut probe_cell = |idx: u32| probe_cell_lane(frame_ref, idx); let mut probe_obj = |slot: u32| probe_obj_live(frame_ref, slot); + let mut probe_py = |slot: u32| probe_py_callee(frame_ref, slot); let mut probe_iter = |depth: u32| probe_stack_iter_lane(frame_ref, depth); let mut probe_pairs = |slot: u32| probe_pair_lanes(frame_ref, slot); st.get_compiled( @@ -15156,6 +16494,7 @@ pub(crate) fn try_enter_resume( ctor_field: &mut probe_ctor_fld, cell: &mut probe_cell, obj_live: &mut probe_obj, + py_callee: &mut probe_py, stack_iter: &mut probe_iter, pairs: &mut probe_pairs, }, @@ -15383,9 +16722,10 @@ fn enter_compiled( // spine already. frameless_code: None, dyn_callee: None, - pin_memo: [u32::MAX; PIN_MEMO], + pin_memo: PinMemo::EMPTY, introspected: Cell::new(false), inspected_locals: std::cell::RefCell::new(None), + bound: BoundLane::new(), inspected_frame: std::cell::RefCell::new(None), cell_list_pins: Vec::new(), }; @@ -15579,7 +16919,7 @@ fn note_native_exit( let key = Rc::as_ptr(&frame.code).cast::(); if let Some(ce) = st.cache.get_mut(&key) { ce.deopts += 1; - if ce.deopts >= DEOPT_BUDGET { + if ce.deopts >= DEOPT_BUDGET || chronically_missed(ce) { ce.tier = Tier::NotJitable; frame.code.jit_hint.mark_not_jitable(); } @@ -15588,6 +16928,20 @@ fn note_native_exit( }); } +/// Compiled code that mostly misses: its side exits and failed entry +/// guards reach [`MISS_RETIRE_EVENTS`] and outnumber the native runs that +/// finished two to one. Its activations run in the interpreter, which the +/// frame JIT would otherwise take over (it leaves code tier 2 holds +/// compiled alone), so it retires well before the absolute budgets. +fn chronically_missed(ce: &CacheEntry) -> bool { + let misses = ce.deopts.saturating_add(ce.guard_failures); + let finished = ce.native_entries.saturating_sub(ce.deopts); + misses >= MISS_RETIRE_EVENTS && misses >= finished.saturating_mul(2) +} + +/// See [`chronically_missed`]. +const MISS_RETIRE_EVENTS: u32 = 16; + /// Charge one side exit of `frame`'s compiled code against its /// [`DEOPT_BUDGET`], retiring the code once spent. fn charge_deopt(frame: &super::Frame) { @@ -15596,7 +16950,7 @@ fn charge_deopt(frame: &super::Frame) { let key = Rc::as_ptr(&frame.code).cast::(); if let Some(ce) = st.cache.get_mut(&key) { ce.deopts += 1; - if ce.deopts >= DEOPT_BUDGET { + if ce.deopts >= DEOPT_BUDGET || chronically_missed(ce) { ce.tier = Tier::NotJitable; frame.code.jit_hint.mark_not_jitable(); } @@ -15641,7 +16995,7 @@ fn native_exit_writeback( // after the call. let parked = if raised { None } else { ctx.parked.take() }; rebuild_stack( - interp, frame, entry, locals_buf, spill, tags, jf, &ctx.pins, parked, + interp, frame, entry, locals_buf, spill, tags, jf, &ctx.pins, &ctx.bound, parked, ); if raised { // As though the CALL instruction just executed and @@ -15676,6 +17030,7 @@ fn rebuild_stack( tags: &[u32], jf: &JitFrame, pins: &PinTable, + lane: &BoundLane, parked: Option, ) { let cf = &entry.cf; @@ -15789,6 +17144,21 @@ fn rebuild_stack( { inserts.push((s.interp_depth, Object::Unbound)); } + // A builtin value's method load that left its receiver for the call + // (see `BoundSite`), open here: the interpreter holds the bound + // method one below the span's marker. + let deferred: Vec<(usize, &BoundSite)> = if lane.sites.is_empty() { + Vec::new() + } else { + cf.null_spans + .iter() + .filter(|s| s.live_from < jf.deopt_pc && jf.deopt_pc < s.live_to) + .filter_map(|s| { + let site = lane.armed_load(s.live_from)?; + Some(((s.interp_depth as usize).checked_sub(1)?, site)) + }) + .collect() + }; inserts.sort_unstable_by_key(|(depth, _)| *depth); // Open method spans: the spilled entry at `native_index` must // rebuild as the bound method, not the bare pin — via a fresh @@ -15858,6 +17228,15 @@ fn rebuild_stack( // fallback. v = interp.load_attr_public(&v, name).unwrap_or(Object::None); } + if let Some((_, site)) = deferred + .iter() + .find(|(depth, _)| *depth == frame.stack.len()) + { + v = Object::BoundMethod(Rc::new(crate::object::BoundMethod::new( + v, + Object::Builtin(site.builtin.clone()), + ))); + } frame.stack.push(v); if rebound.is_some() { // RFC 0068 — LOAD_ATTR in method form leaves the @@ -16307,9 +17686,10 @@ fn resume_parked(interp: &mut super::Interpreter, frame: &mut super::Frame) -> J // is on the spine already. frameless_code: None, dyn_callee: None, - pin_memo: [u32::MAX; PIN_MEMO], + pin_memo: PinMemo::EMPTY, introspected: Cell::new(false), inspected_locals: std::cell::RefCell::new(None), + bound: BoundLane::new(), inspected_frame: std::cell::RefCell::new(None), cell_list_pins: Vec::new(), }; @@ -16452,6 +17832,88 @@ pub(crate) fn stats_for_test() -> (u64, u64, u64) { /// Whether this thread's tier-2 state holds compiled code for `code` (an /// entry that may run its loops), or can't say right now. +/// Whether tier 2's analysis already missed its probes for `code`'s +/// call entry (pc 0), which it never attempts again (see +/// `CacheEntry::probe_misses`), and none of the code's loops has run a +/// back edge: a call can't reach tier 2 any more, and no loop asks it to +/// enter by OSR. +pub(crate) fn missed_call_entry(code: &CodeObject) -> bool { + if code.jit_hint.backedges_seen() { + return false; + } + JIT.with(|cell| { + cell.try_borrow().is_ok_and(|st| { + st.cache + .get(&std::ptr::from_ref(code)) + .is_some_and(|entry| { + matches!(entry.tier, Tier::Cold) && entry.probe_misses.contains(&0) + }) + }) + }) +} + +/// Compile attempts that fail before the frame JIT takes code whose loops +/// tier 2 keeps trying (see [`gave_up_often`]). +const FAILED_COMPILES_HANDOVER: u8 = 3; + +/// Whether tier 2 has failed to compile `code` [`FAILED_COMPILES_HANDOVER`] +/// times and holds nothing compiled for it: code it keeps trying from new +/// entries (`argparse`'s `_parse_known_args`, whose every attempt meets an +/// unsupported shape), which the frame JIT would otherwise leave to it, +/// interpreted, for good. +pub(crate) fn gave_up_often(code: &CodeObject) -> bool { + JIT.with(|cell| { + cell.try_borrow().is_ok_and(|st| { + st.cache + .get(&std::ptr::from_ref(code)) + .is_some_and(|entry| { + entry.failed_compiles >= FAILED_COMPILES_HANDOVER + && !matches!(entry.tier, Tier::Compiled(_)) + }) + }) + }) +} + +/// Whether tier 2 has carved the loop headed at `head` out of its plan +/// for an opcode it never compiles (see +/// [`weavepy_jit::Carved::excludes_for_code`]), or compiled the code with +/// that loop left interpreted for the same reason: it will never run that +/// loop natively. +pub(crate) fn carved_loop_for_code(code: &CodeObject, head: usize) -> bool { + JIT.with(|cell| { + cell.try_borrow().is_ok_and(|st| { + st.cache + .get(&std::ptr::from_ref(code)) + .is_some_and(|entry| match &entry.tier { + Tier::Cold => entry.carved.excludes_for_code(head), + Tier::Compiled(a) => { + u32::try_from(head).is_ok_and(|h| { + a.cf.stayed_heads.contains(&h) && !a.cf.env_heads.contains(&h) + }) && a.carved_for_code.contains(&head) + } + Tier::NotJitable => false, + }) + }) + }) +} + +/// Whether `code` is a large body tier 2 hasn't analyzed and won't until +/// its work reaches [`size_budget`]. +pub(crate) fn waits_for_size(code: &CodeObject) -> bool { + if code.instructions.len() <= LARGE_BODY { + return false; + } + JIT.with(|cell| { + cell.try_borrow().is_ok_and(|st| { + st.cache.get(&std::ptr::from_ref(code)).is_none_or(|entry| { + matches!(entry.tier, Tier::Cold) + && entry.analysis_spent == 0 + && entry.counter < size_budget(code) + }) + }) + }) +} + pub(crate) fn holds_compiled(code: &CodeObject) -> bool { JIT.with(|cell| { cell.try_borrow().map_or(true, |st| { diff --git a/crates/weavepy-vm/src/timsort.rs b/crates/weavepy-vm/src/timsort.rs index 3759ffca7..f1d031222 100644 --- a/crates/weavepy-vm/src/timsort.rs +++ b/crates/weavepy-vm/src/timsort.rs @@ -54,6 +54,19 @@ where pending: Vec::new(), }; let minrun = compute_minrun(n); + // A list shorter than a minimum run is one run, binary-sorted from its + // ascending (or reversed descending) prefix, as CPython's `list.sort` + // sorts it: no run stack, so no allocation. + if minrun == n { + // SAFETY: as below, `0..n` lies in `v`. + unsafe { + let run = ms.count_run(0, n)?; + if run < n { + ms.binarysort(0, n, run)?; + } + } + return Ok(()); + } let mut lo = 0; let mut nremaining = n; // SAFETY: every index handed to the helpers below lies in `v`, which is diff --git a/crates/weavepy-vm/src/trace.rs b/crates/weavepy-vm/src/trace.rs index d901f7baf..abd60f92c 100644 --- a/crates/weavepy-vm/src/trace.rs +++ b/crates/weavepy-vm/src/trace.rs @@ -123,8 +123,8 @@ impl Default for ObserverSnapshot { } thread_local! { - static TRACE_HOOK: RefCell> = const { RefCell::new(None) }; - static PROFILE_HOOK: RefCell> = const { RefCell::new(None) }; + static TRACE_HOOK: crate::gil::ReleaseUnderGil>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; + static PROFILE_HOOK: crate::gil::ReleaseUnderGil>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(None)) }; static MONITORING_TOOLS: RefCell = RefCell::new(MonitoringTools::new()); /// Re-entrance guard. Set while inside any hook callout so a /// hook calling Python code (which itself triggers more events) diff --git a/crates/weavepy-vm/src/tuple_storage.rs b/crates/weavepy-vm/src/tuple_storage.rs index 0bc379154..81ba1cf2d 100644 --- a/crates/weavepy-vm/src/tuple_storage.rs +++ b/crates/weavepy-vm/src/tuple_storage.rs @@ -31,8 +31,16 @@ impl TupleStorage { } /// Move a dynamically sized sequence into one reference-counted block. - pub fn from_vec(items: Vec) -> SharedTuple { - Self::from_exact_iter(items.into_iter()) + pub fn from_vec(mut items: Vec) -> SharedTuple { + let len = items.len(); + // SAFETY: the elements are moved whole into the tuple's slots and + // the vector forgets them at once (it keeps only its buffer). + unsafe { + Self::filled(len, |destination| { + std::ptr::copy_nonoverlapping(items.as_ptr(), destination, len); + items.set_len(0); + }) + } } /// [`Self::from_vec`] straight from an iterator that knows its @@ -44,13 +52,107 @@ impl TupleStorage { where I: ExactSizeIterator, { + let len = items.len(); + // SAFETY: the iterator yields exactly `len` elements, each moved + // into its slot. + unsafe { + Self::filled(len, |destination| { + for (index, item) in items.enumerate() { + destination.add(index).write(item); + } + }) + } + } + + /// A tuple of clones of the objects `items` yields, which must be + /// exactly its length (see `object::clone_refs_into`). + pub fn from_cloned_refs<'a, I>(items: I) -> SharedTuple + where + I: ExactSizeIterator, + { + let len = items.len(); + // SAFETY: the iterator yields exactly `len` objects, each cloned + // into its slot. + unsafe { + Self::filled(len, |destination| { + crate::object::clone_refs_into(items, destination); + }) + } + } + + /// A tuple of the `len` objects at `src`, moved in whole (a `*args` + /// run out of a call's operands). + /// + /// # Safety + /// + /// `src` holds `len` initialized objects whose ownership passes to the + /// tuple: the caller forgets them. + pub unsafe fn from_moved_raw(src: *const Object, len: usize) -> SharedTuple { + // SAFETY: per the caller, the `len` objects move bitwise into the + // tuple's slots (which neither runs code nor unwinds). + unsafe { + Self::filled(len, |destination| { + std::ptr::copy_nonoverlapping(src, destination, len); + }) + } + } + + /// A tuple of clones of `items`: the elements copied whole in one + /// pass, then their counts taken in a second (an element moved + /// through an iterator goes by way of the stack in two unaligned + /// halves, which costs about twenty instructions each). + pub fn from_cloned_slice(items: &[Object]) -> SharedTuple { + // SAFETY: every slot is written by the copy (which neither runs + // code nor unwinds). + unsafe { + Self::filled(items.len(), |destination| { + crate::object::clone_objects_into(items, destination); + }) + } + } + + /// A tuple of clones of `count` runs of `items`, one after another + /// (`t * n`). + pub fn from_repeated_slice(items: &[Object], count: usize) -> SharedTuple { + let len = items + .len() + .checked_mul(count) + .expect("tuple elements exceed layout limit"); + // SAFETY: the `count` runs fill exactly `len` slots. + unsafe { + Self::filled(len, |destination| { + for run in 0..count { + crate::object::clone_objects_into(items, destination.add(run * items.len())); + } + }) + } + } + + /// A tuple of clones of `head`'s elements, then `tail`'s (`a + b`). + pub fn from_cloned_pair(head: &[Object], tail: &[Object]) -> SharedTuple { + // SAFETY: the two runs fill exactly the slots asked for. + unsafe { + Self::filled(head.len() + tail.len(), |destination| { + crate::object::clone_objects_into(head, destination); + crate::object::clone_objects_into(tail, destination.add(head.len())); + }) + } + } + + /// A tuple of `len` elements written by `fill` into its own + /// allocation. + /// + /// # Safety + /// + /// `fill` initializes all `len` slots at the pointer it's given, and + /// doesn't unwind. + #[inline(always)] + unsafe fn filled(len: usize, fill: impl FnOnce(*mut Object)) -> SharedTuple { let (prefix, _) = Layout::new::() .extend(Layout::new::()) .expect("tuple prefix exceeds layout limit"); let (layout, _) = prefix - .extend( - Layout::array::(items.len()).expect("tuple elements exceed layout limit"), - ) + .extend(Layout::array::(len).expect("tuple elements exceed layout limit")) .expect("tuple header exceeds layout limit"); let layout = layout.pad_to_align(); // Allocate words with exactly the target payload's alignment and @@ -59,7 +161,8 @@ impl TupleStorage { macro_rules! allocate { ($($word:ty),*) => { $(if layout.align() == std::mem::align_of::<$word>() { - return Self::from_iter_aligned::<$word, I>(items, layout); + // SAFETY: per the caller. + return unsafe { Self::filled_aligned::<$word>(len, layout, fill) }; })* }; } @@ -67,13 +170,17 @@ impl TupleStorage { panic!("unsupported tuple payload alignment: {}", layout.align()); } - fn from_iter_aligned(items: I, layout: Layout) -> SharedTuple - where - I: ExactSizeIterator, - { + /// # Safety + /// + /// As [`Self::filled`]. + #[inline(always)] + unsafe fn filled_aligned( + len: usize, + layout: Layout, + fill: impl FnOnce(*mut Object), + ) -> SharedTuple { assert_eq!(layout.align(), std::mem::align_of::()); assert_eq!(layout.size() % std::mem::size_of::(), 0); - let len = items.len(); let storage = Rc::<[Word]>::new_uninit_slice(layout.size() / std::mem::size_of::()); let data = Rc::into_raw(storage).cast::().cast_mut(); let tuple = std::ptr::slice_from_raw_parts_mut(data, len) as *mut Self; @@ -85,8 +192,8 @@ impl TupleStorage { // layout without depending on Arc's private field layout. // // The raw pointer comes from the only Arc. No references to the - // uninitialized payload exist. These writes neither allocate nor - // run callbacks, and the Vec iterator yields exactly len elements. + // uninitialized payload exist. Per the caller, `fill` writes + // exactly len elements and doesn't unwind. // Changing the fat pointer's metadata preserves its data address // and provenance. The final Arc drops each moved Object once; // the original MaybeUninit words have no destructors. @@ -94,9 +201,7 @@ impl TupleStorage { std::ptr::addr_of_mut!((*tuple).len).write(len); std::ptr::addr_of_mut!((*tuple).hash).write(CachedHash::default()); let destination = std::ptr::addr_of_mut!((*tuple).items).cast::(); - for (index, item) in items.enumerate() { - destination.add(index).write(item); - } + fill(destination); let result = Rc::from_raw(tuple); debug_assert_eq!(Layout::for_value(result.as_ref()), layout); ThinArc::from_arc(result) diff --git a/crates/weavepy-vm/src/type_surface.rs b/crates/weavepy-vm/src/type_surface.rs index 56231afb8..ceec300da 100644 --- a/crates/weavepy-vm/src/type_surface.rs +++ b/crates/weavepy-vm/src/type_surface.rs @@ -1234,6 +1234,9 @@ fn unwrap_shim(inner: Rc, owner: &Rc) -> Object { return Ok(()); } } + if exact_receiver(owner, first) { + return Ok(()); + } if let Some(owner) = owner.upgrade() { let cls = crate::builtins::class_of(first); if !cls.is_subclass_of(&owner) { @@ -1245,6 +1248,23 @@ fn unwrap_shim(inner: Rc, owner: &Rc) -> Object { } Ok(()) } + // An exact builtin value of the owner's own type (`str.upper(w)`), by + // address: no class to fetch. + fn exact_receiver(owner: &crate::sync::Weak, first: &Object) -> bool { + let bt = crate::builtin_types::builtin_types(); + let exact = match first { + Object::Str(_) => &bt.str_, + Object::List(_) => &bt.list_, + Object::Dict(_) => &bt.dict_, + Object::Tuple(_) => &bt.tuple_, + Object::Set(_) => &bt.set_, + Object::Int(_) => &bt.int_, + Object::Float(_) => &bt.float_, + Object::Bytes(_) => &bt.bytes_, + _ => return false, + }; + std::ptr::eq(Rc::as_ptr(exact), owner.as_ptr()) + } // The dict view methods must see the *instance* receiver: their impl // (`dict_self`) unwraps it itself, and the returned view pins the // subclass instance so its `__del__` can't fire while a view or view @@ -1264,13 +1284,25 @@ fn unwrap_shim(inner: Rc, owner: &Rc) -> Object { binds_instance: inner.binds_instance && !no_receiver, call: Box::new(move |args| { if let Some(first) = args.first() { + // (The commonest receiver, an exact value of the owner's + // type, needs neither the check nor the unwrap below.) + if !no_receiver && exact_receiver(&owner_pos, first) { + return (inner_pos.call)(args); + } if !no_receiver { check_receiver(inner_pos.name, &owner_pos, first)?; } if !keep_instance { let unwrapped = as_native(first); if !unwrapped.is_same(first) { - return with_receiver(args, unwrapped, |v| (inner_pos.call)(v)); + let r = with_receiver(args, unwrapped.clone(), |v| (inner_pos.call)(v))?; + // An iterator type's `__iter__` returns its receiver: + // for a subclass's instance, that's the instance + // (`iter(e) is e`), whose class may step it its own way. + if inner_pos.name == "__iter__" && r.is_same(&unwrapped) { + return Ok(first.clone()); + } + return Ok(r); } } } diff --git a/crates/weavepy-vm/src/types.rs b/crates/weavepy-vm/src/types.rs index 3fed6cba5..5b7fde342 100644 --- a/crates/weavepy-vm/src/types.rs +++ b/crates/weavepy-vm/src/types.rs @@ -184,7 +184,9 @@ pub(crate) enum Verdict { /// A value of the builtin class (one whose attributes all come from /// the class, see `builtin_value_class`) answered `name` with /// `AttributeError`: enum asks `hasattr(value, '__get__')` of every - /// member value. Recorded like [`Self::TypeAttrMissing`]. + /// member value. On the function type, a function storing nothing + /// under `name` did (`inspect` asks `getattr(func, '__signature__', + /// None)`). Recorded like [`Self::TypeAttrMissing`]. ValueAttrMissing = 7, /// The class's instances finalize through the native asyncio `__del__` /// `name` names (`"Future"` or `"Task"`): a Python subclass of the @@ -203,6 +205,95 @@ pub(crate) enum Verdict { /// lookup finds first, under `object`'s own `__getattribute__` (see /// `slot_member_unset`). SlotMember = 11, + /// The class is `re.Pattern` and still answers `__hash__` with its + /// native method (see `stdlib::sre_objects::native_hash`); `name` + /// unused. + NativePatternHash = 12, + /// The class answers `str(x)` of its instances with their `str` + /// payload: no `__str__` that dispatch reaches (see + /// `Interpreter::str_payload_class`); `name` unused. + StrPayload = 13, + /// An instance store of `name` is a `__slots__` member's store: the + /// default `__setattr__`, and a writable member without a default + /// that the lookup finds first (see `Interpreter::leaf_slot_store`). + SlotStore = 14, + /// The class, an `int`, `float` or `str` subclass, answers `str(x)` of + /// its instances with their payload's text: its `__str__` is the + /// base's own method stored in a Python class (an `IntEnum`'s or + /// `StrEnum`'s), or a number's `__str__` and `__repr__` both come from + /// the base (see `Interpreter::num_str_payload_class`); `name` unused. + NumStrPayload = 15, + /// The class's `__format__` is its payload type's own, which formats + /// the payload (an empty spec is `str(x)`); `name` unused. + FormatPayload = 16, + /// The class answers `str(x)` with `enum`'s own `Enum.__str__` under + /// the default attribute access (see `Interpreter::enum_str`); `name` + /// unused. + EnumStr = 17, + /// The class's `__format__` is `enum`'s own `Enum.__format__`; `name` + /// unused. + EnumFormat = 18, + /// The class hashes with `enum`'s own `Enum.__hash__` under the default + /// attribute access (see `Interpreter::enum_hash`); `name` unused. + EnumHash = 19, + /// The class (`enum.property`) keeps `enum`'s own `property.__get__` + /// (see `Interpreter::enum_property_value`); `name` unused. + EnumPropertyGet = 20, + /// The class reads `_name_` and `_value_` of its instances from their + /// dicts under the default attribute access; `name` unused. + EnumFields = 21, + /// The class (`array.array`) keeps its module's own `__new__` and + /// `__init__` (see `stdlib::struct_mod::array_pure_new`); `name` + /// unused. + ArrayPlainNew = 22, + /// The class reads `self._core` from the instance dict: the default + /// attribute access, and no `_core` on the class (see + /// `stdlib::itertools_mod::core_next_fast`); `name` unused. + CoreInDict = 23, + /// The class (`weakref.KeyedRef`) keeps its module's own `__new__` + /// and `__init__` (see `stdlib::weakref_real::keyedref_pure_new`); + /// `name` unused. + KeyedRefPlainNew = 24, + /// The class (a `defaultdict` or a subclass) keeps the native + /// `__missing__` (see `stdlib::collections_native::dd_missing_pure`); + /// `name` unused. + DefaultDictMissing = 25, + /// The class, a `dict` subclass, keeps `dict`'s own `__iter__`, + /// `keys` and `__getitem__`: its instances read as their payloads do + /// (see `Interpreter::plain_dict_payload`); `name` unused. + DictPayloadPlain = 26, + /// The class, a `list` or `tuple` subclass, keeps its base's + /// `__add__`, `__mul__` and `__rmul__` and defines no `__radd__`: its + /// instances concatenate and repeat as their payloads do (see + /// `Interpreter::plain_seq_payload`); `name` unused. + SeqArithPlain = 27, + /// As `PlainNewobj`, for a class with `__slots__` on its MRO (and no + /// `__dict__` attribute of its own making): the default reduction's + /// state is its instance dictionary and its slots' values (see + /// `Interpreter::reduce_newobj_plain`); `name` unused. + SlottedNewobj = 28, + /// The class, a `list`, `tuple`, `str` or `bytes` subclass, keeps its + /// base's six comparison methods: its instances compare as their + /// payloads do (see `Interpreter::plain_cmp_payload`); `name` unused. + SeqComparePlain = 29, + /// The class, an `int` or `float` subclass, keeps its base's + /// conversion method `name` (`__int__` or `__float__`): `int(x)` and + /// `float(x)` of its instances convert their payloads (see + /// `Interpreter::leaf_type_call`). + NumConvPlain = 30, + /// The class's plain instances are always true: a Python class under + /// the default attribute access with neither `__bool__` nor `__len__` + /// (see `instance_always_true`); `name` unused. + AlwaysTrue = 31, + /// `name` empty: the exception class's `str()` is + /// `BaseException.__str__` and its `format()` `object.__format__` + /// (see `Interpreter::exc_str_leaf`). `name` `"k"`: the class is a + /// `KeyError`, whose lone argument that method shows by its `repr`. + ExcBaseStr = 32, + /// The class's instances read `x.__dict__` as their own managed dict: + /// no `__getattr__`, and the default `__dict__` member (see + /// `Interpreter::managed_dict_attr`); `name` unused. + ManagedDict = 33, } pub struct AttrVersion(std::sync::atomic::AtomicU64); @@ -346,13 +437,6 @@ pub(crate) mod type_cache { dict_idx: u32, } - const EMPTY: Entry = Entry { - name: None, - ver: 0, - mro_idx: ABSENT, - dict_idx: 0, - }; - thread_local! { /// This thread's table (`SIZE` entries), or null before the first /// fill. A plain pointer in a constant-initialized cell with no @@ -377,19 +461,48 @@ pub(crate) mod type_cache { // (`TABLE` and `HASH_MEMO` have no destructor, so they are // still readable here.) let table = TABLE.with(|t| t.replace(std::ptr::null_mut())); - if !table.is_null() { + if !table.is_null() && !park(&TABLES, table as usize) { // SAFETY: allocated by `alloc_table` as a boxed slice of // `SIZE` entries, and no longer reachable through `TABLE`. drop(unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(table, SIZE)) }); } let memo = HASH_MEMO.with(|t| t.replace(std::ptr::null_mut())); - if !memo.is_null() { + if !memo.is_null() && !park(&MEMOS, memo as usize) { // SAFETY: as above, `HASHES` entries from `alloc_memo`. drop(unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(memo, HASHES)) }); } } } + /// Tables (and name-hash memos) of threads that have exited, for the + /// next threads to start with instead of zeroing and later dropping + /// their own (a thread's start and join paid both). An entry stays + /// valid on any thread: it names its class by the class's version, + /// which is unique for the process, and its name is its own. Each + /// pointer is one exited thread's, owned by the pool until taken. + static TABLES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + static MEMOS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + + /// How many of each the pool keeps. + const POOLED: usize = 4; + + /// Give an exited thread's table to the pool: `false` when it is full. + fn park(pool: &std::sync::Mutex>, p: usize) -> bool { + let Ok(mut v) = pool.lock() else { + return false; + }; + if v.len() >= POOLED { + return false; + } + v.push(p); + true + } + + /// A table an exited thread left in the pool, if any. + fn unpark(pool: &std::sync::Mutex>) -> Option { + pool.lock().ok()?.pop() + } + /// Entries of a thread's name-hash memo. const HASHES: usize = 1 << 9; @@ -404,11 +517,10 @@ pub(crate) mod type_cache { #[cold] #[inline(never)] fn alloc_memo() -> *mut NameHash { - let empty = NameHash { - name: None, - hash: 0, + let memo = match unpark(&MEMOS) { + Some(p) => p as *mut NameHash, + None => zeroed_slice::(HASHES), }; - let memo = Box::into_raw(vec![empty; HASHES].into_boxed_slice()).cast::(); HASH_MEMO.with(|t| t.set(memo)); let _ = OWNER.try_with(|_| ()); memo @@ -437,11 +549,32 @@ pub(crate) mod type_cache { hash } + /// `n` empty entries (each a `None` name and zeros, which is all-zero + /// bytes) as a leaked boxed slice: zeroed memory comes from the + /// allocator's fresh pages without a store per entry, which a short + /// thread would otherwise pay for its whole table. + fn zeroed_slice(n: usize) -> *mut T { + let layout = std::alloc::Layout::array::(n).expect("small table"); + // SAFETY: a nonzero layout; an all-zero `T` here is a `None` name + // (`Option>`'s null niche) and zero integers, a valid value, + // and the boxed slice `Box::from_raw` rebuilds uses this layout. + unsafe { + let p = std::alloc::alloc_zeroed(layout).cast::(); + if p.is_null() { + std::alloc::handle_alloc_error(layout); + } + p + } + } + /// This thread's table, allocated on first use. #[cold] #[inline(never)] fn alloc_table() -> *mut Entry { - let table = Box::into_raw(vec![EMPTY; SIZE].into_boxed_slice()).cast::(); + let table = match unpark(&TABLES) { + Some(p) => p as *mut Entry, + None => zeroed_slice::(SIZE), + }; TABLE.with(|t| t.set(table)); // (Registers the owner's destructor; a thread already past its // destructors keeps the table until the process exits.) @@ -496,8 +629,9 @@ pub(crate) mod type_cache { } } - /// `a == b` for attribute names, in line for the short ones (most - /// dunders and identifiers fit in sixteen bytes). + /// `a == b` for attribute names, in line up to 32 bytes (identifiers + /// and dunders, `__subclasscheck__` and `__init_subclass__` among + /// them, with overlapping word loads). #[inline] pub(crate) fn name_eq(a: &str, b: &str) -> bool { let (a, b) = (a.as_bytes(), b.as_bytes()); @@ -505,10 +639,16 @@ pub(crate) mod type_cache { if n != b.len() { return false; } - if n > 16 { + if n > 32 { return a == b; } let w = |s: &[u8], at: usize| u64::from_le_bytes(s[at..at + 8].try_into().expect("8")); + if n > 16 { + return w(a, 0) == w(b, 0) + && w(a, 8) == w(b, 8) + && w(a, n - 16) == w(b, n - 16) + && w(a, n - 8) == w(b, n - 8); + } if n >= 8 { return w(a, 0) == w(b, 0) && w(a, n - 8) == w(b, n - 8); } @@ -736,15 +876,122 @@ pub(crate) mod vm_key { pub(crate) const ABC_CLASS: u32 = 20; pub(crate) const CHAINMAP_MAPS: u32 = 21; pub(crate) const NATIVE_GETITEM_ANY: u32 = 22; + pub(crate) const EQ_FN: u32 = 23; + pub(crate) const LT_FN: u32 = 24; + pub(crate) const NEXT_FN: u32 = 25; + pub(crate) const FORMAT_LACKS: u32 = 26; + pub(crate) const ITER_FN: u32 = 27; + pub(crate) const FLOAT_FN: u32 = 28; + pub(crate) const INT_FN: u32 = 29; + pub(crate) const SETITEM_LEAF: u32 = 30; + pub(crate) const INSTANCECHECK_FN: u32 = 31; /// Per comparison (eight). pub(crate) const CMP: u32 = 32; /// Per binary operator (sixteen each): its method, and whether the - /// reflected and in-place methods are absent. + /// in-place method is absent. (64 to 79 held whether the reflected + /// method was absent, which nothing asks any more.) pub(crate) const BINOP: u32 = 48; - pub(crate) const RBINOP: u32 = 64; pub(crate) const IBINOP: u32 = 80; + /// Whether `__len__` / `__contains__` is a built-in base's own over the + /// instance's native payload. + pub(crate) const NATIVE_LEN: u32 = 96; + pub(crate) const NATIVE_CONTAINS: u32 = 97; + pub(crate) const SUBCLASSCHECK_FN: u32 = 98; + /// Whether a metaclass's `__subclasscheck__` / `__instancecheck__` + /// is `type`'s own. + pub(crate) const TYPE_SUBCLASSCHECK: u32 = 99; + pub(crate) const TYPE_INSTANCECHECK: u32 = 100; + /// A class's native `__next__` that runs no Python code. + pub(crate) const NEXT_NATIVE: u32 = 101; + /// Whether nothing on the MRO supplies `__str__`. + pub(crate) const STR_ABSENT: u32 = 102; + /// A class's Python `__anext__`, for compiled `async for` loops' direct + /// awaits. + pub(crate) const ANEXT_FN: u32 = 103; + /// Per comparison (eight): whether the class's method for it is + /// `object`'s own. + pub(crate) const CMP_OBJECT: u32 = 104; + /// The native `__len__` / `__next__` a class resolves (any owner), for + /// the leaf calls of an instance's dunder. + pub(crate) const LEAF_LEN: u32 = 112; + pub(crate) const LEAF_NEXT: u32 = 113; + /// The leaf half of the native `__getitem__` a plain Python class + /// resolves (the `array` class's), for compiled subscripts. + pub(crate) const GETITEM_LEAF: u32 = 114; + /// Likewise its `__add__` (an `array`'s concatenation). + pub(crate) const ADD_LEAF: u32 = 115; + /// A class's own Python `__setattr__`, for the inline stores. + pub(crate) const SETATTR_FN: u32 = 116; + /// Its native `__setattr__` (a `threading.local`'s hook). + pub(crate) const SETATTR_NATIVE: u32 = 117; + /// The leaf half of a class's native `__call__` (an `itemgetter`'s), + /// for callbacks that call its instances (`map`, a sort's key). + pub(crate) const CALL_LEAF: u32 = 118; + /// A logger class's `isEnabledFor`, for the native log methods. + pub(crate) const LOG_ENABLED_FOR: u32 = 119; + /// Its native `__str__` that runs no Python code of its own (an + /// exception's), called with the instance, no bound method built. + pub(crate) const STR_NATIVE: u32 = 120; + /// Its native `__repr__` likewise (an exception's, `object`'s). + pub(crate) const REPR_NATIVE: u32 = 121; + /// A class's Python `__aiter__`, for compiled `async for` loops. + pub(crate) const AITER_FN: u32 = 122; + /// A class's Python `__del__`, for the finalizer's direct call. + pub(crate) const DEL_FN: u32 = 123; + /// The leaf half of a native `__getitem__` a Python class holds for + /// instances that carry a payload (a `decimal` signal mapping's). + pub(crate) const GETITEM_OWN_LEAF: u32 = 124; + /// Per binary operator (sixteen), then per comparison (eight): + /// whether an `int` or `float` subclass takes the operator's methods + /// (forward and reflected, and no in-place one) from its built-in + /// base unchanged. + pub(crate) const NUM_BINOP: u32 = 128; + pub(crate) const NUM_CMP: u32 = 144; + /// Whether nothing on the MRO supplies `__length_hint__` / `__len__` + /// (a container built from an instance probes both). + pub(crate) const LENGTH_HINT_ABSENT: u32 = 152; + pub(crate) const LEN_ABSENT: u32 = 153; + /// A class's Python `__getattr__` hook, for the frameless hook calls. + pub(crate) const GETATTR_FN: u32 = 154; + /// Its Python `__format__`, for frameless `format(obj, spec)` calls. + pub(crate) const FORMAT_FN: u32 = 155; + /// Its Python `__bool__`, for compiled truth tests' direct calls. + pub(crate) const BOOL_FN: u32 = 156; + /// Its Python `__delitem__`, for compiled deletions' direct calls. + pub(crate) const DELITEM_FN: u32 = 157; + /// A data descriptor's Python `__set__`, for compiled stores' direct + /// calls. + pub(crate) const SET_FN: u32 = 158; + /// A class's Python in-place operator methods (`__iadd__`, …), one per + /// `BinOpKind` from here, for compiled augmented assignments' direct + /// calls (`IBINOP`'s keys cache whether the class lacks one). + pub(crate) const IBINOP_FN: u32 = 160; + /// A class's Python unary operator methods (`__pos__`, `__neg__`, and + /// at `+ 3` `__invert__`), by `UnaryKind`, for compiled unary + /// operators' direct calls. + pub(crate) const UNARY_FN: u32 = 176; + /// A class's Python `__abs__`, for compiled `abs(obj)`'s direct call + /// (past `UNARY_FN`'s three). + pub(crate) const ABS_FN: u32 = 180; + /// A class's Python reflected binary methods (`__radd__`, ...), by + /// `BinOpKind` from here (sixteen), for compiled `n obj` of a + /// plain number (apart from `RBINOP`'s absence verdicts). + pub(crate) const RBINOP_FN: u32 = 184; + /// A class's Python `__index__` (past `RBINOP_FN`'s sixteen), for an + /// instance used as an index (`xs[obj]`, `range(obj)`). + pub(crate) const INDEX_FN: u32 = 200; + /// A class's Python `__round__`, for `round(obj)`. + pub(crate) const ROUND_FN: u32 = 201; + /// The leaf halves of a natively served class's `__pos__`, `__neg__`, + /// `__abs__`, `__round__` and `__divmod__` (a `Decimal`'s, a + /// `timedelta`'s), in that order from here, for the operators and + /// builtins that call them. + pub(crate) const NATIVE_NUM_LEAF: u32 = 202; } +/// A builtin type's pure constructor (see [`TypeObject::pure_new`]). +pub type PureNew = fn(&Rc, &[Object]) -> Option; + /// The cached answer (see [`LeafAttrCache`]). #[derive(Clone, Debug)] pub enum LeafAttrKind { @@ -782,15 +1029,21 @@ pub enum LeafAttrKind { /// MRO, reading this index of the instance's tuple (the descriptor's /// index is fixed for its life). TupleField(u32), - /// An instance of a Python data descriptor class (a plain-function - /// `__get__`, and `__set__` or `__delete__`) on the MRO: it wins over - /// the instance dict, and a read calls its `__get__`. Valid while its - /// class's attribute version is `dver`; both held weakly. + /// An instance of a Python descriptor class (a plain-function + /// `__get__`) on the MRO, whose read calls its `__get__`: a data + /// descriptor (`__set__` or `__delete__` too, `data`) wins over the + /// instance dict, any other yields to the instance's own entry. Valid + /// while its class's attribute version is `dver`; both held weakly. DataDescr { descr: crate::sync::Weak, get: crate::sync::Weak, dver: u64, + data: bool, }, + /// A built-in base's own special method with a registered leaf half + /// (see `leaf_builtins::register_fast`): the half, which runs no Python + /// code. + LeafFast(crate::leaf_builtins::Fast), /// Anything else: the full path decides. Other, } @@ -1166,6 +1419,23 @@ pub struct TypeObject { /// in `__dict__` is seen by already-specialised call sites. Also keys /// the per-thread [`type_cache`] (RFC 0077 WS4). pub attr_version: AttrVersion, + /// The version of where the class's names resolve: it moves with + /// [`Self::attr_version`] except when a store only replaces the value + /// of an entry the class already has + /// ([`Self::bump_attr_version_values`]), which changes no name's place + /// on the MRO. The MRO lookup cache, which holds places and not + /// values, is keyed by it. + pub shape_version: AttrVersion, + /// The version of what the class's names bind: it moves with + /// [`Self::attr_version`] except when a store replaces one plain data + /// value (a number, a string, an exact container) under a plain name + /// with another of the same kind + /// ([`Self::bump_attr_version_inert`]). No access binds such a value + /// or asks it for `__get__`, so what remembers only functions, + /// descriptors, dunder entries, the kind of a plain value or an + /// instance's layout (never such a value itself) may be keyed by it: + /// the verdict memos ([`Self::memo_verdict`]) are. + pub bind_version: AttrVersion, /// The leaf burst's per-class attribute-kind cache (see /// [`LeafAttrCache`]). pub leaf_attrs: LeafAttrCache, @@ -1173,6 +1443,14 @@ pub struct TypeObject { /// `tp_name` it was computed under, the qualified name, and whether /// the module is `__main__`. display_name_memo: RefCell>, + /// The interned `str` objects `cls.__name__` and `cls.__qualname__` + /// read as (see [`Self::interned_names`]), the second with the text + /// it was made from. + name_objs: RefCell<(Option, Option)>, + /// The tuples `cls.__mro__` and `cls.__bases__` read as (see + /// [`Self::links_tuple`]). The collector visits and clears them with + /// the class's other links. + pub(crate) link_tuples: RefCell<(Option, Option)>, /// The most attributes an instance's `__dict__` was seen to hold /// (capped): new instances' dicts are presized to it, so `__init__`'s /// stores do not regrow them. @@ -1189,6 +1467,26 @@ pub struct TypeObject { /// native adapter directly (see `stdlib::itertools_mod::native_new`): /// the adapter's kind. A subclass has its own (zero) value. pub lazy_ctor: Cell, + /// The class version at which the frame JIT's constructor path found + /// its calls to run a framed `__init__` that compiled code enters + /// directly (see `frame_jit::records::ctor_enter`); `0` (no version) + /// until then. + pub framed_ctor: Cell, + /// The class version at which the frame JIT's constructor path built + /// an instance store-only (see `frame_jit::records::ctor_enter`); `0` + /// (no version) until then. + pub store_ctor: Cell, + /// For an exact builtin type whose call, for some arguments, runs no + /// Python code and has no effect beyond building the object + /// (`io.BytesIO()`, `threading.Lock()`, `object()`): that call, or + /// `None` for arguments it leaves to the full constructor (see + /// `seqiter::builtin_ctor_pure`). A subclass has its own (empty) one. + pub pure_new: Cell>, + /// The names of [`Self::pure_new`]'s positional parameters, in order, + /// for a class whose calls may name them as keywords + /// (`deque(xs, maxlen=5)`): such a call is that constructor's with the + /// keyword values in place (see `Interpreter::core_pure_new_kw`). + pub pure_new_kw: Cell>, /// Non-zero for an exact `_collections` class the interpreter serves /// natively: `_tuplegetter`, whose instances the attribute paths read /// as tuple items (`stdlib::collections_native::DESCR_TUPLEGETTER`), @@ -1363,6 +1661,52 @@ pub struct InstancePlan { /// order, once its stores proved them for this class version (see /// `Interpreter::core_store_init`). pub slot_members: std::sync::OnceLock>, + /// `user_new` is a Python `__new__` that only allocates (see + /// [`TrivialNew`]). + pub trivial_new: Option>, +} + +/// How many reads a trivial `__new__`'s remembered reassignment +/// rechecks (see [`TrivialNew::swap_memo`]). +pub const SWAP_READS: usize = 6; + +/// A Python `__new__` whose whole body is `return object.__new__(cls)`, +/// after an optional `if cls is X: cls = Y` (`pathlib`'s paths), of a +/// class with a Python `__init__` (see [`InstancePlan::trivial_new`]). +/// While `object` (and `X`) still resolve as when it was matched, `X` +/// isn't the class called and the call binds, the call goes by +/// [`Self::plan`], the class's plan with `object.__new__` in its place +/// (`Interpreter::call_plan`): the function would return a fresh instance +/// of the class, which its `__init__` then initializes. +#[derive(Debug)] +pub struct TrivialNew { + /// The code object the shape was read from (its address). + pub code: usize, + /// `object`'s index in the code's names. + pub object_name: u32, + /// `X`'s, for the `if cls is X: cls = Y` form. + pub swap: Option, + /// Where that form's reassignment starts and where it ends (the + /// `object.__new__` line), see `Interpreter::trivial_new_retarget`. + pub swap_body: (u32, u32), + /// The reassignment's last pick (`Interpreter::trivial_new_retarget`): + /// the function's globals and builtins stamps and the global-value + /// epoch it was made at, the verdict (`0` none yet, `1` no pick, `2` + /// a pick), the class picked (its address), and how many values the + /// reading read (`u64::MAX`: one it can't recheck) and where: + /// [`SWAP_READS`] entries of the dict (`0` the globals, `1` the + /// builtins, else a module dict's address), that dict's stamp (a + /// module's), the position and the value's identity. + pub swap_memo: [std::sync::atomic::AtomicU64; 6 + 4 * SWAP_READS], + /// The positional parameter count (`cls` included) a call has to + /// match; `None` for `(cls, *args)` (with or without `**kwargs`). + pub fixed: Option, + /// The class's plan as though `__new__` were `object.__new__`. + pub plan: Rc, + /// The function's globals and builtins stamps at which its names + /// were last looked up (`0`s: never), then where `object` and `X` + /// were found (see `Interpreter::trivial_new_locate`). + pub memo: [std::sync::atomic::AtomicU64; 4], } /// How a fresh instance's `native` payload is provisioned (see @@ -1649,10 +1993,16 @@ impl TypeObject { metaclass: RefCell::new(None), leaf_attrs: LeafAttrCache::new(), display_name_memo: RefCell::new(None), + name_objs: RefCell::new((None, None)), + link_tuples: RefCell::new((None, None)), inst_dict_hint: std::sync::atomic::AtomicU32::new(0), shared_keys: crate::sync::LazyArc::new(), native_kind: Cell::new(0), lazy_ctor: Cell::new(0), + framed_ctor: Cell::new(0), + store_ctor: Cell::new(0), + pure_new: Cell::new(None), + pure_new_kw: Cell::new(None), collections_kind: Cell::new(0), native_ext: std::sync::OnceLock::new(), abc_state: std::sync::OnceLock::new(), @@ -1666,6 +2016,8 @@ impl TypeObject { setattr_kind: Cell::new(0), mro_kind: std::sync::atomic::AtomicU8::new(0), attr_version: AttrVersion::fresh(), + shape_version: AttrVersion::fresh(), + bind_version: AttrVersion::fresh(), has_del: Cell::new(0), dunder_memo: Default::default(), instance_plan: RefCell::new(None), @@ -1771,6 +2123,11 @@ impl TypeObject { /// [`Self::slot_layout`], decided now if it isn't yet. #[inline] + /// The class's member layout (see [`Self::fresh_slots`]), if it has one. + pub(crate) fn own_slot_layout(&self) -> Option<&SharedSlice> { + self.slot_layout_init() + } + fn slot_layout_init(&self) -> Option<&SharedSlice> { self.slot_layout .get_or_init(|| { @@ -1810,7 +2167,14 @@ impl TypeObject { let mut names: Vec = Vec::new(); for t in self.mro.borrow().iter().rev() { if t.flags.is_builtin { - if t.name == "object" { + // (A value type's payload lives apart from the slots, and + // nothing native adds slots of its own to its subclasses' + // instances, as `OrderedDict`'s order does to a dict's: + // `configparser`'s `_Line(str)` reads its members compiled.) + if matches!( + t.name.as_str(), + "object" | "str" | "int" | "float" | "complex" | "bytes" | "tuple" + ) { continue; } return None; @@ -2127,9 +2491,115 @@ impl TypeObject { /// subclass. Call after any class-dict mutation or MRO reshaping that /// can change what an attribute name resolves to; specialised /// LOAD_ATTR/STORE_ATTR sites guard on the version and deopt. + /// `cls.__name__` (`qualified` false) or `cls.__qualname__` as the + /// class's own string, the interned object `Object::interned_str` + /// makes, remembered on the class: reading a class's name doesn't take + /// the intern table's lock each time. (A class dict entry for the name, + /// which a read finds first, is the caller's.) + pub(crate) fn interned_names(&self, qualified: bool) -> Object { + let qual = if qualified { + self.qualname.borrow().clone() + } else { + None + }; + let text: &str = qual.as_deref().unwrap_or(&self.name); + if let Ok(memo) = self.name_objs.try_borrow() { + let slot = if qualified { &memo.1 } else { &memo.0 }; + if let Some(Object::Str(s)) = slot { + if &**s == text { + return Object::Str(s.clone()); + } + } + } + let obj = Object::interned_str(text); + if let Ok(mut memo) = self.name_objs.try_borrow_mut() { + let slot = if qualified { &mut memo.1 } else { &mut memo.0 }; + *slot = Some(obj.clone()); + } + obj + } + + /// `cls.__mro__` (`bases` false) or `cls.__bases__` as one tuple + /// for as long as the links stay what they are, as CPython's + /// `tp_mro` and `tp_bases` are (`C.__mro__ is C.__mro__`): the tuple + /// made at the first read, while its items are still the class's + /// links, else a new one. `None` for an empty MRO (a class mid- + /// creation, which the full path answers). + pub(crate) fn links_tuple(&self, bases: bool) -> Option { + let current = if bases { + self.bases.try_borrow().ok()? + } else { + self.mro.try_borrow().ok()? + }; + if !bases && current.is_empty() { + return None; + } + if let Ok(memo) = self.link_tuples.try_borrow() { + if let Some(Object::Tuple(t)) = if bases { &memo.1 } else { &memo.0 } { + if t.len() == current.len() + && t.iter() + .zip(current.iter()) + .all(|(o, c)| matches!(o, Object::Type(x) if Rc::ptr_eq(x, c))) + { + return Some(Object::Tuple(t.clone())); + } + } + } + let tuple = Object::new_tuple(current.iter().map(|b| Object::Type(b.clone())).collect()); + drop(current); + crate::gc_trace::track_built(&tuple); + if let Ok(mut memo) = self.link_tuples.try_borrow_mut() { + *(if bases { &mut memo.1 } else { &mut memo.0 }) = Some(tuple.clone()); + } + Some(tuple) + } + pub fn bump_attr_version(&self) { + self.bump_versions(true, true); + } + + /// [`Self::bump_attr_version`] for a store that replaced the value of + /// an entry the class's dictionary already had, in place: what the + /// names resolve to changed, where they resolve didn't + /// ([`Self::shape_version`] stands). + pub fn bump_attr_version_values(&self) { + self.bump_versions(false, true); + } + + /// [`Self::bump_attr_version_values`] when the value replaced and the + /// one that took its place are both plain data + /// ([`Self::bind_version`] stands too). + pub fn bump_attr_version_inert(&self) { + self.bump_versions(false, false); + } + + /// After a bump that left [`Self::bind_version`] standing: what the + /// class itself remembers under the version it had, `was`, and that + /// reads only dunder entries (the construction plan: `__new__`, + /// `__init__`, `__abstractmethods__`) is carried to the new one. + fn carry_bound(&self, was: u64) { + if let Ok(mut plan) = self.instance_plan.try_borrow_mut() { + if let Some((v, _)) = plan.as_mut() { + if *v == was { + *v = self.attr_version.get(); + } + } + } + } + + fn bump_versions(&self, shape: bool, bind: bool) { use std::sync::atomic::Ordering::Relaxed; + let was = self.attr_version.get(); self.attr_version.bump(); + if !bind { + self.carry_bound(was); + } + if shape { + self.shape_version.bump(); + } + if bind { + self.bind_version.bump(); + } self.mro_kind.store(0, Relaxed); // (A leaf class, the common case, has nothing to walk.) if self @@ -2147,7 +2617,16 @@ impl TypeObject { continue; } visited.push(ptr); + let was = t.attr_version.get(); t.attr_version.bump(); + if shape { + t.shape_version.bump(); + } + if bind { + t.bind_version.bump(); + } else { + t.carry_bound(was); + } t.mro_kind.store(0, Relaxed); queue.extend(t.subclasses()); } @@ -2428,6 +2907,20 @@ impl TypeObject { && self.dunder(Dunder::GetAttribute).object_owner() } + /// Whether `x.__class__` of an instance (with no native body) of this + /// class is just the class: [`Self::class_attr_is_plain`], of a class + /// that isn't builtin (a builtin's instances, weak proxies among them, + /// may answer otherwise), or of `super` itself, whose `super_getattro` + /// serves `__class__` as the proxy's own class. + pub fn class_read_is_plain(&self) -> bool { + (!self.flags.is_builtin + || std::ptr::eq( + self, + Rc::as_ptr(&crate::builtin_types::builtin_types().super_), + )) + && self.class_attr_is_plain() + } + pub fn lookup_with_owner(&self, name: &str) -> Option<(Object, Rc)> { // Fast pass — see `lookup` for the gate rationale. if !crate::object::exotic_str_keys_possible() { @@ -2465,7 +2958,7 @@ impl TypeObject { compute: impl FnOnce() -> bool, ) -> bool { let ty = std::ptr::from_ref::(self) as usize; - let ver = self.attr_version.get() | (family as u64) << 56; + let ver = self.bind_version.get() | (family as u64) << 56; // (The slot ignores the version's top byte: a family moves its // entries off the ones the attribute lookups use.) let h = type_cache::name_hash(name) ^ (family as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); @@ -2493,7 +2986,7 @@ impl TypeObject { #[inline] pub(crate) fn verdict_cached(&self, family: Verdict, name: &str) -> Option { let ty = std::ptr::from_ref::(self) as usize; - let ver = self.attr_version.get() | (family as u64) << 56; + let ver = self.bind_version.get() | (family as u64) << 56; let h = type_cache::name_hash(name) ^ (family as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); match type_cache::probe(ty, ver, name, h)? { type_cache::Hit::Absent => Some(true), @@ -2506,7 +2999,7 @@ impl TypeObject { /// version; the cache may forget it. pub(crate) fn verdict_record(&self, family: Verdict, name: &str, verdict: bool) { let ty = std::ptr::from_ref::(self) as usize; - let ver = self.attr_version.get() | (family as u64) << 56; + let ver = self.bind_version.get() | (family as u64) << 56; let h = type_cache::name_hash(name) ^ (family as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); let hit = if verdict { type_cache::Hit::Absent @@ -2525,7 +3018,9 @@ impl TypeObject { #[inline] fn lookup_cached(&self, name: &str) -> Option<(Object, usize)> { let ty = std::ptr::from_ref::(self) as usize; - let ver = self.attr_version.get(); + // (The cache holds each name's place, read again at every hit: a + // value replaced in place leaves it standing.) + let ver = self.shape_version.get(); let h = type_cache::name_hash(name); match type_cache::probe(ty, ver, name, h) { Some(type_cache::Hit::Absent) => return None, @@ -2548,7 +3043,7 @@ impl TypeObject { if let Some(owner) = mro.get(mro_idx as usize) { let d = owner.dict.borrow(); if let Some((k, v)) = d.get_index(dict_idx as usize) { - if matches!(&k.0, Object::Str(s) if s.as_ref() == name) { + if matches!(&k.0, Object::Str(s) if type_cache::name_eq(s, name)) { return Some((v.clone(), mro_idx as usize)); } } @@ -2563,32 +3058,26 @@ impl TypeObject { s: name, hash: type_cache::py_hash_of(name, h), }; - let mro = self.mro.borrow(); - for (i, owner) in mro.iter().enumerate() { - let d = owner.dict.borrow(); - if let Some((dict_idx, _, v)) = d.get_full(&key) { - // Introspection-only entries (RFC 0056 WS4) are invisible - // to dispatch — keep walking as if absent. Only in - // *builtin* dicts, where the docs surface pass installed - // them: a user class that aliases one - // (`__str__ = object.__str__`) means it, per CPython. - if owner.flags.is_builtin && crate::descr_registry::is_surface_only(v) { - continue; - } - let v = v.clone(); - drop(d); - type_cache::fill( - ty, - ver, - name, - h, - type_cache::Hit::At { - mro_idx: i as u32, - dict_idx: dict_idx as u32, - }, - ); - return Some((v, i)); - } + // The MRO's dictionaries probed through guard-free views where + // they are free: nothing in the walk runs code (an exact-`str` + // probe, a clone), and every view ends before the fill. + // SAFETY: as above; the view ends with the walk. + let found = match unsafe { self.mro.peek() } { + Some(mro) => mro_walk(mro, &key), + None => mro_walk(&self.mro.borrow(), &key), + }; + if let Some((i, dict_idx, v)) = found { + type_cache::fill( + ty, + ver, + name, + h, + type_cache::Hit::At { + mro_idx: i as u32, + dict_idx: dict_idx as u32, + }, + ); + return Some((v, i)); } type_cache::fill(ty, ver, name, h, type_cache::Hit::Absent); None @@ -2748,10 +3237,22 @@ fn compute_c3( bases: &[Rc], name: &str, ) -> Result>, RuntimeError> { + // One base (most classes, and `email`'s header classes made per + // header): the class, then the base's MRO, which the merge below + // would give one head at a time. + if let [base] = bases { + let mro = base.mro.borrow(); + let mut merged = Vec::with_capacity(mro.len() + 1); + merged.push(self_ty.clone()); + merged.extend(mro.iter().cloned()); + return Ok(merged); + } let mut lists: Vec>> = bases.iter().map(|b| b.mro.borrow().clone()).collect(); lists.push(bases.to_vec()); - let mut merged: Vec> = vec![self_ty.clone()]; + let mut merged: Vec> = + Vec::with_capacity(1 + lists.iter().map(Vec::len).sum::()); + merged.push(self_ty.clone()); loop { lists.retain(|l| !l.is_empty()); if lists.is_empty() { @@ -3294,6 +3795,17 @@ pub(crate) enum ExcTail { } impl ExcTail { + /// The pseudo-slot named `name`, if one is. + pub(crate) fn of_name(name: &str) -> Option { + Some(match name { + "__traceback__" => Self::Traceback, + "__context__" => Self::Context, + "__cause__" => Self::Cause, + "__suppress_context__" => Self::SuppressContext, + _ => return None, + }) + } + /// The slot's name. pub(crate) fn name(self) -> &'static str { COMMON_SLOT_NAMES[1 + self as usize] @@ -3332,6 +3844,11 @@ pub(crate) fn slot_key(name: &str) -> DictKey { #[cfg(target_pointer_width = "64")] const EXC_TAIL_LEN: usize = 4; +/// An `AttributeError`'s layout (`args`, `name`, `obj`, then the tail): +/// [`SlotStorage::laid_out_pair_mut`] knows its two fields' places. +#[cfg(target_pointer_width = "64")] +static EXC_NAME_OBJ_LAYOUT: std::sync::OnceLock> = std::sync::OnceLock::new(); + /// The shared slot layout of an exception instance whose families' own /// fields are `extra`: `args`, `extra`, then the [`ExcTail`] pseudo-slots, /// which raising and chaining populate. `None` for a shape without one @@ -3342,13 +3859,12 @@ fn exception_layout(extra: &[&'static str]) -> Option> { static PLAIN: Layout = Layout::new(); static VALUE: Layout = Layout::new(); static MSG: Layout = Layout::new(); - static NAME_OBJ: Layout = Layout::new(); static NAME: Layout = Layout::new(); let cell = match extra { [] => &PLAIN, ["value"] => &VALUE, ["msg"] => &MSG, - ["name", "obj"] => &NAME_OBJ, + ["name", "obj"] => &EXC_NAME_OBJ_LAYOUT, ["name"] => &NAME, _ => return None, }; @@ -3994,6 +4510,47 @@ impl SlotStorage { self.leading_interned(names) } + /// [`Self::leading_memo`]'s hit alone: the leading `N` values when the + /// store's layout is the one `memo` remembers, which a caller can try + /// before it has the names at hand. `None` otherwise (the caller then + /// asks [`Self::leading_memo`] with them). + #[inline(always)] + pub fn leading_memo_hit(&self, memo: &LayoutMemo) -> Option<[&Object; N]> { + let SlotsRef::Fixed(layout, values) = self.view() else { + return None; + }; + if SharedSlice::word(layout) != memo.word() { + return None; + } + let values = values.get(..N)?; + if values.iter().any(|v| matches!(v, Object::Unbound)) { + return None; + } + Some(std::array::from_fn(|i| &values[i])) + } + + /// [`Self::leading_memo_hit`], mutably. + #[inline(always)] + pub fn leading_memo_hit_mut( + &mut self, + memo: &LayoutMemo, + ) -> Option<[&mut Object; N]> { + let SlotsMut::Fixed(layout, values) = self.view_mut() else { + return None; + }; + if SharedSlice::word(layout) != memo.word() { + return None; + } + let values = values.get_mut(..N)?; + if values.iter().any(|v| matches!(v, Object::Unbound)) { + return None; + } + let base = values.as_mut_ptr(); + // SAFETY: `N` distinct in-range values, borrowed from `self` for + // the result's lifetime. + Some(std::array::from_fn(|i| unsafe { &mut *base.add(i) })) + } + /// [`Self::leading_memo`], mutably. #[inline(always)] pub fn leading_memo_mut( @@ -4153,6 +4710,23 @@ impl SlotStorage { self.get(which.name()) } + /// [`Self::get`] of an exception's `args`: the first laid-out place + /// when the storage has an exception layout (see [`Self::exception`]), + /// without comparing names. + #[inline] + pub(crate) fn exc_args_get(&self) -> Option<&Object> { + if let SlotsRef::Fixed(layout, values) = self.view() { + if let (Some(DictKey(Object::Str(laid))), Object::Str(key)) = + (layout.first(), &common_slot_keys()[0]) + { + if crate::shared_value::SharedStr::ptr_eq(laid, key) { + return values.first().filter(|v| !matches!(v, Object::Unbound)); + } + } + } + self.get("args") + } + /// [`Self::place_mut`] of the exception pseudo-slot `which`, by /// [`Self::exc_tail_mut`] when the storage has an exception layout. #[inline] @@ -4194,6 +4768,17 @@ impl SlotStorage { let SlotsMut::Fixed(layout, values) = self.view_mut() else { return None; }; + // (An `AttributeError`'s own layout: both places are fixed.) + if a == "name" + && b == "obj" + && values.len() > 2 + && EXC_NAME_OBJ_LAYOUT + .get() + .is_some_and(|shared| SharedSlice::ptr_eq(layout, shared)) + { + let (head, tail) = values.split_at_mut(2); + return Some((&mut head[1], &mut tail[0])); + } let pos = |name: &str| { layout.iter().position( |key| matches!(&key.0, Object::Str(stored) if slot_name_eq(stored.as_ref(), name)), @@ -4482,6 +5067,12 @@ impl SlotStorage { self.get(which.name()) } + /// The populated `args` (see the 64-bit variant). + #[inline] + pub(crate) fn exc_args_get(&self) -> Option<&Object> { + self.get("args") + } + pub fn insert(&mut self, name: &str, value: Object) -> Option { self.insert_with_key(name, value, || slot_key(name)) } @@ -4621,8 +5212,7 @@ pub struct PyInstance { const INSTANCE_POOL_CAP: usize = 128; thread_local! { - static INSTANCE_POOL: std::cell::RefCell>> = - const { std::cell::RefCell::new(Vec::new()) }; + static INSTANCE_POOL: crate::gil::ReleaseUnderGil>>> = const { crate::gil::ReleaseUnderGil::new(std::cell::RefCell::new(Vec::new())) }; } impl PyInstance { @@ -4895,7 +5485,7 @@ impl PyInstance { } } self.deferred.set(false); - crate::gc_trace::track_deferred_owner(std::ptr::from_ref(self) as usize); + crate::gc_trace::track_cleared_instance(self); } /// A value is about to be stored outside the `__dict__` (a slot): @@ -5025,6 +5615,16 @@ impl PyInstance { self.slots.borrow().exc_tail_get(which).cloned() } + /// [`Self::slot_get`] of an exception's `args` (see + /// `SlotStorage::exc_args_get`). + pub(crate) fn exc_args_get(&self) -> Option { + // SAFETY: the view ends with the clone, before anything runs. + if let Some(slots) = unsafe { self.slots.peek() } { + return slots.exc_args_get().cloned(); + } + self.slots.borrow().exc_args_get().cloned() + } + /// Write slot `name` into the side table. pub fn slot_set(&self, name: &str, value: Object) { self.note_slot_store(&value); @@ -5098,6 +5698,10 @@ impl Drop for PyInstance { } // A finalizer, if the class has one, already ran: `rc::Rc`'s `Drop` // queued this instance for it at its last release. + // A native state this instance owns goes with it. (The class + // read needs no borrow: nothing else holds a dying instance.) + let cls_addr = Rc::as_ptr(self.class.get_mut()) as usize; + crate::stdlib::handle_table::on_instance_death(self, cls_addr); let id = std::ptr::from_ref(self) as usize as u64; crate::weakref_registry::on_death(id); // A collector registry entry's weak handle would keep this @@ -5495,3 +6099,42 @@ mod slot_storage_tests { assert_eq!(cloned.get("first").and_then(Object::as_i64), Some(5)); } } + +/// [`TypeObject::lookup_cached`]'s walk of a type-cache miss: the first of +/// `mro`'s dictionaries that holds `key`, its MRO position and dictionary +/// index with the value. Each dictionary is read through a guard-free view +/// where one is free (the probe compares exact `str` keys and runs no +/// code). +#[inline(always)] +fn mro_walk( + mro: &[Rc], + key: &crate::object::StrKeyHashed<'_>, +) -> Option<(usize, usize, Object)> { + #[inline(always)] + fn entry( + d: &DictData, + owner: &TypeObject, + key: &crate::object::StrKeyHashed<'_>, + ) -> Option<(usize, Object)> { + let (dict_idx, _, v) = d.get_full(key)?; + // Introspection-only entries (RFC 0056 WS4) are invisible to + // dispatch — keep walking as if absent. Only in *builtin* dicts, + // where the docs surface pass installed them: a user class that + // aliases one (`__str__ = object.__str__`) means it, per CPython. + if owner.flags.is_builtin && crate::descr_registry::is_surface_only(v) { + return None; + } + Some((dict_idx, v.clone())) + } + for (i, owner) in mro.iter().enumerate() { + // SAFETY: a read that runs no code, ended before the next. + let hit = match unsafe { owner.dict.peek() } { + Some(d) => entry(d, owner, key), + None => entry(&owner.dict.borrow(), owner, key), + }; + if let Some((dict_idx, v)) = hit { + return Some((i, dict_idx, v)); + } + } + None +} diff --git a/crates/weavepy-vm/src/unicode_case.rs b/crates/weavepy-vm/src/unicode_case.rs index f0b032965..a889ffd0e 100644 --- a/crates/weavepy-vm/src/unicode_case.rs +++ b/crates/weavepy-vm/src/unicode_case.rs @@ -67,6 +67,12 @@ pub fn lower(s: &str) -> String { let cps: Vec = s.chars().collect(); let mut out = String::with_capacity(s.len()); for i in 0..cps.len() { + // (An ASCII letter's mapping is its ASCII case: the common case in + // mostly-ASCII text.) + if cps[i].is_ascii() { + out.push(cps[i].to_ascii_lowercase()); + continue; + } push_cps(&mut out, lower_at(&cps, i)); } out @@ -78,6 +84,10 @@ pub fn upper(s: &str) -> String { } let mut out = String::with_capacity(s.len()); for c in s.chars() { + if c.is_ascii() { + out.push(c.to_ascii_uppercase()); + continue; + } push_cps(&mut out, ucd::to_upper_full(c as u32)); } out @@ -90,6 +100,10 @@ pub fn casefold(s: &str) -> String { } let mut out = String::with_capacity(s.len()); for c in s.chars() { + if c.is_ascii() { + out.push(c.to_ascii_lowercase()); + continue; + } push_cps(&mut out, ucd::to_fold_full(c as u32)); } out @@ -271,6 +285,11 @@ pub fn is_titlecase(c: char) -> bool { /// `unicode_isupper_impl`: no lower/title chars and at least one upper. pub fn str_isupper(s: &str) -> bool { + // (ASCII text by its bytes: no lowercase letter and an uppercase one.) + if s.is_ascii() { + let b = s.as_bytes(); + return !b.iter().any(u8::is_ascii_lowercase) && b.iter().any(u8::is_ascii_uppercase); + } let mut cased = false; for c in s.chars() { let f = ucd::case_flags(c as u32); @@ -286,6 +305,11 @@ pub fn str_isupper(s: &str) -> bool { /// `unicode_islower_impl`: no upper/title chars and at least one lower. pub fn str_islower(s: &str) -> bool { + // (ASCII text by its bytes, as `str_isupper`.) + if s.is_ascii() { + let b = s.as_bytes(); + return !b.iter().any(u8::is_ascii_uppercase) && b.iter().any(u8::is_ascii_lowercase); + } let mut cased = false; for c in s.chars() { let f = ucd::case_flags(c as u32); diff --git a/crates/weavepy-vm/src/vm_singletons.rs b/crates/weavepy-vm/src/vm_singletons.rs index ea9a8c24e..35c9c5efe 100644 --- a/crates/weavepy-vm/src/vm_singletons.rs +++ b/crates/weavepy-vm/src/vm_singletons.rs @@ -43,12 +43,11 @@ thread_local! { /// Pending `__del__` finalizer invocations queued by the cycle /// GC. Drained at the next eval-loop tick by the interpreter. /// See [`crate::gc_trace::run_finalizer`] for the producer side. - pub(crate) static PENDING_FINALIZERS: RefCell> = const { RefCell::new(Vec::new()) }; + pub(crate) static PENDING_FINALIZERS: crate::gil::ReleaseUnderGil>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(Vec::new())) }; /// Pending weakref-callback invocations `(callback, weakref_obj)` /// queued when a referent dies (cycle GC, refcount reap, registry /// sweep). Drained alongside the finalizer queue. - pub(crate) static PENDING_WEAKREF_CALLBACKS: RefCell> = - const { RefCell::new(Vec::new()) }; + pub(crate) static PENDING_WEAKREF_CALLBACKS: crate::gil::ReleaseUnderGil>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(Vec::new())) }; } /// Process-wide count of parked `__del__` requests and weakref callbacks @@ -270,12 +269,20 @@ pub fn has_pending_weakref_callbacks() -> bool { .unwrap_or(false) } -/// Drain the pending weakref-callback queue. +/// Drain the pending weakref-callback queue. The hot gate is lowered as +/// [`drain_pending_finalizers`] lowers it (clear, drain, recheck): that +/// drain, which runs first, re-raises the gate for the callbacks still +/// parked here, and a gate left raised while they run would send every +/// call they make down the slow paths. pub fn drain_pending_weakref_callbacks() -> Vec<(Object, Object)> { + crate::hot_gates::clear(crate::hot_gates::PENDING_FINALIZERS); let taken = PENDING_WEAKREF_CALLBACKS.with(|cell| std::mem::take(&mut *cell.borrow_mut())); if !taken.is_empty() { PENDING_FINALIZER_COUNT.fetch_sub(taken.len(), std::sync::atomic::Ordering::Release); } + if PENDING_FINALIZER_COUNT.load(std::sync::atomic::Ordering::Acquire) > 0 { + crate::hot_gates::set(crate::hot_gates::PENDING_FINALIZERS); + } taken } @@ -550,6 +557,16 @@ pub fn clear_thread_python_tls() { } crate::builtin_types::clear_thread_type_registry(); crate::stdlib::local_native::forget_thread(); + // The thread's entry in the traceback dumper's registry (its frame + // and exception stacks) and its interned names: objects, released + // here, where the caller still holds the GIL, not by the thread's + // destructors after it has given the GIL back. + let _ = FAULTHANDLER_REG.try_with(|slot| { + if let Ok(mut slot) = slot.try_borrow_mut() { + slot.take(); + } + }); + crate::stdlib::sys::forget_thread_interns(); } /// Look up the worker thread id for the currently-running OS thread, @@ -682,7 +699,44 @@ pub fn activate_thread_handles(handles: ThreadHandles) -> ThreadHandlesGuard { } }); CURRENT_THREAD_HANDLES.with(|cell| cell.borrow_mut().push(handles)); - ThreadHandlesGuard { _private: () } + ThreadHandlesGuard { pushed: true } +} + +/// Whether the handles on top of this thread's stack are exactly these +/// (every one the same shared cell): activating them again would push a +/// copy of the top, so [`ThreadHandlesGuard::unpushed`] stands in. +pub(crate) fn thread_handles_top_is( + frame_stack: &crate::object::FrameStack, + exc_info_stack: &Rc>>, + excepthook: &Rc>, + unraisable_hook: &Rc>, +) -> bool { + CURRENT_THREAD_HANDLES + .try_with(|cell| { + cell.try_borrow().is_ok_and(|v| { + v.last().is_some_and(|h| { + Rc::ptr_eq(&h.frame_stack, frame_stack) + && Rc::ptr_eq(&h.exc_info_stack, exc_info_stack) + && Rc::ptr_eq(&h.excepthook, excepthook) + && Rc::ptr_eq(&h.unraisable_hook, unraisable_hook) + }) + }) + }) + .unwrap_or(false) +} + +/// Whether the handles on top of this thread's stack are the ones whose +/// frame stack is `frame_stack`: its interpreter activated them already +/// (an embedder entry's re-activation would only push the same again). +pub(crate) fn thread_handles_are(frame_stack: &crate::object::FrameStack) -> bool { + CURRENT_THREAD_HANDLES + .try_with(|cell| { + cell.try_borrow() + .ok() + .and_then(|v| v.last().map(|h| Rc::ptr_eq(&h.frame_stack, frame_stack))) + .unwrap_or(false) + }) + .unwrap_or(false) } /// Read-only view of the current thread's handles. Returns `None` @@ -715,11 +769,23 @@ pub fn swap_thread_handles_stack(new: Vec) -> Vec /// most-recently-pushed handles on drop. #[derive(Debug)] pub struct ThreadHandlesGuard { - _private: (), + /// Whether this guard pushed (see [`thread_handles_top_is`]). + pushed: bool, +} + +impl ThreadHandlesGuard { + /// A guard for handles already on top: it pushed nothing, so it pops + /// nothing. + pub(crate) fn unpushed() -> Self { + Self { pushed: false } + } } impl Drop for ThreadHandlesGuard { fn drop(&mut self) { + if !self.pushed { + return; + } CURRENT_THREAD_HANDLES.with(|cell| { let _ = cell.borrow_mut().pop(); }); @@ -737,8 +803,24 @@ thread_local! { /// Stored as a raw pointer because the VM owns the storage — /// the guard pops on drop so the pointer never outlives the /// owning `&mut Interpreter` borrow. - static CURRENT_INTERPRETER_PTR: RefCell> = - const { RefCell::new(Vec::new()) }; + static CURRENT_INTERPRETER_PTR: RefCell = + const { RefCell::new(InterpStack(Vec::new())) }; + /// The top of [`CURRENT_INTERPRETER_PTR`] (null when it is empty), so a + /// lookup is one thread-local load: a constant-initialized cell with no + /// destructor, readable through thread teardown. + static CURRENT_INTERPRETER_TOP: std::cell::Cell<*mut crate::Interpreter> = + const { std::cell::Cell::new(std::ptr::null_mut()) }; +} + +/// The published interpreters (see [`CURRENT_INTERPRETER_PTR`]); its +/// destruction with the thread clears the top's mirror, so a lookup past +/// it finds none. +struct InterpStack(Vec<*mut crate::Interpreter>); + +impl Drop for InterpStack { + fn drop(&mut self) { + let _ = CURRENT_INTERPRETER_TOP.try_with(|t| t.set(std::ptr::null_mut())); + } } /// RAII guard that pushes `interp` onto [`CURRENT_INTERPRETER_PTR`] @@ -746,16 +828,27 @@ thread_local! { /// might run user code which re-enters the C-API. #[derive(Debug)] pub struct InterpreterGuard { - _private: (), + /// Whether this guard pushed: publishing the interpreter already on + /// top pushes nothing (lookups read the top, which stays the same), so + /// its guard pops nothing either. + pushed: bool, } impl Drop for InterpreterGuard { fn drop(&mut self) { + if !self.pushed { + return; + } // `try_with`: guards can unwind during thread teardown after the // TLS slot is gone; the stack died with it, so popping is moot. - let _ = CURRENT_INTERPRETER_PTR.try_with(|cell| { - let _ = cell.borrow_mut().pop(); - }); + let top = CURRENT_INTERPRETER_PTR + .try_with(|cell| { + let mut stack = cell.borrow_mut(); + let _ = stack.0.pop(); + stack.0.last().copied().unwrap_or(std::ptr::null_mut()) + }) + .unwrap_or(std::ptr::null_mut()); + let _ = CURRENT_INTERPRETER_TOP.try_with(|t| t.set(top)); } } @@ -953,7 +1046,7 @@ thread_local! { /// here instead; the eval loop reaps it at the next /// between-bytecodes safe point — before any subsequent Python-level /// weakref read can observe the stale referent. - static PENDING_CEXT_DROPS: RefCell> = const { RefCell::new(Vec::new()) }; + static PENDING_CEXT_DROPS: crate::gil::ReleaseUnderGil>> = const { crate::gil::ReleaseUnderGil::new(RefCell::new(Vec::new())) }; /// Cheap "is this thread's C-drop queue non-empty?" probe for the /// eval-loop safe point. Thread-local (unlike `PENDING_RW_FLAG`) /// because the queues are: a global flag cleared by whichever thread @@ -1422,8 +1515,14 @@ pub fn warn_default_encoding() -> bool { /// the returned guard. Re-entrant calls produce a stack so the /// most recent guard wins on `current_interpreter_ptr` lookups. pub fn publish_interpreter_ptr(interp: *mut crate::Interpreter) -> InterpreterGuard { - CURRENT_INTERPRETER_PTR.with(|cell| cell.borrow_mut().push(interp)); - InterpreterGuard { _private: () } + // (Re-entering the interpreter already on top, the common nested + // call, leaves the stack as it is.) + if !interp.is_null() && CURRENT_INTERPRETER_TOP.with(std::cell::Cell::get) == interp { + return InterpreterGuard { pushed: false }; + } + CURRENT_INTERPRETER_PTR.with(|cell| cell.borrow_mut().0.push(interp)); + CURRENT_INTERPRETER_TOP.with(|t| t.set(interp)); + InterpreterGuard { pushed: true } } /// Read the most recently published interpreter pointer, or @@ -1434,10 +1533,12 @@ pub fn publish_interpreter_ptr(interp: *mut crate::Interpreter) -> InterpreterGu /// shm-manager child) probe `Py_IsInitialized` after this thread's /// TLS has been destroyed — report "no interpreter" rather than /// aborting the process (RFC 0076 WS5). +#[inline] pub fn current_interpreter_ptr() -> Option<*mut crate::Interpreter> { - CURRENT_INTERPRETER_PTR - .try_with(|cell| cell.borrow().last().copied()) - .unwrap_or(None) + let top = CURRENT_INTERPRETER_TOP + .try_with(std::cell::Cell::get) + .unwrap_or(std::ptr::null_mut()); + (!top.is_null()).then_some(top) } /// `quit` and `exit` — interactive sentinels that raise `SystemExit`. diff --git a/crates/weavepy-vm/src/weakref_registry.rs b/crates/weavepy-vm/src/weakref_registry.rs index 7edbd2631..31873ada1 100644 --- a/crates/weavepy-vm/src/weakref_registry.rs +++ b/crates/weavepy-vm/src/weakref_registry.rs @@ -63,7 +63,7 @@ const WRAPPER_NAMES: [&str; 5] = [ ]; thread_local! { - static WRAPPER_KEYS: [DictKey; 5] = WRAPPER_NAMES.map(|name| DictKey(Object::from_static(name))); + static WRAPPER_KEYS: crate::gil::ReleaseUnderGil<[DictKey; 5]> = crate::gil::ReleaseUnderGil::new(WRAPPER_NAMES.map(|name| DictKey(Object::from_static(name)))); } impl WrapperKey { @@ -160,6 +160,27 @@ pub(crate) fn wrapper_value(inst: &crate::types::PyInstance, key: WrapperKey) -> .cloned() } +/// The referent of weakref wrapper `inst` (or `None` once it died), by a +/// call of its deref closure read in place from the wrapper's laid-out +/// slots (no reference taken): `None` for a wrapper that keeps them some +/// other way, which [`wrapper_value`] reads. +#[inline] +pub(crate) fn wrapper_deref_in_place( + inst: &crate::types::PyInstance, +) -> Option> { + if inst.inline_values.get() { + return None; + } + let layout = WRAPPER_LAYOUT.get()?; + // SAFETY: a read of the wrapper's own slots; the closure called below + // touches only its weak slot, never the wrapper. + let slots = unsafe { inst.slots.peek() }?; + match slots.values_for_layout(layout)?.first()? { + Object::Builtin(b) => Some((b.call)(&[])), + _ => None, + } +} + /// Weakref kinds as exposed to Python. Numeric so the field /// fits in a `u8`. pub mod kind { diff --git a/crates/weavepy/src/lib.rs b/crates/weavepy/src/lib.rs index 5e3a97417..575da8255 100644 --- a/crates/weavepy/src/lib.rs +++ b/crates/weavepy/src/lib.rs @@ -299,6 +299,11 @@ fn run_source_with_options_impl( opts: &RunOptions, keep_interpreter: bool, ) -> (Option, Result<(), Error>) { + // The GIL, for the whole run: the interpreter is built, run, shut + // down and released by this thread, beside whatever threads the + // program starts (declared first, so released last; a blocking call + // gives it up while it waits, as in any thread). + let _gil = vm::gil::hold_gil(); // `-x`: drop the first physical line (typical use is to allow a // shell-style shebang to live above a self-extracting payload). let effective_source: String; diff --git a/docs/PERFORMANCE-PROGRESS.md b/docs/PERFORMANCE-PROGRESS.md index e7d6a34a2..183c2b261 100644 --- a/docs/PERFORMANCE-PROGRESS.md +++ b/docs/PERFORMANCE-PROGRESS.md @@ -7,6 +7,87 @@ plan, what's done, and what's next, so a new session can pick up the work. ## Where WeavePy stands +Measured on November 19, 2026, at `c69d14ad` (PR #112), a PGO build from a +fresh training run against CPython 3.14.8 (load averages between 2 and 5). +The everyday battery: 0.966 times CPython's time over three runs (0.956, +0.957 and 0.984), against 1.258 at `83efee9b` four days earlier. WeavePy is +ahead on 28 of the 54 cases, past one and a half times CPython's time on 5 +and past twice on one: `threading_queue_ops` 2.2, `argparse_ops` 1.9, +`inspect_typing_ops` 1.7, `email_html_ops` 1.6, `exceptions_ops` 1.5. A plain +release build of the same tree reads 1.18: the profile-guided layout is +worth a fifth of the battery's time (see the instruction-cache figures +under "Done"). The suite, with the `83efee9b` PGO build in the same run: +warm time 0.843 (that build 0.851), cold time 0.957 (0.952), peak RSS 1.183 +(1.144) by the suite's runner and 1.172 (1.174) with footprint 1.252 +(1.269) by three runs a workload under `/usr/bin/time`; the new build runs +the suite in 0.990 of the older one's warm time. The published 1.13 for +peak RSS doesn't reproduce with either build today: CPython's own figure +moves between sessions. + +Measured on November 20, 2026, at `f96980aa` (PR #112), a PGO build beside +the `c69d14ad` one in the same runs: the battery in 0.996 of that build's +time (best of three runs a case), `threading_queue_ops` at 1.9 times +CPython's time where it was 2.2. Against CPython this session read both +builds about a tenth slower than the day before's (1.04 to 1.12 a run for +each), so the 0.97 above stands as the last quiet-machine figure. What the +day's work moves is outside the battery: a program with a second thread +(under 1% slower than without one, from 13% to 55%), a thread back from a +blocking call (the GIL after one switch interval, not two), a contended lock +(handed to its waiter after 5 ms), and attribute-heavy loops in tier 2 (the +`attr_access` fixture at 0.66 of its instructions), and dicts that lose keys +from the front or the middle (an LRU cache, a queue of pending work: one to +two orders of magnitude slower than CPython before, level to twice its time +now). + +Measured on November 15, 2026, at `83efee9b` (PR #112), a PGO build +against CPython 3.14.8 on a host that wasn't idle (load averages between +2 and 9). The everyday battery: 1.258 times CPython's time over three runs +(1.236, 1.258 and 1.265), within the earlier build's spread; by +instructions (synchronous compiles, quick builds) 1.282 times CPython's +against 1.297 at the start of the day. WeavePy is ahead on 21 cases (20 +before), past twice CPython's time on 9 and past three times on none (2 +before): `file_read_binary_chunks` 2.9, `class_features` 2.9, +`enum_dataclass_ops` 2.8, `email_html_ops` 2.7, `configparser_ops` 2.7, +`threading_queue_ops` 2.7, `inspect_typing_ops` 2.7, `bigint_ops` 2.2 and +`argparse_ops` 2.1. The suite in the same session: warm time 0.842, cold +time 0.952, peak RSS 1.129. The commits after `83efee9b` (see "Done") +weren't in the build. + +Measured on November 15, 2026, at `98339f92` (PR #112), two PGO builds of +that commit on the same idle host against CPython 3.14.8: one from the +usual training, one from a training that also runs the everyday battery +(the training now does, see "Done"). The everyday battery: 1.228 times +CPython's time over two runs (1.228 and 1.227) for the battery-trained +build, 1.265 (1.252 and 1.278) for the other, against 1.357 at +`2ce79fa5`. WeavePy is ahead on 20 cases (17 before), past twice CPython's +time on 9 (12 before) and past three times on 2: `enum_dataclass_ops` 3.1 +and `class_features` 3.1, then `email_html_ops` 2.8, +`file_read_binary_chunks` 2.8 (its time is in the reads), +`inspect_typing_ops` 2.6, `threading_queue_ops` 2.6 (3.4 before), +`configparser_ops` 2.5 and `argparse_ops` 2.5. The suite in the same +session, battery-trained build: warm time 0.847, cold time 0.955, peak RSS +1.135, and 1.000 of the other build's time, so the battery in the +training costs the suite nothing. The commits after `98339f92` (see +"Done") weren't in either build. + +Measured on November 14, 2026, at `2ce79fa5` (PR #112), a PGO build from a +fresh training run against CPython 3.14.8 on the same idle host, beside +the November 13 PGO build PR #110's figures came from. The everyday +battery: 1.357 times CPython's time over two runs (1.345 and 1.369), +against 1.431 for the earlier build in the same session. WeavePy is +ahead on 17 cases (16 before), past twice CPython's time on 12 (14 +before) and past three times on 5: `inspect_typing_ops` 4.0, +`threading_queue_ops` 3.4, `class_features` 3.3, `weakref_gc_ops` 3.2 +and `file_read_binary_chunks` 3.0 (1.5 by instructions: its time is in +the reads). The cases this PR went after moved the most: +`datetime_time_ops` 2.02 to 0.75, `bytes_ops` 2.36 to 1.36, `csv_ops` +2.15 to 1.40, `threading_queue_ops` 4.11 to 3.38, `glob_fnmatch` 1.61 to +1.36. The suite in the same session: warm time 0.849, cold time 0.949, +peak RSS 1.123, and 1.004 of the earlier build's time, so the battery's +fixes cost the suite nothing. The commits after `2ce79fa5` (see "Done") +weren't in that build; by instructions on quick builds the battery +stands at 1.34 times CPython's against 1.45 at the start of this PR. + Measured on November 13, 2026, at `4e230310` (this PR), a PGO build from a fresh training run against CPython 3.14.8 on the same idle host. The benchmark suite: warm time 0.850, cold time 0.959, peak RSS 1.137, and @@ -427,6 +508,5736 @@ branch and pull request. ## Done +- **Container operators, iteration adapters, and class method sites** + (PR #112, November 17). Ratios are instructions, WeavePy's over + CPython's; cycles where noted. + - A `BINARY_OP` that built a heap value on the generic path didn't mark + its site, so compiled code took the numbers' helper and left at the + next instruction (`d1 | d2`, `k & s`, `b * 3`). The site is marked + now, and compiled code serves dict union, `bytes` repetition and + `bytes % args` natively. `plain_compare` answers two exact dicts' `==` + (1,135 cycles to 215, CPython 160), two sets' comparisons (1,444 to + 710, against 400) and a keys view against a set (1,083 to 753, + against 542) when no key or value can run Python. + - `zip` replaced its result tuple whenever it built one, so `for t in + zip(xs, ys)`, which still holds the last tuple, never reused one; it + keeps the tuple before as a spare now, indexes tuple and list cursors + directly, and stops in compiled code when its release frees nothing + that could finalize: a ten-item `for t in zip(t, t)` 3,878 cycles to + 2,460 (1,770), three sources unpacked 5,366 to 3,788 (1,917). + `list(islice(lst, 10))` takes the slice at once (7,879 instructions to + 4,620, against 3,679), a collecting consumer takes a `yield from` over + a sequence in one run (12,506 to 8,171, against 5,490), and + `dict(zip(ks, gen))` takes its pairs straight from the sources + (16,066 to 11,355, against 6,247). + - A method load on a user class receiver resolved `C.s(x)` and + `C.make()` through the type lanes every time: the site remembers a + class's plain function, static or class method now, keyed by the + class's and its metaclass's versions, a metaclass method of the same + name being a non-data descriptor the class overrides (`C.s(1)` 919 to + 297, against 678; `Color(1)` 5,491 to 3,917, against 2,672). + `object.__setattr__` stores into a plain instance natively, which a + frozen dataclass's `__init__` calls per field (`Key(i, "x")` 5,135 to + 3,956, against 3,392), and the current interpreter, which 248 builtin + sites look up, is one thread-local load. + - A frameless call of a pure leaf with keyword-only parameters cached no + call shape, so the frame JIT never knew the callee: `fkw(i)` for `def + fkw(a, b=2, *, c=3)` 901 to 356 (677). `None` and `bool` keys take the + native dict probe (argparse's `registry[None] = cls`), a list's + unit-step slice assignment splices in place, the type cache compares + names up to 32 bytes in line (17-byte dunders went to `memcmp`), and + tier 2 stops analyzing code from its back edges once it has handed the + code to the frame JIT (argparse's `_parse_known_args` was analyzed + ten times, twice each). + - Later the same day. `decimal` keeps the context it found last under a + `contextvars` generation, which every change of the current context + and every mapping write moves (unique across threads): `D1 * D2` 1,466 + to 1,306 (1,028), and `decimal_telco` in the suite 1.17 to 1.07. + Exited threads leave their type cache and literal-string cache to the + next threads instead of zeroing and dropping them (a thread's start + and join 728,556 to 523,657, against 182,851). A named tuple's field + read off a local answers from its site's stamp first (two reads 1,076 + to 382, against 821). `MAP_ADD` and `SET_ADD` have their own helpers, + as `LIST_APPEND` had, and the three read a local's value in place + (`{x: x for x in t}` 6,803 to 5,994; `{x for x in t}` 5,842 to + 4,659). Keyword dicts and dict literals insert keys whose hashes + differ pairwise without probing, and every container compiled code or + the core loop builds defers its collector tracking without scanning + its elements (a collection promotes the deferred ones that can anchor + a cycle first): `{'a': i, 'b': 2}` 1,331 to 1,119 (937). `bytes.strip` + tests membership through a table, and `dict(zip(ks, gen))` takes its + pairs straight from the sources. Tier 2 gives up OSR entries that + average fewer than 16 iterations (the floor was 8): `difflib`'s + `find_longest_match` entered its inner loop about nine times a pass, + paying a hand-off and a frame rebuild each time while the frame JIT, + which had left the code to tier 2, kept its outer loop interpreted; + `SequenceMatcher(...).ratio()` ran 10,265,084 instructions to + 4,195,398 (CPython 4,487,196). + - That evening. Compiled code stores into an `OrderedDict` through the + leaf half of its own `__setitem__`, which the class caches under its + attribute version, instead of the general store: `od[k] = v` in a + tier-2 loop 1,325 to 897 (701), in a called function 1,178 to 947 + (996). The frame JIT's direct call of a built-in subclass instance's + native method takes small int arguments (`od.move_to_end(5)` 786 to + 492, against 434). A method site remembers a callable an instance holds + in a materialized dict, by position and name, as it did for a split one: + a `threading.Condition` over a lock with `_release_save` assigns its + names out of the class's order, so `self._is_owned()` took the full + method load (`notify()` 2,427 to 1,751, against 1,057). Reading a native + method off such an instance (`self._lock.__exit__`, to call with + `*args`) answers from the site's cached builtin before three slow + paths, and the leaf registry remembers its last hit: `with cond:` 4,312 + to 3,124 (2,415), a `Queue` put and get 16,368 to 14,016 (11,764). + `test_set` failed about once in 40 runs: a set mutated from an + element's `__eq__` while another operation held it queued the mutation + by address alone, so a later set at the same address replayed a stale + `clear()` on its next `add`. The queue now holds a weak handle and drops + a dead set's ops. `re.match(compiled, s)` went through `re._compile`, + which raises and catches a `KeyError` before handing a compiled pattern + back; the native cache front now returns it (16,572 to 1,703, against + 7,626; `ConfigParser.write` 3.46 M to 1.60 M, against 1.94 M). A method + site keeps a native stream's method for its kind (three `StringIO` + writes and a `getvalue()` 8,450 to 7,737, against 4,663), and a subclass + of `str`, `int`, `float`, `tuple`, `bytes` or `frozenset` that keeps its + base's `__new__` wraps an argument of the base's exact type directly + (4,995 to 2,254, against 1,409). + - Loops over opaque iterators. Tier 2 stepped a set through its fully + general iterator step and dict keys after that step's setup; it now + steps list, tuple, range, set and dict iterators in place for any lane + (10 set items 6,691 to 3,188, against 1,978; 10 keys 5,498 to 4,553, + against 1,976). `for a, b in pairs` reads each pair where it sits (4,821 + to 3,069, against 1,657), `enumerate` over a list or tuple reads its + pairs in place in both JITs (a tier-2 `i * x` sum 7,565 to 4,293, + against 6,342), and an exhausted `reversed(xs)` leaves compiled code's + loop in place instead of through the interpreter (3,891 to 2,192, + against 2,230). The frame JIT runs these loops for less than tier 2 + still does, but handing tier 2's code with such loops to it cost + `pyaes` 2.6 times its instructions, `deque_ops` 1.6 and `richards` 1.5: + their int work wins back more than the iterator steps cost. + - Container methods. A frozenset of atomic values isn't registered with + the collector (it can't change, so it can never close a cycle; + `gc.is_tracked` registers it on asking): `frozenset((1, 2, 3))` 2,181 + to 1,446 (1,432). `dict.update` from a plain dict whose keys run no + code, `dict.copy`, and `set.add` and `set.update` of natively hashed + values have leaf halves, which call sites run in place instead of + through the general call (`set.update` also cloned the whole set as a + snapshot on every call): `x = {}; x.update(sd)` 2,237 to 1,771 (1,500), + `x = set(); x.update(t)` 3,598 to 1,978 (1,700). + - Strings and collection. `str.partition` and `rpartition` return the + separator and an unsplit string themselves, as CPython does, and build + their pieces from slices; `splitlines` and `split` scan short ASCII + strings by byte; one-character pieces are the shared strings + (`partition` 1,266 to 838, against 987; `splitlines` 1,574 to 1,215, + against 997). `list(enumerate(xs))` over a list or tuple builds its + pairs at once (6,843 to 4,853, against 4,521). `min`, `max`, `sorted` + and `list.sort` call a leaf builtin key's body directly and read a + built-in value's length natively for `key=len` (`min(l, key=abs)` 5,515 + to 3,587, against 3,573; `sorted(w, key=len)` 6,715 to 5,767, against + 4,510), and `hex`, `oct` and `bin` of a machine int format in a stack + buffer (1,354 to 793, against 786). + - Leaks found on the way. A cycle through a list or dict that a builtin + built was never collected when the builtin didn't register it: list + slices and starred targets in the core loop, `list.copy()`, `dir()`, + `json.loads`, `re.findall`, `dict.fromkeys`, the generic `dict | dict`, + `+` and `*` of lists, and every binder's `**kwargs` dict. They now + defer their tracking as other built containers do (`json_bench` pays + 4% for it). A `**kwargs` dict that its code only ever feeds to a `**` + spread (a decorator's wrapper) can't outlive its call and skips the + registration; one that may escape pays about 170 instructions. + - Builtin subclasses and getters. A compiled call site settled on a + container's or string's method declined an instance of a subclass (a + `Counter`, an `OrderedDict`, a `class L(list)`) and sent it through + the general call, which found the method's receiver shim, checked the + receiver and unwrapped it. The site now runs its kernel on the + instance's native payload (a dict view keeps the instance), and + `len()` and `in` read the payload when the class keeps the base's own + `__len__` or `__contains__`: `d.get(k)` 1,990 to 432 (CPython 671), a + list subclass's `append` and `pop` 3,521 to 652 (767), `len(d)` 2,014 + to 400 (359), `k in d` 1,666 to 319 (573), `d.items()` 1,801 to 861 + (880). A site settled on `itemgetter`'s or `attrgetter`'s native + `__call__` takes the instance itself, which it had passed to the + general call to rewrite: `ig(t)` 737 to 477 (484). A differential + sweep against CPython found `round(True)` returning `True` and + `float.hex` and `int.bit_length` accepting an argument. + - Bytes and binary files. A sized read of a buffered binary file made + one `read(2)` per call into a vector, then copied that into the + `bytes` object; a read of less than half a buffer is now served from + the stream's read-ahead, which one `read(2)` of a buffer's worth fills + (CPython's `BufferedReader` does the same, and line reads already + shared it), and a larger read lands in the result's own storage. A + read to the end of a regular file is sized by `fstat` and read into + the result directly instead of through 64 KiB chunks and two copies, + a write of at least a buffer's worth with nothing staged goes to the + descriptor without passing through the write buffer, and `bytes * n` + builds in the result's storage (a fill for one byte). Reading 4 MB in + 8 KiB chunks went from 5.9 million instructions to 3.6 million + (CPython 1.7 million), reading it whole from 12.8 to 4.4 (1.5), + writing it from 8.6 to 4.2 (4.2), and `b"x" * 4_000_000` from 9.4 to + 4.7 (1.0). The rest of the last two was page faults: mimalloc maps + blocks over 2 MiB from the OS and unmaps them when freed (see + `alloc.rs`), where macOS's allocator keeps a freed large block for + reuse, so each round faulted its 4 MB in again. The allocator now + keeps up to four such blocks (32 MiB each, 64 MiB in all) for an + allocation of about their size, freeing any idle past the purge delay + at the runtime's memory ticks. In wall time, `b"x" * 4_000_000` went + from 1.9 ms to 0.08 (CPython 0.33), a 4 MB whole-file read from 2.3 to + 0.22 (0.52), and `bytearray(4_000_000)` from 1.4 to 0.08 (0.31), with + the suite's peak RSS unchanged. `[0] * 1_000_000` also copied each + item through an iterator: a unit of values without a reference count + now copies bitwise, doubling (58 million instructions to 5.1, against + 13.2; 10.3 ms to 1.3, against 1.3). `bytes.split()` and `bytes.hex()` + without options build their pieces and digits directly (5,284 to + 3,546 against 3,386, and 2,197 to 1,377 against 1,185). + - Loops calling a function held in a local. Tier 2 compiled such a loop + and called the function through its generic call helper, about 800 + instructions more a call than the frame JIT's direct entry: `f(1, 2, + 3)` of a local `f` ran 932 instructions an iteration under tier 2 and + 114 with it off (CPython 515). The analysis now records which of a + loop's dynamic calls have a Python callee, and a loop whose typed + arithmetic and guarded calls don't repay them (24 typed operations, + or one guarded call, for each) is left to the frame JIT: 932 to 198. + A float-heavy loop with such a call stays in tier 2, which saves it + about 30 instructions a float operation. Fixtures, suite and battery + are flat. A call of a global function tier 2 can't compile (one with + keyword-only parameters, `*args` or `**kwargs`) took the same generic + path; the analysis now recognizes those too, by the `LOAD_GLOBAL` + ahead of the call's self-or-null slot (`fkw(i, c=4)` 1,115 to 350, + against 697). Only callees of at most 64 instructions count: the + first version of the rule also turned away `nbody`'s driver loop, + whose callee is a long function tier 2 compiles itself (+37%). + Tier 2 now compiles functions with keyword-only parameters too: they + are locals the caller's binding fills before the body runs, so the + analysis seeds and guards them like the positional ones. A loop in + `def f(n, *, scale=2, off=1)` ran under the frame JIT at 67 ms for + twenty calls of 200,000 steps (plus a float loop of the same shape) + and runs at 36 ms in tier 2 (CPython 351). Direct native calls still + take only positional callees. + - Helpers that call helpers. A loop calling a short global function + that calls another (`g_mid(t)` with `return g_leaf(x)`) ran 1,045 + instructions an iteration (CPython 932): tier 2 took the loop and + called `g_mid` through the frameless evaluator, which interpreted + both bodies. The analysis now asks, for each guarded call of a + global, whether its callee would run that way (a short loop-free + function tier 2 hasn't compiled as a scalar leaf and that isn't one + of the evaluator's tiny shapes), and the call-bound rule counts such + calls as it counts dynamic ones. The frame JIT then took the loop, + but lowered only `g_mid` in line: `g_leaf` had run only nested in + `g_mid`'s frameless evaluations, which counted nothing toward its + warmth, and its call went through the inlined body's call helper + (377 instructions). A callee of a callee lowered in line now counts + as warm once the evaluator has built its plan (a counter in the + evaluator's in-place call path instead cost `call_overhead` 10% of + its cycles at the same instruction count). The chain runs at 342 + (a closure chain 833 to 358), `g_two` with a branch 651 to 252, and a + float loop around a tiny callee keeps tier 2's 155. Code whose + loops have run but that tier 2 still holds nothing for (`argparse`'s + `_get_values`, whose comprehensions it only ever left cold) went on + waiting for tier 2 for good; the frame JIT now takes it after 16 + such triggers. The battery runs 0.6% fewer instructions (`email`, + `traceback` and generator cases 5%); fixtures are flat. + - Constructors. A sweep of 45 common constructions against CPython + found builtin types two to four times slower to build: their calls + went through the type call, the instance plan and `__new__`/`__init__` + dispatch even when they only make an object. A builtin type now + carries a pure constructor for the arguments that run no Python code + (the pure arms `builtin_ctor_pure` already had, one per type, so a + type without one misses at a load instead of after twenty + comparisons): `object()` 2,314 to 815 instructions (CPython 727), + `threading.Lock()` 2,797 to 1,547 (965), `io.BytesIO()` 3,875 to 2,015 + (972), `io.StringIO()` 4,014 to 2,124 (2,028), `complex(1, 2)` 3,115 to + 724 (1,525), `memoryview(b)` 2,816 to 1,189 (1,523). + `threading.RLock()` forwarded an empty `*args, **kwargs` to the native + lock: 8,398 to 3,032. Still slow: `array.array` (a pure-Python module, + 9.6 times CPython), and classes partly in Python (`defaultdict(list)` + 2.9, `OrderedDict()` 4.6, `functools.partial` 2.9, `itemgetter` 2.8). + `os.scandir` and `os.listdir` validate names as UTF-8 before the + lossy decoder, which cost about 300 instructions a name. + `OrderedDict()` returns from `__init__` when there's nothing to add + (4,762 to 3,077, against 1,039). + - Smaller single operations, from a sweep of 80 common statements. + `sum(d.values())` and `sum(d.keys())` read the dict in place (3,734 to + 1,548 for three items, against 1,678). The pure `zip` steps, which + only produce an item when every source has one, take strict zips too, + as the end where `strict=` is checked stays the general step's (a + `for a, b in zip(x, y, strict=True)` loop over five items 16,909 to + 7,255, against 4,973). `del xs[a:b]` of a unit step drains by its + bounds instead of building every index, and compiled code deletes + such a run itself when its items release without running code + (`L.extend(x); del L[-5:]` 2,873 to 1,460, against 1,399); the items + now release last first, as CPython's do. Finished, joined threads + leave the runtime's thread registry, which every reap scanned in full + (thread start and join 663k to 545k instructions over a thousand + threads, still 3.2 times CPython's). + - A second sweep, of 104 statements over the standard library's + smaller types and builtins. Complex arithmetic left compiled code for + the core loop's operator dispatch each time; the frame JIT's + binary-operation helper now computes `+ - * /` of an exact `complex` + with a number itself (`c1 * c2` 2,008 instructions to 584, against + 540). `setattr(obj, name, v)` of a plain instance is a leaf builtin + that stores into the instance dictionary as the generic path does, + the name interned (1,953 to 1,211, against 699). `functools.reduce` + joins the builtins compiled code and the core loop run in place + instead of leaving for the full call path (`reduce(operator.add, + xs)` 4,641 to 1,916, against 2,033). `sorted(d)` reads a dict's keys + directly rather than through an iterator (4,121 to 2,160); + `{**d}` and `f(**kw)` copy the source's table into the empty target + whole; `str.center`, `ljust`, `rjust` and `zfill` build in one + allocation and return an exact `str` that needs no padding as itself + (`center` 2,208 to 868, against 923); `bytes.join` of a list or tuple + of `bytes` reads the parts in place (3,153 to 2,316); and + `struct.unpack` of `bytes` skips the buffer adapter (2,536 to 2,074). + `itertools.accumulate` and `product` stay 2.4 and 2.0 times CPython's: + their iterator steps spread over a dozen helpers. Container methods + without an in-place lane paid the method-call protocol, about 250 + instructions around a cheap body: `dict.copy` and `set.copy` now run + as opaque bodies compiled code calls directly, `dict.pop` of a `str` + or `int` key is a leaf (778 to 588, against 542), and `list.remove` + has a kernel when the items up to the match compare natively and the + removed one releases without running code (2,005 to 1,329, against + 1,289; the full path scans the same way first). `dict.pop()` and + `dict.copy(1)` now raise CPython's messages. + - Keyword calls. Compiled code constructing a class with keywords + (`Parameter(name, kind, default=d)`) worked out the keywords' + permutation onto `__init__`'s parameters, comparing every name, on + each call (about 330 instructions); a per-thread memo keyed by the + function, its code, the names tuple and the argument count keeps it, + asking afresh for a function whose defaults may have been reassigned. + The keyword binder also reads keyword-only defaults by position when + they line up with the parameters, as positional calls already did. + `P("a", 1, default=i)` with two keyword-only parameters 3,294 + instructions to 2,838 (CPython 3,365). + - User-class protocols, from a third sweep of 83 statements. `bool(x)` + of an instance took the type call's dispatch and several method + lookups (a plain instance 3,933 instructions to CPython's 422): it is + the truth test now, the in-place `__bool__`/`__len__` evaluation + first and `PyObject_IsTrue`'s protocol after (465; through a Python + `__len__` 4,534 to 1,398). A missing attribute that a pure-leaf + `__getattr__` answers ran it as an activation behind a cascade of + lanes that each missed; compiled code and the core loop now evaluate + it frameless first (3,869 to 1,319, against 1,010). Frameless + evaluation also runs `x in c` and `not in` over a native container + (anything that could run code declines), so a `__contains__` that + tests its own list evaluates in place: `2 in box` 3,759 to 1,047 + (1,026). `__bool__ = None` now raises CPython's "cannot be interpreted + as a boolean". `int(text, base)` of plain digits is the pure + constructor's (`int('ff', 16)` 2,503 to 814, against 986), and + `"".join(reversed(s))` reads the string's characters into the + snapshot directly and joins the rest of it at once (10,403 to 7,664, + against 4,362); `str.join`'s error for a non-`str` item now names its + index, as CPython's does. `list(obj)` of an instance whose `__iter__` + returns `iter(self.items)` ran `__len__` (the length hint) and + `__iter__` as full calls and stepped the iterator one item at a time; + both now evaluate as pure leaves when they can (`iter()` joins the + builtins a frameless evaluation may call: it mutates nothing), and a + list's or tuple's iterator drains at once (8,138 instructions to + 5,073, against 2,736). An `__iter__` that returns a list or another + non-iterator now raises CPython's `TypeError` on every path; a `for` + loop used to iterate it. Each loop over a dict registered its + iterator's mutation watch in a thread-local hash map and removed it + after (about 200 instructions a loop); the first eight watched dicts + now sit in a vector scanned in place, the map holding any beyond + (`[k for k in d]` of three keys 2,541 to 2,410 under callgrind). + `min(xs, key=len)` ran `len` through the general call for each item, + the key path taking only some of the leaf builtins' kinds; it takes + every kind now, and compares machine-int keys directly (5,756 to + 3,929, against 3,864). `format(x, 'g')` computed `str(x)`, a shortest + repr nothing used, before parsing the spec, then formatted the fixed + form a second time after the scientific one: a plain `g`, `G` or + `.Ng` spec of a float now goes straight to the general format, which + lays the fixed form out from the scientific digits (rounded at the + same place), and `format()` of an exact `float`, `int` or `str` is a + leaf builtin (5,272 to 3,874, against 2,417). A non-`str` spec raises + CPython's message. `list(zip(a, b, c))` over lists and tuples stepped + the zip one tuple at a time through the pure steps; it drains in one + pass now, then takes the end step CPython's does (one more item from + each source before the first exhausted one), so the sources are left + exactly as stepping leaves them (9,056 to 6,069, against 4,556). + - A fifth sweep (74 statements over I/O buffers, dates, regular + expressions, `itertools` and `functools` variants). `date.fromisoformat` + was the pure-Python parse (14,759 instructions to CPython's 1,513); the + exact class's `YYYY-MM-DD` and `YYYYMMDD` now parse natively beside + `datetime.fromisoformat`'s, every other spelling and every error the + Python method's (1,056). `math.fsum` and `math.dist` stepped their + argument through the interpreter's iterator, publishing the + interpreter for each item; a list or tuple of floats and ints is read + in place (7,043 to 2,850, against 1,590), and their `TypeError` now + reads as CPython's. `str.maketrans` joins the builtins run in place + (7,615 to 5,968), and `sum(reversed(xs))` of ints adds the rest of the + reversed snapshot at once (3,558 to 2,286, against 1,755). A `for` + loop over a Python iterator class ran its `__next__` as a full + activation through the general step for every item, compiled code + having no lane for it (440 instructions an item to CPython's 136): a + `__next__` that evaluates as a pure or effect leaf (`self.i += 1; + return x`, its stores committed at the return) now runs frameless from + compiled loops and from the native consumers (`list`, `sum`), its + `raise StopIteration` still the full path's (248 an item; `list(it)` + of ten items 3,279 to 2,738). The core loop's `FOR_ITER` takes the + same shortcut, so a cold loop over one runs 282 an item instead of + 532. + - A native class method read through a class (`dict.fromkeys`, + `itertools.chain.from_iterable`, which `itertools` installs over the + Python one) resolved through every frame JIT read lane before the + general one bound it, about 3,000 instructions a read to CPython's + 700. The site's class memo now holds the descriptor and binds a fresh + method at each read, as `classmethod.__get__` does, and a native + static method's function (`str.maketrans`) is memoized as a builtin + is (645 instructions, 0.93 of CPython's). `dict.fromkeys` of an ASCII + string, a dict, or a set builds in place as a list's keys do (6,821 + to 1,582, against 2,352). + - `islice` steps its source in place when the source is a plain list + or tuple cursor, but a `chain` source always took the general step, + about 480 instructions an item through both adapters. A `chain` whose + current source is a cursor with an item left, or whose next source is + a list or tuple with items (the spent cursor's release freeing + nothing), now steps in place for one-source adapters, so + `list(islice(chain(xs, xs), 4))` runs 10,011 instructions instead of + 13,365 (CPython 4,837). + - A Python descriptor with `__get__` but no `__set__` or `__delete__` + (a non-data descriptor, `functools.cached_property` among them) left + every read through its instances to the full path, since the + instance's own entry may shadow it: a read that ran its `__get__` + took 5,235 instructions to CPython's 924, and one that found the + cached value 936 to 409. The class attribute cache now records such a + descriptor beside the data descriptors, the instance's own entry + answers ahead of it in the in-place lanes, and on a certain miss its + `__get__` runs through the data descriptors' call lane (1,002 and + 395 instructions; a fresh object's first `cached_property` read + 11,087 to 5,952, against 3,899). + - `itertools.starmap` had no in-place step, so each item took the + general one (about 2,000 instructions). Over a list or tuple of + tuples with a callback that runs as a pure leaf it now steps as + `map` does: `list(starmap(operator.add, pairs))` of eight pairs + 18,403 to 8,135 (CPython 4,572). + - `dict(**d)` copied the keyword mapping the call had just built, + passing each key through a Rust string on the way. That mapping is + held by nothing else, so with all its keys exact strings it is now + the new dict (5,948 instructions to 2,367, against 2,443). An exact + string's `template.format(**d)` likewise formats from that mapping as + `format_map` does, in place, when its values render plainly (8,523 to + 7,013, against 3,943); every error stays the general call's. + - `getattr(obj, name)` with no default declined its in-place lane for + every built-in receiver, so `getattr(s, 'upper')()` took the full + call (3,013 instructions to CPython's 1,291). A string's or + container's method now binds in place as the attribute load binds it + (1,589). + - `member in SomeEnum` bound `EnumType.__contains__` to the class and + called the bound method generically; a metaclass's plain-function + `__contains__` is now called with the class directly, through the + dunder lane that evaluates pure leaves in place (4,455 instructions to + 2,718, against 1,141). + - Python 3.14's `heapq.nsmallest` and `nlargest` call the new max-heap + accelerators (`heapify_max`, `heapreplace_max`), which the native + body lane didn't list, so every call asked twice whether it could + take one and then went through the full call. They join `heappush` + and the rest, and a call site remembers a leaf builtin called + unbound the first time (`heapq.nsmallest(2, xs)` 27,568 instructions + to 18,258, against 11,260). + - A crash fixed on the way, present since before this PR: + `test_statistics.TestKDE` segfaulted in most runs outside the gate. + `statistics.kde`'s cumulative `cdf` runs `sum(W(...) for x_i in + supported)` from compiled callers; the generator's call of `W` put + its frame on the pending list before the lazily running callers + (`p_expected`, `cdf`) registered theirs above it. When `W` returned + the generator's entry wasn't on top and stayed behind, naming an + activation gone from the native stack, and a later flush wrote + through it (found with memcheck on a system-allocator build). An + entry now leaves the list from wherever it sits. + - `BytesIO.write` had an in-place half only for buffered file writers, + so every write to a `BytesIO` took the full native body (1,464 + instructions to CPython's 545); a write at the stream's end with + nothing exported now appends in place (850). `getvalue()` of an open + `BytesIO` or `StringIO` gets a leaf half too (1,097 to 922). + - `OrderedDict` is a Python class over a native order dict that starts + on the first store. The store's leaf half declined while there was + none, so every fresh `OrderedDict`'s first store took the full path; + it now starts the order in place (three stores into a fresh one + 12,212 instructions to 7,246, against 2,956). Construction from an + iterable unpacks an exact 2-tuple directly, the other shapes still + stepping as CPython's `odict` does for its errors (from a generator of + five pairs 47,414 to 36,109, against 10,146). `list(od)` of an exact + `OrderedDict` called its `len` and its `__iter__` through the generic + protocol and stepped the order's iterator; it takes the order's keys + at once now (8,647 to 3,392, against 2,437), and `list(od.items())` + and the other views take their entries likewise where every key looks + up natively (14,502 to 6,980, against 4,469). + - `obj.__dict__` reached the reader that answers it from the site's + memo only after a dozen other lanes (properties, class values, + published dicts) declined; a site that has read the managed dict + for the instance's class at its version now reads it first (811 + instructions to 255 in the container). `for k in d` over a plain dict + steps its keys directly once the iterator's watch is set, without + the views' and `OrderedDict`'s checks (20 keys 5,167 to 4,341). + - `SomeEnum(value)` ran `EnumType.__call__` and `Enum.__new__` in + Python for every lookup (`inspect.Parameter` converts its kind that + way, `re` its flags): 5,642 instructions for `Color(1)` to CPython's + 2,659. Where a class's metaclass `__call__` and its `__new__` are + `enum`'s own and it has members, a member of the class comes back as + it is, and a value that hashes natively is looked up in + `_value2member_map_` (the verdict and the maps remembered under the + class's and metaclass's versions); anything else is the Python + call's (`Color(1)` 1,530, `Color(member)` 960 to 2,521). + - A dataclass's `__eq__`, evaluated in place, read `other.__class__` + and `self.__class__` through the general instance-attribute + resolution each time; the in-place read answers `__class__` first + where `object`'s descriptor does (`dc == dc2` 2,362 instructions to + 1,944 in the container). + - `itertools.takewhile`, `dropwhile` and `filterfalse` had no in-place + step; over a list or tuple cursor with a predicate that runs as a + pure leaf they step as `filter` does, `takewhile` consuming the item + that stops it as CPython's does (`list(takewhile(lambda x: x < 3, + xs))` 8,673 instructions to 6,181 in the container). + - A compiled `for i, x in enumerate(xs)` stepped its pairs in place + but took its end through the general step, which in a generator + expression materialized the generator's frame shell and finished the + run in the general loop, once per generator. The end of a list or + tuple cursor now retires the iterator in place as those cursors' + ends do, detaching from the list where nothing its release frees + could finalize (`sum(i * v for i, v in enumerate(xs))` of five + items 8,697 instructions to 6,226 in the container). The core loop's + `enumerate` arm ends in place the same way (`_strptime`'s loop). + - The battery's slow-step census (`WEAVEPY_BURST_STATS=1` over every + case) showed slices of `bytearray`s and of `str` subclasses (`re`'s + `_plain_slice` over `email`'s header tokens) taking the full step at + every call. The core loop's slice arms take a `bytearray` (a new + one), and a `str`, `list` or `tuple` subclass keeping its base's + `__getitem__` (the base's exact slice, as CPython's). `str.encode`'s + leaf half reads a `str` subclass's text too (`email.utils`'s + `_has_surrogates` over header values), and the core loop's + `GET_ITER` iterates a `list` or `tuple` subclass's payload when its + class inherits the base's `__iter__`, as compiled code already did + (`email`'s token lists). `os.stat`, `lstat`, `fspath`, `getcwd`, + `access`, `listdir` and `locale.setlocale` join the native-body lane + (through the interpreter's call, for a path-like's `__fspath__`), so + a call no longer takes the full step and its frame shell + (`os.path.exists(p)` about 4,000 instructions fewer, 1.34 to 1.12 of + CPython's; `locale.getlocale()` 1.24 to 1.05). So do `fsdecode`, + `fsencode` and `dir`, the hash constructors and `zlib`'s functions, + `sys.audit`, `weakref`'s dead-entry callback, `json`'s encoder + constructor and the import system's module locks, the rest of the + census's builtin calls (`hashlib_zlib` 1% fewer instructions, + `file_small_open_close` 2%, `os_stat_exists` 12%). `with open(p) as + f` loaded the file's `__enter__` and `__exit__` through the full step; + `LOAD_SPECIAL` takes a native file's own methods in place (another + 1.5% of `file_small_open_close`). A function-level `import m` or + `from m import x` of an imported module, in place in compiled code + already, is the core loop's helper's too, for interpreted callers + (`shlex.__init__`'s imports at every construction). + - A loop over a Python iterator class whose `__next__` isn't a leaf + (`email.feedparser`'s `BufferedSubFile`) took the full step for + every item, compiled code exiting to the core loop to take it. The + `FOR_ITER` lane calls such a `__next__` with the activation waiting + on the pending list, its `StopIteration` the loop's end, and compiled + code takes the lane in place (`Parser().parsestr(msg)` 8% fewer + instructions). + - Tier 2's item store into an exact dict went through the generic + store and rechecked every guard afterward, where its item read had a + leaf path; a store by a key that hashes and compares natively now + goes straight into the dict (`d[k] += 1` in a compiled loop 1,276 + instructions to 1,024, against 743). + - `defaultdict` construction and misses ran its native `__init__` and + `__missing__` through the generic paths: `defaultdict()` 4,817 + instructions to CPython's 1,484, a miss 6,888 to 2,105. The exact + class's plain calls build the instance in place through its own + constructor hook, which the native-constructor lane now consults for + Python classes too, and compiled code's item read stores and returns + a miss's value where the factory is a common builtin type, as + `__missing__` does (1,972 and 2,720; `defaultdict(list)` with one + miss 11,452 to 4,034, against 3,192). `OrderedDict()` of the exact + class, whose `__init__` does nothing without arguments, builds through + the same hook (2,983 to 1,636, against 1,049), and so does + `functools.partial(func, *args)` over a callable that isn't itself a + partial, laid out as its native `__new__` lays it (4,837 to 2,317, + against 1,801), and `deque()` and `deque(xs)` of a list or tuple, laid + out as its `__init__` lays it (3,713 to 1,960 and 5,694 to 2,326, + against 2,283 and 4,228). + - `email`'s header parsing ran three of its common steps through the + full handler on every call. A compiled pattern's `findall` declined a + str subclass's instance (the parser's tokens), so `_validate_xtext` + cost 43,662 instructions to CPython's 2,945; `findall` and `split` + now read the instance as its string and return exact strs, as + CPython's slices do (2,671). `super().value` of a property built the + super proxy each time; the getter now runs as an inline activation in + the core loop and as a direct call from compiled code, its site + remembering the property for the receiver's class (6,885 to 2,106, + against 1,201). The core loop's subscript arm had slice cases for + `bytearray`s and str, list and tuple subclasses that its own type + check never let through, so `token[:]` took the slow step (2,895 to + 1,718, against 831). Setting a `From` header on a new message went + from 1,092,000 instructions to 941,000 (CPython 553,000). + - A getter like `return list(self.defects)` stopped evaluating in place + once its leaf plan compiled: the compiled plan's call step lacked the + interpreted plan's builtin-constructor case, so every call declined, + and 64 declines in a row withdraw a function's leaf verdict for good. + With the case added, the read costs 1,683 instructions instead of + 1,944 (CPython 1,089). Inside a generator's step, which can't call a + getter that runs as an activation, the miss had also walked every + other attribute read before declining; it now declines at once. + Together, `sum((x.all_defects for x in xs), [])` over four items went + from 36,700 instructions to 14,800 (CPython 7,700). `sum()` of lists + extends the list it built after the first item instead of building a + new one per item, as the intermediate totals are unobservable. + - `os.walk` stepped its directory listing with `next(scandir_it)` + through the general call; `next()` now steps a scandir iterator in + place, and `os.scandir` takes the builtin lane (a warm walk of a + 42-entry tree from 764,000 instructions to 738,000, against 565,000). + A walk's remaining time is mostly system calls. + - Only about half of the linker order file's names still matched the + binary's functions, so start-up on Linux touched 10.5 MB of code (the + kernel maps 64 KiB around each page a fault touches) and peaked at + 17 MB against CPython's 9. Extending the order with callgrind + profiles of start-up, import mixes, the bench fixtures and ten + battery cases (`scripts/extend-order-file.py`) halves the resident + code: peak RSS goes from 17.1 to 12.0 MB at start-up and from 23.6 + to 17.4 MB after importing `json`, `re` and `collections`, and + start-up is about 3% faster. On macOS, which faults single pages, + peak RSS drops 2-4%. + - `inspect.signature` read a function's `__defaults__`, + `__kwdefaults__` and `__code__`, and probed the names it lacks + (`getattr(func, "__signature__", None)`, `hasattr(func, + "__wrapped__")`), through the full attribute lookup. The fields now + read in place, and a miss the full lookup found on a function that + stores nothing under the name is remembered on the function type + (`inspect.signature` of a one-parameter function from 105,600 + instructions to 87,100; `f.__defaults__, f.__kwdefaults__` from 4,870 + to 2,733, against 1,136). + - Compiling a regular expression that isn't in the on-disk program + cache cost about 2.7 million instructions per pattern, against + CPython's 580,000. Three steps took the general paths every time: + `int(c)` over the program's named opcode constants (an `int` + subclass), `charmap[i] = 1` on the charset's `bytearray`, and + iteration over the parser's `SubPattern`, which has `__getitem__` but + no `__iter__`, so each item went through the sequence protocol's + Python iterator and a Python `__getitem__` call. `int()` of an `int` + subclass that keeps `int`'s `__int__` now answers in place, the core + loop stores bytes into a `bytearray`, and `SubPattern` iterates its + list (400 uncached patterns from 1,101 million instructions to 930 + million, against 233 million: the parser's two largest functions + still run interpreted). A start-up also no longer calls `globals()` + 195 times in `posix`'s re-export loop (0.9% of its instructions). + - Compiled code read a receiver that isn't a local (`p.x` of a global) + through a slower helper than a local's: a `__slots__` member, a + class's plain value through an instance, and a named tuple's field + were each found only after the helper had tried the other kinds. The + stack helper now checks the slot the site recorded and, first, the + class value and field its local twin checks (a loop reading a global + slotted instance's field from 520 instructions an iteration to 251, + a class value from 390 to 302, a named tuple field from 699 to 288; + CPython 282, 278 and 417). A `functools.partial` call found its + fields by comparing their names on every call; it now remembers the + slot layout as `deque`'s methods do (1,870 instructions a call to + 1,693, against 939). + - A `for` loop over a generator first tries the generator's native + step, which has no switch and so can't call Python code: a body that + subscripts an object with a Python `__getitem__` (as + `collections.abc.Sequence.__iter__` does, behind `x in path.parents`) + stopped partway at every item and finished on the general path. A + body whose steps keep stopping now skips them, and the loop resumes it + through its switched path, which calls the method directly (one step + in 256 retries). A five-item generator of that shape went from 33,800 + instructions to 19,500 (CPython 7,600) and `Path.relative_to` from + 337,000 to 303,000 (169,000); the lazy resume's own cost is most of + what's left. + - A struct sequence (`os.stat_result`, `time.struct_time`, + `sys.version_info`, `os.terminal_size`) keeps its fields in its + instance dict, but its class answers each name with a property whose + getter is a native function, so `st.st_mode` was a descriptor call + through the general attribute path. The attribute caches now treat + those properties as the instance's own field, the fields' keys are the + interned names compiled code holds, and the type rejects `del` of a + field as CPython does ("readonly attribute"). A struct sequence + compares with a tuple as its own tuple, without a method call. Reads + went from about 2,100 instructions to 500-800 (CPython 270-390) and + `sys.version_info >= (3, 8)` from 3,740 to 2,310 (700). + - `shutil.get_terminal_size()`, which argparse's help formatter calls + for every formatter it makes, cost 62,600 instructions against + CPython's 29,500. Three of its steps left compiled code: the + `os.environ` misses (`_Environ.__getitem__` subscripts a dict keyed by + `bytes`, whose missing key only the interpreter raised), the + `OSError` from `os.get_terminal_size()` (a builtin the core loop + didn't call in place), and `os.terminal_size(fallback)`, which went + through the general class call into the type's `__init__`. A missing + `bytes` key now raises where the code catches it, the call runs in the + core loop's lane, and a struct sequence built from a tuple or list of + plain values is made directly (6,000 instructions to 3,640, against + 1,930). The call as a whole now costs 49,300. + - Releasing containers. A dying dict dropped each key and value through + a call to its drop glue, even an `int` key, and a list did the same for + each item unless all of them were scalars; a tuple from the free list + was refilled through checks a parked tuple can't fail. A dict now + gives each entry up in line (a plain decrement for a value someone + else still holds), a list does the same for items it doesn't own last + (a dying one still goes through the nested release), and a pooled + tuple's slots are written directly. `d.copy()` of a 100-entry dict + with its release went from 8,270 instructions to 5,010 (CPython + 4,400), `dict(d)` of 20 entries from 3,080 to 2,500 (1,910), + `list(t)` of 100 strings from 5,810 to 3,760 (4,490), and a loop over + `enumerate` of ten items from 6,400 to 5,760 (4,120). + - Dunder reads that took the full attribute lookup. A never-raised + exception's `__traceback__`, `__cause__` and `__context__` are unset + slots, which the slot reads in compiled code and the interpreter + declined, so each read cost about 4,000 instructions (CPython 200); + they now answer the slot descriptor's default. A bound method's + `__self__`, `__func__`, `__name__`, `__qualname__` and `__doc__` read + in place (1,690 instructions to 490 compiled, 1,750 to 615 + interpreted, against 530), and `cls.__qualname__` joins the per-site + memo `__name__` has, now that assigning it moves the class's version + (1,380 to 230, against 420; interpreted, the core loop reads a class's + names directly, 1,700 to 1,080). `cls.__mro__` and `__bases__` still + build a tuple per read (3.4 and 4 times CPython's cost) because + keeping one on the class needs the collector to see it. + - A class now keeps the tuples `__mro__` and `__bases__` read as, while + its links stay the same (the collector visits and clears them with the + MRO), so `C.__mro__ is C.__mro__` as in CPython and a read no longer + allocates (1,480 instructions to 1,090 compiled, 1,100 to 760 + interpreted). + - Native code calling back into Python. `max(xs, key=attrgetter("x"))` + called the getter through the general call, a bound method for each + item, where `sorted` already evaluated such keys in place; `min` and + `max` now do too (25,750 instructions for ten items to 8,960, against + 5,350; `itemgetter` 18,500 to 4,870, against 3,970). A dict or set + store of a key whose `__hash__` is Python (an `Enum` member, a frozen + dataclass) left compiled code at every store, and every hash ran a + reentrant call; a `__hash__` that evaluates as a pure leaf now runs in + place, and compiled code stores the key with that hash when it meets + the entry by identity or the slot is free (`x[Color.RED] = v` 3,780 + to 1,500, against 1,230; a ten-entry dict comprehension of such keys + 35,900 to 16,700, against 10,300). + - `"%r" % x` sent every `%r` through the general conversion, which + formats through a spec with alignment even for a bare `int`; an `int`, + `bool`, `None` or `str` now renders in place (`"P(%r)" % 5` from 2,820 + instructions to 1,140, against 1,730). A container's repr found each + item's Python `__repr__` by walking the class's MRO and called it as a + bound method; it now calls the memoized function directly, and a + pure-leaf `__hash__` is tried before the native kinds' checks + (`repr(p)` of an instance whose `__repr__` is `"P(%r)" % self.x` from + 6,230 to 4,500, against 2,390; `set(xs)` of ten such keys from 22,500 + to 19,700, against 8,800). + - `functools.cmp_to_key(f)` built a new class for every call (the + pure-Python fallback's, which the native function forwarded to), so + `sorted(xs, key=cmp_to_key(f))` of ten items cost 253,000 instructions + against CPython's 18,000. It now returns a key factory of one shared + class. And `self._cmp(a, b)` in that class's methods, a call of a + function a `__slots__` member holds, left compiled code at every call: + the method load now reads a laid-out slot member and remembers its + position. The sort now costs 88,000 instructions; CPython's C key + wrapper makes no Python calls but `f`'s, which the rest of the gap + is. + - Native modules that call back into Python (`bisect`'s `key`, about a + hundred other call sites) went through `Interpreter::call_object`, + the embedder's entry, which publishes the interpreter and activates + its thread handles (cloning four of them) for every call. From a frame + of the same interpreter both are in effect already, so the call goes + straight on (`bisect_left` with a `key` over a 34-item list from + 8,090 instructions to 6,310, against 4,050). Every comparison of two + instances also paid 28 instructions to rule out a struct sequence; + only instances of builtin classes check now. + - A memory leak: every `threading.Thread` (each makes a + `_thread._ThreadHandle`) left its handle's state, a lock among it, in + a process-wide registry that nothing ever removed from, so a program + that keeps starting threads grew without bound and paid an ever larger + map's inserts. The registry now holds the states weakly (the handle's + methods keep them alive) and sweeps dead entries when it doubles. + - Iterator classes written in Python. `next(it)` of one went from the + compiled call site through the builtin's full call path to a bound + `__next__` call, about 900 instructions more than a `for` loop's step + of the same iterator; it now steps a frameless `__next__` as `FOR_ITER` + does (`self.i += 1; return self.i`: 2,046 instructions to 1,574, + against 1,124). And a bare `raise StopIteration` that ends a + frameless `__next__` built and unwound the exception through a full + call: when a `for` loop, `list()` or `next(it, default)` is the + catcher and nothing could see it (no store buffered, no tracer), the + step now reports the end itself. Ending a loop over a used-up + iterator went from 7,600 instructions to 1,700 (CPython 3,240), a + 20-item loop over a fresh one from 1,424 an item to 1,082 (1,080), + and `list()` of it from 1,635 to 1,332 (1,107). + - The frozen `itertools` classes' `__next__` (`return + next(self._core)`) is now native, so `c.__next__()` of a `count`, as + `threading` names its threads, costs 850 instructions instead of + 2,783 (CPython 554). Their `__iter__` returned the native core rather + than the object, so a subclass's own `__next__` was skipped by `for` + loops and `islice`; it returns the object now, as CPython's do. + - `reversed(s)` of a string took the general type call, which built + a new native constructor object for the call and released it again + (taking the descriptor registry's write lock on the way out, though + its comment promised a read probe), and copied the characters one + `chars()` step at a time. Its pure constructor now admits `str` and + `bytes`, the type-call path reuses one constructor per type, the + registry's release probes under the read lock first, and an ASCII + string's characters are copied by index: `reversed(s)` from 4,158 + instructions to 1,557 (CPython 907), `''.join(reversed(s))` from + 7,547 to 4,984 (4,340). + - An `accumulate` without a function ended each loop through the + general step (its pure step declined at the end): it now ends in + place, as `zip`'s does (`for` over five items 5,297 to 4,155 against + 2,600), and so does a `pairwise`. A compiled `list(x)`, `tuple(x)`, + `set(x)`, `dict(x)` or `str(x)` whose pure constructor declined (`x` + a `map`, a generator) tried the same attempt again and three more + before reaching the container lane; it goes there directly now, about + 380 instructions a call (`list(accumulate(xs))` 6,837 to 5,643 + against 3,147, `list(pairwise(xs))` 8,105 to 6,837 against 3,760). + - `yield from xs` of a list in compiled code left at + `GET_YIELD_FROM_ITER` and at the delegation's end in every generator: + a three-item one cost 12,515 instructions against 2,303. Compiled code + now takes a builtin sequence's iterator in place and steps a list's or + tuple's cursor without leaving (5,734, the same as the equivalent + `for` loop of yields), and a class whose `__iter__` is such a + generator iterates in 6,299 instructions instead of 13,055 (2,538). + - Keyword calls of the `itertools` classes (`product(xs, repeat=2)`, + `accumulate(xs, initial=0)`) left compiled code at `CALL_KW` and bound + their keywords through the general call, about 2,700 instructions: + the adapter is now built in place (5,945 to 3,074, CPython 3,354). + The combinatoric adapters also build each tuple straight from its + items, without an intermediate vector (`list(product(xs, xs))` 12,046 + to 9,524). + - `iter(obj)` of a class with a Python `__iter__` looked the method up + twice uncached and called it as a bound method; it now calls the + cached function directly, as `for` loops do (3,159 instructions to + 2,273, against 1,284). `struct.unpack` was a Python wrapper over the + native one; like `pack`, it now reads a `bytes` or `bytearray` buffer + natively and keeps the wrapper for other buffers and errors (2,088 + to 1,229, against 1,061). + - A dict iterator under `zip` or `enumerate` (`heapq.nlargest(n, + d.items())`, as `Counter.most_common` calls it) took the general + step for every item, since only sequence cursors counted as ready to + step in place. A dict iterator past its first, checked, step now + counts too while its dict is unchanged (`zip(range(3), it)` over a + dict's items 15,122 instructions to 12,227, `most_common(3)` 38,153 + to 33,766, against 18,348). + - `isinstance(x, C)` for an ABC `C` asked, on every call, whether the + metaclass keeps `type`'s `__instancecheck__`, by a string lookup + through its MRO; the answer is now remembered per metaclass version + (`isinstance(o, Base)` 1,238 instructions to 1,009, against 2,179; + `issubclass(Impl, Base)` 2,442 to 1,922, against 2,052). A + class-like instance's plain Python `__instancecheck__` or + `__subclasscheck__` (the `typing` aliases') is called directly rather + than as a fresh bound method (`isinstance(i, typing.Hashable)` 8,130 + to 7,753, against 4,649; the rest is its two Python calls). + - A compiled `obj.attr = value` stored in line only over a scalar; one + that replaced an object (`node.next = other`, `self.current = node`) + took a helper, about 124 instructions more, even when another owner + kept the old value. The in-line store now gives the old value up by a + plain decrement when it isn't the last reference. A site that first + added its attribute (a loop's first pass) settled on appending and + took the helper for every later pass's replacement; it now replaces + in line too. Replacing an object in 100 instances went from 30,957 + instructions to 17,297 (CPython 17,669), and a second pass's stores + from 54,605 to 29,666 (29,001). + - Fixed: the core loop's instance attribute stores left a finalizer the + replaced value queued for the next safe point, so `holder.d = + Dying()` ran the old object's `__del__` one statement late (at the + next call) in every tier. + - `dict(x)` from compiled code reached the general type call after the + container lane declined it; the lane builds it now (a mapping, a + lazy iterable of pairs, or an eager container). + - A function's first call decides whether it is a frameless leaf; the + decision allocated four vectors to walk the body, about 1,000 + instructions of a first call's 6,000 (CPython's first call costs about + 150). It walks the body (at most 64 instructions) in stack buffers + now, and only generator-shaped code scans its body for a generator + start: a first call of a fresh function went from 7,937 instructions + to 6,611. The rest is building the code's tables and the first pass's + site caches, which CPython does when it quickens the code. + - Fixed: the frozen standard library's code cache named its artifacts by + module alone, so two builds whose embedded sources differ (a merge + base and a PR in the bench gate, a developer's branches) recompiled + and replaced each other's artifacts at every start, about 14 million + instructions a run (it also made whole-process A/B counts of two + builds misleading). Artifacts are now named by module and source + hash, and a write removes the module's day-old artifacts for other + sources. + - Stepping an instance whose class has a native `__next__` (an + `io.StringIO` under `csv.reader`, a `for` loop over one) looked the + method up by name on every step; it is found once per class version + now. The CSV reader also updates its per-row state (`line_num` and + its re-entry flag) in place rather than re-inserting it: reading 200 + rows went from 1,568,659 instructions to 1,482,021 (CPython 912,416). + - Fixed: a `StopIteration` thrown into a generator that never started + was converted to `RuntimeError`; CPython's PEP 479 conversion covers + only the body past its start, so it escapes as it is there. + - `setattr(obj, name, value)` of an attribute already there interned + and hashed the name and stored it through a dictionary insert; it now + replaces the value at the position it found (1,193 instructions to + 891, against 726). Fixed alongside: when the replaced value was its + last reference, its `__del__` ran one statement late; that case now + takes the full path, which runs it at once. + - `format(x, 'g')` (and `%g`, the type-omitted form with a precision) + copied the digits through four strings; it lays them out from the one + scientific formatting and strips zeros in place (3,850 instructions to + 3,283, against 2,416). A test pins the output for 6,000 values and 15 + specs to CPython's. + - A compiled `len(obj)` site whose leaf half declined an instance went + through the builtin's lane to reach a frameless `__len__`; it + evaluates it in place now (1,670 instructions to 1,245, against + 1,004). Operator and subscript dunder calls enter a warm leaf's + compiled plan rather than its interpreted one. + - The bench gate's A/B legs ran in a fixed order, PR, base, CPython, + so every PR sample followed another program's run and every base + sample a near-identical one's; a PR that changed no code could fail + it, and this PR's Linux gate flagged `fib` and `richards` three runs + in a row while both builds executed the same instruction counts with + the same simulated cache misses and branch mispredictions (the PR's + slightly fewer). The legs now run in a balanced order (PR, base, + base, PR, then the mirror), two samples each a round. + - Where the everyday battery's worst cases stand, measured on + `argparse_ops` (2.1 times CPython's instructions): its 60 iterations + are 85% warm-up. In steady state an iteration costs 2.1M + instructions against CPython's 1.5M (1.37 times); iterations 2 to 60 + average 4.8M against 1.7M. Interpreted, an iteration costs 2.9M (the + core loop averages 39 instructions a bytecode: its pc and + instruction pointer live on the stack, so dispatch alone is about + ten), and through iteration 60 the JITs add about 1M an iteration + more than they save: tier 2's analysis of code it then rejects is + about 8% of the case, the frame JIT's compiles 2%. `import argparse` + costs 30M to CPython's 11M, spread over decoding cached code, + interning its names and running module bodies, with nothing over + 3%. + - A sweep of 198 more single statements (string, `re`, dict, list, + call, `os.path`, `pathlib`, `datetime` and small standard-library + operations) reads a geomean of 0.95 times CPython's instructions. + From its tail: tier 2's generic `BINARY_OP` helper always took the + interpreter's full operator dispatch, where compiled frames have + direct helpers; it now builds two lists' or tuples' concatenation, two + dicts' union, sets' algebra and `bytes` concatenation off its + borrowed operands (`xs + [y]` in a loop 2,992 instructions to 2,251, + against 1,461; `d | e` 3,261 to 2,340, against 1,727). `len()` of a + range joined the builtin's fast half (2,026 to 1,053, against 980), + and `dict(mapping, **kw)` copies the mapping once and interns its + keyword names (4,329 to 3,712, against 1,560; the keyword call's own + route is the rest). + - Fixed: compiled code's check that an attribute certainly misses (ahead + of calling `__getattr__`) probed the instance dictionary with a + comparison that runs a colliding key's Python `__eq__`, from a + frameless activation: the `__eq__` saw its caller's caller in + `sys._getframe`, and ran four times a lookup instead of once. The + probe now runs no Python and leaves such a dictionary to the full + lookup. This was the bug that a stricter generic-share limit for tier + 2 had exposed; that limit still isn't adopted, since it now costs + the `nbody` fixture 38% (tier 2 runs its boxed float arithmetic + faster than the frame JIT does). + - Tier 2's analysis runs on the thread that runs the program, and a + trace of `argparse` building and running a parser 180 times + (`WEAVEPY_JIT_TRACE=1`, about 200 ms in all) showed 44 ms of it + there: 104 functions analyzed to compile 12 trivial ones. Three + things cut that to about 20 ms (5% of the battery case's + instructions, with the bench fixtures unchanged): + - A method site that doesn't resolve types the method's body, a + whole analysis of its own, and the answer wasn't kept: the analyzer + asked again on every pass over every such site (12 analyses of one + callee in a 22-instruction function). An attempt now remembers + the sites that didn't resolve, as it did those that did (44 ms to + 32). + - An analysis starts over for each loop it carves out, each retry + with other assumptions and each callee it types, and nothing + bounded the product: `_parse_known_args2`, 169 instructions, took + 160 passes an attempt, twice. Each attempt now has a work budget, + counted in instructions passed over: 1,024 units and eight passes + over the code itself, plus what the code's own calls and loop + iterations have paid for (one unit for every eight). The costliest + kernel among the bench fixtures uses half its allowance. An attempt + that runs out stands as a rejection, so the frame JIT takes the + code at once; code whose calls run long loops (16 iterations a + call) waits instead, interpreted, until its work pays for twice the + budget. `WEAVEPY_T2_FREE`, `WEAVEPY_T2_PASSES` and `WEAVEPY_T2_WPP` + set the three numbers. + - The plan's set of jump targets is a bitmap instead of a hash set + built on every pass (the hottest line of the analysis; 1.2% of the + case). + What's left is mostly the cost of running the analyzer cold: about + 150 microseconds an attempt, most of it instruction-cache misses in + code that last ran thousands of calls ago, on 100 attempts that + reject. Cheaper rates were tried and cost the short numeric fixtures + too much (work alone paying for analysis: `spectral_norm` 2.1 times + slower, `nbody` 1.7), as did a budget summed over a function's + attempts (`difflib`'s `find_longest_match` compiles on its second + loop entry, after a first that fails). + - A field of a natively served value (`dt.hour`) has no site memo, so + every read takes the compiled site's slow path, where two lanes + added on this branch (a bound native method's memo, a property's + cached getter) had gone ahead of it: the `datetime_ops` fixture ran + 4.7% more instructions than the merge base on Linux. The native + field is read first again (352.5M instructions to 340M). + - Fixed: the `generators` fixture ran either 667M or 763M instructions, + run to run, on any build (and always the higher with synchronous + compiles), which the bench gate read as a regression one run in two. + `sum(gen)` drains a generator's whole body in one step; the body gets + hot and compiles during that step, and its native code needs more + value-stack room than the step had sized the stack for. Every native + entry was then turned away, and after 32 at one instruction the entry + was given up for the rest of the run; how many entries were lost + depended on where the step's periodic check happened to end it. The + step now grows the stack when the native code arrives, and an entry a + small stack turned away no longer counts against the entry (680M in + every run of a quick build, 673M synchronous). + - A compiled attribute read keeps two classes' field positions in line + and up to four more in the site's table, but the table was consulted + last: a third class's read went through the whole miss chain (the + property, class-attribute and descriptor lanes, then the table, then + an attempt to memoize the value as a class attribute, which a field + never is) at about 1,000 instructions. `argparse` reads `action.dest` + and its neighbors over three action classes: 120 such reads an + iteration, 7% of its steady state. The table is now the first thing + the slow path tries for an instance (an entry is for a class version + at which the name resolved to the instance, so nothing ahead of it + would answer otherwise): 1.908M instructions an iteration to 1.796M. + - `getattr(cls, name[, default])`, which `inspect`, `typing`, `functools` + and `dataclasses` call on every object they handle, cost three to + four times CPython's instructions whenever the answer wasn't a plain + hit: a missing name with a default (`getattr(cls, "__wrapped__", + None)`) 1,761 against 579, `getattr(cls, "__name__")` 2,444 against + 558. Each call classified the name against two lists of dunders by + comparing strings (some forty comparisons), asked `type` itself for + the name, walked the class's MRO three more times, and for + `__name__` gave up and took the full call. Now the two lists are one + hashed table, `type`'s answer is remembered by name, `__name__` and + `__qualname__` are read where they live, and the whole answer is + kept for a class under plain `type` by its attribute version and the + name object. The memo owns only scalars and builtin functions; any + other value it borrows from the Python class whose dictionary holds + it, so a value a class drops dies when it does. All six shapes + measured now cost 610 to 630 instructions (CPython 560 to 600); in + the `inspect_typing_ops` case this helper was 6% of the instructions. + - Programs with a second thread. The battery's slowest case on a + profile-guided build is `threading_queue_ops` (2.6 times CPython's + time): a thread started and joined costs 180 microseconds against + 60, and an item handed to a worker through a `queue.Queue` 20,900 + instructions against 14,200. In the hand-off, `Condition.__exit__`'s + `self._lock.__exit__(*args)` read a native method off a temporary + and found the site's memo, then threw the answer away: the receiver + could only leave by a plain decrement, which is never allowed once + reference counts are shared between threads, so each read went on + through the whole miss chain (1,750 instructions, twice an item). + The read now releases the receiver as the core loop releases any + operand when the plain decrement doesn't apply: 22,200 instructions + an item to 19,300. + - What a second thread costs everything else, measured by running + single-threaded battery cases with one idle thread alive: 13% to 55% + more cycles (`list_dict_basics` 13%, `collections_ops` 26%, + `class_features` 34%, `enum_dataclass_ops` 55%), where CPython's + don't move. Keeping reference counts plain in an experiment took + back four fifths of it, the borrow counters' bias the rest: counts + go atomic for every thread as soon as a second one registers (a + locked increment or decrement costs about twenty cycles on x86), and + compiled code's in-line releases and clones, which test that flag, + call their helpers instead (5% to 20% more instructions). Under the + GIL the counts could stay plain if no thread ever touched one + without holding it; that isn't established today (118 blocks run + with the GIL released, and a thread's start and its thread-local + state's teardown run outside it), so it is the next piece of work + of its size rather than a change to make in passing. + - First steps toward plain counts with several threads. An audit build + (a check, in the shared-count paths, that the updating thread holds + the GIL) run over the thread tests found no update outside the GIL + while a program runs, and two places at its edges. The main thread + gave the GIL back when the main module returned and ran + `threading._shutdown`, the exit handlers and the finalizers without + it, beside daemon threads that still held it: it now holds the GIL + from the main module through shutdown, as CPython's finalization + does (a join inside gives it up while it waits). And a thread's + thread-local caches were dropped by its destructors after it had + given the GIL back: its entry in the traceback dumper's registry + (its frame and exception stacks) and its interned names are now + released by the worker while it still holds the GIL, and the + docstring cache, the static-string table, the empty tuple and the + `getattr` memo take the GIL to drop. The sixty-odd other + thread-local caches that hold objects or strings (class handles, + key tables, registries, memos) now take it too, and the command + line's run holds the GIL from before the interpreter is built until + it is released. With that, the audit over 24 groups of CPython's + tests (threads, queues, futures, asyncio, sockets, subprocesses, + multiprocessing, the C API) records no update outside the GIL by + any thread while it lives, and none at a worker's exit; what is + left is the main thread's last steps after the run (reading the + exit status off the exception, its own destructors at process exit) + and a fatal-error dump from a foreign thread. Still to do before + counts can stay plain with several threads: those last steps, the + same audit on Linux and Windows (their blocking calls differ), a + flag of its own for "other threads exist" (the shared-counts flag + stands in for it in two places), and a test job that runs the audit. + - Reference counts stay plain with several threads. Under the GIL a + count needs no atomic update as long as every thread that touches an + object holds the GIL while it does, and that now holds by + construction: a worker takes the GIL before its first touch of an + object and keeps it on its guard stack through its thread-local + destructors (the stack is the first thread-local the thread uses, + so the last one destroyed), and no block that runs with the GIL + released builds or drops an object (all 118 were read; one, a + blocking `channel_send`, built its exceptions and dropped a + withdrawn item inside the block, and now hands the outcome back + out). Counts turn atomic, under the GIL, only when something will + touch one outside it: free-threading, a thread the VM didn't start, + the traceback watchdog, or a thread whose outermost GIL scope ends + while others still run (an embedder reading a result, the command + line's last steps beside daemon threads). Windows keeps atomic + counts until its blocking paths get the same audit, and + `WEAVEPY_ATOMIC_COUNTS=1` restores them anywhere. "Other threads + exist" is a flag of its own now, for the three places that asked + the shared-counts flag that question (frames made whole before a + blocking call, retired code objects, pickle's pins). An audit + build that checks the GIL at every count update ran over 36 groups + of CPython's tests and the bundled thread tests with no plain + update outside the GIL, on macOS and on Linux. On a release build + one idle thread now costs the four battery cases measured before 3% + to 8% more cycles (`list_dict_basics` 3%, `enum_dataclass_ops` 4%, + `class_features` 5%, `collections_ops` 8%) where atomic counts + cost 12% to 30%, and an item through a `queue.Queue` with three + consumers 19,300 instructions to 16,800 (CPython 14,200). What is + left is the cell borrows' lock word, which a second thread still + turns on. + - A thread back from a blocking call waited two switch intervals for + a busy thread, and `sys.setswitchinterval` changed neither. The + hand-off wants both clocks run out, the holder's turn and the + waiter's wait, but the waiter's only started at the first + checkpoint after the holder's had expired: 10 ms where CPython + waits about 6. The two now run side by side, and the interval a + program sets is the one the checkpoints use: 5.2 ms at the default, + 0.2 ms at 10 microseconds (CPython 6.2 and 0.18). A test that + sleeps beside two busy threads took 21.5 s and takes 0.23 s + (CPython 0.29 s). + - A thread's interpreter shares its parent's table of leaf builtins + instead of copying it (two hash maps and a vector of handles built + at each start and dropped at each exit, a twentieth of a start and + join). Starting and joining a thread: 522,000 instructions to + 463,000 with the change above (CPython 192,000, kernel included; + in user space the cost is spread over the thread module's Python, + a fresh allocator heap and interpreter for each thread, and their + teardown). + - Cell borrows stay lock-free with several threads too. A borrow took + its cell's lock word (a compare-exchange, a thread-local read and a + release store) from the moment a second thread registered: 93,000 + locked instructions a call of `collections_ops` with an idle thread + alive, all of them these. Under the GIL the lock word orders nothing + the GIL doesn't, and the borrow counter alone keeps a shared and an + exclusive borrow apart, across threads as within one, so borrows + now take the lock only once some thread may touch a cell without + the GIL (the cases that turn counts atomic). The count of live + lock-free guards, which decides whether a thread may hand the GIL + over at a checkpoint, is the GIL holder's: a thread's own leave it + when it really gives the GIL up and return with it. The lock word + was also a deadlock: a thread blocked inside a set's membership + test (its `__eq__` sleeping, writing or taking a lock) held the + set's word, and another thread adding to the set spun on it with + the GIL held, forever. Now the add waits for the first thread with + the GIL released and then happens (CPython lets it through at once; + the deferred-operation path that covers a nested mutation would + have dropped it). The audit build, which now checks the GIL at + every lock-free borrow as well, found none outside it over 45 + groups of CPython's tests on macOS and the thread modules on Linux. + One idle thread no longer shows in the four cases: 0% to 0.6% more + instructions, cycles within the 2% the runs spread over (3% to 8% + more cycles before this, 13% to 55% two days ago). + - A lock's waiter is handed the lock. Past five milliseconds a + contended `Lock` or `RLock` acquire waited on the lock itself, GIL + released, and got it only by waking in the gap between the + holder's release and its next acquire. That gap is a few bytecodes, + and it shrank as threaded code got faster: the first acquire + against a holder that retakes the lock at once went from 10 to 40 + ms to 80 to 450 ms, and the hand-off test started to fail one run + in three. A release now keeps the lock for a waiter that is past + its turn (nobody else can take it meanwhile), as CPython's lock + hands itself to a waiter of over a millisecond, and the waiter goes + from its grace period to that wait without coming back for the GIL: + 5 ms for that first acquire (CPython 6 to 8). + - A method that adds to a `__slots__` member runs in line. Tier 2 ran + `self.a += 1; return self.a` in line only when `a` was an instance + dictionary field; for a slot member each call went through the + method helper (538 instructions against 128). The in-line form now + covers a member slot of a class whose instances have no dictionary: + 126 instructions, a slotted `tick()` loop 4.2 times as fast. + - Tier 2 keeps loops whose attribute traffic it handles in line. Its + admission rule left any loop with more attribute operations than + typed ones to the frame JIT, on the grounds that each attribute + access costs tier 2 a helper call. Scalar fields of split-layout + instances and laid-out slot members have been read and written in + line for a while, so those accesses no longer count: the + `attr_access` fixture's loop runs 1,183 instructions an iteration + in tier 2 against 1,333 in the frame JIT (362 cycles against about + 400; CPython 3,329 and 1,115), the fixture 0.885 of its + instructions. Both figures are still a hundred instructions an + attribute operation: each access redoes its receiver's guard chain + (about 60 instructions), and the two string field reads go through + a helper (172 each); the next entry takes those on. + - Tier 2's attribute accesses check less each time. Three cuts in + the in-line path, measured on the `attr_access` fixture's loop (two + scalar reads, two float fields read and rewritten, two `tick()` + updates, two string fields compared): + a string, bytes or object field that still holds the value its site + read last finds that value's pin again in line (the helper's own + first answer, 172 instructions each time before): 1,182 to 972 + instructions an iteration; + an instance validated by one access of a local's field (an instance + pin with no published dictionary, its values split over its class's + names) stays validated for the accesses of that local that follow + in the block, through in-line stores and field updates too, until + something that can run code or reshape it (a helper's store, any + other call, the local's rebinding): 972 to 874, a field read then + written 161 to 118; + and a site's class version and index are constants in its code + instead of loads from the guard table (a guard never changes once + made): 874 to 786. Cycles went 348 to 228 an iteration; the frame + JIT ran this loop at 1,333 instructions and about 400 cycles, and + CPython runs it at 3,329 and 1,115. + - Integers past 64 bits. The battery's `uuid_secrets_ops` (1.6 times + CPython's time) spends its time making and reading 128-bit values, + and each step cost two to four times CPython's: + `int(text, 16)` of 32 digits took 7,300 instructions, because the + constructor's quick arms try a machine-int parse, decline on its + overflow, and the full constructor's layers each try it again + before the big value is built; the arms now build it themselves + (2,800, 602 ns to 218; CPython 160 ns), as they do for long decimal + text (456 ns to 207; CPython 143). Hex text is then tried before the + general parse and read through a digit table (218 ns to 124). + Arithmetic of a big value with a machine int promoted both sides, + copying the big one: sums, differences, products, right shifts and + masks now read it in place (`big + 1` 977 instructions to 664). + `to_bytes` built a byte-order string and a copy of the value before + looking at its arguments; a non-negative value now goes straight + into the result, at any length. And a method called on a big + `int`, a float, a tuple or a `bytes` object went through the method + memo at every call from compiled code, whose per-site cache held + lists, dicts, sets and strs only: the site now keeps the method for + the receiver's kind, as it did for streams + (`big.bit_length()` 804 instructions to 589). + - Removing a key from a dict cost time in proportion to the keys behind + it. The table keeps positions dense (the i-th key is entry i, which + the iterators and the position caches rely on), so a removal moved + every later entry down and renumbered the slot table: a cache that + evicts its oldest key, a table of pending requests, an LRU touch + (`v = d.pop(k); d[k] = v`), `OrderedDict.popitem(last=False)` and + `move_to_end` were all quadratic. At 20,000 live keys, in ns an + operation (CPython's in brackets): `OrderedDict` LRU 77,900 (195), + `move_to_end` 87,100 (87), pop and re-insert 41,000 (155), add and pop + the oldest 40,000 (107), a `WeakValueDictionary` window 45,600 (829). + The removals a program makes in bulk (`del d[k]`, `d.pop(k)`, an + `OrderedDict`'s, a dead weak value's) now leave a tombstone in the + entry list, and positions stay dense through a rank index over the + tombstones: a bitmap, a Fenwick tree over it that is built only once + a tombstone sits past the front run (a queue's tombstones are all at + the front, where a position is its entry less the run), and the last + translation, which a walk by position continues from. The table + closes the gaps in one pass when its entry list fills or tombstones + outnumber keys, so each removal pays a constant share. Removals + elsewhere (a namespace's `del`, a class's attribute) still shift, so + a table that never takes a bulk removal has no tombstone and pays one + test per positional access; the bench fixtures read 1.000 of their + instructions. The same operations now: 378, 158, 143, 129 and 4,560 + ns, flat from 1,000 keys to 20,000 (`dict` FIFO by `next(iter(d))` + 282 ns, where CPython's own scan past its tombstones takes 6,400). + The index's pointer first took the table from 48 to 56 bytes, which + cost 16 bytes a dict in the allocator's size classes (a million + two-key dicts 262 MB to 277 MB). The slot table is now one word, a + pointer whose length is the shift's (compiled code tests the shift + for a table without slots, where it tested the length), so a table + is 48 bytes again and a dict takes what it took (262 MB); the + fixtures read 0.997 of their instructions, a probe's mask coming + from the shift it already loads. + - What is left on those loops is the call, not the dict. Tier 2 ran a + method call on a builtin value as two generic helpers: a load that + allocated a bound method and pinned it for the rest of the + activation, and a call that looked the builtin's kind up again + (`d[i] = i; d.pop(i - 1000)` 2,088 instructions an iteration against + the frame JIT's 1,247 and CPython's 1,248, and 169 ns against 108). + A builtin value's method table never changes and its lookup runs no + code, so for a method the core loop's leaf lane runs in place the + load now leaves the receiver where the bound method would go and the + call runs the builtin on it; an exit between the two rebuilds the + bound method the interpreter expects. 1,384 instructions (119 to 129 + ns). The frame JIT still runs such a loop in 1,118: the two helper + calls cost about 270 more than its method site, and a loop of + container calls has no typed work for tier 2 to win that back with. + So tier 2 now leaves a loop to the frame JIT when it makes such a + call for fewer than four typed operations (`WEAVEPY_T2_METHODS`): the + pop loop runs in 1,102 instructions, under CPython's 1,248, and pop + and re-insert went 138 ns to 92 (CPython 130), a queue worker's loop + 4% faster, with the suite's loops that mix such calls with typed + work (`chaos`, `go`, `raytrace`) within 1% either way. + `OrderedDict` calls were the next share: the frame JIT tried its + fused call (receiver, simple arguments, call in one helper) on every + method call of a local, and a call with a keyword or a computed + argument walked the instructions, declined, tried the native method + a second time, and then ran through the method site anyway, about + 450 instructions each. Compiled code now makes the attempt only + where the arguments can be what it serves, the second try is gone, + and the fused arguments fold `%`, `//` and `>>` of two ints as they + did `+`, `-`, `*` and the bit operations (`od.move_to_end(i % n)` + 1,594 instructions to 1,288, CPython 938; add and + `popitem(last=False)` 3,515 to 3,039, CPython 2,201; with a plain + key `move_to_end` is 1,050 against 941 and a store 824 against + 1,120). A keyword call of a native method (`popitem(last=False)`) + also built a vector of cloned arguments for the method's leaf half, + which now reads them in place (the add-and-pop loop 313 ns to 272; + CPython 190). And `set.discard` and `set.remove` probed the set + once to see whether the call could run without Python and then ran + the general body, which probes again inside a comparison scope and + replays the deferred-operation queue: a `str`, `int` or `float` key + that one native probe settles is now removed by that probe + (`s.discard(k); s.add(k)` 2,252 instructions to 1,348, 197 ns to + 111; CPython 1,530 and 122). Weak-value dictionaries (22,400 + instructions an insertion and expiry against CPython's 7,900, spread + over the weak reference class's Python-level `__new__`, `__init__` + and callback) are what is left of this group. + - A scaling sweep (about 110 container and string operations timed at + n and 8n keys under both interpreters, flagging a cost per operation + that grows where CPython's doesn't) found more of the dict removal's + kind, each an everyday idiom: + Set operations copied their operands. A comparison (`a <= b`, + `a == b`) took a snapshot of both sets first, so sets of different + sizes took time in proportion to the larger to be told apart; the + methods (`intersection`, `difference`, `issubset`, `issuperset`, + the three `_update`s) built a new set from each operand, hashing + every key again; and `a -= b`, `a &= b` and `a ^= b` computed + `a - b` whole and copied it back into `a`. At 32,000 keys against + three: `small <= big` 19.9 µs (CPython 57 ns), `big -= small` 1.56 + ms (243 ns), `big.intersection(small)` 1.46 ms (244 ns), + `small.issubset(big)` 875 µs (103 ns), `big == other` of another + size 37 µs (36 ns). The algebra now runs on the tables themselves + (`setalg`): a stored key carries its hash, so nothing is hashed + again and no `__hash__` runs; a pair of keys that needs a Python + `__eq__` defers, which leaves the operation to the old path with + nothing changed; and each operation walks the side it has to, the + smaller one for an intersection, a subset test or a disjointness + test, the right one for an in-place difference (planned with both + sets only read, then applied by position). The same figures: 83 ns, + 331 ns, 162 ns, 111 ns and 61 ns, on a quick build. The method + forms now keep the elements CPython keeps where equal keys differ + (`{1, 2}.intersection({1.0, 2.0})` is `{1.0, 2.0}`, as the operator + already gave). + A dict's keys view did the same against a set: `small & d.keys()` + built the 32,000 keys as a set first (1.18 ms; CPython 242 ns; now + 456 ns), as did `d.keys() >= small` and `isdisjoint`; they probe the + dict's table with the set's stored hashes. `small - d.keys()`, which + CPython answers by walking the dict (375 µs), takes 416 ns. + A string built by `s += piece` in a loop copied itself at every + append once the loop was compiled: the core loop grew a `str` local + in place when nothing else held it, but the compiled binary + operation didn't know its result was about to be stored back into + its left operand's local. Its site now carries that local, and the + helper lets the local go and appends where the string is (649 ns an + append at 32,000 appends, growing with the length, to 50 ns flat; + CPython 104 to 118). A concatenation whose left operand is a + temporary nothing else holds (`a + b + c`'s second `+`) grows that + one too. + A function with n parameters took n² to parse and to compile: both + duplicate-parameter checks scanned a vector, and every use of a + local searched the names for its index. CPython's own + `test_collections` makes a 150,000-field `namedtuple`, whose + constructor is such a function: 117 s, now 1.5 s (CPython 1.9). + And `int("x12")` in a `try`, the everyday test for a number, ran the + big-integer parser at each of the three layers that reach the + constructor's quick arms before the full constructor rejected it + (the arms had started building big values a few commits back): the + arms decline text that isn't digits at its first byte, 4% of the + `exceptions` workload's instructions. + - The sweep's constant factors, and two more cliffs found beside them. + Copying a sequence's items moved each one through an iterator: an + object returned by value travels as a tag byte and fifteen more, + stored and reloaded unaligned, about twenty instructions an item. + `tuple(xs)`, `a + b`, `t * n`, `(*xs,)`, slices, `list(xs)`, + `xs.copy()`, `extend` and the snapshots `min`, `max` and `sorted` + take now copy the items whole and take their counts in a second + pass, and a vector that becomes a tuple hands its items over in one + copy. At 1,000 ints: `tuple(xs)` 8.0 µs to 1.0 (CPython 1.9), + `t + t` 10.1 to 1.9 (2.8), `t * 2` 9.9 to 2.4 (2.6), `(*xs,)` 6.4 + to 1.5 (3.6), `t[::-1]` 5.1 to 1.6 (1.6). A dict's or a set's + entries copy the same way (`dict(d)` and `d.copy()` 5.6 µs to 3.7; + CPython 3.2), and a list whose items all outlive it is released + without rewriting its slots. + `for x in reversed(xs)` in a loop tier 2 compiled stepped its + iterator through the interpreter's general `next`, 41 ns an item + (the same loop over the list itself 3.5): the reversed list's + iterator steps in place, as a list's does (7 ns; CPython 22). + A tuple's hash walked its items twice and reduced each int modulo + the hash prime, and `hash()` first checked each item's hashability + through a call: one pass, an int below the prime is its own hash, + and scalars are checked in line (34 instructions an item to 13; + `hash(t + (i,))` of 1,000 ints 9.0 µs to 2.8, CPython 3.4). + A `memoryview` slice left compiled code for the interpreter and + built four vectors on the way to a view that needs none (3,530 + instructions to 1,536; 283 ns to 152, CPython 72: the view's own + copy, with its format string, is most of what is left). + `str.count` of one character ran the substring search per + occurrence (29 µs to 1.8 on a 33,600-character text, CPython 11.9). + The first cliff: `b[i:j] = data` on a `bytearray` rebuilt the whole + buffer as a list of int objects, spliced that, and wrote every byte + back, whatever the slice's size, and `del b[i:j]` removed the + slice's bytes one at a time, moving the tail for each. On a 1 MB + buffer a four-byte store took 9.1 ms (CPython 171 ns) and + `del b[:16]` 388 µs (72 ns). Both work on the bytes now: a store of + the same length writes in place, any other moves the tail once, and + an extended slice is stored or closed up in one pass (237 ns, and + 23 µs for the delete, which still moves the megabyte: CPython keeps + a start offset, and that is what is left here). + The second: merging dicts. `d.update(other)` gave up its one-pass + merge when `d` held more than 32 keys (checking them for Python + `__eq__` was thought too dear) and then stored key by key through a + snapshot of `other`; `d.update(d)` did all of that to change + nothing; `dict(pairs)` and `d.update(pairs)` made an iterator and a + vector for every pair; and an items view was read as pairs like any + iterable. The merge now probes with each key's stored kind and + stops only at a key that needs Python (the keys before it are in, + and the general path merges them again harmlessly), a dict merged + into itself returns at once, a list or tuple of exact pairs is + walked in place under one borrow, `zip` of two plain sequences + builds its dict first, and an items view merges as its dict. At + 1,000 keys: `d.update(other)` with half the keys shared 68 µs to 27 + (CPython 34), `d |= other` the same, `d.update(d)` 46 µs to 66 ns + (63), `dict(pairs)` 110 µs to 33 (31), `d.update(pairs)` 74 to 26 + (31), `d.update(other.items())` 103 to 4.0 (36), `dict(d.items())` + 131 to 4.4 (36), `d.update(zip(ks, vs))` 92 to 24 (40). + Left: a generator of pairs (`d.update((k, v) for ...)` 136 µs + against 63, the generator's resumption from native code), + `dict(d, **kw)` (the keyword-spread call's own machinery, about + 6,000 instructions), small-dict merges at 1.3 to 2 times CPython + (the new container's tracking and release), `list.pop(0)` and + `xs * 2` (16-byte items against 8), and the `bytearray` start + offset. + - Bytes-like values were copied whole before anything read them. A + second sweep, of 90 operations on 200,000-item buffers of each kind + (`bytes`, `bytearray`, `memoryview`, `array`, and the containers), + put `array[i]` at 870 times CPython's time, `struct.unpack_from` at + 61 times and `bytearray.decode` at 33. One accessor was behind most + of it: the value's bytes as an owned vector, so a call that reads + four bytes of a buffer first copied the buffer; and `array` is a + Python class over a `bytearray`, each item read through + `struct.unpack_from`, so indexing a large array copied all of it per + item. The readers now borrow: `struct` reads and writes the buffer + where it is, with native halves for `unpack_from` and `pack_into` + (over a 200,000-byte `bytearray`: 5.1 µs to 109 ns, CPython 101; + 706 ns to 76, CPython 105), hashing, `zlib`, the codecs' functions, + `int.from_bytes` and `str(b, encoding)` take a `bytes` object's own + bytes, a new `bytes` is built from a slice in one copy where it took + two (`a + b` and `bytes(bytearray)` at 200,000 bytes 11.2 µs to 4.6, + CPython 4.6), and the codec engine returns well-formed UTF-8, ASCII + and Latin-1 text as it is, where it decoded every byte to a code + point and encoded the lot again (`bytearray.decode()` of 200,000 + bytes 636 µs to 15, CPython 26). + The `array` class's item methods are native for plain indexes and + values, as CPython's C type's are, each falling back to the Python + method it replaces for anything else (other index and value types, + every error): `a[i]` 26.7 µs to 61 ns on 200,000 ints (CPython 44), + `a[i] = x` 1.5 µs to 56 ns (49), `a.append(x)` 503 ns to 66 (76), + `a[i:j]` 3.4 µs to 526 ns (148), iteration 1.5 µs an item to 174 ns + (63), and `tolist`, `count`, `index`, `in` and `fromlist` unpack or + pack every item in one call. + A `memoryview`'s plain byte reads and writes skip the shape and + format machinery (`view[i]` 235 ns to 48, CPython 36; a run store + 375 ns to 225). `frozenset(a_set)`, `set(a_frozenset)` and + `set(a_dict)` take the source's table with its stored hashes (11.9 + ms to 1.3 for 200,000 keys, CPython 2.4); `dict(zip(xs, ys))` keeps + its direct build past 4,096 pairs (28 ms to 3.5 at 200,000, CPython + 9.0); list and tuple comparison settles two machine ints in line + (425 µs to 211 for 200,000 items, CPython 192); `range(n)[k]` stays + at machine width when it can. + Two wrong answers came out of the new tests: `struct.unpack_from` + read a non-int offset (an object with `__index__`, or a `str`) as + zero, and unpacked from a released view; and a strided view is now + refused with `BufferError`, as CPython refuses it, not gathered. + Left: an array's slices and iteration (3.6 and 2.8 times CPython: a + slice of an instance leaves compiled code, and the iterator's step + goes through its slots), `view[i] = x` and `range(n)[k]` in compiled + code (4 and 2.9 times, the same exit), `bytearray` methods (no + native lane: `append` 130 ns against 41), SHA-256 itself (2 times: + the hash's throughput, not its argument), and about forty other + callers of the copying accessor (`io` has thirteen). + - A third sweep, of 130 I/O, codec, text and library operations on + large inputs, found the same kinds of cost in more places. + `zip(*rows)` was quadratic in its rows: each step checked that no + source was another's alias by comparing every pair, and a transpose + has a source per row (20,000 rows of three: 404 ms, CPython 2.1). + The answer can't change, so the zip keeps it from its first native + step (sorted addresses when there are many sources): 2.3 ms. The + grouping idiom that passes one iterator several times + (`zip(*[it] * n)`) is the aliased case, and steps as before. + A string slice with a negative bound or a step spread the whole + string into a vector of code points first, so `line[-20:]` and + `text[:-1]` cost the string's length: on 226,000 ASCII characters, + `s[-20:]` 295 µs to 60 ns (CPython 63), `s[:-1]` 641 µs to 12 µs + (5.8), `s[::-1]` 651 µs to 15 µs (101). ASCII text is sliced by its + bytes. + UTF-16 and UTF-32 went through the general codec engine's code + point vectors even for well-formed text: a `str` is encoded straight + from its text, ASCII as a byte and its zeros, and well-formed input + is decoded in one pass (226,000 characters: encode 809 µs to 93, + CPython 75; decode 878 µs to 166, CPython 67). Results match + CPython's on 447 cases of well-formed and malformed input under + every error handler. + `x in a_bytearray` copied the buffer before searching it (5.2 µs + to 0.17 for a hit near the front of 200,000 bytes; CPython 1.5). + `list(b)`, `memoryview.tolist()`, `bytes(a_list)` and + `bytearray(a_list)` converted item by item through the general + protocols (5.5 ms, 10.7 ms and 1.5 ms for 200,000 bytes; now about + 0.2 ms each, CPython 0.8 to 0.9). `struct.iter_unpack`'s iterator + steps natively (17.2 ms to 5.7 for 50,000 records, CPython 1.75). + `bytearray` has a native method lane for `append`, `extend`, `pop` + and `decode` (`append` 77 ns to 63, CPython 36), and compiled code + reads `b[i]` and `len(b)` and stores `view[i] = x` in line (`b[i]` + 189 ns to 25, CPython 31; the store 204 to 48, CPython 42). + `range(n)[k]` in compiled code 210 ns to 40 (77), `slice.indices` + at machine width 252 ns to 104 (130), a forward stride slice of + bytes checks its bounds once (`b[::2]` 137 µs to 52, CPython 25), + and `bytes.translate` maps in one pass (173 µs to 121, CPython 70). + Left from this sweep: `BytesIO.getvalue()` copies the buffer each + call (CPython hands out its own bytes object until the next write), + `re` on a `bytearray` or `memoryview` widens the whole subject per + call, `BytesIO` reads and writes at 2 to 3 times CPython, + `iter_unpack` at 3 times, UTF-16 decoding at 2.5 times. + One thing the native `array` methods broke, which the ecosystem lane + caught: the C API's `PySequence_Check` took an instance for a + sequence only when its class's `__getitem__` was a Python function, + so Pillow's `putdata(array(...))` refused the array. A natively + served `__getitem__` on a class that declares itself a sequence + counts too, as CPython's own `array` type does. + - Iterating byte strings and arrays. `for b in data` over a `bytes` or + `bytearray` left compiled code at every step for the interpreter's + general `next` (39 ns a byte, CPython 21); both tiers now step them + in place (8 ns). `sum`, `min` and `max` of one take its bytes + directly (`sum` 22 ns a byte to 0.2; CPython 5.3). The array + iterator's native step and the item methods read their instance's + slots where the class lays them out, not by name (`for x in a` 72 ns + an item to 42, CPython 35), and `list(a)`, `tuple(a)` and + `sorted(a)` unpack the array at once when its `__iter__` is its own + (91 ns an item to 21, CPython 15). An ASCII string's run with a + negative bound (`s[:-1]`) is copied once from the text, not through + a vector of bytes (14 µs to 6 for 226,000 characters, CPython 6.2). + - `io.BytesIO` reads, `readinto` and writes after a seek went through + the file layer's general path (its sibling stream, read-ahead and + write-buffer checks, and a vector per read): `read(64)` 164 ns to 68 + (CPython 62), `readinto` 154 to 54 (44), a write over earlier bytes + 165 to 64 (46), and a `bytearray` written 146 to 62 (51). Each is + now a fast half on the stream's buffer, declining a closed stream, + one with bytes parked ahead, an exported buffer, and a stream read + into its own buffer. + - A fourth sweep, of 55 interpreter-level operations at n and 8n + (compiling large and deeply nested code, calls with many arguments, + deep inheritance, recursion, tracebacks, formatting, library + algorithms), found two more growth cliffs. Compiling functions + nested `d` deep cost about `d` cubed: each enclosing scope asked for + each nested function's free names, recomputed from the whole subtree + every time (80 nested closures, 47 ms to compile, CPython 2.1). The + free names are kept for the compilation, by the function's place in + the tree: 3.6 ms. And `deque.rotate` made room at the front one + rotation's worth at a time, so every few rotations shifted the whole + deque item by item (`rotate(n // 3)` on 4,000 items: 17.6 µs, CPython + 0.6); the room is now as large as the deque, made by moving its + items once, and a rotation trades its items with the free slots as + one block (4.0 µs). `extend` and `extendleft` of a list or tuple are + native (`extendleft` of two items 309 ns to 194, CPython 93); a + generator still goes in item by item, so an exception partway leaves + the items before it, as CPython does, which needed the dispatch's + by-name rule for `extend` (materialize the iterable first) to leave + a plain class's native methods alone. Generator chains, which cost + more per level the deeper they go (16 levels: 85 ns a level-step, + CPython 16), are left for now. + - `re` over a `bytearray` or a `memoryview` (how h11 and urllib3 parse + a socket's buffer) converted the whole subject to code points on + every call, so a search near the front of 200 KB cost 28 µs (CPython + 0.27) and a `findall` over it 24 ms (0.17). The bodies that run no + Python code (`search`, `match`, `fullmatch`, `findall`, `split`, + `finditer`, and `sub` with a bytes replacement) now read a + `bytearray`, or a plain view's window of a `bytes` or `bytearray`, + where its bytes are, and return `bytes` pieces as CPython does (0.47 + µs and 0.24 ms). Results equal the old ones on 524 cases over five + buffer kinds. + `bytes.fromhex` read its text as a vector of characters: ASCII text + is now read by its bytes through a digit table (51,200 bytes: 6.3 ms + to 1.4 for five, CPython 1.4 for five; errors still come from the + character reader, so their positions are unchanged). + - `{**d}` and `f(**kw)` into an empty dict inserted the source's keys + one at a time, rehashing and growing the table (200,000 int keys + 13.3 ms, str keys 19.9 ms; CPython 1.9 and 2.8): both the core + loop's arm and the full handler now copy the source's table whole + when they can, and merge a display's `**d` into a non-empty dict as + `dict.update` does (1.9 and 3.4 ms). A deque's `in`, `count` and + `index` compare plain items (numbers, strings, bytes, `None`) + natively before the Python loop that any other item needs (`x in d` + of 200,000 ints 2.5 ms to 1.9; CPython 2.5), and `index`'s error + reads as CPython's. + - A sweep of 75 class-protocol operations against CPython (named + tuples, dataclasses, enums, getters, dunders, iterators) put + `operator.itemgetter` on a named tuple at 13.7x (479 ns, CPython + 35): its fast half took only exact tuples, lists and dicts, so a + subclass declined through seven call lanes to the full body. It now + reads a subclass's payload when the class keeps the base's + `__getitem__` (96 ns). `methodcaller` read its three fields by name + and built a bound method and keyword list for every call; it now + reads them at their slots and calls a plain instance's Python method + with the instance first (502 ns to 358; CPython 99). `str(x)` of an + instance with only a Python `__repr__` looked `__str__` up along the + MRO and built a bound method to probe for `__repr__` (217 ns to 148; + CPython 64), and `f'{x!r}'` went through a bound method and a Rust + string (241 ns to 125; CPython 58): both call the function directly + now, and `str(x)`'s error for a non-string result is CPython's. + - A frameless `__next__` could end at a bare `raise StopIteration` + only with no attribute store buffered, so the usual shape (`self.i + += 1` ahead of the exhaustion test) ran the whole last step as a + frame, raised, and caught (`list(It())` of three items 1.87 µs, + CPython 0.62): the buffered stores now land as a return lands them, + and the step ends as exhausted (0.93 µs). `next(it)` without a + default still declines on such a step, since its full call raises + the exception with its traceback and would repeat the stores. + - A named tuple built with a default filled in (`P(1)` of + `namedtuple(..., defaults=...)` or a `typing.NamedTuple` with a + default) or with keywords (`P(x=1, y=2)`) ran the generated + `__new__` as a frame and went through `object.__new__`'s seeding + (743 and 914 ns; CPython 228 and 340): the construction lanes now + place keywords by field name and take the rest from `__new__`'s + defaults as they stand, building the tuple directly (256 and 279 + ns). A rebound `__defaults__` or `__new__`, and every call that + binds otherwise, still runs the function. + - The frameless `f(*args)` path took only plain functions given + their exact arity, so `obj.m(*args)` (a method read as an attribute + first) ran as a frame, and a spread short of the arity went through + the keyword binder: a bound method's receiver now binds first, and + trailing parameters come straight from the positional defaults + (`obj.m(*args)` 243 ns to 136, CPython 87; `f(*(1,))` with a + default 84 to 74, CPython 45). + - `a > b` of a class that defines only `__lt__` looked up `__gt__`, + found `object`'s, bound and called it to get `NotImplemented`, then + went through the general protocol to the reflected `b.__lt__(a)` + (341 ns, CPython 130; `max()` over 50 such instances 11.7 µs, + CPython 5.6). `object`'s orderings are now recognized per class and + skipped, and two instances of one class call the reflected method + directly, in compiled code as a frameless leaf (73 ns; `max()` 5.5 + µs). `weakref.ref` calls have a leaf half that calls the referent's + deref closure in place (78 ns to 45, CPython 26), and `r(1)` raises + CPython's `TypeError` instead of ignoring the argument. + - `for x in itertools.chain(xs, ys)` stepped each item through six + layers (the core loop's lazy step, the zip check, the itertools + machine's dispatch, then a peek and a skip of the active cursor): + 349 instructions an item (two 100-item lists 6.3 µs, CPython 2.1). + The core loop's lazy step now takes `chain` first, and the active + list, tuple or range cursor is read and stepped in one call (173 + instructions; 4.2 µs). + - A compiled frameless leaf (a getter, a `__hash__`, a comparison) + cached where an instance keeps a field only for split layouts. An + instance whose `__dict__` was materialized (a `cached_property` + computed, `vars(obj).update(...)`, anything `copy` or `pickle` + rebuilt) resolved the field by name and checked its class on every + read, about 500 instructions (`hash(obj)` of `return hash(self.x)` + 151 ns against 105 for a split instance). Its position in the + published dictionary is cached too and checked by name as read + (116 ns). + - `shlex.split` reads its input one character at a time + (`instream.read(1)` of a `StringIO`), and each read took the text + layer's whole path: the characters' bytes copied out, checked as + UTF-8, newline-translated and un-bridged into a new string, about + 650 instructions. A read of ASCII characters with no `\r` now copies + them straight out of the buffer as a leaf half (`shlex.split` of a + five-word command 25.5 µs to 21, CPython 14). A read past the end + keeps the position a seek left, and a closed `StringIO`'s error + drops the period, as CPython's does. + - Compiled code ran a container method's kernel in line only for a + receiver in a local (`x.append(v)`): one an expression left on the + stack (`self.items.append(v)`, `d[k].append(v)`) loaded the method + through the method-site helper and called it through the call-site + helper, about 145 instructions more (`o.l.append(1)` 34 ns, CPython + 24; `d[k].append(1)` 40, CPython 31). The stack's receiver now has its + type checked in line too and the kernel called with the result in the + slot above; the receiver is released as the full call releases its + operands (a temporary's finalizers run before the next statement) and + the result moved into its slot (28.5 and 32.4 ns). + - `OrderedDict.fromkeys` stored its keys one subscript at a time in + Python (270 keys 21.2 µs; CPython's C loop 12.7). An exact + `OrderedDict` now takes a list's, tuple's or str's keys through + `dict.fromkeys` and its native update in one pass (10.0 µs); + subclasses keep the loop for their own `__setitem__`, and an + unhashable key still raises from the loop, which words the error as + CPython's `OrderedDict` does. + - Tier 2's `len()` and `next()` of an instance with a native leaf + dunder (`len(deque)`) looked the dunder up along the MRO on every + call (190 of the 270 instructions a `len(dq)` cost): the class now + caches the builtin it resolves per version. + - UTF-16 decoding of ASCII text checked each unit, gathered the low + bytes into a vector, then validated and copied them into the string + (110 KB 47 µs, CPython 19): it now checks eight bytes at a time and + packs each word's four low bytes straight into the string's + allocation (22.5 µs). + - The native pickler and unpickler knew `bytes` but not `bytearray`, + so protocol 5 (the default) sent any data holding one to the Python + pickler (64 KB `dumps` 35.8 µs and `loads` 39 µs; CPython 2.2 and + 1.5). Both now handle `BYTEARRAY8`, memoized as CPython's pickler + memoizes it and framed as it frames one (8.2 and 3.2 µs; the bytes + written are the Python pickler's exactly). + - `int.from_bytes` of a short `bytearray` or `memoryview` took the full + method (2,000 four-byte memoryview slices 1.3 ms, CPython 0.46): the + leaf half now reads them in place (0.39 ms), and a released view + raises `ValueError` as CPython's does. `struct.iter_unpack`'s step + reads its iterator's state at the class's slot places instead of by + name (50,000 items 6.1 ms to 4.8; CPython 2.0), and a `bytes` + subclass reaches the core through a view instead of failing. + `array("d", floats)` checked its items' types in a Python loop: + a native check now (25,000 floats 967 µs to 299; CPython 429). + - `zlib.crc32`/`adler32` and `hashlib`'s constructors and `update` + copied a `bytearray`'s or `memoryview`'s whole buffer before reading + it: they read it in place now (`crc32` of 200 KB 13.2 µs to 7.5, + CPython 8.4). `adler32` took a modulo per byte; it reduces once per + 5,552-byte block, as zlib does (473 µs to 72; CPython 12), and + reduces its starting value even for no data, as zlib does. A released + view raises `ValueError` and a strided one `BufferError` in all of + them, as CPython's do. (SHA-256 itself is the `sha2` crate's portable + code, about half OpenSSL's AVX2 speed on this machine.) + - Iterating a memoryview made an object of every element first, then + walked that snapshot (`for b in memoryview(data)` over 200 KB 9.6 ms, + CPython 4.9). A plain byte view of a `bytes` object now steps as the + bytes do, sharing their storage when it covers them (1.4 ms), and one + over a whole `bytearray` steps the bytearray live, so a store made + mid-loop is seen, as CPython's iterator sees it (the snapshot missed + it). A released view's error reads as CPython's in `iter`, `tobytes` + and `tolist`. + - `bytes.fromhex` now decodes runs of whole pairs, a bad digit found + from the table's high bits, before looking at whitespace (400,000 + digits 520 µs to 347; CPython 263). `b"".join` of `bytearray` parts + reads them in place instead of copying each into a part list first + (2,000 parts 53 µs to 22.6; CPython 26). + - `memoryview.tobytes()` copied a contiguous view's bytes twice (200 KB + 17.9 µs, CPython 5.8): once now (6.0 µs). A strided one-dimensional + view is gathered in one read of its buffer instead of a buffer read + per element (`mv[::2].tobytes()` 3.0 ms to 0.37; CPython 0.64). + `bytearray.extend` of a list or tuple of ints took the full method + (four ints onto 200 KB 563 ns, CPython about 220): the leaf half takes + them, all checked first (171 ns). + - `next(iter(d))` (a dict's first key) took `next`'s full call for a + dict or dict view's iterator, and `iter()` of a view the general + builtin path (`next(iter(d))` 188 ns, CPython 78; `iter(d.values())` + 106 ns, CPython 61). `next`'s leaf half now steps a dict iterator as + `for` does, leaving a changed dict and the end to the full call, and + `iter`'s takes views and `mappingproxy` objects (118 ns and 64; + `next(iter(d.items()))` 291 ns to 180, CPython 141). + - Compiled code called an instance's `__getitem__` directly only when + it was a Python function, so every subscript or slice of an `array` + (whose `__getitem__` is a native method with a leaf half) left for the + core loop, and tier 2 took the general subscript path for it. Both + tiers now call a plain class's native leaf half in place, released as + the full call releases its operands (`a[i:i + 4]` 5,050 instructions + to 2,070 and 502 ns to 217, CPython 168; `a[i]` 84 ns to 59, CPython + 63). The slice reads its source's seven slots by position once the + class layout matches, instead of by name. `a + b` and `copy.copy(a)` + ran Python methods: they're native now, and compiled `+` of two + instances of one class calls a native `__add__`'s half in place + (`a + b` 1,075 ns to 202, CPython 85; `copy.copy` 673 to 350, CPython + 209). `len()` of an instance with a native `__len__` caches the half + itself rather than finding it again on every call. + - `operator.methodcaller`'s native call had no leaf half, so compiled + code left for the core loop on every call, and the native read its + fields, the method and a bound method through the general paths + (`methodcaller("lower")("ABC")` 535 ns, CPython 78). A leaf half now + runs a native value's leaf method (a `str`, `bytes`, `list`, `dict`, + `set` or `int` receiver, positional arguments only) in place (106 ns; + `dict.get` through one 573 to 108, CPython 59; `sorted(words, + key=methodcaller("lower"))` 377 to 129 ns an item, CPython 105). When + the half declines (a Python method of an instance, or an `itemgetter` + of a Python `__getitem__`), compiled code runs the native body in + place with the instance first, as the core loop's rewrite of the call + passes it, instead of leaving for the core loop (`methodcaller("f", + 1)(obj)` 515 ns to 184, CPython 75). + - A store through a class's own `__setattr__` looked the hook up along + the MRO on every store, twice when it was Python (`o.x = i` with a + one-line Python hook 3,670 instructions, CPython 1,230). The class + now caches its Python and native hooks per version (3,385). The rest + is the hook's activation in the core loop: compiled code leaves for + it on every store. + - Building an `itemgetter`, `attrgetter` or `methodcaller` ran its Python + `__init__`, whose `*items` takes a frame (`itemgetter(1)` 321 ns, CPython + 121; `attrgetter` 416, CPython 151; `methodcaller` 389, CPython 108). + The exact classes now have pure constructors that lay their slots out + at once (189, 178 and 206 ns); a subclass, keywords to `methodcaller`, a + name that isn't a `str`, or a class changed since registration take the + Python `__init__`. + - A keyword call of a native method or function took the core loop's + keyword lane: the names copied into strings, the operands into + vectors, and the general call (`xs.sort(key=None)` 279 ns, CPython 90; + `sorted(xs, reverse=True)` 335, CPython 207). `list.sort` and `sorted` + now have keyword halves for no key and a plain flag, bound as the + existing keyword halves bind (with keyword-only and positional-only + parameters marked, so `xs.sort(None)` and `sorted(iterable=xs)` still + raise), and the sort they share also takes tuples of ints and strings + (`pairs.sort()`). `xs.sort(reverse=True)` 286 ns to 108, `sorted(xs, + key=None)` 335 to 186. The per-call lookup of a builtin's keyword + half took a lock each time: a per-thread cache answers it. + - `list(product(...))` and its kin stepped each row through four layers + of the lazy-iterator step (`list(product(range(5), repeat=3))` 592 + instructions a row, CPython about 200). `list()` of a combinatoric + iterator (`product`, `permutations`, `combinations`, + `combinations_with_replacement`, a bounded `repeat`) now steps the + machine to its end directly (478). The rest is the tuple itself: a + per-thread free list for small tuples, parked at their last release, + made no difference (the allocator's own free and malloc cost what the + list's push and pop do). + - More keyword calls in place: compiled code builds `dict(a=1, ...)` from + the keywords as the core loop's arm does (400 ns to 126 in the + container, CPython 107), and `s.encode(encoding=...)` and + `s.split(sep=..., maxsplit=...)` take keyword halves (263 to 117, and + 361 to 214). Keyword halves can mark a parameter `?name`, optional but + positional too, so `s.split(maxsplit=1)` binds without its `sep`. + - The keyword sorts also take a key whose keys compute without running + code: `len` of strings and built-in containers, an `itemgetter(i)` of + tuples or lists (its index read once for the whole sort), or an + instance whose native `__call__` has a leaf half (`attrgetter`). The + keys sort as CPython decorates them, stable in both directions + (`sorted(items, key=itemgetter(1))` of ten pairs 6,530 instructions to + 4,300, 995 ns to 600; CPython 392). `sorted` takes a dict or a dict's + view too (`sorted(d.items(), key=itemgetter(1), reverse=True)`). + - A callback that calls an instance with a native `__call__` (`map(itemgetter(1), + xs)`, a `key=attrgetter("n")`) looked `__call__` up along the class's + MRO and found its leaf half again for every item, and cloned both + operands (893 instructions an item for `map(itemgetter(1), pairs)`). + The class now caches the half per version, and the call passes views + of the operands (608). + - `random.randint`, `randrange` and `choice` ran `random.py`'s Python + methods over the native `getrandbits` (`randint(1, 100)` 340 ns, CPython + 171). For the `Random` class itself, unchanged since import, with an + instance that doesn't override `_randbelow` or `getrandbits` and plain + int arguments (a list, tuple or ASCII string for `choice`), they're + native now, drawing as `_randbelow_with_getrandbits` draws, so a seeded + stream is the same as CPython's (108, 94 and 109 ns; CPython 171, 157 + and 167). `shuffle` of a list is native the same way (100 items 13.5 + µs to 3.0; CPython 13.7). Anything else calls the Python method, as + does every call while a trace or profile hook is set (a debugger steps + into `randint`: `test_pdb` does). (A native `uniform` was slower than + the compiled Python one, whose `self.random()` compiled code already + calls natively: its guards cost more than the call.) + - `copy.deepcopy` walked every container through `copy.py`'s Python + dispatch (a small nested dict 6.3 µs, CPython 3.8; fifty rows of dicts, + lists and tuples 228 µs, CPython 153). A tree of exact dicts, lists and + tuples over `None`, bools, ints, floats, strings and bytes, with no memo + given, is now copied natively as `copy`'s own table copies it: shared + parts stay shared, cycles are kept, and a tuple whose items all copy to + themselves is returned itself (1.4 µs and 22 µs). Anything else in the + tree, a memo, a tree over 200 deep, or a trace hook takes the Python + function. + - `Counter.most_common(n)` ran `heapq.nlargest` in Python over the + items, with an `itemgetter` key (ten counts, `most_common(3)` 4.4 µs, + CPython 1.8). An exact `Counter` whose counts are all ints now sorts + them natively, largest first and equal counts in insertion order, as + `nlargest` orders them. + - A disabled level's `logger.debug(...)` ran two Python calls, `debug` + with its `*args` and `**kwargs`, then `isEnabledFor` (214 ns, CPython + 141). `Logger`'s five level methods are native now: on a logger whose + class keeps `logging`'s own `isEnabledFor`, with the logger disabled or + `False` cached for the level, no keywords and no trace hook, they + return at once; everything else is the Python method (119 ns; `info` + 186 to 107, CPython 106). And compiled calls of a native method on an + instance ran it in place only when the instance had no attributes at + all: now when it has none of the method's name (a `Logger`, the + `random` module's `Random`). + - A call binding a `*args` tuple moved the surplus arguments into it one + at a time through an iterator, each by way of the stack: they move in + one copy now (`f(*t)` of three items 1,166 instructions to 1,120). + - A builtin type called with keywords naming its next positional + parameters in order (`int(text, base=16)`, `enumerate(xs, start=1)`, + `str(b, encoding=...)`, `bytes(s, encoding=...)`) took the general + keyword call (341 ns for that `enumerate`, CPython 145; `int` 300, + CPython 201). Compiled code calls it as the positional call it is, the + keyword values already in the positional places (131 and 75 ns in the + container's build, where the positional calls take 122 and 58). + `zip(xs, ys, strict=True)` and `map(f, xs, strict=True)` of a plain + `bool` flag are built natively the same way (396 ns to 202 in the + container; CPython 321). + - `b.decode(errors=...)` and `b.decode(encoding=...)` of bytes and + bytearrays take a keyword half too (270 ns to 165 in the container; + CPython 103), and the full method now rejects an unknown keyword with + CPython's `TypeError`, where it ignored it. `max(xs, default=0)`, + `min(...)` likewise (no key: the positional half, or the default for an + empty list or tuple; 298 ns to 133 in the container) and `round(x, + ndigits=2)` (its positional half, 394 to 223). + - `BytesIO.getvalue()` copied the whole buffer on every call (34 µs for + a 1 MB stream, CPython 23 ns, which hands out its bytes object until + the next write). The stream keeps its last result now and returns it + again until a write, a truncate, a re-`__init__`, a `__setstate__` or + a `getbuffer()` (whose view can write in place) changes the buffer, + and a stream made from a bytes object starts with that object (70 to + 90 ns a call at any size). + - `l.sort()` of a list of floats compared them through the general + comparison (6,963 µs for 20,000 floats; `sorted()` of the same list + 1,645, CPython 2,118 for both): it compares two floats directly now + (1,628 µs), as `sorted()` did. + - `pickle.dumps(1)` took 1,768 ns (CPython 674) and `pickle.loads` of a + small stream 1,751 (CPython 344). Each call ran two Python frames + (the stand-in built-in object's `__call__` with its `*args` and + `**kwargs`, then the Python `dumps`) before the native encoder, and + the encoder's guard then checked the code and defaults of 52 Python + functions (30% of the call's instructions). `dumps` and `loads` are + built-in functions now, as CPython's are, running the native engine + with no Python frame and anything it declines in the Python pickler + directly. And the guards check each function once per change to any + function's code or defaults (a count kept for this, never reset), + and otherwise only which functions the classes and tables hold (789 + ns and 1,049). The tables themselves aren't walked either while their + dicts' mutation stamps hold (the unpickler's has 70 entries, a third + of the call's instructions), and `loads`'s default `encoding` and + `errors` are made once: 760 ns and 756. + - `list(filter(None, xs))` and `filter(bool, xs)` over a list or tuple + stepped the filter once an item (153 instructions each; 5,564 µs for + 200,000 ints, CPython 2,552). When every item left has a truth that + runs no code, the items kept are counted, then copied at once, and the + source is stepped past its end as stepping it leaves it (4,164 µs to + 1,848, or 5.3 ns an item for 1,000 items, CPython 13.4). + - `struct` unpacks of one or two numbers built a list and then the tuple + from it, and counted the format's values on every call: the tuple is + built directly now, the count kept with the compiled format + (`iter_unpack` 1,249 instructions an item to 1,061). + - A `Vec` of plain data became a `bytes` (or another shared slice) one + element at a time: it's one copy now (`pickle.dumps` of 200 KB of + bytes 21.4 µs to 18.5). + - A stepped slice (`b[::2]` of 200 KB) took its items through a + stepping iterator, a capacity check and a bounds check each: it writes + them from an exact-length range now, indexed unchecked within the run + the count proves (54.5 µs to 26.2, CPython 26.9; bytes 29.5, CPython + 33.8). `bytearray * n` copied the operand before repeating it (17.2 + µs to 11.3, CPython 13.0), and `bytearray.translate` copied the + receiver and looked bytes up in a table checked at every byte (155 µs + to 72, CPython 88): both read the bytearray in place now, translate + after it has its table and deletion set, as CPython reads them. + - `BytesIO.getbuffer()` and every other `bytearray` export registered + itself in a map hashed with SipHash (three hashes a view, about a + tenth of `getbuffer()[0]`), now the interpreter's fast hasher; and a + memoryview's format is a shared string, so a slice of a view no longer + allocates a copy of it. + - `BytesIO.write(view[i:i + 64])` took the full method, which copied + the view's bytes out first, and slicing the view took five checked + cell borrows to copy its layout (2,828 instructions a write and + slice). A one-dimensional view of unsigned bytes now writes from where + its bytes are, and the view's layout is read guard-free (545 µs for + 2,000 writes to 367, CPython 265). The full method now raises + CPython's `BufferError` for a strided view and `ValueError` for a + released one, where it wrote the first and accepted the second. + - Every native entry into the interpreter (an iterator step from + `csv`, a callback from a C extension) pushed the interpreter's pointer + and its four thread handles onto thread-local stacks and popped them + after, about 230 instructions an entry and six entries a `csv` row. + When the interpreter and its handles are already on top, as for a + nested entry, nothing is pushed or popped (a 5,000-row `csv` round + trip 7.27 ms to 6.98). + - `csv.writer.writerow` stepped every row through the interpreter's + iterator protocol, one entry a field, and made each number's text a + Python string before joining it. A list or tuple of strings, numbers, + bools and `None`s is read at once now (writing those runs no code, so + a live iteration would see the same items), and numbers and bools are + joined as text (5,000 rows 3.49 ms to 2.49, CPython 2.92). + - A compiled `for v in d.values()` stepped the view through the general + dict iterator (251 instructions a value, CPython 139), where keys had + a step of their own: values take the same direct step now, the dict + unchanged since the first step and its length checked (189). + - `format(x, "g")`, `"e"` and `%g` rounded every float through Rust's + exact formatting, which for most values falls back to big-number + arithmetic (two thirds of `format(1.5, "g")`'s 3,938 instructions, + CPython 2,291). For a zero or normal float at no more than 15 + significant digits whose shortest round-trip digits fit, those digits + padded with zeros are the correctly rounded ones (the shortest form is + within half an ulp, under half a unit of the 15th digit), so they're + used as they are (3,237). A test checks every precision from 0 to 20 + across the exponent range against `decimal`'s rounding of the exact + binary value. + - `decimal.localcontext()` took 54 µs (CPython 0.7): nearly all of it + `Context.copy()`, which ran `Context.__init__`'s nine validating + attribute setters and signal-dict checks over a context's values, + already valid (243,000 instructions). The copy sets them as they are + now and builds its own flag and trap mappings (56,000; `copy()` 43 µs + to under 10, `localcontext()` to 16). + - `list(accumulate(xs))` with no function over a list or tuple stepped + the adapter once an item through four layers (741 instructions an item + of a ten-item list, CPython 424). Its running totals of machine ints or + floats are computed at once now, the adapter committed as its last step + leaves it only when every total is native (359). And `zip` of three to + eight list or tuple cursors checks and steps them in one pass, not two + (`for x, y, z in zip(a, a, a)` 1,064 instructions a step to 1,025). + - A compiled call of a `functools.partial` read the partial's stored + function, arguments and keywords up to three times (for a pure leaf, + then a builtin, then a bound call), each through a thread-local and a + slot-layout check: they're read once now and the path chosen from the + function's kind (`partial(f, 1, c=3)()` 3,021 instructions to 2,766, + CPython 2,191). + - `f.read(4096)` of a buffered binary file took the full native method + (its argument parsing, checks and dispatch layers, 1,700 instructions + beside the copy) even when the bytes were in the read-ahead already. + The method's leaf half now serves such a read from the read-ahead, an + open, readable file with nothing written to flush (2,635 instructions + a read on average to 1,932, half the reads refilling the buffer). + - The macOS `torch` probe in CI twice panicked with "cell is already + borrowed" in the builtin-method memo, a cache shared by the whole + process. Its lookups now go without it when it is borrowed, and a + store that finds it borrowed is skipped, so no lookup can panic there. + - A `re` search whose pattern starts with a literal stepped the subject + one unit at a time to the prefix's first character, with a bounds and + an end check at each (about ten instructions a byte; `search` of a + four-byte literal 254 bytes into a bytearray 4,434 instructions, + CPython 3,074). Over bytes, and text matched as its ASCII bytes, that + scan is `memchr` now (1,963). + - `str.rfind` stepped back one candidate first byte at a time (2.48 + million instructions for `text.rfind("line 5 ")` over 200 KB whose + match is near the start, CPython 0.83 million), and `bytes.rfind` used + the reverse substring searcher, which has no vector prefilter. Both run + the forward searcher over windows taken from the end now, 256 bytes and + then four times larger each time, overlapping by the needle's length + less one (134,000); one-byte needles use `memrchr`, and short + haystacks a plain scan. + - `BytesIO.tell()` and `seek(n)` took the full native methods (925 and + 1,119 instructions a call, CPython 340 and 459): an open `BytesIO` + with nothing read ahead or written to flush is served by leaf halves + now, `seek` for an absolute position not below zero (574 and 608). + And every compiled `f.method(...)` of a native stream first tried the + fused local-method call, which serves instances and containers only, + and then found the stream's method past the slow loader's other lanes: + other receivers decline the fused call at once now, and the loader + reads a stream's cached method first (`BytesIO.write(b)` 968 + instructions to 889, `read(64)` 881 to 763, `tell()` 574 to 490; + CPython 627, 545 and 340). + - A `for` loop over a csv reader reached its native `__next__` through + the interpreter on every row, since the reader may call Python (its + input iterator, or `float` for the numeric quoting styles): 8,460 + instructions a row for a five-field line from a list, CPython 4,250. + The reader has a leaf half now. It takes a line from a list or tuple + iterator, or from a text stream that holds it in its buffer, when the + line is one whole record. A line of plain and quoted fields is cut + into its fields directly, with `memchr` finding each delimiter and + closing quote, and any other line runs through the parser in place; + the stream's line is consumed only once the record is read. Rows cost + 3,150 from a list, 3,810 for quoted fields (9,020 before, CPython + 4,590), 3,670 from a `StringIO` (9,020, CPython 5,000), and 3,890 + from a file (9,230, CPython 5,040). + - The rows of `product`, `permutations`, `combinations` and + `combinations_with_replacement` were built by cloning each item out of + its pool through an iterator, which moves every object by way of the + stack (126 instructions for a three-item row). Rows gather their items + by address now and copy each into the tuple whole (85), so + `list(combinations(range(8), 3))` costs 24,950 instructions on x86 + (27,250 before). + - A `for` loop over `struct.iter_unpack("[key] = value; return None` + (`UserDict`'s, a wrapper's), or `self.[][key] = value` for + a small int (`ChainMap`'s `self.maps[0]`), now stores into that dict + in place when the store runs no code (1,256; `UserDict` 1,257, + CPython 1,012; a `ChainMap` 3,527 to 1,394, CPython 1,212). + `x in SomeEnum` ran `EnumType.__contains__` in a frame (its `try` + keeps it from being a leaf); when the metaclass keeps `enum`'s own + method, the membership test now answers as it does, in place: a + member of the class, else a scan of the class's value lists (a + `Flag` class, whose `_missing_` runs, takes the call), and + `SomeEnum[name]` reads the member map the same way, each verdict kept + per class and metaclass version. `Color.RED in Color` 2,730 to 870 + (CPython 1,244); `Color["RED"]` 1,333 to 514 (CPython 612). + - Arithmetic and comparisons over an instance of an `int` or `float` + subclass (`IntEnum.A + 1`, `I(2) < 3`) left compiled code at every + operator for the general path, about 3,500 instructions each + (CPython about 400). When the class takes the operator's forward + and reflected methods from its built-in base unchanged and defines + no in-place one (a verdict kept per class version), CPython runs the + base's own slot over the payload, so compiled code now runs the + operator over the payloads through the numbers' own arms: `a + 1` + 3,528 to 497 (CPython 403), `a < 2` 3,439 to 537 (CPython 416). + `IntFlag`'s own `|` and any Python override still take the call. + - Text of `str`, `int` and `float` subclass instances took the general + path. An f-string looked up and bound the base's `__format__` and + called it through the full call path (about 3,000 instructions; + CPython about 1,300), and `str()` repeated its lookups on each call. + Two verdicts kept per class version now settle them. The first is + whether `str(x)` is the payload's text: a `__str__` that is the + base's own method stored in a Python class (`IntEnum`'s and + `StrEnum`'s), or a number's `__str__` and `__repr__` both from the + base. The second is whether `__format__` is the payload type's own. + An enum member whose class keeps `enum`'s own `Enum.__str__` (and + `Enum.__format__`) renders `Class.name` from its dict the same way + (unless a tracer or profiler is watching). `str.join` reads `str` + subclass items as their payloads, as CPython's join does, and `%` + with bare `%s` conversions and the `!s` conversion that compiled + `"%s-%s" % (a, b)` becomes take these texts too. `f"{I(5)}"` 3,855 + to 753 (CPython 1,475); `f"{StrEnum.A}"` 3,106 to 766 (CPython + 1,227); `str(I(5))` 2,743 to 765 (CPython 879); + `f"{Color.RED}"` 14,818 to 1,447 (CPython 3,130); `str(Color.RED)` + 3,783 to 1,255 (CPython 1,942); `"-".join` of `StrEnum` members + 3,385 to 1,177 (CPython 1,185); `"%s" % StrEnum.A` 2,399 to 1,023 + (CPython 1,031). + - Enum members as dict keys hashed through `Enum.__hash__` + (`hash(self._name_)`), a leaf evaluation on every probe, and + `member.name` and `member.value` called `enum.property.__get__`, + which calls the getter. A member whose class keeps `enum`'s own + `__hash__` now hashes its `_name_` in place. When the descriptor's + class keeps `enum`'s own `__get__` and its getter is `Enum.name` or + `Enum.value`, the read takes the member's `_name_` or `_value_` from + its dict. Both decline while a tracer or profiler is watching. A + function returning `d[member]` went from 1,896 to 1,337 (CPython + 1,437), one returning `member.name` from 2,798 to 1,798 (CPython + 1,556), and one returning `member.value` from 2,116 to 1,773 (CPython + 1,553). + - `array.array` is a Python class whose item methods the `_struct` + module serves natively, but its construction still ran the Python + `__new__` (with `*rest` and `**kwargs` packed), `_setup` and a + `**kwargs` `__init__`. `array.array("i")` cost 9,027 instructions + (CPython 1,535). The class now has a pure constructor: for a numeric + typecode, and a list of plain ints or floats it holds, the instance + is laid out in place as `_setup` lays one out, while the class keeps + its own `__new__` and `__init__` (and no tracer or profiler is + watching). `array.array("i")` is now 1,704 instructions and + `array.array("i", [1, 2, 3])` 3,080, down from 20,899 (CPython 3,039). + `__new__`'s parameters are now positional-only, so + `array.array("i", initializer=[1])` raises CPython's `TypeError`. + - The enum member reads above found `_name_`, `_value_` and the + descriptor's `fget` by scanning the dict's names, 181 instructions a + name. They now use the names' hashes, computed once, and the + positions they last had in a split layout. The interpreter's + attribute path takes the same in-place read. A function returning + `member.name` is now 1,569 (CPython 1,556), `member.value` 1,594 + (CPython 1,561), and `d[member]` 1,216 (CPython 1,434). + - A csv reader keeps its state in its instance dict, and each row's + fast step found five entries by hash (about 90 instructions each). + It now reads them at the positions the constructor inserts them, + checking the key there, so `next(reader)` went from 2,423 to 1,838 + (CPython 1,494). `list()` of an instance looked up `__len__` and + `__length_hint__` on the class each time to decide what to probe; + their absence is now remembered per class version. + - `dataclasses.asdict` recursed through `_asdict_inner` in Python, a + call, a `fields()` tuple and a `getattr` per field (24,387 + instructions for three fields, one a list; CPython 15,074). With + the default `dict` factory, a tree of plain dataclass instances + (fields read from their dicts, no descriptor of the name on the + class), exact lists, tuples and dicts, and plain scalars now copies + natively (`_weave_collections._asdict_plain`): 7,461. Any other value + (a namedtuple, a set, an enum, a slots dataclass), a custom factory, + or a watching tracer or profiler takes the Python copy. + - `itertools.tee([1, 2, 3])` cost 38,843 instructions (CPython 2,478). + Each branch ran the Python `_tee.__new__`, whose native core call + left compiled code every time: a module builtin that the in-place + builtin lane doesn't list runs through the interpreter. `tee` now + builds the shared data object and its branches natively + (`tee_native`, listed for the lane). Each branch is still a `_tee` + instance, which can be weakly referenced as CPython's tee objects + can, over a native core. `_tee.__next__` gained a leaf half that + steps that core over the shared buffer, or a source whose step runs + no code, in place. Creation went to 9,308, and draining two + three-item branches from 66,691 to 28,744 (CPython 5,178). + `math.comb` and `math.perm` of machine ints now multiply in 128-bit + integers, falling back to big ints on overflow: `comb(10, 3)` went + from 3,744 to 630 (CPython 683). `itertools.compress` over two + sequences steps in place when its selectors are plain bools, ints + or `None` (`list(compress(...))` of four items 8,123 to 6,207, CPython + 3,325). `bisect` calls a key that runs no code (an `itemgetter`) in + place (6,951 to 4,119, CPython 2,340). `OrderedDict(pairs)` and + `OrderedDict(d)` with `str` or `int` keys build in place. + - `math.isqrt` of a machine int takes the float root's estimate and + corrects it to the exact floor, where it went through big ints, and + `math.gcd` folds machine words without collecting them first + (`gcd(84, 36)` and `isqrt(1000)` together went from 1,689 to 1,194, + CPython 1,160). `dict()` of a generator or iterator of pairs no longer + allocates two throwaway globals dicts or copies its pairs into a + second list, and sizes the dict once (`dict((k, v) for k, v in + pairs)` of ten pairs went from 15,945 to 14,508, CPython 10,769). + - `WeakKeyDictionary` and `WeakSet` lookups ran their Python methods, + which make a `ref` of the key and probe the table through the + reentrant path (weak references compare through their referents): + `wkd[k]` cost 13,908 instructions (CPython 1,996), `k in weakset` + 12,930. `functools.singledispatch` looks its dispatch cache up this + way on every call, so a dispatched call cost 19,575 (CPython 3,646). + For a key that compares and hashes by identity (a class, a function, + a plain instance), the entry is the stored live reference whose + referent is the key itself. The tables' `__getitem__`, `get`, + `__contains__`, a `__setitem__` of a present key and a `WeakSet.add` + of a present item now find it natively. Other keys, and any lookup + while a tracer or profiler watches, take the Python methods. `wkd[k]` + went to 1,455, `weakset.add(x)` from 9,647 to 1,026, and a + singledispatch call to 4,184. A `WeakValueDictionary` store builds a + `KeyedRef` (a `ref` subclass with a `key` slot), and that ran its + Python `__new__` and `__init__`. While the class keeps them, it is + now built in place (`wvd[k] = v` 10,194 to 6,847, CPython 5,995). + - A `threading.local` attribute store left compiled code every time: + the interpreter stored it in place through the class's native + `__setattr__` hook, but the compiled store helpers had no such arm. + Both now do (`tl.x = i` 1,966 to 726, CPython 954). `SimpleQueue`'s + native `put` and `get` found `_queue` and `_locked` by scanning the + instance's names. They now use the names' hashes and remembered + positions (`PyInstance::attr_get_memo`), and a put and get went from + 3,626 to 2,415 instructions in one run (CPython 945). + - An adapter whose source is a `cycle` (`islice(cycle(xs), n)`) took + the general step for every item, since only plain cursors, counters, + repeaters and chains counted as sources whose step runs no code. A + `cycle` over a plain cursor, or replaying its saved items, now does + too: `list(islice(cycle("ab"), 5))` went from 12,154 to 9,882 + (CPython 4,806). A `defaultdict` miss filled natively looked + `__missing__` up on the class each time to check that it is the + native one. That check is now remembered per class version, and + counting eleven words with `d[w] += 1` went from 19,473 to 17,291 + (CPython 15,140). `Struct.unpack` and `Struct.pack` read the + instance's `_fmt` by scanning its names on every call. They now use + the name's hash and remembered position (`Struct("4}"` 1.67 to 1.18 times CPython). + - The fast halves of `round`, `pow`, `repr`, `hex`, `oct` and `bin`, + which take only native numbers or strings, now count as pure, and a + frameless evaluation adds two strings (a new string it holds), so + callbacks using them no longer decline to a full call per item + (`sorted(xs, key=lambda x: round(x, 1))` 1.04 to 0.77 times CPython; + `min(xs, key=lambda x: pow(x - 25, 2))` 1.69 to 1.00; `map(lambda x: + hex(x)[2:], xs)` 1.88 to 1.32; `map(lambda x: repr(x) + "!", xs)` + 1.61 to 1.14). + - The `str` methods the leaf table registers as opaque (`count`, + `zfill`, `title`, `rjust`, `partition`, `index`, the `is...` tests and + the rest) read their immutable receiver and run no code, but the + frameless evaluator's purity test rejected the kind, so a callback + calling one declined to a full call per item. On an exact `str` + receiver they now count as pure, as do the fast halves of the `bytes` + methods (`map(lambda s: s.zfill(8), ws)` 2.05 to 1.38 times CPython; + `sorted(ws, key=lambda w: w.count("a"))` 2.11 to 1.37). + - Widening that exposed an older fault: a frameless evaluation's + subscript returned a pointer into a container the evaluation had + built itself, so `return s.split(".")[0]` read the item after the + list was freed (a wrong result after warm-up, then a crash). An item + of a container the evaluation holds is now held too. + - `list(zip(*rows))` over four to eight lists built each tuple through + an intermediate vector; it now fills the tuple's own allocation + directly (`list(zip(*m))` of an 8x8 matrix 1.64 to 1.19 times + CPython). + - `list(chain(gen, gen))` resumed each generator once an item through + the adapter's general step (about 1,500 instructions an item, 3.5 + times CPython), while `list(gen)` folds a generator's yields straight + into the list. A chain being drained now drains a generator source + the same way, whole, then moves on as a source's end moves it (0.90 + times CPython); a raise leaves the generator active, as stepping it + would. + - `list(islice(gen, n))` took each item through the adapter's general + step, which snapshots and writes back its state every item. Draining + one over a generator now steps the generator in a row with the state + read and written back once (the skipped items first, then the stop + bound, as before), 3.32 to 1.84 times CPython; the rest is the + generator's resume per item. + - `list(zip(gen_a, gen_b))` likewise steps each row's sources in order, + stopping at the first source's end with that row's earlier items + dropped as CPython drops them, instead of the adapter's general step + per row (2.74 to 2.02 times CPython). + - Compiled code raised a dict's missing-key `KeyError` in place, but an + index out of range (`xs[0]` of an empty list) left for the + interpreter to raise. An exact list's, tuple's or ASCII string's + `IndexError` is now raised in place too, with CPython's message + (`try: L[0] except IndexError: pass` 2.27 to 1.44 times CPython). + - `int.as_integer_ratio`, `conjugate` and `is_integer` join the leaf + method table, and the opaque and fast-half methods of exact `int` and + `float` receivers count as pure, so `statistics`' `_exact_ratio` + (`try: return x.as_integer_ratio()`) runs frameless for each item + (`statistics.mean` of 20 ints 2.15 to 1.84 times CPython). + - An exception unwinding through calls leaves each activation's spine + shell and locals vector with its traceback entry, and nothing reused + them: every level of every such raise allocated both (the vector grown + from empty) and freed them with the traceback. The traceback entry + that last holds a departed activation's shell now releases its values + as before and keeps the emptied shell and vector in a per-thread spare + list, walking the departed callers it was the last hold on, and the + next spine shells and inline activations take them (a raise through + six frames caught and dropped: 30 allocations to 12, 21,970 to 20,284 + instructions). + - A compiled loop over `filter(None, gen)` (or `filter(bool, gen)`) + stepped the generator through the core loop's lane and four layers of + general steps, about 1,640 instructions an item. The frame JIT's + adapter step now resumes the generator by its native code where it + stands and tests each item's truth natively (a class instance's + through its frameless `__bool__` or `__len__`); an item whose truth + would run code goes back ahead of the generator, the adapter's source + becoming a `chain` of the two, for the general step to test. `chain`, + `filter` and `islice` over a generator also skip the three adapter + steps that can't take them (50 items: `filter` 3.40 to 1.73 times + CPython, `chain` of two generators 2.37 to 2.11, `islice` 2.50 to + 2.01). + - An attribute store on an instance whose class has a Python + `__setattr__` (or a `property` whose Python setter doesn't evaluate + frameless) left compiled code for the core loop, which ran the hook's + body interpreted as an inline activation. The frame JIT's setter + helper now calls the function directly, as the property getter and + operator lanes do, on the store's own slots (`f(recv, name, value)`), + and drops its result; the core loop drops a result it settles (the + new `MethodOp::Store`). A store in a body inlined into its caller's + code keeps the exit. (`o.x = v` through `object.__setattr__` 2.25 to + 0.99 times CPython, `super().__setattr__` 1.93 to 1.22, + `self.__dict__[k] = v` 2.99 to 1.56.) + - An item store into an instance whose class's `__setitem__` is a + Python function took the same exit; a declined `STORE_SUBSCR` now + calls the method directly too, on the store's slots + (`f(cont, key, value)`), its result dropped as the setter's is + (`c[k] = v` through a Python `__setitem__` that stores into a dict + attribute 3.20 to 1.86 times CPython, a `dict` subclass's + `super().__setitem__` 1.82 to 1.03, `ChainMap` 1.28 to 1.08). + - A truth test (`if obj:`, `while`, `and`/`or`) of an instance whose + class decides its truth with a Python `__bool__` or `__len__` that + doesn't evaluate frameless left compiled code for the general call. + The truth helpers now call the method directly where nothing below + the value is virtual, taking the result as the protocol does (an + exact `bool` from `__bool__`, a length from `__len__`, with CPython's + errors otherwise; the new `MethodOp::Truth` settles a result the core + loop finishes) (`if obj:` through a `__bool__` that counts its calls + 4.70 to 0.71 times CPython). + - `x in obj` (and `not in`) through a Python `__contains__` and + `del obj[k]` through a Python `__delitem__` took the same exits. The + frame JIT now calls both directly where the operands are on the stack + and nothing below them is virtual: `__contains__`'s answer is taken + as a `bool`, or through `obj_truthy` with the frame synced (the new + `MethodOp::Contains` settles one the core loop finishes), and + `__delitem__`'s result is dropped (`in` 2.13 to 1.33 times CPython, + `del` 2.85 to 1.11). The interpreter took an answer's truth without + its `__bool__` (`x in obj` was true for an answer whose `__bool__` + says false); it now uses `obj_truthy`, as CPython's + `PyObject_IsTrue`. + - `len(obj)` of an instance whose class's `__len__` is a Python + function that doesn't evaluate frameless went through the general + call. The builtin's call site now calls the method directly, its + slot taking the method, and takes the result as `len()` does (the + new `MethodOp::Len` settles one the core loop finishes) (2.79 to + 1.18 times CPython). `len()` also accepts an `int` subclass from + `__len__`, as CPython does, and names the class in its error. + - An attribute store through a data descriptor other than a `property` + (a validating field descriptor's Python `__set__`) took the store's + exit too. The setter helper now finds such a descriptor on the class + and calls its `__set__(descriptor, obj, value)` directly on the + store's slots, as it calls a setter (a `__set__` that checks + `isinstance` and stores with `setattr` 4.59 to 1.93 times CPython). + - An augmented assignment on an instance whose class has a Python + in-place method (`x += v` through `__iadd__`) left compiled code at + every run: the operator lane took only classes lacking one, and the + full handler never marked the site as one that sees instances, so it + compiled as a numeric site. The full handler now marks such sites, + and the operator lane calls the in-place method directly; a + `NotImplemented` goes on to the regular operator with the frame + synced (the new `MethodOp::Inplace` carries the operands for a call + the core loop finishes) (`x += 1` through an `__iadd__` that counts + 4.41 to 1.32 times CPython). + - `set.add` of an instance whose class's Python `__hash__` evaluates + frameless declined the method's kernel and went through the general + call, which hashed it the same way several layers down. The kernel's + site now hashes it with the frameless evaluation and adds it on an + exact miss (a stored key of equal hash that isn't the same object + would need `__eq__`: declined), the computed hash going in with it + (`s.add(k)` for a `__hash__` returning `hash(self.key())` 1.94 to + 1.00 times CPython). + - `dict.get` of such a key takes the same path: the entry that is the + same object, or the default when no stored key could equal it + (`d.get(k)` 1.86 to 0.89 times CPython). + - An f-string field of an instance whose class's Python `__format__` + doesn't evaluate frameless went through the general call. A declined + `FORMAT_VALUE` now calls the method directly on the field's slots + (an empty spec when there is none) and takes its result as + `PyObject_Format` does (the new `MethodOp::Format`) (`f"{k}"` + through a `__format__` that calls a method 1.63 to 0.73 times + CPython). The general path rendered a `str` subclass result as its + repr (`"'subz'"`); it now takes the text. + - `str(obj)` of an instance whose class's Python `__str__` doesn't + evaluate frameless went through the general constructor call. The + call site now calls the method directly, the type's slot taking it, + and takes the result as `str()` does (the new `MethodOp::Str`); a + warm pure-leaf `__str__` keeps its frameless path (`str(k)` through a + `__str__` that calls a method 1.34 to 0.73 times CPython). + - A read that a class's frameless `__getattr__` answered went straight + to the hook again only when the receiver was a local; one on the + stack (a global, an attribute chain, a call's result) took the whole + miss detection first. The stack receiver's slow read now tries the + site's hook memo first, as the local's does (a proxy's `p.a` through + `__getattr__` 1.43 to 1.13 times CPython). + - A `bytes` iterator feeding a native adapter (`map`, `filter`, `zip`) + took the general checked step for each item, the dictionary + iteration guard included; it now takes the plain cursors' in-place + step, as its `pure_ready` already promised (`urllib.parse.quote`, + whose drain is `map(quoter, bs)`, 3.6% fewer instructions). + - A callable instance (its class's Python `__call__`) as a native + adapter's callback (`map(adder, xs)`, a `filter` predicate) took the + general call for each item, which built a bound `__call__`. The + callback now calls the class's function over the instance and the + item, frameless when it is a pure leaf (`list(map(adder, range(20)))` + 2.30 to 1.31 times CPython, an `__call__` that counts 3.10 to 2.50). + - Compiled `repr(obj)` and f-string `!r` and `!s` conversions of an + instance whose class's `__repr__` or `__str__` is a Python function + took the general call, as `str(obj)` did. They now call the method + directly, as the `len(obj)` and `str(obj)` lanes do (`repr(k)` 1.16 to + 0.75 times CPython, a frameless `__repr__` 1.76 to 1.14, `f"{a!r}"` + 1.66 to 0.78). The `str(obj)` lane had sent an enum member to its + `Enum.__str__` (0.87 to 1.24); these lanes now take the text the + general call finds natively first, an enum member's, a number + subclass's, or a `Decimal`'s (`str(Color.RED)` 0.62, `repr(Decimal)` + 1.10 to 0.92, `f"{d!r}"` 2.05 to 0.86). + - `k in d` and `k in s` of an instance whose class's `__hash__` and + `__eq__` both evaluate frameless settled in place only when the + stored key was the same object. An equal but distinct key made each + of three in-place tests hash it and decline before the general path + hashed it a fourth time. The in-place test now compares a stored key + of the same hash with the frameless `__eq__` too, as the subscript's + probe does, and so does compiled `d.get(k)` (`k in d` 2.81 to 1.12 + times CPython, `k in s` 2.99 to 1.14, `d.get(k)` 1.90 to 1.08). + - `template % args` whose conversions are all bare `%s`, over plain + instances (with `str` and `int` arguments beside them), went through + the general `%` engine, which runs each conversion through the full + spec formatter, after two fast paths that decline instances. Such a + template now renders in one pass, each instance's text as the engine's + `%s` takes it (its `__str__` frameless when a pure leaf), and anything + else (a count that doesn't match, a tuple subclass, a width) still + goes to the engine (`"%s" % k` 2.72 to 1.42 times CPython, with a + `__str__` that formats 2.53 to 1.90). + - Compiled `d[k]` of an instance key whose class's `__hash__` + evaluates frameless took the general subscript in place, which probes + the table through the reentrant path. The in-place subscript now + reads it with the frameless hash, matching a stored key as itself or + by a frameless `__eq__`, and leaves a miss and anything else to the + general path (`d[k]` 1.32 to 1.16 times CPython, an equal key with a + frameless `__eq__` 1.35 to 1.18, one with a full `__eq__` 1.21 to + 1.14). + - `str(obj)`, `f"{obj}"`, `f"{obj!s}"` and `"%s" % obj` of an instance + whose class defines only a Python `__repr__` took the general call, + since the direct lanes looked only for a Python `__str__`. They now + call the `__repr__` that `object.__str__` calls (an empty-spec + `f"{obj}"` through `object.__format__`'s `str(obj)`), its result + checked as `__str__`'s, and the frameless `str()` path evaluates a + pure-leaf `__repr__` too (`str(q)` 1.85 to 0.86 times CPython, + `f"{q}"` 1.96 to 0.74, a frameless `__repr__` 2.35 to 1.49, `"%s" % q` + 1.60 to 1.46). A non-string result's TypeError now says `__str__`, as + CPython's does. + - `mc(obj)` of an `operator.methodcaller` whose method is a Python + function of `obj`'s plain class ran the native `__call__`, which made + a full call of the method from native code. A compiled call site now + lays the call out as `obj.name(*args)` (up to two stored arguments) + and calls the method directly, and a native adapter's callback calls + it over the item and the stored arguments, frameless when a pure leaf + (`mc(q)` 2.21 to 1.65 times CPython, `list(map(mc, qs))` 3.08 to + 2.60). + - A compiled loop that stores a pair whole (`for t in enumerate(xs)`, + `for kv in d.items()`, `for t in zip(xs, ys)`) built a tuple a step + and released the last one through the store's helper and the tuple + free list, about 370 instructions an item, twice CPython's. The + `FOR_ITER` now refills the local's previous pair in place when the + local holds it alone and its items release without running anything, + as CPython's free list would hand the same allocation back (a tuple + counted once checked in line first, so a list of pairs' loop doesn't + call the helper). `for t in enumerate(xs)` went from 2.09 to 0.90 + times CPython, `for kv in d.items()` 2.26 to 1.07 and `for t in + zip(xs, ys)` 1.44 to 1.09; other loops are within a few instructions. + - A compiled `d[i]` of an exact dict missing an int key left compiled + code at every miss: the helper that raises a missing key's `KeyError` + in place took an int key for a sequence index and gave up on any + other container. A dict's int key now reaches its own check, so the + frame's handler catches the miss in compiled code (`try: d[i] except + KeyError` 1.95 to 1.40 times CPython). + - A tier-2 comparison of two tuples (or strings, or numbers the typed + lanes don't hold) went through the interpreter's rich comparison and + then rechecked every guard the loop depends on, since Python code + could have run. A comparison no Python code answers (see + `plain_compare`) is now settled off the borrowed operands with no + guard rechecked, as tier 2's leaf binary operations are, and a pair or + triple it builds goes into a fixed-size allocation (`(i, i) == (i, + i)` in a loop 1.57 to 1.19 times CPython). + - A keyword call of a `**kwargs` function probed the dictionary for + each keyword it collected, through a borrow of the dictionary's cell, + and the interpreter's frameless path allocated and freed a new + dictionary each call. A call's keyword names are distinct (the + compiler rejects a repeat), so each is now appended without a probe, + through the one handle the call holds, and the frameless path reuses + the spare dictionary tier 2's keyword calls keep when the callee can't + let it escape (`f(a=1, b=2)` of `def f(**k)` 1.63 to 1.42 times + CPython, five keywords 1.48 to 1.29). + - A tier-2 `type(x)` cloned the pinned `type`, staged its argument in + an owned four-slot array and went through the native constructors' + dispatch before pinning the class. It now reads the argument's class + off the borrowed pin (`type(i) is int` in a loop 1.57 to 0.92 times + CPython). + - Every list and dict a program builds is registered with the cycle + collector's deferred set, which first reaps up to two dead + predecessors at its tail. That check ran as a reversed range loop, a + third of the registration's cost; unrolled, a build saves about 22 + instructions (`[0] * 8` in a loop 1.20 to 1.16 times CPython). + - A compiled construction of a class whose `__init__` runs on a frame + of its own (one that calls `super().__init__`, say) first tried the + frameless paths on every call: the arguments' defaults counted, the + store-only shape and the leaf verdict asked again, about 175 + instructions, though the class's plan had already found no store-only + shape and the code no leaf (verdicts that don't turn for the class's + version). Those attempts are now skipped (`R(i)` whose `__init__` calls + `super().__init__(x, 1)` 1.40 to 1.32 times CPython). + - A tier-2 `len(dq)` of a deque looked up the class's `__len__`, asked + the builtin's leaf verdict and called it, and the builtin then read + the length through the same direct operation the deque's methods use. + A deque's own `__len__` (recognized by identity, as this thread's + `collections` module registered it) now reads the length directly + (`append`, `len(dq)`, `popleft` in a loop 1.32 to 1.15 times CPython). + - A compiled call of a leaf builtin initialized a four-object scratch + array on every call, used only when the callee is a bound method of + the builtin or an instance whose native `__call__` it is. It's now + left uninitialized until an arm writes it (about five instructions a + call, `next(iter(xs), None)` 1.26 to 1.25 times CPython). + - `str(obj)` of a plain class's instance asked whether it was a + number subclass's or an enum member's first, about 60 instructions of + class verdicts. A number's text needs a native payload and an enum + member's class a metaclass of its own, so a plain class's instance + (no payload, a `type` metaclass) now asks neither. + - A compiled `str(obj)` whose `__str__` (or the `__repr__` that + `object.__str__` calls) is a warm pure leaf left it to the type call's + frameless path, which looks the method and the leaf verdict up again, + and `repr(obj)` and `len(obj)` called such a leaf directly as an + activation. All three now evaluate it in place, as the f-string lanes + do, the result checked as each protocol checks it (`str(q)` 1.44 to + 1.04 times CPython, `str()` of a repr-only class 1.46 to 1.07, + `repr(r)` 1.14 to 0.90, `"".join(str(q) for q in qs)` 1.42 to 1.20). + - The other askers of the enum-member verdict (`"%s" % obj` and the + general `str()` path ask it twice an operand) now skip it for a plain + class too, the metaclass check moved into the verdict itself (`"%s" % + q` about 70 instructions fewer). + - A unary operator (`-x`, `+x`, `~x`) on an instance left compiled + code at every run, and `abs(obj)` went through the builtin's general + call. The full handler now marks unary sites that see instances, + where the frame JIT puts the operand on the stack and calls the + class's Python `__neg__`, `__pos__` or `__invert__` directly, and + `abs()` joins the `len()` and `repr()` lane (a warm pure leaf + evaluated in place) (`-d` 3.23 to 0.78 times CPython, `abs(d)` 2.46 + to 0.97). Set aside on 2026-11-27 after `test_multiprocessing_forkserver` + timed out beside it; that test times out and fails as often without + it (8 runs each, two at once). + - `iter(obj)` of an instance whose class's `__iter__` is a Python + function joins the same lane, its result checked as `iter()` checks + it (`iter(d)` 1.81 to 1.39 times CPython). + - `n obj` of a plain number and an instance whose class defines the + reflected method (`2 * v` through `__rmul__`, `1 + v` through + `__radd__`) left compiled code at every run: the binary-operator lane + took only an instance on the left. A number's own operator answers + `NotImplemented` for an instance, so the lane now calls the class's + Python reflected method directly with the operands swapped, a + `NotImplemented` from it the operator's `TypeError` with the operands + in written order (`1 + d` 3.20 to 1.18 times CPython). + - The enum-member check's plain-class test looked only for an unset + metaclass, but a class statement records `type` itself, so most + plain classes still asked the verdict. It now accepts either + (`"%s" % q` 1.50 to 1.41 times CPython). + - `format(obj)` of a class that keeps `object.__format__` (which is + `str(obj)`) joins the same lane as `f"{obj}"`: the Python `__str__` + (or the `__repr__` `object.__str__` calls) called directly, in place + when a warm pure leaf, its result checked as `__str__`'s (`format(q)` + 1.38 to 0.66 times CPython). + - An effect leaf (a method that stores attributes, run frameless with + its stores buffered) that read back an attribute it had just stored + went through the general attribute read to find the buffered value, + after the field read's own search of the buffer. The field read now + answers with the latest buffered store's value itself (`for x in + It()` over a class whose `__next__` does `self.i += 1`, then reads + `self.i`, 1.55 to 1.28 times CPython). + - `template % obj` of a tuple subclass's instance (a namedtuple's + `__repr__` runs `repr_fmt % self`) took the general formatter, and in + compiled code it left for the interpreter every time. Its tuple's + scalar and string items now go to the native formatter, as an exact + tuple's do (`repr(p)` of a namedtuple 2.37 to 0.95 times CPython, + `'%r' % p` 1.96 to 0.78). Compiled `hash(obj)` of an instance whose + class's `__hash__` is a Python function calls it directly, as `len`, + `repr` and `format` already did, its result settled as `hash()` + settles it (`hash(fd)` of a frozen dataclass 2.04 to 1.21). + - Asking which leaf builtin a callback is (`map(abs, xs)` asks once an + item) answered builtins from the interpreter's own table with a hash + lookup every time, since only the registry's answers refreshed the + one-entry cache in front of it. Those answers refresh it too now, and + the cache's check is in line in its callers with the lookups out of + line (`sum(map(abs, xs))` 1.96 to 1.85 times CPython). + - A frameless leaf evaluation ran `str + str` but declined `str % args` + and `str * n`, so a `__str__` or `__repr__` that formats its fields + (`return "Q%d" % self.n`) declined every call until 64 misses revoked + its verdict for good, and every caller outside the frame JIT's own + lanes (`"%s" % q`, `"{}".format(q)`, `map(str, xs)`, tier 2's calls) + paid a full Python call for it. The evaluation now runs both as the + core loop's string arms do (`"%s" % q` 1.85 to 1.15 times CPython, + `"{}".format(q)` 1.78 to 1.22, `", ".join(map(str, qs))` 2.00 to + 1.23). + - An f-string (`FORMAT_VALUE` and `BUILD_STRING`) made a function no + pure leaf, so a `__str__` or `__repr__` written as `return + f"P({self.x}, {self.y})"` never evaluated frameless. A plain + conversion of a string, int, float, bool or `None` (any other piece + declines) and the join now run in leaf evaluations (`"%s" % p` + of such a class 1.42 to 1.09 times CPython, `", ".join(map(str, + ps))` 1.68 to 1.21, `f"{p}"` 0.73). + - That join first concatenated two pieces and appended the rest one at a + time, each append regrowing the string. It now joins all of an + f-string's pieces (up to 16) at once from their registers + (`f"{type(self).__name__}(x={self.x})"` as a `__repr__` 1.37 to 1.16 + times CPython, `self.__class__.__name__` 1.29 to 1.11). + - Once `collections` registered `ChainMap`'s native `__contains__`, + every `x in obj` of an instance asked whether the class was a + `ChainMap` first, looking `__contains__` up by name, uncached, before + the class's cached Python `__contains__`. The cached method comes + first now, and only a class without one asks (`3 in box` of a class + with a Python `__contains__` 1.37 to 1.18 times CPython). + - Among the standard library's small loop-free functions, an f-string's + `!r` (`CONVERT_VALUE`) and `a, b = pair` (`UNPACK_SEQUENCE`) were + the second and third commonest single instructions keeping one from + being a leaf. Leaf evaluations now run `!s` and `!r` of strings, + numbers, bools and `None`, and unpack an exact tuple or list of up to + eight items (`sorted(pairs, key=f)` with `a, b = pair` in `f` 2.63 to + 1.34 times CPython, `list(map(repr, objs))` with an `!r` `__repr__` + 1.28 to 0.98). A compiled `repr(obj)` of such a class now evaluates + it in place rather than calling its compiled body (0.82 to 0.87). + - A fresh generator whose start no fast step runs (a call building its + loop's iterator, `for i in range(n)`) went through every check of the + native step, then the fast step's, before declining to the lazy + resume that runs its first step. Its prologue verdict is now checked + first (`for x in gen(1)` 1.87 to 1.76 times CPython, about 220 + instructions a generator). + - Leaf evaluations also run `seq[a:b]` with computed bounds + (`BINARY_SLICE`, lowered to the slice and subscript they already ran) + and dict literals of up to eight pairs whose keys a native probe + hashes and compares (`return {"x": x, "y": y}`; a duplicate keeps the + first key and the last value, as a literal does): `s[a:b]` in a small + function 0.81 to 0.67 times CPython, `list(map(lambda w: {"w": w}, + words))` 2.35 to 1.64. + - So do list literals and tuples past three items (up to eight each, + built from their own registers): `return [a, b]` 1.05 to 0.87 times + CPython, `sorted(words, key=lambda w: [len(w), w])` 1.66 to 1.44, + `list(map(lambda w: (w, w, w, w), words))` 2.67 to 1.80. + - Two trims to those evaluations: a list or tuple's items are gathered + in a plain loop (collecting them through `Option` cost 35 + instructions an item), and an f-string's `!r` piece skips the plain + conversion after it, which only passed the string on + (`list(map(repr, objs))` with an `!r` `__repr__` 1.06 to 0.96 times + CPython; compiled `repr(obj)` of one 0.89 to 0.84, against 0.83 + before such a `__repr__` evaluated in place). + - A builtin type's method called through the type (`map(str.upper, + words)`, `str.lower(s)`) checked its receiver against the type, then + cloned the receiver to unwrap a subclass's payload, even for an exact + value of the type. An exact value now goes straight to the body + (`list(map(str.upper, words))` 1.91 to 1.55 times CPython). + - An instance used as an index (`xs[obj]`, `range(obj)`) had its + `__index__` looked up as an instance attribute, uncached, then called + as a bound method, and compiled `xs[obj]` left for the interpreter + every time. A plain instance's class's Python `__index__` is now + found through the class's cache and evaluated in place when a pure + leaf, and compiled code reads a list's, tuple's or string's item + with it (`xs[obj]` 4.77 to 0.87 times CPython, `range(obj)` 4.00 to + 2.75). + - A binary operator run outside compiled code (`sum()`, + `functools.reduce`, `operator.add`) called one Python method directly + only for two instances of one class with no reflected method; anything + else looked both methods up by name and called them as bound methods. + It now finds the method as compiled code does: two instances of one + class (whose reflected method CPython never tries), an instance over a + scalar, or a number over an instance's reflected method, through the + class's cache (`sum(objs, 0)` over a class with `__add__` and + `__radd__` 2.51 to 1.97 times CPython). Bringing that path in line + showed the compiled one wrong for a built-in subclass's instance over + a scalar (`Evil(int) + 1` whose `__add__` returns `NotImplemented`): + it raised the operator's TypeError where the scalar's own slot adds + the payload. Neither takes that shape now. + - A method that stores into a dict or list (`self._d[k] = v` in a + `__setitem__`) was no effect leaf: only attribute stores, buffered + until the return, were. A subscript store now lands at once where + nothing after it can decline and no attribute store waits, as + compiled stores run it (a displaced value whose release could run + code declines, and the one it displaces is held until the evaluation + ends, since registers may still borrow from inside it, as + `xml.dom.pulldom`'s `_emit` reads an event out of the node it then + unlinks); anywhere else the evaluation declines (`d[k] = v` + through a Python `__setitem__` from a tier-2 loop 2.17 to 1.19 times + CPython). + - A pure-leaf callback called without its trailing defaulted + parameters (`map(scale, xs)` of `def scale(x, factor=2)`, a sort key, + `c.get(k)` of `def get(self, k, default=None)` through `map`) wasn't + evaluated in place: the native callers' leaf call wanted every + parameter given. The function's defaults now fill them, unless + keyword-only parameters, `**kwargs` or a replaced `__defaults__` are + in play (`list(map(scale, xs))` 3.89 to 1.26 times CPython, + `sorted(xs, key=scale)` 4.23 to 1.22). + - So do the dunder calls the runtime makes itself (`call_dunder_function`: + operators outside compiled code, tier 2's subscripts), and `round(obj)` + now finds a plain instance's class's Python `__round__` through the + class's cache and calls it so, rather than looking it up by name and + calling it as a bound method (`round(obj)` with `def __round__(self, + ndigits=None)` 3.95 to 1.40 times CPython). + - A compiled leaf plan's `isinstance(other, C)` (the first test of most + `__eq__` methods) went through the builtin call's method-slot and + kind lookups before the check itself. It now goes straight to the + check, as the core loop's leaf arm runs it (`x in objs` over a class + whose `__eq__` tests `isinstance` first 1.63 to 1.42 times CPython). + - `list()`, `tuple()` or `sorted()` of a range's iterator + (`reversed(range(n))`, a partly consumed `iter(range(...))`) stepped + it an item at a time into an unsized vector. The rest of its ints is + now built at once, presized, the iterator moved to where its steps + would leave it (`list(reversed(range(20)))` 1.73 to 0.97 times + CPython). + - A store through a property's Python setter (`obj.v = x`) first tried + the plain store, which failed only after checking the class, and + then looked the property up again through the class's cache before + running the setter. The store's site now remembers the property and + its setter under the class's attribute version, so later stores at + that site skip the plain store and the lookup. A re-initialized + property, a new `__setattr__` or a receiver of another class takes + the full path again. A local receiver's store went from 1.39 to 0.92 + times CPython, a global's from 1.43 to 0.90 and a slotted class's + from 1.49 to 0.92. + - A read answered by a class's Python `__getattr__` rechecked the whole + default lookup each time: the class's `__getattribute__`, a cached + verdict that the class lacks the name, the instance's own dictionary + and the hook's lookup. A site that saw the hook answer now keeps the + class version only when the class certainly lacks the name, and under + that version probes only the instance's dictionary. A compiled leaf + plan's `d.get(k, default)` also probes the dictionary directly + instead of going through the builtin's method slot and kind lookups + (`def __getattr__(self, name): return self.data.get(name, 0)` 1.35 + to 1.04 times CPython, a hook that returns a constant 0.88 to 0.62). + - A compiled leaf plan's `len(x)` of a `str`, `list`, `tuple` or `dict` + went through the builtin's method slot, its kind and the general + builtin call. It now reads the length in line, as the plan's `hash(x)` + already did. `min` and `max` with a key compared each pair of keys + through the full rich comparison; keys that compare without running + code (numbers, strings, tuples of them) now compare natively first + (`max(words, key=lambda w: len(w))` 1.42 to 1.21 times CPython, + `key=lambda w: (len(w), w)` 1.51 to 1.28). + - A compiled call of `functools.partial(operator.add, 3)` settles its + site on `operator.add`, the call the core loop makes once it unwraps + the partial. The site's lane then saw the partial instance, missed, + and went through `h_call`'s whole chain of lanes before reaching the + builtin's fast half. The lane now unwraps the partial itself and runs + that fast half on the stored argument and the call's (1.26 to 0.98 + times CPython). + - `any()` and `all()` of a `map` or `filter` stepped it through the + general iterator protocol and tested each item's truth in full. They + now step a native adapter the way its own native step does, read a + plain item's truth directly, and settle a `map` builtin's leaf kind + once rather than per item. ASCII `str.isupper()` and `str.islower()` + read bytes instead of case tables, `str` methods check their argument + count in line, and `str.split` with a one-byte separator allocates its + list once for a short line (`any(map(str.isupper, words))` 2.44 to + 1.73 times CPython, `all(map(str.islower, words))` 2.28 to 1.50, + `"a,b,c".split(",")` 1.32 to 1.07). + - A named tuple's field read in compiled code (`p.x`) tried the site's + field and class memos, which never hold a field descriptor's answer, + before the tuple field stamp that answers it. The stack, local and + inlined-body read helpers now check that stamp before their slower + lanes (`p.x + p.y` of a global 850 to 546 instructions an iteration, + `self.x` in an inlined method 1,476 to 731, 0.52 times CPython). A method call with a computed argument on an instance whose + site cached a native method (`od.move_to_end(i % n)`) skips the fused + call's general native path for the method load and the call site's + native lane, and `OrderedDict` leaves borrow its two dicts instead of + cloning them (1.74 to 1.28 times CPython). + - `sorted(xs, key=attrgetter("name"))` read each key through the + getter's general attribute read. The sort now settles the getter's + name once and, for a `__slots__` class, the slot's position once per + class (2.67 to 0.96 times CPython). `list(filter(f, xs))` with a leaf + builtin predicate runs it in place, as `map` does, then tests the + result's full truth, and `str.isalpha`, `isalnum`, `isspace`, + `isdigit`, `isdecimal` and `isnumeric` read ASCII text in one pass + (`list(filter(str.isalpha, words))` 2.08 to 1.52). + - A boolean comparison from native code (`min`, `max`, `in`, + `list.index`) of a plain instance whose comparison method is a pure + leaf now evaluates that method in place, forward or reflected, ahead + of the protocol's lookups and call layers. A `!=` that `object.__ne__` + answers (a class defining only `__eq__`) inverts the leaf `__eq__`'s + answer the same way, in compiled code too (`a != b` 3.13 to 0.60 + times CPython, `min(objs)` 1.71 to 1.24, `objs.index(x)` 1.76 to + 1.39, `max` of a `total_ordering` class 2.88 to 1.95). + - A comparison of two instances inside a pure method (`self != other` + in `total_ordering`'s `__gt__`, `self.p == other.p` in an `__eq__`) + declined the whole leaf evaluation, so the method ran as a full call. + Leaf plans, interpreted and compiled, now run the instances' + comparison method as a nested leaf call, under the nested-call limit + and never while a store waits (`max` of a `total_ordering` class + 1.95 to 1.18 times CPython). + - `del buf[i]` of a bytearray left compiled code for the interpreter + on every call. The container instruction lane now removes the byte in + place when no buffer view holds the bytearray. `str.splitlines()` on + ASCII text skips the runs between line breaks a word at a time, and a + line with no break gives the string itself, as CPython does + (`ba.extend(b"x"); del ba[-1]` 1.99 to 0.96 times CPython, + `s.splitlines()` of one line 1.25 to 0.82). + - A sort key that is a lambda returning one part of its argument + (`lambda kv: kv[1]`, `lambda r: r["age"]`, `lambda p: p.x`) ran as a + leaf call for every item. The sort now reads such a lambda's shape + once and takes each item's part directly, as it does for + `itemgetter` and `attrgetter`, unless a trace or profile hook is + active (`sorted(d.items(), key=lambda kv: kv[1])` 1.39 to 0.62 + times CPython). + - `f(*args)` in compiled code of a warm leaf function reached the leaf + through three layers built for a frame view of the call. A lane ahead + of them now evaluates a leaf whose parameters the tuple fills exactly + in place, releasing the operands last first when the tuple held the + last references to its items, as the full call does (`f(*args)` 1.39 + to 1.09 times CPython). Leaf plans read `len()` of a list or dict + without a borrow guard, and the check that a builtin's fast half only + reads its arguments is one set lookup instead of scanning three + tables. + - Tier 2 reads the count of weak references made before and after + every native method call (`d.append(x)` on a deque), to leave for the + interpreter when the call made one. The count was a thread-local, + which costs a runtime call on macOS; it is now one process-wide atomic + read with a plain load (`d.rotate(1)` in a loop 1.28 to 1.12 times + CPython). + - The one-part lambda shape the sort reads (`lambda w: w[0]`) is now + decided once per code object and read by every native adapter's + callback (`map`, `filter`, `itertools.groupby`, `min`/`max` keys), + strings' items included, rather than run as a leaf call per item + (`groupby(words, key=lambda w: w[0])` with `list(g)` 1.56 to 1.43 + times CPython). + - A `for` loop over an `itertools` adapter stepped it through four + dispatch layers, each testing for the kinds it takes (a `chain` cost + about 200 instructions an item before reading it). `islice`, `chain`, + `count` and `cycle` now step in one small helper ahead of them, an + `islice`'s skipped items included (a step other than 1 used to take + the general path every time), and every other adapter goes straight + to its own step. A two-source `zip_longest`, `zip(count(), xs)` and + `compress` over lists read their cursors in place, and `next()` and + `sum()` use the same steps. Against CPython: `for x in islice(ys, 5, + 95)` 2.49 to 1.28 times, `for x in chain(ys, ys)` 1.78 to 1.18, `for + x, y in zip_longest(ys, ys)` 5.07 to 1.15, `for i, y in zip(count(), + ys)` 2.47 to 1.16, `for x in compress(ys, sel)` 2.20 to 1.42, + `list(zip_longest(ys, ys))` 2.47 to 1.16 and `sum(islice(count(), + 100))` 3.74 to 2.18. + - `heapq` compared tuple entries (`(priority, count, task)`, the usual + heap item) through the full comparison protocol, about 440 + instructions a comparison. Two exact tuples that differ first at a + pair of ints, floats or strs (or are equal throughout such pairs) + now compare in place, as two scalars already did; anything else, + NaNs included, still takes the full comparison (`heappush` and + `heappop` of `(int, int)` entries 1.39 to 0.73 times CPython, a + Dijkstra loop over a dict graph 1.14 to 0.67). + - Tier 2 keeps each object a loop reads off another in a table entry + until the activation leaves, so a loop that walks a linked structure + (`while n is not None: t += n.v; n = n.nxt`) added an entry a node + through the read's helper: 486 instructions a node against the frame + JIT's 185. Tier 2 now leaves a function whose loops do that + (`x = x.attr` of the object lane) to the frame JIT unless they do + enough typed arithmetic or make a typed Python call, as it already + did for loops over lists of objects (the walk above 1.71 to 0.65 + times CPython with slotted nodes, 1.49 to 0.63 with dict-backed + ones). + - `itertools.accumulate(xs, func)` called its function through the + full call machinery for every item. Over a list or tuple, a callback + that runs no Python frame (`operator.add`, `max`, a small lambda) + now runs in place while the running value is a plain scalar, as + `map`'s callback does (`list(accumulate(xs, operator.add))` 3.18 to + 1.57 times CPython). + - A deque is a Python class over native helpers, and several of its + protocols still ran Python or left compiled code. `for x in d` now + gets its iterator, steps it and ends without leaving compiled code + (the loop's end used to raise `StopIteration` twice and resume in + the interpreter); `list(d)`, `sorted(d)` and the like copy the items + off the backing list; `x in d` searches plain items natively; + `deque(range(n))`, `deque("text")` and `deque(xs, maxlen)` (so + `d.copy()`) build the instance directly; and `extend` steps any + iterable in a native loop. Each lane checks, once per class version, + that the class still has the native method. Against CPython: `for x + in d` 8.01 to 2.37 times, `list(d)` 3.90 to 0.99, `5 in d` 2.65 to + 0.80, `deque(range(10))` 2.37 to 0.71, `d.copy()` 1.87 to 1.06 and + `d.extend(range(3))` with three `popleft` calls 3.58 to 2.32. + - A subscript of a dict subclass (`defaultdict`, `Counter`, a plain + subclass) took its in-place lane only for a `str` or `int` key that + something else also held: a tuple key, or a key the subscript held + alone (`d[w + "x"]`), fell to the method lookup, and a `defaultdict` + miss with such a key left compiled code. Reads and stores now go to + the payload as an exact dict's do, for any key that compares + natively, a missing `defaultdict` key built in place, in the frame + JIT (the site that once ran `__missing__` included) and in tier 2. + Against CPython: `g[w + "x"].append(w)` on a fresh `defaultdict` + 3.41 to 1.09 times, `g[(j, j)].append(j)` 3.57 to 1.14, `dd[(a, b)]` + 1.40 to 0.87, `dd[(a, b)] += 1` 1.77 to 0.97, and grouping words by + `"".join(sorted(w))` 1.45 to 1.02. + - Several operations on dict subclasses went through the mapping + protocol a key at a time where an exact dict takes one native pass. + A `for` loop over a `defaultdict` or `Counter` left compiled code to + find `__iter__`; it now gets the payload's iterator in place, and + `list(d)`, `sorted(d)` and the like collect the payload's keys. + Merging or copying from a subclass that keeps dict's `__iter__`, + `keys` and `__getitem__` (remembered per class version) reads its + table directly, as CPython's `dict_merge` does: `Counter(c)`, + `c.copy()`, `d.update(c)`, and `defaultdict(f, d)` (so `dd.copy()`) + copy the table whole. An exact `OrderedDict` hands its entries over + in its own order for `dict(od)` and `od.copy()`. `dict == dict` + compares in place while keys and values settle natively, instead of + copying both dicts first, and `key=d.get` of such a subclass runs in + place. Against CPython: `od.copy()` 11.61 to 2.23 times, + `Counter(c)` and `c.copy()` 6.74 to 0.92 and 1.03, `dd.copy()` 4.06 + to 1.00, `list(dd)` 3.86 to 0.96, `dict(od)` 3.62 to 0.83, `max(d, + key=d.get)` 3.83 to 1.74, `dd == od` with tuple keys 3.56 to 2.67, + and `for k in dd` 2.38 to 1.57 (what is left there is every dict's + iteration step, 1.3 to 1.5 times CPython's). + - An `OrderedDict` store by a tuple key, or by a key the store held + alone, left compiled code: its in-place store took `str` and `int` + keys only, and settled an owned key's release before storing. It now + takes any key the store's leaf half probes natively and releases an + owned key in full afterward. `od.copy()` and `OrderedDict(od)` of a + dict whose order is its payload's own (nothing moved to an end, keys + that compare natively) copy both tables whole instead of storing a + key at a time. Against CPython: `od.copy()` 2.23 to 0.52 times, + `OrderedDict(od)` 1.31 to 0.61, and filling an `OrderedDict` by + tuple keys then draining it with `popitem` 2.83 to 1.47. + - `==` between instances of list, tuple, set or dict subclasses that + inherit their type's equality (two named tuples, a named tuple and a + tuple) left compiled code and compared an element at a time through + the interpreter; such operands now compare as their payloads, as a + number or string subclass's already did. A `for` loop over a set + subclass took a general step in the interpreter for every element; + it and `list()` of one now use the payload's iterator. `sum()` of an + `array.array`, a deque or such a subclass sums the items in one pass + while they are plain numbers. Against CPython: `L(xs) == L(ys)` + 10.86 to 1.29 times, `T(xs) == T(ys)` 7.21 to 1.33, `S(a) == S(b)` + 4.59 to 0.74, `for x in S(a)` 10.03 to 1.10, and `sum(array)` 11.17 + to 1.54. + - The compiler's memo of nested functions' free names (kept by each + function's place in the tree) also answered for the copies of + statements the compiler makes and frees along the way (a class + body's, for name mangling): a later copy could land where an earlier + one had been and get its answer, so a module could end up holding + `__class__` as a free name with no cell behind it ("bad cell index" + importing `test_dataclasses`, depending on where allocations fell). + The memo now keeps only the functions of the tree the compilation + was given, which lives unchanged until it ends. + - A named tuple (or any tuple subclass that inherits `__hash__` and + `__eq__`) used as a dict key or set element was hashed and compared + through the general path on every probe; its payload now hashes and + compares natively. A truth test alternating between two or three + classes thrashed the single remembered verdict; three more are kept. + A slice of a `range` with machine-sized bounds no longer goes through + big-integer arithmetic, and `len()` of a mapping proxy or memoryview + is read in compiled code. Against CPython: `d[nt]` 8.74 to 1.61 + times, `hash(nt)` 2.94 to 1.06, `nt in s` 6.46 to 3.44, truth tests + of two and three classes in one loop 3.65 to 1.05 and 3.88 to 1.21, + `r[2:8]` 4.28 to 1.68, `len(mappingproxy)` 4.15 to 1.21, and + `len(memoryview)` 4.45 to 1.58. + - A `for` loop over an `array.array` called the iterator's `__next__` + through the general step for every item; the loop now builds the + iterator with no Python code and reads each item off the buffer in + its own small helper, and `tolist()` reads them in one pass. + `hasattr()` and `getattr()` with a default on a `SimpleNamespace` + answered a miss by building and discarding an `AttributeError`; they + now answer from its dictionary. A store to a namespace that isn't a + local (`cfg.x = v` on a global) left compiled code on every pass. + `+` and `*` on list and tuple subclasses that keep their base's + methods run as their payloads' operations, a set subclass built from + a set copies its table whole, and the default reduction of an + instance with `__slots__` (what `copy.copy()` and `pickle` ask for) + is built natively once `copyreg` has left the slot names on the + class. Against CPython: `for x in array` 7.96 to 2.05 times (floats + 5.44 to 1.45), `array.tolist()` 4.63 to 1.67, `hasattr(ns, "z")` + 7.56 to 1.04, `ns.b = i` on a global 2.52 to 0.95, `L(xs) + L(ys)` + 3.83 to 2.48, `S(s)` 3.15 to 1.58, `x.__reduce_ex__(4)` of a slotted + instance 11.75 to 1.45, and `copy.copy()` of one 4.61 to 1.50. + - `datetime.time` had no native lanes: building one ran the Python + `__new__` and its checks (16,000 instructions), and hashing, + comparing or formatting one ran Python methods. An exact `time` is + now built, read, hashed, compared and formatted natively, as `date` + and `datetime` are, and so are `datetime.time()`, `timetz()`, + `combine()`, `date.fromordinal()` and `str()` of a date or datetime. + `hash()` of a date, time, datetime or timedelta, and a dict or set + probe by one, reach the native hash without a call, and a field of a + value that isn't a local (`CONFIG_DATE.year`) is read ahead of the + site's other lanes. `setattr(obj, name, value)` stores into a + `__slots__` member in place. Against CPython: `time(1, 2, 3)` 9.39 + to 1.07 times, `dt.time()` 33.95 to 2.67, `hash(t); t == t` 10.53 to + 3.16, `t.isoformat()` 2.48 to 0.44, `datetime.combine(d, t)` 2.94 to + 1.17, `date.fromordinal(n)` 5.33 to 0.86, `str(dt)` 4.00 to 0.51, + `hash(dt)` 3.91 to 1.35, `GLOBAL_DATE.year` 1.70 to 0.67, and + `copy.copy()` of a slotted instance 1.50 to 1.34. + - A `for` loop over an `OrderedDict`, or over its `keys()`, `values()` + or `items()` view, left compiled code at `GET_ITER` to call the + native `__iter__` through the interpreter and registered the iterator + with the collector; the loop now builds the order iterator in place, + unregistered like a plain dict's. `array.array`'s `pop`, `insert`, + `remove`, `extend`, `reverse`, `count`, `index`, `tobytes`, `in`, + `del` and `==` were Python methods over a list copy of the array; + they have native halves that read the buffer (for subclasses too, as + CPython's C methods do), and a tuple builds an array natively. A + multi-name `operator.attrgetter` reads plain attributes without a + frame. Tier 2's pin memo keeps each tag beside its pin index, a + set's entries together, so a lookup reads one stretch of memory. + Against CPython: `for k in od` 3.97 to 1.66 times, `for k, v in + od.items()` 3.07 to 1.82, `attrgetter("x", "y")(p)` 3.66 to 1.79, + `a.append(x); a.pop()` 6.62 to 0.98, `a.insert(0, x); a.remove(x)` + 12.19 to 1.24, `a.index(x); a.count(x)` 1.39 to 0.45, and + `array("i", (1, 2, 3))` 4.23 to 1.01. + - Tier 2 aborted the process ("below the cap") when one of its + attribute reads returned an instance whose class defines `__del__`: + a pin never holds such a value (it would delay the finalizer), and + the read took a refused pin for a full table. The read now hands the + value back to the interpreter, as it does at the cap. A hot loop + reading such an attribute (`x = self.resource`) crashed on `main` + too. + - A store to a module attribute from outside the module (`mod.x = v`, + as `warnings.catch_warnings` rebinds `warnings.filters`) went through + the dict's general insert, which re-stamps it: every cached global + load in that module then missed and left compiled code once. A name + the module already holds is now rebound in place, as `STORE_GLOBAL` + rebinds it (the builtins module keeps the stamping store, which the + sites that fuse `len(x)` rely on), and the store has a lane in + compiled code. Native functions run in place from compiled code only + when listed as never reading the calling frame; `sys.getsizeof`, + `abc`'s instance and subclass checks, `time.mktime`, the `datetime` + and `warnings` helpers, `open` and the `os` file calls, `pickle` and + `json` round trips, `binascii`, `csv` and `re`'s cache were missing + and left compiled code on every call. Truth tests of a class, mapping + proxy, range, slice, memoryview, complex, property or dict view on + the stack (`x = cls or default`), `n in range(...)`, a range's + slice and `del buf[a:b]` of a bytearray also left it. Against + CPython: `with warnings.catch_warnings()` 3.48 to 1.70 times, + `isinstance(x, Proto)` for a runtime-checkable protocol 4.08 to 2.67, + `sys.getsizeof(x)` 2.43 to 0.68, `d.isocalendar()` 14.61 to 6.42, + `27 in r` 1.39 to 0.33, `r[2:8]` 1.66 to 0.68, and `buf.extend(b); + del buf[-2:]` 1.86 to 1.01. + - A call to a small function that takes `**kwargs` (`def f(a, **kw)`) + fell between two lanes in compiled code: the frameless leaf lane + turns away a body with extended parameters, and the direct call + turned away every leaf, expecting the leaf lane to take it. Such a + callee now takes the direct call. `+` and `*` on a `list` or `tuple` + subclass that overrides neither reached the payload's concatenation + only after the compiled operator had left for the interpreter; the + operator's helper now answers from the payloads itself. A + `datetime.time`'s native hash, comparison and accessors looked each + field up by name; they now read the slots by position, as the date + and datetime natives do. Against CPython: `f(i)` for + `def f(a, **kw)` 2.14 to 1.26 times, a method of that shape 2.12 to + 1.33, `sub + sub` for a list subclass 2.15 to 1.42 and for a tuple + subclass 2.20 to 1.11, `sub * 2` 2.16 to 0.99, `hash(t); t == t` for + a `time` 3.09 to 1.72, and `datetime.combine(d, t)` 1.22 to 1.00. + - A generator resumed from compiled code (`for v in gen():`, + `next(g)`) repeated, on every resume, checks that depend only on its + code and the pc it rests at: that no `yield from` rests there, that + the native code enters there, the body's verdict, the stack room. + The native code now remembers each pc a suspended generator has + resumed at and come to a `yield` or `return`, and a resume there asks + only what can change between two resumes (the frame's own extra + state, the recorder, the recursion depth, a body that lately stopped + partway): 296 to 219 instructions a resume before the body runs. A + slice with a `slice` object key (`xs[::2]`) went through the + subscript helper's general lanes before the slice lane, and a list's + contiguous slice copied item by item; `GET_ITER` of a list or tuple + tested the other kinds first; and the frame JIT stepped a tuple's + iterator through a helper call an item. A tuple loop now steps in + line, as a list's does. Against CPython: `for v in gen(10)` 2.11 to + 1.90 times, four `next(g)` calls 1.11 to 0.98, a generator method + loop 2.27 to 2.02, `zip(gen(), gen())` 2.23 to 2.09, + `xs[:]; xs[::2]; xs[-3:]; xs[2:8]` 1.37 to 1.23, a nested + comprehension over tuples of rows 1.44 to 1.28, and + `for x in tup: pass` with tier 2 off 1.52 to 1.05. A recursive + `yield from` walk pays the new check without using it (3.02 to + 3.08); generator loops remain about twice CPython's cost. + - `xml.etree.ElementTree`'s natives (WeavePy has no `_elementtree` + accelerator; the Python `Element` has native bodies) were reached the + slow way from compiled code. `for child in elem` left it at + `GET_ITER` on every loop and again at the loop's end, where the + native iterator's last step raised a `StopIteration` for the + interpreter to catch; `elem.find(path)`, `findall` and `findtext` + rebuilt the path's steps from `ElementPath`'s cache on every call + (four dictionary lookups by name, a tuple built to hash, each select + closure decoded again); and the iterator read `_children` and `tag` + by name through the instance dictionary. `GET_ITER` and `FOR_ITER` + now have lanes for an element and its iterators (`iter()` and + `itertext()` too), which end without an exception; each module keeps + the steps of the last four paths, valid while nothing has stored + into `ElementTree`'s namespace, `ElementPath`'s, or its cache; and + fields are read by position where the instance's values lie over the + class's shared names. Against CPython's C accelerator: + `for child in elem` 4.57 to 2.19 times, `elem.find("name")` 4.5 to + 2.2, `findtext` 4.9 to 2.1, `findall("item")` 1.75 to 1.09, + `for e in root.iter("item")` 3.17 to 2.56, a full `iter()` walk 7.40 + to 5.90, and a loop that reads an attribute and a child's text of + each item 3.25 to 2.20. The generator resume's new check moved to + the code object (four resume pcs in one word), so a generator + resting in a `yield from` is turned away before its locals are + looked at: the recursive walk is back at 3.03. + - An aware `datetime` whose `tzinfo` is a `zoneinfo.ZoneInfo` ran + almost everything as Python code. The `datetime` natives took only + `None` or an exact `timezone` for a `tzinfo`, so building such a + value, `replace(tzinfo=zone)`, and every operation on it fell back + to `_pydatetime`; each offset it then asked its zone for was + `ZoneInfo`'s pure-Python lookup (CPython has `_zoneinfo` in C): the + local timestamp, a bisection of the transitions and, past the last + one, the POSIX rule's two transition days of the year; and the + fields of a value the Python `__new__` had built were read by name, + a string scan each. The natives now keep any `tzinfo` object (an + instance of a `tzinfo` subclass, as the constructor checks), read + such a value's slots by position, and ask a new native lookup + (`stdlib::zoneinfo_native`) for a zone's offset, which reads the + zone's own data in place on every call, so it agrees with the Python + methods whatever is done to the zone. It serves a class that + resolves the zone methods to the base class's own and an instance + whose dictionary holds only what the module sets; anything else runs + the Python code. The zone's own `utcoffset`, `dst`, `tzname` and + `fromutc` have native bodies over the same lookup. Against CPython, + for a `ZoneInfo("America/New_York")` value: `dt.utcoffset()` 8.42 to + 0.86 times, `dt.replace(tzinfo=zone)` 16.86 to 1.85, building one + 3.64 to 0.36, `utc_dt.astimezone(zone)` 11.49 to 0.95, + `datetime.now(zone)` 15.60 to 1.13, `fromtimestamp(t, zone)` 10.15 to + 0.84, `dt.isoformat()` 6.18 to 0.28, `dt.timestamp()` 9.16 to 0.30, + `a < b; a - b` 8.84 to 1.94, `hash(a); a == b; a - b` across zones + 20.02 to 0.77, and `zone.utcoffset(dt)` 9.07 to 2.79. + - `codecs.lookup(name)` normalised the name in Python code (a loop + over its characters) up to three times a call before reaching its + cache; it now remembers the codec each spelling last resolved to + (the registry's own object, emptied with the registry's cache), so a + repeated lookup is one dictionary probe. A pass that printed every + native function the in-place lane refused across the stdlib sweeps + and the everyday battery found nineteen more that never read the + calling frame and left compiled code on every call: + `string.Formatter`'s two parsers, `contextvars.copy_context`, the + `datetime` class methods, `os.path`'s `normpath` and `splitroot` + helpers, `re`'s cached compile and match entry, `os.walk`, + `time.strptime`, the tokenizer, the XML parser's constructor and + `ElementTree`'s serializer, and the event loop's per-run + bookkeeping. Against CPython: `codecs.lookup("utf-8")` 9.84 to 0.72 + times, `string.Formatter().format(...)` 2.37 to 1.32, and + `contextvars.copy_context()` 6.17 to 2.41. + - `datetime`, `date`, `time`, `timedelta` and `Decimal` values were + fast under compiled code's own operators and slow under everything + else. A builtin that compares, adds, hashes or tests them (`sorted`, + `max`, `min`, `sum`, `bisect`, `heapq`, `in`, `list.index`, a tuple's + comparison, a dict's keys, `bool`, `abs`, the `operator` functions) + went through the general dunder protocol to reach the native method: + about 1,900 instructions a comparison, in the method lookups, a bound + method and the call. The general comparison, binary operation and + key equality now try the native comparison and arithmetic first for + a natively served left operand, as `COMPARE_OP` and `BINARY_OP` do; + truth takes a native `__bool__`'s pure half (only opaque natives + were admitted, so `if delta:` and `if amount:` took the full path); + unary minus and plus, `abs`, `round`, `int` and `float` call a native + dunder's body directly, in compiled code too; a `Decimal` hashes and + compares as a dict or set key without leaving compiled code, and a + dict display takes these values as keys; and a `Decimal` compares + with an `int` or a `float` natively (the float by its exact value, + `FloatOperation` recorded or raised as the context says). Against + CPython: `sorted(datetimes)` 12.98 to 2.68 times, `max(dts); + min(dts)` 9.47 to 2.67, `sum(timedeltas, timedelta())` 6.21 to 2.42, + `sorted(dates)` 12.46 to 2.86, sorting `(datetime, int)` tuples 12.23 + to 3.05, `bisect`, `in` and `index` over datetimes 11.18 to 3.41, a + heap of datetimes 5.03 to 2.20, `sorted(decimals); max; min` 5.99 to + 1.67, `sum(decimals)` 3.12 to 1.69, `bool(dec)` 5.63 to 1.49, + `dec > 5` 2.56 to 0.49, `dec == 1.5` 15.94 to 0.22, `abs(dec); -dec; + +dec` 3.30 to 2.09, and a `Decimal` as a dict key and set member + 6.05 to 3.27. + - A dict subclass built from a dict (`MyDict(d)`) copied the dict + three times: `dict.__init__` asked for the mapping as a new dict, + cloned each of its entries into a vector, and inserted them one by + one. An exact dict's table is now copied whole into an empty target, + as `dict(d)` copies it. Five more native functions that never read + the calling frame run in place from compiled code: + `decimal.getcontext` (which every `Decimal` method without a native + body calls), `dict.fromkeys`, `hmac.compare_digest`, + `zlib.decompressobj` and `json`'s scanner constructor. A decimal + context's flag mapping copied itself with `dict(self)`, which read + each entry through its own checked `__getitem__`; it copies its + entries directly. Against CPython: `MyDict(d)` 4.93 to 2.56 times, + `decimal.getcontext()` 6.05 to 1.57, `ctx.flags.copy()` 24.00 to + 1.47, `decimal.Context(prec=10)` 40.85 to 24.14, `ctx.copy()` 18.97 + to 16.37, `with decimal.localcontext(): pass` 11.19 to 9.27, and + `json.loads(..., object_hook=f)` with a custom encoder's `dumps` + 1.46 to 1.23. The context objects themselves remain Python code. + - An instance of a `str`, `bytes`, `int`, `float`, list or tuple + subclass that keeps its base's methods (a named tuple, an `IntEnum` + or `StrEnum` member, a plain `class Name(str)`) reached every + builtin through the generic method protocol: a comparison looked up + `__lt__` on the class, built a bound method and called it, about + 2,000 instructions where the payloads' own comparison takes a few + dozen. Comparisons, binary and unary operators, `int()` and + `float()`, hashing and equality as a dict key or set member now + work on the payloads directly when the class keeps the base's + methods for the operation (a verdict remembered per class version), + and an immutable payload's hash is remembered on the instance. A + subclass's instance on the right of a comparison still has its + reflected method run first, so the items of `[a] == L([b])` compare + `b` against `a` as CPython's do, and a subclass made unhashable + stays unhashable. Against CPython: `sorted(names); max(names); + min(names)` over a `str` subclass 11.51 to 2.03 times, + the same over an `int` subclass 11.55 to 3.87, a `float` subclass + 12.86 to 3.90, an `IntEnum` 12.39 to 3.98 and a `StrEnum` 12.42 to + 2.14; `sorted(named_tuples)` 6.95 to 1.59, `max` and `min` of them + 6.23 to 1.78, `set(named_tuples)` 3.25 to 2.19, a tuple subclass's + sort and set 6.26 to 1.73; sets and dict comprehensions keyed by + such values 4.72 to 3.05; `bool`, `abs`, negation, `int()`, + `float()`, `str()` and `len()` of them 3.15 to 1.75; `+`, `*` and + `/` on them 2.07 to 1.23; and `int(dec); float(dec); round(dec)` of + a `Decimal` 2.63 to 1.87. + - Each step of an `async for` over an async generator built an + `asend` awaitable, drove it through the interpreter's `SEND`, + raised a `StopIteration` to carry the item back and caught it, and + a loop holding one was never compiled, because its step, its start + and its end all left compiled code. The step now resumes the + generator in place, in the interpreter and in compiled loops alike: + the item goes straight to the loop's target, and only a suspension + on an inner `await` makes the awaitable (already driven) for the + consumer to yield through. `GET_AITER` and `END_ASYNC_FOR` run in + compiled code, a class's coroutine `__anext__` is awaited as a + direct call is (no bound method or coroutine object unless + something needs one), and an `await` of an `asend`, `athrow` or + `aclose` awaitable (`await anext(g)`) is driven from compiled code + without the `StopIteration`. Against CPython, under `asyncio`: + `async for v in agen(10)` 3.62 to 1.49 times, the same with work in + the body 3.31 to 1.39, over a generator that awaits per item 2.80 + to 1.37, over a generator wrapping a generator 3.71 to 1.57, over a + class with `__aiter__` and `__anext__` 3.12 to 1.16, an async list + comprehension 3.53 to 1.86, one with a condition 3.50 to 1.41, an + async dict comprehension 2.71 to 1.35, `await anext(g)` 3.18 to + 1.15, and an awaiting consumer of an awaiting generator 2.77 to + 1.21. Driven by hand, with no event loop, the ten-item loop went + from 3.34 to 0.92. What remains under `asyncio` is per generator, + not per item: the event loop's first-iteration hook and the weak + set it keeps the generator in, and `await g.asend(v); await + g.aclose()` (4.43 to 3.42). + - Weak reference callbacks ran with the interpreter's "pending + finalizers" gate still raised: the finalizer drain, which runs + first, re-raised it for the callbacks still queued, and the + callback drain never lowered it, so every callback and everything + it called took the slow call paths (a full frame, no lean + activation, tier 2's general entry). The callback drain now lowers + the gate as the finalizer drain does. The weak tables' own + bookkeeping also runs natively: `WeakSet.add` and + `WeakKeyDictionary.__setitem__` of a new item that hashes by + identity make the reference and insert it without their Python + methods' frames, and the tables' three removal closures (the + callbacks those references carry) have native twins that the + callback drain runs in their place when the closure is the + table's own and the table is of the class it was written for. + Against CPython: a `WeakSet` add and the item's death 4.60 to 1.81 + times, a `WeakKeyDictionary` store and the key's death 5.10 to + 2.37, a `WeakValueDictionary` store and the value's death 1.98 to + 1.26, a reference with a Python callback 3.44 to 2.22, and, since + `asyncio` keeps every running async generator in a weak set, an + empty `async for` over a fresh generator 3.64 to 2.61, the ten-item + loop 1.57 to 1.34, a generator wrapping a generator 1.57 to 1.31 + and an async comprehension with a condition 1.41 to 0.98. + - A class attribute store advanced the class's attribute version even + when it changed nothing, and every cache keyed on that version (the + MRO lookup cache, each site's resolution, the construction plan) + started over. Three changes narrow that. Storing the very object a + name already holds is no change at all (`weakref.finalize` sets + `finalize._dirty = True` per instance, which emptied the class's + caches each time). The MRO lookup cache, which records where a name + resolves and reads the value again at each hit, is keyed by a + "shape" version that a store replacing an existing entry's value + leaves alone. And a store that replaces one plain data value with + another (`Counter.count += 1`) carries the class's construction + plan, which reads only `__new__`, `__init__` and + `__abstractmethods__`, across the version change. Tier 2 also + claimed the calls of any `__init__` that names its own class + (`self.v = v + C.base`): the class's constructor entry made the + function look self-recursive, the claim kept it off the lean call + path and the frame JIT's direct constructor call, and tier 2's own + form of it is one the interpreter never enters, so each + construction ran through the fully framed path. The claim now + needs a form the interpreter can enter. A dying instance's Python + `__del__` is called with the instance directly (a remembered class + lookup, no bound method, no scratch dictionary), and the finalizer + drain returns without a second drain when nothing was queued + meanwhile. An async generator's `asend`, `aclose` and `__anext__` + load as method forms and make their awaitable in compiled code. + Against CPython: a constructor that names its own class 5.36 to + 1.68 times, a class counter bumped in `__init__` 5.35 to 2.43, + `self.__class__.total += x` 2.47 to 1.62, `weakref.finalize` and + its firing 4.40 to 2.10, `await g.asend(v); await g.asend(v); await + g.aclose()` 2.93 to 2.30, and an instance with a `__del__` that + stores 2.72 to 2.52. Reads of other attributes after a class store + still resolve again (`Cfg.a = i; c.read()` 6.39 to 5.59): the + per-site caches hold values and stay keyed on the full version. + - A `match` statement left compiled code at its first pattern test: + `MATCH_SEQUENCE`, `MATCH_MAPPING`, `MATCH_KEYS`, `MATCH_CLASS`, + `GET_LEN` and an empty `UNPACK_SEQUENCE` had no lowering, so every + `match` in a hot function ran its whole body interpreted. Each now + has a helper that settles the common subjects in place (lists and + tuples, dicts with plain keys, instances whose class supplies + `__match_args__` as a tuple of names, the built-in classes that + match themselves) and leaves the rest to the general operation. A + `STORE_GLOBAL` likewise exited on every store; it now writes the + module dictionary through a helper and keeps the load caches it + doesn't touch. A class store that replaces a value with one of the + same plain kind (a counter, a flag, a string) now keeps the method + caches of every site that reads the class, which are keyed on a + version only a change of binding advances, and keeps the leaf + verdicts of its methods. A coroutine or generator function waited + for tier 2 as a function called in a loop does, although it's never + entered through a call; it now compiles after the short wait. A + `TimerHandle` shares its base's slot layout, so `call_later` and + `call_at` build one in place. Against CPython: a sequence `match` + 3.12 to 0.76 times, a mapping `match` 1.55 to 0.60, dataclass class + patterns 1.96 to 0.83, `Shape(...)` patterns over a union of + classes 2.21 to 0.93, built-in class patterns 2.94 to 0.96, a + module-level counter (`global n; n += 1`) 2.17 to 0.77, a class + counter with a method call beside it 2.43 to 1.73, a class flag + flipped around a call 1.68 to 1.18, and `asyncio.wait_for` 3.05 to + 2.34. Reads of another class value right after a class store still + resolve again (`Cfg.a = i; c.read()` 5.65 to 3.58). + - `decimal` context operations ran as Python methods under a native + `Decimal`: every `ctx.prec = n` was a Python `__setattr__` with two + nested calls, `Context()` nine of them, and `Context.copy` stored + its attributes in another order than `__init__`, which gave every + copy (so every `localcontext()` block) a materialized `__dict__` + that the arithmetic then read through its uncached path. The + `setattr()` and `delattr()` builtins also materialized the + `__dict__` of any instance they were called on (an eagerly + evaluated lookup meant for names with lone surrogates), taking it + off the split attribute layout for good. `Context.__init__`, + `__setattr__`, `copy`, `clear_flags`, `clear_traps`, `Etiny`, + `Etop`, `sqrt` and `fma`, `setcontext`, the signal mappings' item + reads and writes, and `Decimal.sqrt` and `Decimal.fma` now have + native halves that keep the Python method for anything they'd + convert or raise on. The native `__setattr__` is one compiled code + calls in place, as it calls `threading.local`'s, and `setattr()` + reaches it the same way. A class whose own `__init__` is a native + method gets its `__text_signature__` from that method, so `inspect` + still reads `Context`'s signature. Big powers of ten come from a + table made once. A new context's flags are `False` and its traps + `True` or `False`, as the C module's are. `await f(...)` of a + coroutine function that takes `*args` (an + `async def __aexit__(self, *exc)`) runs the body directly, the + surplus packed as the frame is bound. Against CPython: + `with localcontext(): pass` 9.03 to 2.36 times, the + `with localcontext() as c: c.prec += 2` pattern 9.01 to 2.56, + `ctx.prec = n` 6.05 to 1.12, `setattr(ctx, "prec", n)` 16.7 to + 1.01, `ctx.copy()` 15.7 to 3.08, `Context(prec=10)` 24.3 to 4.00, + `setcontext(ctx)` 3.31 to 1.09, `ctx.clear_flags()` 57.5 to 1.92, + `ctx.flags[Inexact]` 13.1 to 1.32, `Decimal.sqrt` 15.1 to 0.43, + `fma` beside three natives 6.04 to 0.59, arithmetic at 50 digits + 7.46 to 2.43, and an `async with` whose `__aexit__` takes `*args` + 1.78 to 1.34. A context's copy still costs three times CPython's + (three objects, two mappings and an owner reference each way), and + a keyword constructor call still leaves compiled code. + - The `Decimal` methods past the arithmetic operators still ran as + Python: `next_plus` copied the context and added through three + Python layers, `exp`, `ln` and `log10` ran their integer series in + Python big-int arithmetic, and the digit-string methods built their + results a character at a time. `remainder_near`, `scaleb`, `shift`, + `rotate`, the four logical operations, `next_plus`, `next_minus`, + `next_toward`, `logb`, `number_class`, `compare_total`, + `compare_total_mag`, `max_mag`, `min_mag`, `radix`, `exp`, `ln` and + `log10` now have native halves on `Decimal` and on `Context`, and + the constructor takes a `(sign, digits, exponent)` tuple natively. + The transcendental three are the Python module's own algorithms + (`_dexp`, `_dlog`, `_dlog10` and the series under them) carried over + step for step, so a result agrees digit for digit; 180,000 generated + cases match CPython's C module and the Python methods, flags + included. A native method that replaces a Python one now keeps its + docstring and its `__module__`, so `help` describes it and `doctest` + finds its examples again (`test_decimal` runs 788 tests, up from + 767). `-x`, `+x`, `abs(x)`, `round(x, n)` and `divmod(x, y)` on a + natively served value reach its method through a per-class cache in + place of a class lookup a call. Against CPython: `next_plus` and + `next_minus` 89.1 to 0.67 times, `next_toward` 73.8 to 0.87, + `compare_total` with `max_mag` and `min_mag` 32.1 to 0.88, the + logical operations 25.6 to 1.30, `remainder_near` 23.8 to 1.10, + `scaleb` 22.8 to 0.15, `logb` with `number_class` 19.3 to 0.28, + `shift` 17.6 to 1.43, `rotate` 16.8 to 0.95, `Decimal(tuple)` 14.3 + to 0.36, `exp` 4.97 to 0.71, `ln` 3.21 to 0.59, `log10` 2.75 to + 0.50, `divmod(x, y)` 1.79 to 1.01, the unary operators 2.12 to 1.39 + and `round(x, 2)` 1.59 to 1.12. A fractional power (`x ** y`) and + the three-argument `pow` still run their Python code (1.9 and 5.6 + times). + - A small function called back by a builtin (`map`, `filter`, + `sorted`'s key, `reduce`) is evaluated without a frame, and compiled + once warm. Two things kept the compiled form slow. Its in-line read + of a global was guarded on the function object it was compiled for, + so a lambda, which is a new function each time its expression runs, + took the out-of-line read on every call; the guard is now the + function's globals and builtins, which those functions share. And a + call to another small function through a global went out of line to + that function's uncompiled form: only method calls were compiled in + line. A global callee that is a pure leaf is now compiled in line + behind a check that the register still holds that function (a + global's value arrives as a borrowed object, so the check reads its + tag and payload). The comparison dispatch ran its value-subclass + lanes on every pair of plain instances before reaching their own + method; a pair with no payload now skips them. Against CPython, for + a callback that calls a helper: `map` 1.10 to 0.62 times, `filter` + 1.33 to 0.92, `reduce` 1.20 to 0.75, `sorted(key=...)` 1.14 to + 0.83, `max` and `min` keys 1.12 to 0.77, `starmap` with + `accumulate` 1.54 to 1.17, a `bisect` key with `groupby` 1.24 to + 0.98; a heap of instances with a Python `__lt__` 1.55 to 1.43, and + `in`, `index` and `count` over instances with a Python `__eq__` 1.38 + to 1.30. A callback that isn't such a function (it loops, or takes + keywords) still pays about 1,300 instructions of call layers around + its compiled body. + - `operator.itemgetter`, `attrgetter` and `methodcaller` as callbacks + went through their own call for every item: three class lookups an + item to recognize a `methodcaller` and find its method, and for a + `map` stepped by a `for` loop the attempt was made twice. A drained + `map` (`list(map(...))`, `"".join(map(...))`, `set(map(...))`) now + reads the callback's shape once: a getter of one index, key or + attribute name reads each item's part with no call, an attribute's + place is remembered for a run of one class's instances, and a + `methodcaller`'s method is looked up once per class. Stepped maps, + `filter`, and `sorted`, `min` and `max` keys take a getter's part + as a plain read (which `filter` could not take before, having to + allow no side effects) and call a `methodcaller`'s leaf method in + place. `getattr`, `hasattr` and `attrgetter` remember where a class's + instances keep a name and read it there. Against CPython, over 40 + items: `list(map(attrgetter("x"), objs))` 1.86 to 0.98 times, + `list(map(itemgetter(1), pairs))` 1.86 to 1.31, + `list(map(itemgetter("k"), rows))` 1.46 to 1.10, + `list(map(methodcaller("norm"), objs))` 2.79 to 1.31, a `for` loop + over that `map` 4.14 to 1.81, `sorted(objs, key=methodcaller(...))` + 2.46 to 1.58, `filter` with a getter 3.21 to 1.78, `min` and `max` + with getter keys 1.87 to 1.18, and `"".join(map(itemgetter(0), + words))` beside `",".join(map(str, xs))` 2.47 to 0.81. A stepped + `map` still costs about 300 instructions an item around its + callback (`for v in map(itemgetter(1), pairs)` 2.36 times). + - Set displays that unpack, truth tests through `__bool__`, and + `chain` over adapters. `{*items, x}` adds a list's or tuple's + natively hashed items to the new set in one pass instead of stepping + an iterator over them. `any`, `all`, `filter(None, ...)` and every + other truth test evaluate a plain class's leaf `__bool__` in place, + with no call. `list(chain(map(...), map(...)))` drains each `map` or + `filter` source through its own batch lane instead of stepping it + through the general path. Against CPython, over 40 items: + `[*L, i]; (*L, i); {*L, i}` 1.89 to 1.21 times, `any(ps); all(ps); + list(filter(None, ps))` over instances with `__bool__` 2.47 to 1.27, + and `list(chain(map(attrgetter("x"), objs), map(itemgetter(1), + pairs)))` 3.69 to 1.06. Three iterator fixes came with it: `chain` + stayed exhausted after its active source raised, where CPython's + carries on with that source at the next step, and `batched` and + `zip_longest` carried on after a source raised, where CPython's end + for good. + - Sequences by `__getitem__`, and `collections.abc.Sequence`. A class + with `__getitem__` and no `__iter__` is iterated by a helper iterator + whose `__next__` was a Python frame that called `__getitem__` in + another. `zip`, `enumerate`, `map`, `reversed` and a `for` loop's + slow lane now step that iterator natively (forwards and reversed), + its two slots read in place, and a class once seen to be such a + sequence gets its iterator built with no lookups and no `__init__` + call. A `__getitem__` that is just `return self.items[key]` reads a + list, tuple or dict field with no call at all, from these steps and + from any compiled `obj[key]`; the list's own index miss ends the + iteration without an `IndexError` being built, raised and caught. + `Sequence.__iter__` is a generator (`v = self[i]; yield v; i += 1`): + a generator whose loop has that shape steps on its suspended frame + instead of being resumed, from its first item to its end, and stays + a generator (its frame, `send`, `throw` and `close` see every step). + Against CPython, over 40 items: `tuple(seq)` 2.46 to 1.03 times, + `sum(seq)` 2.36 to 0.93, `x in seq` 1.82 to 0.99, `list(zip(seq, + seq))` 4.38 to 1.49, `list(enumerate(seq))` 3.85 to 1.34, + `list(reversed(seq))` 4.38 to 1.46, `set`, `max`, `min`, `any` and + `all` together 2.41 to 1.09, and unpacking 2.46 to 1.07; a `for` + loop over a one-item sequence 7.25 to 1.10. For a `Sequence` + subclass: a `for` loop 2.74 to 1.12, `list(s)` 1.89 to 1.12, `in`, + `index` and `count` 1.90 to 1.02, and a one-item loop 2.90 to 0.99. + `UserList` stays at 1.66 (its `__getitem__` asks `isinstance(i, + slice)` first, about 340 instructions through the general call + lane), and a `__getitem__` that computes its item still pays about + 500 instructions a call around its body. One fix came with it: + `reversed(seq).__setstate__(n)` now clamps `n` to the sequence's + span and does nothing once the iterator is exhausted, as CPython's + does. + - Mappings written in Python that only wrap a dictionary are read as + the dictionary they wrap (2026-12-03). A `collections.abc.Mapping` + subclass whose `__getitem__` is `return self._d[key]` and whose + `__iter__` is `return iter(self._d)` (and `collections.UserDict`) + used to be copied, merged, spread and listed one Python call per + key, through the mixin's `keys()` and the views' generators. For + such a thin wrapper, `dict(m)`, `d.update(m)`, `{**m}`, `f(**m)` + and `list`, `sorted`, `set` and the other builtins over + `m.keys()`, `m.values()` and `m.items()` now read the wrapped + dictionary directly. The rule is narrow on purpose: both methods + must be those two bodies over the same exact `dict`, and `keys` and + the views' `__iter__` must be the standard library's own, so + nothing a program could observe is skipped; any other mapping keeps + the full protocol, with the mixin's generator frames in its + tracebacks. Along the way: `yield from d` steps a dictionary's + iterator with no call; `m[key]` from a generator's native step + takes the delegating read; a missing key caught by `except + KeyError:` with no name bound and nothing run (`Mapping.get`, + `Mapping.__contains__`) is raised without the `__getitem__` call + whose frame nobody can see; the interpreter reads a field at a + site that sees several classes from the site's per-class entries + before the general lookup; `attrgetter`, `getattr` and key + functions remember where instances keep a field whose class also + holds a default for it (a dataclass field with a default); and + `iter(obj)` makes a generator-function `__iter__`'s generator + without the general call. Against CPython: `dict(m)` 4.35 to 0.15 + times, `{**m}` 3.04 to 0.16, `f(**m)` 2.61 to 0.38, `m == m2` 1.69 + to 0.81, `list(m.keys())` 4.13 to 1.07, `list(m.values())` 1.79 to + 0.60, `list(m.items())` 1.75 to 0.63, a `UserDict` mix 3.08 to + 0.39, `m.get` hits and misses 2.06 to 1.47, `key in m` 2.24 to + 1.65, `sorted(rows, key=attrgetter("x"))` over dataclass instances + 1.82 to 1.06 and `map(attrgetter("x"), rows)` 2.43 to 1.58, a + one-item `yield from d` 6.19 to 4.88, and attribute reads at a + four-class site in the interpreter alone 3.23 to 2.02. Two fixes + came with it, each matching CPython: `dict(m)`, `update` and `**m` + list every key before reading any value and never ask the + mapping's length; and a `KeyError` from `m[key]` under `f(**m)` + reads as the duplicate-keyword `TypeError`, while every other + error, and every error under `{**m}`, passes unchanged. Still + slow: a generator's create, first resume and last resume (a + one-yield generator in a `for` loop is 2.2 times CPython's cost), + and a `for` loop over a view (1.8). + - Callbacks with defaults or keyword-only parameters, and + `functools.partial` objects with keywords, are bound without the + general argument binder when a builtin calls them (2026-12-03). + `map`, `filter`, `sorted`, `max` and the other native loops used to + send a callback such as `def f(v, scale=2, *, off=1)`, or + `partial(f, scale=3)`, through the full call path for every item: + a fresh argument vector, a keyword dictionary and a frame. A + callback that needs no frame now has its defaults, keyword-only + defaults included, bound in place and is evaluated in the loop; a + `partial`'s stored keywords are matched by name against the + function's parameters with no merged dictionary; a callback that + does need a frame (a loop in its body) is bound by the short binder + that fills defaults; and the second tier's direct entry takes + keyword-only parameters, which it used to refuse. Callback plans + are also compiled after 2,500 evaluations rather than 20,000: a + compile costs about what 1,700 to 4,000 evaluations of the + interpreted plan do. Against CPython: `list(map(f, xs))` with + `f(v, scale=2, *, off=1)` 3.19 to 1.16 times, with + `f(v, *, off=1)` 3.58 to 1.21, `sorted(xs, key=partial(f, + scale=3))` 2.38 to 0.65, `list(map(partial(f, scale=3), xs))` 2.46 + to 0.67; for callbacks with a loop in the body, `map` with a + keyword-only default 3.29 to 1.97, `map` over a `partial` 2.56 to + 1.57, `sorted` with a `partial` key 2.53 to 1.50, and calling the + `partial` from a Python loop 3.00 to 1.98; and `len(obj)` with a + Python `__len__`, between its 2,500th and 20,000th call, 1.44 to + 0.75. Two fixes came with it. `sys._getframe()` inside a compiled + function that a native loop called answered the calling function's + frame, and left a stale frame behind, when the caller's own frame + hadn't been recorded yet; the caller's frame is now recorded first. + And a compiled plan no longer keeps its function's code alive after + the function is gone. One cost: the everyday battery's + `decimal_fraction_ops` reads 1.4% more instructions, because two + plans (`Rational.__float__` and `Fraction.__str__`) compile at + their 2,500th run for 1.7 million instructions each and then run no + faster than interpreted (their property reads and calls go through + the same helpers either way), 2,000 runs before the case ends; the + rest of the battery is unchanged (geometric mean 1.002). Still + slow: a callback with a loop in its body is 2.0 times CPython's + cost from `map` (the second tier's entry costs about 1,000 + instructions a call), and a plan whose work is all property reads + and calls gains nothing from being compiled. + - Generator bodies that unpack (2026-12-03). A generator whose loop + unpacks each item (`for k, v in pairs: yield v`, `for i, x in + enumerate(xs): yield i, x`, `for k, v in d.items(): yield k, v`) + lost the in-place resume, because the native step didn't admit + `UNPACK_SEQUENCE`; each `next` went through the registered resume + instead. The step now unpacks an exact tuple or list of the right + length, and stops untouched before anything else (another iterable, + a wrong length), which the full resume then unpacks or raises for. + And a body that no native step can run at all (one that calls a + function on every item, say) is marked once when it's scanned, so + each resume declines on one check instead of trying the step and + backing out. Per 100 items against the previous build: an unpacking + loop 115,000 to 80,000 instructions, an `enumerate` loop 167,000 to + 121,000, a `d.items()` loop 178,000 to 144,000, a method yielding + `i, x` from `enumerate` 158,000 to 118,000, and `tuple(b for a, b + in pairs)` 37,000 to 22,000 (half of CPython's cost). The + battery and the fixtures are unchanged (geometric means 0.998 and + 1.000). Still slow: these loops are 2.0 to 2.4 times CPython's + cost, and a body that calls (`yield str(x)`, `yield f(x)`, + `yield x.method()`) 1.6 to 2.8 times. A call can't join the native + step, which runs without the interpreter's switch and has no way to + leave part-way with an error pending, so those bodies take the + registered resume, about 360 instructions an item before the body + does any work. The recursive `yield from` of a tree walk is the + other generator gap (1.7 times CPython's cost on the + `generators_tree` fixture's walk): its profile is flat, about 990 + instructions for each resume of a collapsed chain. + - Attribute hooks and misses on subclasses of built-in types, and + generator expressions feeding `all()`, `any()`, `sum()` and + `str.join()` (2026-12-03). The `email` case of the everyday battery + pointed at both: its token classes subclass `list` and `str`, look + names up through `hasattr` and `__getattr__`, and fold themselves + with `''.join(str(x) for x in self)`, `all(x.ok for x in self)` and + `sum((x.defects for x in self), [])`. A missing attribute on an + instance of a `dict`, `list` or `str` subclass used to search the + payload's methods on every read; the miss is now one verdict per + class and name. A `__getattr__` hook that isn't a frameless leaf is + called directly from compiled code, with the site remembering that + the class half of the lookup misses, and a leaf hook that reads + `self[name]` works on a built-in subclass. An `AttributeError` that + leaves such a hook now carries `name` and `obj`, as CPython's does, + and the two are stored in place on the exception instead of in a + side table. `all()` and `any()` take strings, containers and plain + instances from the generator in place (an instance of a class with + neither `__bool__` nor `__len__` is true on one verdict), and + `sum(lists, [])` extends its total from each list. `str(s)` of an + exact string is the string with no call, `str()` of a `str` + subclass instance is its payload on one verdict, and a property + read is tried before the other lanes of a slow attribute site. + Against the previous build, in instructions per operation with + CPython's figure in parentheses: `d.x` through `__getattr__` on a + `dict` subclass 11,200 to 1,330 (1,240); the same on a `list` + subclass 12,400 to 1,440 (1,210); a non-leaf hook on a plain class + 5,800 to 2,080 (1,800); `hasattr` of a missing name on a `list` + subclass 7,600 to 1,370 (640); `all(x.v for x in parts)` 9,100 to + 4,600 (5,500); `all()` over a property 14,800 to 8,200 (7,100); + `sum((x.defects for x in parts), [])` 17,000 to 8,300 (7,700); + `''.join(str(x) for x in parts)` 16,800 to 13,000 (11,100); and + `[str(x) for x in parts]` 10,900 to 7,200 (6,800). Exception + subclasses also accept the keyword fields their bases define + (`name` and `obj` for `AttributeError`, `name` for `NameError`, + `name`, `path` and `name_from` for `ImportError`) and reject + unknown ones with CPython's message. The battery and the fixtures + are unchanged (geometric means 1.002 and 1.001). Still slow: a + hook that raises (`hasattr` of a name the hook refuses) is 2.1 to + 3.3 times CPython's cost, most of it building and unwinding the + exception; a generator expression that reads a non-leaf property of + each item is 2.1 to 2.6 times; and `str.join` over a generator + keeps a fixed cost of about 2,000 instructions. + - Errors raised by built-in operations inside compiled code + (2026-12-03). A sweep of 36 raise-and-catch shapes showed that an + explicit `raise` already stayed in compiled code, but an error from + a built-in method (`"abc".index("z")`, `[].pop()`), from a number + operator (`1 // 0`, a negative shift count, zero to a negative + power), from `len()` of an object without a length, from `next()` + on an exhausted iterator or from a failing `assert` left it: the + operation declined, the interpreter ran it again to build the + error, and the loop re-entered compiled code at the handler. The + method kernels now hand their error back with a status of its own, + and the call site raises it in place, so the handler runs with no + exit; an inlined body that can't raise there drops the kept error + and declines as before. Integer division and the other number + operators keep the error their first attempt built instead of + computing it twice. `len()` of a number, `None` or a function + answers its `TypeError` without a lookup of `__len__`; `next()` on + a plain cursor at its end builds `StopIteration` directly; and + `assert cond, message` builds its `AssertionError` in the + constructor lane. `str(e)` and `format(e)` of an exception whose + class keeps `BaseException.__str__` read `args` on one verdict per + class. The common error constructors no longer find their class by + name. Against the previous build, in instructions per + raise-and-catch with CPython's figure in parentheses: + `"abc".index("z")` 4,660 to 3,100 (2,280); `1 // (i - i)` 5,100 to + 2,960 (2,180); `len(5)` 7,650 to 4,560 (2,900); `next(it)` at the + end 3,400 to 2,760 (1,820); a failing `assert` 3,800 to 3,000 + (1,930); and `str(e)` in a handler 4,360 to 3,710 (2,170). Four + messages now match CPython's: `str.index`, `find` and `count` name + themselves and the argument's type, the strip methods say "strip + arg must be None or str", `divmod()` of operands that don't divide + names `divmod()`, and `len()` names an instance's class. Still + slow: every frame an exception leaves costs about 2,900 + instructions against CPython's 1,130, spread over some twenty + functions with none above 270; and a plain `raise ValueError("x")` + caught in the same frame is 2,970 against 1,820. + - Exceptions that leave a compiled callee (2026-12-03). A callee + entered directly from compiled code runs without a frame record + until something asks for one, and a raise that left it was one of + those things: the callee registered itself, the caller did too, and + the interpreter's unwinder took both apart. A callee that raises + while still unregistered is now unwound where it stands: its locals + move into the shell its traceback entry keeps, the entry is linked, + the record goes back to rest, and the caller sees the raise as if + one of its own operations had failed, so its handler (or its own + caller's) runs with no exit. A caller that has no frame record yet + keeps the shell's back link pending until it gets one. Generators, + inlined bodies, traced code, constructors' paired `__new__` and + `__init__` runs, and a callee whose own handler covers the raise + take the old path. An inlined body whose callee keeps raising now + counts as an exit, so the site stops inlining it. On top of that, + `hasattr(obj, name)` and three-argument `getattr` call a Python + `__getattr__` hook directly and read its `AttributeError` as the + answer: when nothing else holds the error, it's dropped with no + traceback entry and the hook's locals are released at once, as + CPython's own probe does. `next(obj)` calls a Python `__next__` + directly, a hook's `AttributeError` keeps `name` and `obj` when it + surfaces from a plain read, and `StopIteration` is built without + the general constructor. In instructions per call, the previous + build to this one with CPython's figure in parentheses: one raising + frame under a `try` 6,430 to 5,190 (3,490); two frames 9,540 to + 6,570 (4,950); four frames with loops in their bodies 15,960 to + 11,430 (8,200); a raising `__init__` 7,350 to 6,170 (3,850); a + raising `__eq__` 6,270 to 5,120 (3,400); `hasattr` on a hook that + raises 8,670 to 3,530 (3,600); `getattr(h, "zz", None)` 9,830 to + 3,770 (3,670); `hasattr` on a hook that answers 3,030 to 1,280 + (1,340); and `next(it)` on a Python iterator at its end 9,380 to + 5,660 (3,480). The battery's `exceptions_ops` drops 7%. Still slow: + a hook shaped `try: return self._d[name]` / `except KeyError: raise + AttributeError(name)` registers at its own catch and takes the old + path (`hasattr` on it 9,770 against 5,590); `next(obj)` without a + default pays for a raising `__next__` twice (a side-effect-free + attempt that declines, then the call); each unwound frame still + costs about 1,400 instructions; and a raise caught in the same + frame is unchanged. + - `except` clauses that can't see their exception (2026-12-03). A + clause such as `except KeyError: x = None`, `except (A, B): pass`, + `except E: continue` or a bare `except:` with a body of constants, + local reads and local stores has no way to look at what it caught: + it binds no name, and nothing in its body can ask for the current + exception, raise, or run other code. Such a clause, when it's the + first of its `try`, now runs with nothing pushed and nothing built. + A code object's handlers are classified once. At a raise, the + classes the clause names are read through the handler's own + `LOAD_GLOBAL` sites (or its closure cells or locals) and checked to + be exception classes, the locals the body reads are checked to be + bound, and the stack is cut and the body's few stores are done in + place; execution resumes after the clause's `POP_EXCEPT`. Three + places use it. A caught exception that nothing else holds is + released after the body, as `POP_EXCEPT` would release it, with no + traceback entry, no frame record and none of the handler's + instructions run; the interpreter's catch does the same. A missing + dict key, an index out of range, a missing attribute and a `raise` + of an exception class or a fresh instance check for such a clause + before the error is built, context chained or message formatted, + and build nothing when one catches it. And a raise that leaves a + callee entered directly from compiled code is swallowed at the + caller's `CALL` when the caller's clause is blind, with no + traceback entry or shell for the callee. The lane declines whenever + the difference could show: under tracing or profiling, when a store + in the body would release the last reference to an object that may + have a finalizer (CPython runs that finalizer with the exception + still current), when a class the clause names isn't an exception + class, and when compiled code hasn't written its whole operand + stack to the frame. `tests/regrtest/test_blind_except_clauses.py` + checks the lane against CPython's answers for finalizers, weak + references, rebinding of the caught class, nested clauses, + closures and tracing. In instructions per iteration, the previous + build to this one with CPython's figure in parentheses: `x = d[k]` under `except KeyError: x = None` 2,710 to + 1,040 (1,840); the same with `pass` 2,640 to 970 (1,850); with + `continue` 2,680 to 850 (1,810); `xs[3]` under `except IndexError` + 3,000 to 950 (1,860); a tuple of two classes 3,050 to 1,100 + (2,190); a function shaped `try: return d[k]` / `except KeyError: + return None` 4,500 to 1,330 (2,410); a missing attribute under + `except AttributeError: pass` 4,710 to 1,880 (4,320); a raising + callee under `except E: pass` 5,400 to 3,390 (3,370); and `raise + ValueError("x")` caught in the same frame 3,020 to 1,910 (1,830). + The battery's `exceptions_ops` drops 20%. Of the 2,764 handlers in + the standard library, 37% have this shape. Not covered: clauses + after the first, classes named by attribute (`os.error`), a bound + but unused name, bodies with attribute reads, calls or augmented + assignments, and errors the runtime's own functions build + (`[].pop()`, `next(it)`, `int("x")`). + - Sites that see a few classes, and loops the loop tier ran worse + (2026-12-03). Two groups of fixes, found by timing one-line loops + over objects of one, two and three classes. First, which tier runs + a loop. The loop tier (tier 2) steps a list of objects at a cost per + element that only typed work or a call it enters natively repays, + and it already declined loops whose only call was to a short + function it evaluates without a frame. That rule left out the + smallest functions (`return o.a`, a constant, an argument), so `for + o in xs: t += rd(o)` stayed in tier 2 at more than twice the frame + JIT's cost; they're now counted like any other frameless callee. + Tier 2 also burns one receiver class into a method call. A receiver + of another class took a generic resolution and call of about 3,000 + instructions, every time, and nothing counted it: a loop + alternating between two classes ran that way for good. Such misses + now count toward the same call-density verdict that retires a loop + making too many generic calls, and the frame JIT takes the code. + Second, per-site caches that held one entry. A compiled attribute + read kept one class's field position of its own beside the code's + shared one, replaced on every miss, so a site alternating between + two classes missed on every read; it now keeps three, the displaced + one moving down, and resolves a `__slots__` member once per class + instead of taking the whole miss chain and a lookup by name. A + property site remembered one getter to run in place, and only the + one its slot held first; it remembers two. A getter's own `self.a`, + read for the second class, went through the general resolution; it + now reads the position the site's polymorphic entries give, which + hold `__slots__` members too. And a method call lowered in line + guarded two receiver classes at most, the third taking a method + load and an ordinary call each time while the last guard changed + hands; it guards as many as the site recorded, up to four, and a + site's classes are counted once each (the count used to add up the + same class from three tables). + `tests/regrtest/test_poly_field_slot_sites.py` checks these reads + against CPython's answers for unset and deleted slots, a member + replaced on the class, a subclass that declares the slot again, + published dicts, `__getattr__` and `__getattribute__` hooks, a + reassigned `__class__`, and one to seven classes at a site. In + instructions per iteration, the previous build to this one with + CPython's figure in parentheses: `t += rd(o)` over a list of + objects 860 to 320 (560); `out.append(rd(o))` 920 to 540 (550); + `[rd(o) for o in xs]` 935 to 340 (500); a call of a function with + an object argument in a `range` loop 850 to 280 (635); a slot read + in a loop over two classes 2,020 to 385 (555), and a plain + attribute 470 to 235 (545); a slot read in a callee over two + classes 1,180 to 420 (760), and over three 1,200 to 445 (850); a + property over two classes 1,025 to 500 (910) in the loop and 1,320 + to 795 (1,120) in a callee, slotted 1,670 to 540 (920) and 1,950 to + 835 (1,130); a method call over two classes 1,770 to 330 (860) in + the loop and, over three in a callee, 1,240 to 460 (1,175). Loops + that tier 2 enters natively (scalar helpers, methods with loops of + their own) are unchanged, and so are the bench fixtures and the + suite (0.9996 and 1.0001 with the first change alone). Still + slower than it should be: the second class at a property site runs + its getter through the frameless evaluator where the first is + lowered in line, and a site with more classes than its guards pays + a method load and a call for each miss. One divergence found and + left alone: a subclass that declares a base's slot name again + shares the base's storage, where CPython keeps two. + - A native adapter's call of a warm Python leaf function (`map(f, + xs)`, `filter(f, xs)`, `sorted(xs, key=f)`, `max(xs, key=f)`) + enters the function's compiled leaf code with its checks made in + one place: the function's current code is a warm general leaf + called with exactly its parameters, its frameless evaluations + haven't given up, and no trace hook is set. A call the code + declines counts as a miss and takes the full call, as before. + `list(map(f, xs))` and `map(f, xs, ys)` over plain sequences step + each item with one view of the cursor, release scalar items with + no call, and run a two-source map of a Python function in bulk, + as the builtin lane already did; `sum()` of a native adapter takes + each step that runs no code straight, without the general + iterator layers. The previous change's lane for a polymorphic + attribute read also skipped a published dict's hint and scanned + the other classes' entries on every read, which cost + `csv.DictReader` 400 instructions a row; it now consults the hint + first. `tests/regrtest/test_warm_leaf_adapter_callbacks.py` checks + declined and raising items, a `__code__` swapped between drains + and mid-drain, replaced defaults, `StopIteration` from the + callback, unequal and strict sources, the same iterator given + twice, generator sources, heap items, and a trace hook. On macOS, + in instructions per item, the previous build to this one with + CPython's figure in parentheses: `list(map(f, xs))` 959 to 777 + (767); `list(map(f, xs, ys))` 1,279 to 987 (862), and of a lambda + 1,379 to 988 (914); `sum(map(f, xs, ys))` 1,254 to 1,043 (779); + `starmap` 1,160 to 1,068 (773); `list(filter(f, xs))` 1,069 to + 977 (731); `sorted(xs, key=f)` 907 to 824 (757); `max(xs, + key=f)` 775 to 698 (742); a `for` over `map(f, xs)` 1,007 to 904 + (733); a `csv.DictReader` row 12,164 to 11,529 (12,215). + - A decorator's wrapper that only forwards its arguments to its one + free variable (`def wrapper(*args, **kwargs): return fn(*args, + **kwargs)`, or `fn(*a)`), decided once per code object, runs as its + target when that target is a pure leaf: a compiled call site caches + it as it caches a frameless leaf, and `map()`, `filter()`, + `sorted()` and the other native callers call the target in place. + Nothing can observe the wrapper's missing frame: the target's + evaluation declines anything that would raise (the full call then + raises it through the wrapper, which the traceback names), and no + trace or profile hook may be set. A keyword call of a + placeholder-free `functools.partial` over a pure leaf (`p(x, + c=1)`) binds the stored keywords and the call's by name, the call's + overriding, and evaluates in place, with no `String` per keyword and + no frame. A native callback that can't run as a pure call (a + function whose body calls something) skips the pure lanes' probes. + `tests/regrtest/test_forwarding_wrapper_callbacks.py` checks errors + raised through the wrapper, a rebound or empty cell, a wrapper that + calls itself, builtin, method and class targets, a replaced + `__code__`, methods, keyword calls, and trace and profile hooks; + `tests/regrtest/test_partial_leaf_keyword_calls.py` checks + overrides, keywords naming positional parameters, missing, + unexpected and duplicate arguments, declined operands, replaced + code and keyword defaults, subclasses, placeholders and a trace + hook. On macOS, in instructions per call, the previous build to this + one with CPython's figure in parentheses: `partial(fk, b=5)(i, + c=1)` 7,563 to 1,516 (3,287), and with the call overriding `b` + 7,480 to 1,505 (3,255); a `functools.wraps` wrapper called from a + loop 2,331 to 822 (1,813); `list(map(wrapper, xs))` 3,805 to 1,150 + (1,794) per item, and over two sources 4,983 to 1,235 (1,919); + `map()` over a callback with a loop 3,550 to 3,357 (1,635), and + over one that appends to a list 2,833 to 2,651 (763). Still slower: a wrapper over a function that isn't a leaf runs both + frames, and a callback with a call in its body pays tier 2's direct + entry, about 1,000 instructions a call. One known divergence left + alone: `super().__call__()` in a `partial` subclass passes the wrong + first argument. + - Keyword calls of builtin and `datetime` methods. A keyword call of + a builtin type's method on its exact receiver whose keywords name, + in order, the parameters after its positional arguments + (`s.replace(a, b, count=1)`, `n.to_bytes(4, byteorder="big")`, + `b.split(sep=b",")`, `s.expandtabs(tabsize=4)`) is its positional + call: the receiver, positionals and keyword values already sit on + the stack in that order, so the method's leaf body runs on them in + place, as a positional call's does, with no keyword pairs built. The + methods that already had a keyword half (`str.split`, `encode`, + `splitlines`, `bytes.decode`) keep it. The keyword binder for + registered native halves takes eight parameters instead of four, and + `datetime`'s natives register theirs: `datetime.replace`, + `date.replace`, `astimezone`, and `isoformat` of a `datetime` (`sep`, + `timespec`) or a `time` (`timespec`), which before called the + `_pydatetime` method whenever a keyword was given. The binder that + remains for the others builds its argument list on the stack. + `str.split`, `rsplit` and `bytes.split` now raise CPython's + `TypeError`s for too many arguments and for a parameter given by + position and by name (`s.split(",", sep=",")` returned a list). + `tests/regrtest/test_builtin_method_keyword_positions.py` checks the + methods, gaps and reordered keywords, errors and their messages, and + the `datetime` keywords, `fold` and time zones. On macOS, in + instructions per call, the previous build to this one with CPython's + figure in parentheses: `dt.isoformat(sep=" ")` 22,681 to 2,052 + (8,760); `dt.isoformat(timespec="seconds")` 22,754 to 2,118 (9,674); + `t.isoformat(timespec="minutes")` 9,542 to 1,508 (4,905); + `dt.replace(hour=5)` 2,561 to 1,485 (1,288), and with two keywords + 2,884 to 1,544 (1,441); `b.split(sep=b",")` 2,866 to 1,629 (1,282); + `s.expandtabs(tabsize=4)` 1,636 to 968 (866); `s.replace(",", ";", + count=1)` 1,920 to 1,505 (1,353); `i.to_bytes(4, byteorder="big")` + 1,345 to 992 (1,060). The calls the existing keyword halves serve + cost 1% to 6% more (`s.encode(encoding="utf-8")` 942 to 999 against + CPython's 1,196) from the wider binder and the checks ahead of it. + Still slower: a keyword call that maps to positions still pays about + 400 instructions in `CALL_KW`'s helper and the checks over a + positional call compiled code makes directly. + - Dict displays that merge and then list pairs, and `bytes` of text. + In `{**d, "k": v}` the compiler builds the listed pairs into a + second dict and merges it into the first; compiled code now puts + the pairs straight into the merged dict, in order, a listed key + replacing a merged one's value in place, with no second dict. Each + key, a `str`, a machine `int` or a finite `float`, probes the dict + natively; a stored key of another kind with an equal hash (`True` + against `1`), a dict watcher, or a target that isn't an exact dict + leaves both steps to the general path. `bytes(text, encoding[, + errors])` and `bytearray(...)` of the same arguments encode through + `str.encode`'s leaf for UTF-8, ASCII and Latin-1 and their aliases, + where before they took the general constructor; text a codec can't + encode, other codecs, and keywords still take it, so errors and + handlers are CPython's. `tests/regrtest/test_dict_merge_then_pairs.py` + and `tests/regrtest/test_bytes_from_text_codecs.py` check order, + repeated and equal keys of mixed types, released values, other + mappings, codecs, error handlers, subclasses and keywords. On macOS, + in instructions per iteration, the previous build to this one with + CPython's figure in parentheses: `{**d, "d": 4}` of three keys 2,760 + to 1,854 (1,691); with two pairs, one replacing, 3,135 to 2,040 + (2,101); of twenty keys 3,750 to 2,710 (2,370); `bytes(s, "utf-8")` + 4,721 to 991 (1,286); `bytes(s, "latin-1")` of non-ASCII text 4,035 + to 1,176 (1,328); `bytearray(s, "ascii")` 4,212 to 1,329 (1,835). + Still slower: `{**d}` copies the table at its exact size, so the + first listed key regrows it, and the empty display dict costs about + 120 instructions to build. + - Exponent formatting, tier-2 instance comparisons, `dict(zip(text, + ...))`, and code-cache page drops on Linux. A float in exponent form + (`format(x, ".3e")`, `"%e"`, `E`, and the `g` forms that choose it) + took Rust's exact formatter, whose fast half fails often (`3.14159` + to four digits) and whose bignum fallback costs over a thousand + instructions; its digits now come from 128-bit integer arithmetic, + as fixed-point already did: the float is `m * 2**e` exactly, so + `x * 10**k` is an exact fraction whose floor gives the digits, + rounded half to even on the exact remainder, the decimal exponent + estimated from the binary one and settled on the digit count. Up to + 17 significant digits of magnitudes from about `1e-20` to `1e38` take + it; others take the shortest digits where those settle the rounding, + else the old formatter. `tests/regrtest/test_float_exponent_format.py` + checks the result against the exact value rounded with `Fraction`, + and 200,000 random floats in 19 formats matched CPython's output + byte for byte. A comparison in a loop tier 2 compiles, of a plain + instance whose class's comparison method is a warm pure leaf (a + dataclass's `__eq__` or ordering), now evaluates the leaf on the + operands where they are, as the frame JIT's comparison site does, + instead of the general rich comparison + (`tests/regrtest/test_tier2_instance_compare_leaf.py`). + `dict(zip(keys, values))` built in one step only from lists and + tuples; a string source now joins them, each character a + one-character string, the iterators left where the general zip + leaves them (`tests/regrtest/test_dict_zip_text_sources.py`). On + Linux the frozen code cache dropped its mapping's pages after every + function body it read, so the next read faulted them back in; it + now drops them every 64 reads, as macOS already did, which cuts + start-up (`weavepy -c pass`) from 12.6 to 10.7 ms and the everyday + battery's `argparse_ops` by 5%, `logging_ops` by 5% and + `email_html_ops` by 2% (container medians of 15 interleaved runs) + for 0.3 MB more peak memory at start-up and 2 to 4 MB in the larger + runs. On macOS, in instructions per iteration, the previous build to + this one with CPython's figure in parentheses: `format(x, ".3e")` + 4,008 to 1,801 (3,226); `"%.6e" % (0.1 + 0.2)` 4,179 to 3,124 + (3,210); `f"{z:.2E}"` 2,525 to 1,780 (3,029); `format(y, ".4g")` + 3,818 to 2,076 (2,450); `a == DC(1, 2)` of a dataclass in a tier-2 + loop 4,470 to 3,407 (2,627); `a < OD(1, i)` of an ordered one 5,000 + to 4,063 (3,187); `dict(zip("abc", L))` 5,576 to 3,983 (4,201); of + ten characters 10,208 to 6,445 (7,146); `dict(zip(L, text))` 10,368 + to 6,631 (7,221). Still slower: constructing the dataclass in a + tier-2 loop, which most of that comparison loop now is. + - One-character replacements, `dict(d, k=v)`, sort keys read from a + dict, `list(islice(...))`, and the dict-subclass merge rule. A sweep + of 66 common one-line operations against CPython (instructions per + iteration under Callgrind) found these four the furthest behind. + `s.replace("o", "0")`, one ASCII character for another, listed every + match before building the result; it now copies the text once and + changes each match in place, as CPython's `replace_1char_inplace` + does (`tests/regrtest/test_str_replace_one_byte.py`). `dict(d, k=v)` + of an exact dict went through the class call, a keyword vector of + owned strings and a scratch dict; a compiled call now copies `d`'s + table once and puts each keyword's name in with the native probe + (`tests/regrtest/test_dict_copy_with_keywords.py`). + `sorted(xs, key=d.__getitem__)` and `key=d.get` of an exact dict + called the leaf half once an item; the keys now come from one view + of the table (`tests/regrtest/test_sorted_dict_value_keys.py`). + `list(islice(src, stop))` over a source whose steps run no code (a + `count`, `cycle`, `chain` or plain cursor) took each item through the + general collector and its end through two declined steps; the items + up to the stop now come in one pass and the end is set where the + general step sets it, the source let go + (`tests/regrtest/test_islice_list_drain.py`). Checking `dict(D(...))` + against CPython turned up a merge-rule difference: CPython's + `dict_merge` reads a dict subclass's table whenever the subclass + keeps dict's `__iter__`, whatever its own `keys` and `__getitem__`, + but `dict(x)`, `dict(x, k=v)`, `{**x}`, `f(**x)`, `d.update(x)` and a + subclass's construction from `x` called an overridden `keys()` or + `__getitem__`; they now read the table under CPython's rule + (`tests/regrtest/test_dict_subclass_merge_rule.py`). Still different: + `d | x` and `d |= x` read the table of a subclass that overrides + `__iter__`. On macOS, in instructions per iteration, the previous + build to this one with CPython's figure in parentheses: + `S.replace("o", "0")` 1,350 to 907 (1,285); `dict(D, extra=1)` 4,349 + to 2,168 (1,806); `sorted(D, key=D.__getitem__)` of nine keys 8,495 + to 6,572 (5,123); `list(islice(count(), 5))` 6,137 to 4,887 (3,562). + - Wide integers, one-byte splits, tuple sort keys, and two-item + `itemgetter`s. Arithmetic on integers past 64 bits whose operands and + result fit 128 (`+`, `-`, `*`, `//`, `%`) runs in native 128-bit + arithmetic instead of promoting both sides to arbitrary precision. + `bytes.split` of a one-byte separator counts the matches with + `memchr` to size the list, then cuts the pieces between them. Sorting + by tuple keys compares string and integer elements directly rather + than through the generic equality and ordering protocol, and + `itemgetter(a, b)` and `itemgetter(a, b, c)` build their tuple from a + fixed array. On macOS, in instructions per iteration, the previous + build to this one with CPython's figure in parentheses: `(I * I * I) + // 12345` of a nine-digit `I` 2,672 to 1,811 (about 1,550); `B.split(b" + ")` 3,902 to 3,416 (about 3,400); `sorted(PAIRS, + key=itemgetter(1, 0))` of nine pairs 20,785 to 12,563 (15,670). + - Interpreter paths found by sweeping one-line cases with both JIT + tiers off, where warm-up code runs, and the `json.loads` key memo. + The interpreter's fused call of a small pure function first checks + that the whole argument run is plain loads ending in the `CALL`, so a + keyword call or one with a computed argument no longer scans the run + and declines (about 110 instructions a call). Reading `obj.__dict__` + remembers, per class version, that the class's instances read their + own dict, instead of looking up `__getattr__` and `__dict__` by name + on every read. `xs[a:b] = ys` with literal bounds, which compiles to a + store of one slice constant, splices in the interpreter's leaf arms + instead of the full step. A contiguous list slice and the starred + middle of an unpacking copy their items in bulk. The JSON decoder + files each key under its own randomized string hash, computed once and + kept on the new key for the dict insert, instead of SipHashing it + twice more in a separate set. On macOS, in instructions per + iteration, the previous build to this one with CPython's figure in + parentheses, interpreted: `fd(i, b=3)` 1,335 to 1,178 (about 655); + `OB.__dict__.get("zz", 0)` 2,083 to 1,663 (about 720); `a = L[:]; + a[2:5] = [0]; del a[0]` 4,562 to 3,731 (about 2,250). With the JITs + on: `json.loads` of a three-key object 16,146 to 15,833 (about + 15,100). + - Constructors in tier 2, fresh instances' fields, and two container + methods. A loop that both builds an instance and compares it + (`DC(i) == DCI`) is one tier 2 compiles, and its constructor call went + through the generic `instantiate` and a lean `__init__` frame, about + 2,000 instructions more than the frame JIT's. Tier 2 now builds an + instance whose `__init__` only stores its parameters as the frame JIT + does, filling the fields in place with no `__init__` frame. Reading a + field of a fresh instance (`P(i).a`), whose release is its last, took + the slow helper's ten other checks before the same field read; that + read now comes first, and every early answer of the slow helper runs + a finalizer or a weak reference's callback the release queued before + the next instruction (a polymorphic site's answer ran `__del__` late). + `array` subscripts and `len()` read the buffer where the array holds + it, with no count taken, and `OrderedDict.move_to_end(k, last=False)` + renumbers a run that is a good share of the table in one pass over + its slots. On macOS, in instructions per iteration, the previous + build to this one with CPython's figure in parentheses: `DC(i) == DCI` + of a dataclass 4,692 to 2,842 (about 2,900); the same of a plain class + with its own `__eq__` 5,492 to 3,289 (about 3,050); `t += P(i).a` + 2,268 to 1,519 (about 1,500); `t += D(i).a` through + `super().__init__` 3,353 to 2,907 (about 2,200); `OD.move_to_end(k); + OD.move_to_end(k, last=False)` 2,730 to 2,515 (about 1,550); `AR[3] + + AR[-1] + len(AR)` 1,994 to 1,871 (about 1,000). + - Dict displays with instance keys, and the gate a dict subclass's + `__missing__` raises over builtin lookups. `typing.NamedTuple` + evaluates its annotations under `annotationlib`'s `_StringifierDict`, + whose `__missing__` may serve builtin names, so builtin reads take + their slow paths while it is registered. It stayed registered for + good: the stringifiers it makes hold it in a cycle, and the table's + own reference kept any collection from freeing it. Meanwhile a pure + leaf's builtin reads declined, and 64 declines revoke a leaf for + good, so a frozen dataclass defined before a `NamedTuple` lost its + pure `__hash__` (`hash((self.a, self.b))`) and every hash of it ran a + frame. An owner is now dropped once no function or frame holds its + dict, however many hold the owner itself (code runs with the globals + only through one), and the gate prunes every 32nd ask rather than + every 1,024th. The frame JIT's `BUILD_MAP` also takes instance keys + whose `__hash__` is a pure leaf, while no two keys' hashes agree, + instead of leaving the compiled code. On macOS, in instructions per + iteration, the previous build to this one with CPython's figure in + parentheses, in a script that defines a `NamedTuple` after the + dataclass: `{FZ(i % 7): 1}` 9,604 to 5,647 (about 5,400); + `hash(FZ(i, 1))` 6,091 to 4,671 (about 5,250). + - In-memory streams' set-up and teardown, and `math.gcd` and + `math.lcm` of machine words. Every stream allocated a + lock for its descriptor syscalls and two strings for its name and + mode, and its destructor settled a `.buffer` sibling and flushed + staged bytes through borrow-checked cells. The lock is now made at + its first use, which an in-memory stream never reaches; built-in + names and modes are kept as static strings; and the destructor of a + stream with no descriptor, nothing staged, and no sibling returns + after clearing its weak references. `gcd` of words ran its binary + GCD in 128-bit arithmetic, and `lcm` built big integers for every + argument; both now stay in 64-bit words while the result fits one. + Also fixed: `os.fdopen(fd).name` + read back as a `property` object instead of `fd`, as `open(fd)` + reports it. On macOS, in instructions per iteration, the previous + build to this one with CPython's figure in parentheses: + `b = io.BytesIO(); b.write(b"abc"); b.getvalue()` 3,295 to 2,720 + (about 1,955); `math.gcd(i, 360) + math.lcm(4, 6)` 2,982 to 1,197 + (about 1,480). + - Typed buffer reads, wide encodings, and string slices in compiled + code. `list(struct.iter_unpack(...))` stepped its iterator once per + chunk through the full iterator protocol; a collecting container now + reads every chunk still to come in one pass while the iterator's + class keeps its own methods. `view[i]` of a 1-D view with a simple + format (`memoryview(b).cast("I")[i]`) left the frame JIT at every + read, since only plain byte views had an in-place arm; it now reads + the element in place when freeing the view runs no code. `s.encode` + to UTF-16 or UTF-32 by a common spelling took the full codec path, + which normalized the name twice; the leaf encoder now takes them. + A string slice with whole-number bounds and no step (`x[:8]`) is cut + in the compiled code's subscript helper instead of the generic + container path, and `isinstance` and `issubclass` call a metaclass's + plain-function `__instancecheck__` or `__subclasscheck__` (as + `typing.Protocol`'s is) without building a bound method. Also fixed: + a `struct.iter_unpack` iterator over a `bytearray` keeps it from + being resized until the iteration ends, as CPython's holds its + buffer. On macOS, in instructions per iteration, the previous build + to this one with CPython's figure in parentheses: + `list(struct.iter_unpack("`, copying each and + allocating it again as a `str`: it now collects the dict keys' own + strings and sorts once (`inspect.getmembers` of a class 211,206 + instructions to 190,518, CPython 136,682). `s.encode(encoding="utf-8")` + took the codec lookup, normalizing the name each call (3,975 to 2,198, + against 1,494), and now raises CPython's `TypeError`s for unknown or + repeated keywords, which it ignored. A one-base class's MRO is the + base's with the class in front, no merge (`type()` 17,599 to 16,376). + - Where the time goes. `email`'s `HeaderRegistry` builds a new class + with `type()` for every header it makes, so every header's lookups + start on a cold class; WeavePy's `type()` is cheaper than CPython's + (17,537 instructions to 121,421), but an address header still costs + 1.05 million instructions to CPython's 546,000, at 3.7 times its + cycles. In argparse, `parse_args` runs 2,200 bytecodes and 62 Python + calls a parse: interpreted, WeavePy spends about 150 instructions a + bytecode to CPython's 75, and 724 a call in the core loop's call and + return alone; compiled and warm it's 1.6 times CPython's. A plain + `for v in gen()` loop spends 685 instructions an item to CPython's + 400, 291 of them in the resume's checks (`gen_native_next`). + - Across seven of the worst cases (`argparse`, `email`, `configparser`, + `enum_dataclass`, `inspect_typing`, `class_features`, `collections`; + synchronous compiles), compiling is 8.3% of the instructions, the core + loop's own code 10.9%, calls 10%, allocation 10.3%, attribute paths + 10.3%, and the rest is spread over hundreds of functions: the largest + single one, `leaf_burst`, is 7.7%. Cachegrind puts `argparse_ops` at a + 3.8% instruction-cache miss rate (32.7 million misses in 858 million + instructions); compiled code takes 1.6% of the misses and the VM's own + code 92%, so for short cases the footprint is the interpreter's and the + runtime's, not the JITs'. The core loop's dispatch jump mispredicts 1.9 + million times there. + - Threads. A two-thread ping-pong through `queue.Queue` costs 173,884 + instructions and 249,454 cycles a round trip to CPython's 65,984 and + 67,867, with twice the context switches. While a second thread runs, + every container's cell borrow takes an atomic compare-and-swap + instead of the biased check; starting and joining a bare thread costs + 281,455 instructions to 86,833 (per-thread tables zeroed and dropped, + the allocator's per-thread heap, the interpreter's fork). + +- **Configparser's constructions, compiled patterns, and where the short + cases spend** (PR #112, November 16, later). Ratios are instructions, + WeavePy's over CPython's. + - `re.match(p, s)` with a compiled pattern runs `re._compile`, which + probes its cache with `(type(p), p, flags)` and catches the + `KeyError`. A pattern hashed through the interpreter (a `__hash__` + call that built and hashed a tuple), and a tuple holding one wasn't a + key compiled code could probe, so the miss left for the core loop, + which hashed the key again before raising. A pattern now hashes + natively while its class keeps the native `__hash__`, and the miss + raises in place: `re._compile(p, 0)` ran 18,402 instructions to 11,430 + (CPython 6,129), and `ConfigParser.write` 19% fewer. + - `functools.partial(f, k=v)` left compiled code (no keyword lane for a + Python class with a native `__new__`) and set its five slots one probe + at a time: 8,338 instructions to 5,749 (2,216). `for k in mapping` + over an instance whose `__iter__` is a Python function left too; it's + called directly now, its result checked as `iter()` checks it (5,812 + to 2,814, against 1,786). Together, a `SectionProxy` ran 58,882 to + 47,197 (24,155). + - A value type's subclass with a Python `__new__` (`configparser`'s + `_Line(str)`) went through the generic construction, with `__new__` + and `__init__` each a nested run: it now takes the inline activations + a plain class's does (10,000 instructions to 5,435, CPython 4,063). + The configparser case ran 7% fewer instructions. + - `(x,) * n` and `[x] * n` of a short sequence repeat in place in + compiled code and the core loop (argparse's metavar formatter left 13 + times a parse). + - `dataclasses.replace` ends in `self.__class__(**changes)`, which had + no lane for a class: it left compiled code and took the generic call. + The mapping's keywords now bind to `__init__` as a keyword call's do, + and the call runs inline (27,452 instructions to 19,239, CPython + 11,984; cycles 3.9 times CPython's to 2.1). The keyword and mapping + constructions share one body. + - `super(C, obj).__class__` built the proxy's dict one probe at a time, + and the class read, finding the proxy's last reference on the stack, + declined to release it and took the attribute miss path: it releases + it now, a queued finalizer running before the next instruction + (4,269 instructions to 1,785, CPython 1,236). + - A `list` or `tuple` subclass's `self[0]` (`email`'s `TokenList`) and + `for entry in os.scandir(...)` (`glob`) were slow steps; they read the + payload and step the iterator in place. Branch relaxation in the code + generator found each branch's place by binary search on every pass: + 32% less of the compiles' finishing work. + - The battery stands at 1.233 times CPython's instructions on quick + builds (1.237 this morning): `class_features` ran 10% fewer, + `configparser_ops` 8%, `enum_dataclass_ops` 5%, `email_html_ops` 3%. + - Why the short cases trail. Argparse's case runs each operation 180 + times. CPython's instructions an iteration are flat from the first + (1.5 million); WeavePy's fall from 5.6 million over the first 20 to + 2.3 million after 600, with the frame JIT still compiling functions + for the first time after 300 iterations (functions run once an + iteration reach the threshold late). Turning either JIT tier off, or + both, leaves the case's instructions and time where they are: the + gap is the interpreter and the runtime. Even warm, an iteration takes + 2.3 times CPython's cycles on 1.5 times its instructions: cachegrind + finds 5% of instructions missing the instruction cache and 13% of + conditional branches mispredicted, both spread over the interpreter, + the helpers and compiled code. Tier 2 analyzed 144 functions in the + case and compiled 11; the rejections (`dynamic call (loop-free)` + after a full analysis, and probe misses that carve loop by loop) took + most of its 44 ms of analysis, about 64 million instructions. + And calls from native code into Python (`map(partial(cls, k=v), xs)`) + cost about 1,200 instructions of nested-run overhead each, with + keyword names copied to `String`s at every hop: 11,300 instructions an + item to CPython's 6,200. + +- **Builtin subclasses, generator steps, and a misread fixture gate** (PR + #112, November 16). Ratios are instructions, WeavePy's over CPython's. + - The local fixture A/B tools ran every bench fixture at a work size of + one, so a tier-2 policy that weighed a loop's dynamic calls three times + read even locally and cost `nbody` 35% (the bench gate flagged it 41% + to 56% slower on all three platforms). The policy is reverted, and the + tools take the gate's work sizes from `fixtures.rs`. + - `email`'s header parser builds `TokenList`, a `list` subclass, and + `Terminal`, a `str` subclass, and runs generator expressions over them. + `super().__init__()` reaching `list.__init__` or `set.__init__` left + compiled code for the core loop on every call (only `dict.__init__` + was admitted), `GET_ITER` of a list subclass left too, a property read + in a generator's fast step declined outright although a pure getter + runs no activation, and `TO_BOOL` of a `str` subclass left because the + native truth admitted only one kind of builtin `__len__`. With those + fixed, and attribute sites remembering the pure getter they last ran, + a `TokenList()` ran 11,607 instructions to 5,375 (CPython 3,296), + `TokenList.value` 35,107 to 13,154 (6,339), and the email case 12% + fewer. + - An explicit `super(C, obj)` as a value built through every call lane + (5,540 instructions to 2,224 against CPython's 979), and its + `__class__` took the generic attribute path (9,790 to 3,951). + - `object.__new__` walked a builtin subclass's MRO five times a call; one + walk now answers all of its questions, memoized by class version. + `os.stat` laid its result's nineteen fields into a dict one probe at a + time and read ten back by name (13,457 instructions to 9,272). + - Objects whose `__dict__` was published (`copy`, `pickle`, `vars()`, + and `dir()`, which configparser's `ConverterMapping` runs on its + parser) lost compiled code's field reads: every attribute read went + the whole miss path, about 800 instructions. `dir()` no longer + publishes, and attribute sites remember where a name sat in a + published dict (two reads of a copied object: 1,875 instructions to + 509, CPython 896). Class attributes read through an instance now + memoize objects without `__get__` too (configparser's compiled + patterns), and native `re` objects lay their slots over their + classes' own layouts. `ConfigParser.read_string` ran 10% fewer + instructions, `ConfigParser.get` 20%. + - `typing`'s subscripts (`List[int]`, `Optional[str]`) went through + `_tp_cache`, whose `f(*args, **kwds)` forward to an `lru_cache` + wrapper had no lane in compiled code, whose cache probe hashed only + builtin scalars, and whose subscript site, compiled before the core + loop ran it, had no direct `__getitem__` call: `typing.Optional[str]` + ran 13,031 instructions to 3,164 (CPython 2,683). + - The frame JIT now takes code tier 2 failed to compile three times + (argparse's `_parse_known_args` had stayed interpreted for good), and + `ref.__new__` and `_sre.exec_match` over a `str` run in place (a + 100-entry `WeakValueDictionary`: 1,241,587 instructions to 877,688). + - Where compiled code still left for the core loop, per site: an + exception's `args` (its own slot layout), an f-string's `!r` of a + list, a generator expression's dict view at its end, an exhausted + tuple of objects (enum's `for flag in self, other`), and an `IntFlag` + operator (a builtin subclass's Python method). Enum flag operations + ran 14% fewer instructions, a dataclass's `repr` 25%, + `dataclasses.asdict` 24%, `e.args` 44%. + - Native helpers: `binascii.hexlify` ran a branch and a growing push a + digit (33 instructions a byte, now under CPython's), and `upper()`, + `lower()` and `casefold()` sent every character of non-ASCII text + through the Unicode tables (a mixed 400-character string: 36% fewer + instructions). + - Tried and dropped: native `LOAD_GLOBAL` hits in compiled code (the + helper costs as much as its guards would in line), native reads of + polymorphic split fields (their IR pushed `deltablue`'s hot functions + over the inline budget), and a Linux-only symbol order (the release + build's fat LTO renames most of what the profiles name; start-up RSS + moved 2%), and a lower frame-JIT threshold (60: the battery ran 1% more + instructions). The battery stands at 1.252 times CPython's + instructions on quick builds, against 1.285 at the start of the day; + `class_features` ran 21% fewer instructions, `email_html_ops` 13%, + `configparser_ops` 8%, `enum_dataclass_ops` 7%. + +- **Tier 2's wasted work, a start-up deadlock, and more cliffs** (PR #112, + November 15). Ratios are instructions, WeavePy's over CPython's unless + stated, with synchronous compiles. + - Tier 2 cost the everyday battery more than it gave it: with tier 2 + off, the battery ran 2% fewer instructions, and no case ran more than + 3% more. Three causes, each fixed. The analysis found each pc's + innermost loop by searching the whole loop forest per pc, once per + analysis and carving step, which made a failed attempt on a big + function expensive (the argparse case ran 13% more instructions with + tier 2 than without; now the two are even). A recompile at a loop the + compiled frame couldn't enter dropped the frame first, and when the new + analysis missed its probes the code went cold and compiled the same + frame again on the next call (difflib's `find_longest_match`, four + compiles a run, 7% of the case). And the frame JIT leaves code with + loops to tier 2, which left two kinds of code interpreted for good: + code whose call entry tier 2 had already missed (it never attempts + that entry again; `urllib.parse._checknetloc` ran interpreted on every + call) and compiled code whose activations mostly side-exit or fail + their entry guards, which waited for absolute budgets of 64. Call heat + now goes to the frame JIT once tier 2 has missed the call entry and + the code has got hot that way 128 times with none of its loops run + (taking it at the first such heat cost raytrace 8%: `Scene.trace`'s + loop runs only for rays that hit something, which the first rows + don't, and tier 2 compiles that loop by OSR later), and compiled code + retires once its misses reach 16 and outnumber its finished native + runs two to one. With tier 2 off the battery now runs + 0.8% fewer instructions instead of 2%; the enum and dataclass case (8%) + and the threading and queue case (6%) are what's left. Tier 2 makes a + loop's dynamic calls through general helpers where the frame JIT runs + a Python callee in line (a keyword call in a range loop: 1,080 + instructions an iteration under tier 2, 265 under the frame JIT), but + weighing those calls three times in the generic share cost the + `nbody` fixture 35% and `generators` 16%: a driver loop the frame JIT + takes runs its callee's float loop there too, where tier 2 entered it + by OSR. Still open: a share of 10% instead of 20% would send more loops + to the frame JIT (the battery 0.4% fewer instructions, the suite even), + but there a Python `__eq__` that a native instance-dict lookup runs + sees the wrong caller frame in an activation's first lookup: the core + loop publishes its activation only before the calls it makes itself. + - `os.environ.get(name)` and `name in os.environ` read the backing store. + `Mapping`'s versions find a missing variable through `__getitem__`, + which raises and catches two `KeyError`s, and programs probe unset + variables constantly (argparse's color and gettext checks probe 22 for + each parser): a miss is 0.31 of CPython's instructions instead of 2.2 + times. An `ArgumentParser()` went from 2.66 to 1.96. + - Natively built instances (a `re.Match`, a `Decimal`, a `datetime`, an + ElementTree iterator) get their slots at birth instead of an all-unset + block that was dropped at once: an allocation, a fill and a free less + per object. A trivial `re.match` went from 1.25 to 0.92. + - `super().__repr__()` and the other names WeavePy keeps outside the type + dicts (`__str__`, `__dir__`, `type.mro`, `__prepare__`, the builtin + bases' dunders) resolve through `LOAD_SUPER_ATTR`'s direct path instead + of building the `super` proxy and reading it back: 5.2 to 2.2. + - Builtin subclasses. A `str`, `int`, `float`, `complex`, `bytes` or + `tuple` subclass's `__slots__` are laid out as `object`'s are: any + builtin base but `object` kept members in the keyed form, which + compiled code never reads in line, so each member read of a + `configparser` `_Line` (a `str` subclass) took the attribute miss path + (3.40 to 0.41). Constructing a builtin subclass's instance asks the + type cache whether `__init__` is overridden instead of probing each + class dict with a fresh key, and the collector's "not due yet" answer + comes from one load (a `str` subclass's construction, 4.1 to 3.4). + - `yield from` a range, tuple or list iterator steps it in place: the + core loop's `SEND` took the full step for any delegate but a + generator or an asyncio future, so every item went through the + general handler (`yield from range(100)`, 3.40 to 1.27). A list's end + keeps the general path, since it detaches the list and may free a + subclass's owner. + - Smaller ones: `object.__setattr__(self, name, value)` (a frozen + dataclass's `__init__`) passes the name object through a per-thread + memo to the intern pool instead of copying and re-interning its text, + and a method site keeps a builtin type's unbound or class method + (`object.__setattr__`, `dict.fromkeys`) for its version; `lru_cache` + keys holding a plain instance or a user class take the native lookup + (`typing`'s `_tp_cache`); `OrderedDict.__setitem__` called as a method + settles through its leaf half; a `weakref.ref` subclass's instances + share the class's `__call__` and `__repr__` instead of two closures + each (a `KeyedRef` per `WeakValueDictionary` item); and a thread's + interpreter fork takes its parent's leaf builtin table instead of + rebuilding it (a thread's start and join, about 10% fewer + instructions). + - Fixed: a process's first thread could deadlock at start-up. The thread + that revokes the cell bias spun, holding the GIL, until the first + thread's lock-free guards drained; a count that never drained hung + torch's DataLoader on macOS (its first queue feeder thread never + reached Python code), and the ecosystem shard ran out its 30 minutes. + While the GIL guards every cell the revoker can't race a guard holder, + so past 50 ms it goes on. A temporary torch-only CI job found it: the + ecosystem harness now sends a timed-out probe `SIGABRT` first, so a + probe with `faulthandler` on dumps every thread, and keeps the output's + tail in the row's reason. + - Fixed: `reversed()` of an iterator, a set or a native adapter raises + `TypeError`, as CPython's does; it read the source to the end first, + so `reversed(itertools.count())` hung. + - Looked at and left: an explicit `super` object (`super().__class__`, + which CPython doesn't compile to `LOAD_SUPER_ATTR` either) is about 8 + times CPython's, through a dozen general layers, and rare; setting an + `EmailMessage` header is 3.4 times CPython's, a flat profile of + polymorphic attribute sites and frames with nothing dominant. + +- **Threads that have exited, lock hand-offs, and more cliffs** (PR #112, + November 15). Ratios are WeavePy's instructions over CPython's, before + and after, with synchronous compiles. + - Single-thread reference counting comes back. Starting any thread made + reference counts atomic and cell borrows locked for the rest of the + process, and frames register before every native body so other + threads can look. A `queue.Queue` put and get after one finished + thread cost 26,500 instructions instead of 16,000. A `join()` now + joins the OS threads of the workers that have finished, and once none + is left (and no thread the VM didn't start ever took the GIL) the + joining thread restores the bias. The everyday battery runs every + case in one process, so the six cases after `threading_queue_ops` + paid for it: by wall time on quick builds, `asyncio_ops` 0.69 of the + earlier build's, `print_to_buffer` 0.74, `weakref_gc_ops` 0.79, + `sqlite_ops` 0.80, `inspect_typing_ops` 0.81. + - Code that runs while a second thread is alive. Every release that + wasn't the last took the last owner's checks out of line, compiled + calls that bind defaults weren't entered directly, a direct call's + return released through the slow path, and lazily running frames + registered before every native body in case another thread looked. + Releases that aren't the last are now one locked update, the direct + call protocol makes locked updates instead of declining, and frames + register first only for a watchdog that reads them without the GIL: + every release of the GIL (C code's `PyEval_SaveThread` included) + settles them first. A queue put and get with an idle second thread + alive: 26,430 instructions to 18,695 (16,380 with none, CPython's + 11,800). `threading_queue_ops` 1.82 to 1.64. + - Lock hand-offs. A contended acquire took the lock as soon as it was + free, while the GIL holder ran on; the holder then blocked at its next + acquire of the same lock, so a producer and a consumer sharing a + queue's mutex switched threads at every operation (34,000 context + switches for 60,000 items against CPython's 45). The waiter now waits + for the lock to come free with the GIL released and takes it only + once the GIL is back, as CPython's does. `threading_queue_ops` 2.79 to + 1.82. + - `yield from` two levels deep. The direct chain step declined a + delegate whose own body no fast step runs, though a delegate resting + in a `yield from` of its own steps without running its body, so each + level resumed as an activation: 4.45 to 1.71 (one level was 1.85, + three or more 1.0 or less). + - A sweep of common idioms (`target/mb/idioms.py`-style loops, one + function a case) found `datetime.datetime.now()` at 6.1 times + CPython's instructions: `_pydatetime` ran `fromtimestamp` in Python + (`time.localtime()` unpacked, the constructor, and the fold probe's two + more `localtime` calls and datetime arithmetic). `now`, `fromtimestamp` + and `date.today` are native for the exact classes with no `tzinfo` or + an exact `timezone`, following `_fromtimestamp` step for step, with + results identical to the Python methods' across DST gaps and folds in + eight zones, and bound by the dispatch loop without the descriptor: + `now()` 6.14 to 1.15, `date.today()` 0.56. f-string fields with a + format spec left compiled code for the core loop at every field, and + the formatter rendered `str(value)` before reading the spec: + `f"{x:.2f}"` 1.49 to 0.46. `dict((k, v) for ...)` copied each pair into + a vector and set up a key-comparison scope per insert: 1.40 to 1.01. + `str.startswith` of a tuple took the generic call; a method read off a + built-in value hashed its name into the method memo at every call (164 + instructions, 68 with a per-thread cache of each call site's last + answer); `zip` of three to eight sequences stepped each source through + the general checks (2.41 to 2.17). + - Two more idiom sweeps (about 90 operations: binary formats, hashing, + iteration helpers, application-level library calls). The cliffs, with + their ratios before and after: `struct.pack` 4.30 to about 1.0 (a + Python function forwarding `*v` to the packer, which copied and + SipHashed the format text each call; now a native that packs plain + values in place and calls the Python function for anything else); + unpacking a `namedtuple` 4.27 to 0.96 (compiled code left for the core + loop, which iterated the tuple subclass); `str.format_map` 3.72 to + 1.17 (always the interpreter's format engine, by a generic call); + `list(reversed(xs))` 2.11 to 1.08 and `xs[::-1]` 1.94 to 1.10; + `next(itertools.count())` 1.90 to 0.90 (`next` wasn't a leaf); + `md5(b).hexdigest()` 2.06 to 1.53 (each byte formatted through + `core::fmt`); a `csv` writer's `writerow` reading the dialect's + attributes by name every row; a sort key's native `__call__` looked + up per item; `heapq` fetching the interpreter before comparisons that + don't need it. + - Python dunders from native code. `str(x)`, `len(x)`, f-string + formatting and `x in obj` of a plain instance call the class's + `__str__`, `__len__` or `__contains__` without a bound method, in + place when it's a pure leaf; a class without `__format__` is cached as + such. The frame JIT's fused `len(local)` read declined instances, so + each `len(obj)` reran the whole global load. `str(t)` 2.14 to 1.03, + `f"{t}"` 2.31 to 1.36, `len(t)` 1.43 to 1.05, `3 in obj` 1.86 to + 0.68. + - Smaller ones: a Python `__next__` called without a bound method by + `for` and `next()` (and `iter()` of a builtin iterator subclass's + instance is the instance, which fixed a subclass's `__next__` being + skipped); `BUILD_SLICE` and slice subscripts in pure leaves; native + `re.Pattern` hashing and equality; a keyword leaf half for + `bytes.translate`; `list.sort()`'s leaf half comparing strings and + ints directly; a property with a native getter read in the compiled + attribute site. + - The PGO training runs the everyday battery too (`tools/pgo/train.sh`), + its profile merged with the rest rather than into the order file's + hot group: the library paths it runs get branch weights and inlining. + Two builds of one commit: the battery at 0.96 and 0.98 of the other's + time over two runs, the suite at 1.000. + - Fixed on the way: a method leaf called unbound with no receiver + (`list.pop()`) indexed an empty argument list and panicked + (`test_types.test_call_unbound_crash`). + - Tried and dropped: `LOAD_GLOBAL`'s cache hit emitted in line. A loop + reading a module global went from 182 instructions an iteration to + 116, but in real code (`dataclasses.asdict`, whose 35 global reads a + call were all helper calls) the in-line guards cost what the helper + did, for more code. + +- **Operation-level cliffs in the everyday battery** (PR #112, November + 14). Each case broken into single operations, each operation's + instructions counted against CPython's with synchronous compiles + (`WEAVEPY_FRAME_JIT_SYNC=1`), and the outliers profiled in the + container. Ratios are WeavePy's instructions over CPython's, before and + after. + - `bytes`. Methods read their receiver in place instead of copying it; + a short search skips `memmem`'s set-up (`replace` scanned with a + `memcmp` at every position); slices, indexing, plain `%` formatting, + `bytes(n)` and `bytearray(b)` have fast paths. `replace` 3.08 to + 1.13, `b[5:20]` 3.08 to 0.93, `b"%d:%s" % args` 2.69 to 1.44, + `bytes(10)` 2.60 to 0.78. + - `datetime`. `astimezone` ran `_pydatetime`'s local-time search in + Python (six or seven `time.localtime` calls and datetime arithmetic); + `replace`, `timestamp` and `astimezone` are now native for exact + classes with no `tzinfo` or a fixed-offset `timezone`, following + `_mktime` and `_local_timezone` step for step, with results identical + to the Python methods' across DST gaps and folds in five zones. + `astimezone(utc)` 9.32 to 0.86. + - `OSError`. Its family's builtin `__init__` kept every construction + off the leaf path; the leaf path's instance already holds what that + `__init__` sets. `OSError(errno, msg)` 6.22 to 1.98. `gettext` + raises and catches one per catalog lookup, about 50 per + `argparse.ArgumentParser()`. + - Dunder reads by name. `getattr(cls, name)` and `hasattr(cls, name)` + declined every dunder off a short list, so `dataclasses`' + `hasattr(type(obj), "__dataclass_fields__")` took the full + type-attribute path; a dunder `type` doesn't define and the full path + doesn't synthesize now resolves in the class's MRO. 6.06 to 1.51. + - Comparison methods resolved once. `x in xs` and sorting instances of + one class with a Python `__eq__` or `__lt__` went through the whole + rich-comparison dispatch per element; the method is now resolved once + per scan or sort. `x in xs` 2.14 to 1.55, sorting 1.51 to 0.90. + - Builtins called through the generic path. A native function compiled + code calls without a leaf registration leaves for the interpreter's + general call, about 2,500 instructions. `WEAVEPY_BURST_STATS`' + "generic call" lines, summed over the battery minus an empty run, + rank them; those whose plain shapes run no code now have leaf halves: + `os.urandom`, `int.from_bytes` (one builtin per thread instead of a + fresh one per read), `binascii.hexlify`, `round`, `repr` of scalars, + `list.sort()` of strings or numbers, `weakref.ref.__init__`, and + `str`, `tuple` and `int` `__new__` of a value of the type. A builtin + method read off its type (`str.upper`) is a receiver-checking shim, + which now takes the method's leaf kind. `secrets.token_hex(8)` 2.29 + to 0.97, `f = str.upper; f(s)` 2.49 to 0.96. + - Smaller ones: `weakref.ref(x)` as a pure constructor (3.19 to 1.53); + `dict(zip(xs, ys))` and `dict(d)` built directly (2.42 to 0.95); + `functools.partial` callbacks unwrapped in `map` (5.18 to 1.09); + `itertools.chain` of ranges drained at once (2.20 to 0.36); a + property read through `getattr` in the leaf lane (3.36 to 1.03); + `type(o).__name__` remembered under `ABCMeta` (3.45 to 0.56); the + csv writer's dialect read once per `writerows` and plain fields + copied whole (2.26 to 1.52); `os.stat`'s field names shared through + a per-thread cache of literal strings (1.53 to 1.40); `json.dumps`'s + `sort_keys` sorting `str` keys in place; a thread's type cache taken + from zeroed memory, and leaf-builtin registrations no longer making + every interpreter rebuild its map. + - Tried and dropped: leaving loops whose work is Python calls on + objects to the frame JIT. It cut one shape 4x (2,470 instructions an + iteration to 573) and was neutral on the suite and the battery, but + it handed loops whose calls tier 2 makes natively to the frame JIT, + and the bench gate read `nbody` at 1.6 times its base. + - **Comparison methods, descriptors, thread-locals and queues** (this PR, November 13). The everyday battery's class and thread cases, taken one operation at a time: @@ -2875,6 +8686,18 @@ slowdown in that run was the even-sized chunks, since fixed. ## What the measurements say +- **The battery's whole-case profile is flat** (November 14, callgrind + over all 54 cases with synchronous compiles). The core loop's own body + is 4.9% of the instructions, allocation and release about 7%, and no + other function passes 2%; the layers around a native caller's call into + Python are 2.5%, and compiling about 2% (9% to 14% in the shortest + cases). What gave way was operation-level: a case broken into single + operations and each counted against CPython shows one or two at 3 to + 9 times, a general path taken where a cached or native one was + missing. Two measuring traps: a breakdown script's loops must each sit + in a function of their own (one function with an `if` per case runs + them interpreted, 3 times slower), and short runs under load measure + loops still waiting for their background compile. - **A call from native code into Python costs four or five times a call from compiled code** (November 13). The same `__eq__` body costs 2,200 instructions called directly from a compiled `COMPARE_OP`, 4,080 when @@ -3467,6 +9290,71 @@ slowdown in that run was the even-sized chunks, since fixed. ## Next +What PR #112's breakdowns left (instructions against CPython, quick +builds, synchronous compiles): + +- `typing` subscripts (`typing.List[int]` 6.1, `Optional[str]` 5.8): the + native subscript calls `_tp_cache`'s Python wrapper, which forwards + `*args, **kwds` to the `lru_cache`, through the nested native-to-Python + entry. +- `email`'s header parsing (setting one header 3.0) and `configparser` + (`write` 2.8, `read_string` 2.0): flat profiles of interpreted library + code, the core loop's call and return about 1,000 instructions a call. +- The remaining builtins called through the generic path, ranked by the + battery's "generic call" counts: `getattr` misses (an `AttributeError` + raised and caught), `str.join` and `list.extend` over generators, + `next` of a generator, `print` with keywords, `StringIO.write`, + `setattr` on plain instances, `len` and `hash` through Python methods. +- A raise caught in its caller (2.2) and three frames up (2.4). +- Thread start and join (4.6 times CPython's instructions): each thread + zeroes and later drops a 4,096-entry type cache (128 KB) and tier 2 + analyzes again what another thread compiled. And code that runs while a + second thread is alive still costs about 15% more than with one: the + frame JIT's in-line reference-count updates go to helpers when counts + are shared (the code generator has no atomic instructions), and cell + borrows take the locked path. +- Keyword calls of a function with keyword-only parameters in a tier-2 + loop: tier 2's static binding requires `kwonly_count == 0`, so `f(i, + c=4)` goes through its dynamic keyword helper (1,240 instructions + against CPython's 1,060), where the frame JIT alone inlines the call in + 330. +- Exceptions raised in a callee (2.1 times CPython's instructions) and in + the same frame (1.6): about 40 layered helpers of 50 to 300 instructions + each (normalization, the instance, its traceback, frame shells for the + traceback, the handler search per frame), no single one dominant. +- Generators: a resume through `gen_native_next` is about 300 + instructions, `lazy_gen_resume` (a body that calls) about 360, and + creating one about 1,000, against CPython's 150 or so a resume (`for x + in gen` 1.63, `all(f(x) for x in xs)` 1.40, a generator created and + drained 1.94). Plan item 2. +- `decimal`: each operation finds the current context through the + `contextvars` mapping and the context's fields, about 390 instructions + of a multiplication's 1,600 (CPython 1,100). +- `dataclasses.asdict` (2.3) and `replace` (2.3), `IntFlag` `|` (1.7), + a dataclass `repr` (1.9): flat profiles of interpreted library code. +- The frame JIT's generic call helper, `h_call` (about 250 to 300 + instructions before the callee runs: a chain of shape checks for + `lru_cache` wrappers, `__call__`, `__reduce_ex__`, leaf builtins, then + the general path), which an instance with a native `__call__` + (`operator.itemgetter` 1.6), a builtin with keywords and + `functools.partial` (1.8) all take. A call site that remembered its + callee's shape could skip to it. +- `pickle.dumps` of a small dict (1.8): every call re-verifies about 13 + module functions the engine depends on (their code and defaults); a + global epoch bumped by `__code__`, `__defaults__` and `__kwdefaults__` + assignments would let it check a stamp instead. +- `string.Template.substitute` (1.9), `itertools.groupby` (1.8), + `urllib.parse.quote` (1.6), `bisect.insort` (1.6), `random.randint` + (1.7): Python-level library code over callbacks. +- Tier 2's method calls on built-in values it can't type: the counting + idiom `d[k] = d.get(k, 0) + 1` runs 1.9 times CPython's instructions in + tier 2 against 0.94 in the frame JIT alone, because tier 2 reads + `d.get` dynamically, builds a bound method every iteration and calls it + through its dynamic helper. A typed `DictGet` with a default (the + analyzer already lowers `d[k]` on a dict lane) would close it. +- Two-argument `super(C, obj)` used other than for an immediate attribute + read (5.95), and `super(...).__class__` (7.8). + What the everyday battery points at (`tools/pybench/everyday.py`; see "What the measurements say"): diff --git a/tests/ecosystem/manifest.toml b/tests/ecosystem/manifest.toml index c513ad46f..5b0ff1977 100644 --- a/tests/ecosystem/manifest.toml +++ b/tests/ecosystem/manifest.toml @@ -189,7 +189,10 @@ probe = "probes/packaging_probe.py" [packages.packaging.selftest] source = "packaging==26.3" -requirements = "pytest==8.4.2 pretend==1.0.9 hypothesis==6.155.7 tomli_w==1.2.0" +# packaging==26.3 repeats the row's pin: the in-tree pip resolves +# pytest's `packaging>=20` to the newest release instead of keeping the +# installed one (26.4 broke the 26.3 suite on 2026-11-23). +requirements = "packaging==26.3 pytest==8.4.2 pretend==1.0.9 hypothesis==6.155.7 tomli_w==1.2.0" # Two enumerated trims, both interpreter-speed-bound (measured # 2026-08), neither a correctness signal: # --ignore=tests/property — upstream's hypothesis property-fuzz lanes diff --git a/tests/regrtest/expectations.toml b/tests/regrtest/expectations.toml index 92fc02ef3..e8065b6b6 100644 --- a/tests/regrtest/expectations.toml +++ b/tests/regrtest/expectations.toml @@ -787,7 +787,7 @@ reason = "isinstance()/issubclass() now implement CPython's full protocol: the d [tests."cpython/Lib/test/test_iter.py"] status = "pass" -reason = "RFC 0037 WS7: full iterator-protocol fidelity. The prior gc-reachable hang is gone — the legacy __getitem__ sequence protocol and iter(callable, sentinel) now build *lazy* iterators (frozen _seqtools _SeqIter/_CallableIter) instead of eagerly materialising, so an unbounded sequence iterates on demand. Built-in iterators gained a faithful __reduce__ ((iter, (remaining,)) / (reversed, (fwd,), idx)) that resolves the iter/reversed builtin through the live builtins module dict so a hash-colliding custom __eq__ exhausts the iterator before its state is snapshotted (gh-101765); a PEP 585 generic alias iterates by yielding typing.Unpack[self] once (matching CPython ga_iternext). Plus: file objects are iterable (for line in f / x in f / list(f)) and writelines accepts any iterable; pickle gained memoisation so co-referenced instances unpickle shared; closures over enclosing-function locals resolve in nested methods; and tracebacks carry PEP 657 column offsets (co_positions/f_lasti/tb_lasti translated to CPython byte offsets). (skipped=2 are @cpython_only refcount subtests.)" +reason = "RFC 0037 WS7: full iterator-protocol fidelity. The prior gc-reachable hang is gone — the legacy __getitem__ sequence protocol and iter(callable, sentinel) now build *lazy* iterators (the frozen _seqtools _SeqIter, and a native callable_iterator) instead of eagerly materialising, so an unbounded sequence iterates on demand. Built-in iterators gained a faithful __reduce__ ((iter, (remaining,)) / (reversed, (fwd,), idx)) that resolves the iter/reversed builtin through the live builtins module dict so a hash-colliding custom __eq__ exhausts the iterator before its state is snapshotted (gh-101765); a PEP 585 generic alias iterates by yielding typing.Unpack[self] once (matching CPython ga_iternext). Plus: file objects are iterable (for line in f / x in f / list(f)) and writelines accepts any iterable; pickle gained memoisation so co-referenced instances unpickle shared; closures over enclosing-function locals resolve in nested methods; and tracebacks carry PEP 657 column offsets (co_positions/f_lasti/tb_lasti translated to CPython byte offsets). (skipped=2 are @cpython_only refcount subtests.)" [tests."cpython/Lib/test/test_iterlen.py"] status = "pass" diff --git a/tests/regrtest/test_abs_dunder_direct.py b/tests/regrtest/test_abs_dunder_direct.py new file mode 100644 index 000000000..4dc1b8a48 --- /dev/null +++ b/tests/regrtest/test_abs_dunder_direct.py @@ -0,0 +1,86 @@ +"""Compiled `abs(obj)` of an instance whose class's `__abs__` is a Python +function calls it directly (in place when a warm pure leaf); the +results (any type, `abs()` doesn't check them), a missing `__abs__`'s +TypeError, raises caught in the frame or past it, numbers and instances +at one site, and a method replaced later match the general call.""" + +import fractions +import unittest + + +class V: + def __init__(self, x): + self.x = x + + def __abs__(self): + return V(self.x if self.x >= 0 else -self.x) + + +class Const: + def __abs__(self): + return "abs" + + +class Boom: + def __abs__(self): + raise KeyError("abs") + + +class NoAbs: + pass + + +class AbsDunderDirect(unittest.TestCase): + def test_results(self): + vs = [V(i - 50) for i in range(100)] + c = Const() + out = [] + for _ in range(100): + for v in vs: + out.append(abs(v).x) + self.assertEqual(abs(c), "abs") + self.assertEqual(out[:3], [50, 49, 48]) + mixed = [V(-3), -4, 2.5, fractions.Fraction(-1, 3), Const()] + res = [] + for _ in range(1000): + for m in mixed: + r = abs(m) + res.append(r.x if isinstance(r, V) else r) + self.assertEqual(res[:5], [3, 4, 2.5, fractions.Fraction(1, 3), "abs"]) + + def test_errors(self): + n = 0 + for i in range(1000): + try: + abs(Boom()) + except KeyError: + n += 1 + with self.assertRaises(TypeError) as cm: + abs(NoAbs()) + self.assertEqual(n, 1000) + self.assertIn("bad operand type for abs()", str(cm.exception)) + + def outer(): + return abs(Boom()) + + for i in range(500): + with self.assertRaises(KeyError): + outer() + + def test_replaced(self): + class K: + def __abs__(self): + return 1 + + k = K() + out = [] + for i in range(2000): + out.append(abs(k)) + K.__abs__ = lambda self: 2 + for i in range(2000): + out.append(abs(k)) + self.assertEqual((out.count(1), out.count(2)), (2000, 2000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_accumulate_collected.py b/tests/regrtest/test_accumulate_collected.py new file mode 100644 index 000000000..9d1efe9a3 --- /dev/null +++ b/tests/regrtest/test_accumulate_collected.py @@ -0,0 +1,89 @@ +"""`list(accumulate(xs))` and `tuple(accumulate(xs))` over lists and tuples. + +Running totals of ints and floats, with and without `initial`, from the +start or after some were taken; a first item of any kind; totals past the +machine-int range (exact big ints); mixed kinds and objects with `__add__` +(summed as the general step sums them, in order); and an adapter that is +exhausted afterwards, its source too. +""" + +import itertools +import unittest +from itertools import accumulate + + +class Num: + adds = 0 + + def __init__(self, v): + self.v = v + + def __add__(self, other): + Num.adds += 1 + return Num(self.v + (other.v if isinstance(other, Num) else other)) + + +def manual(xs, initial=None): + out = [] + total = initial + if initial is not None: + out.append(initial) + for i, x in enumerate(xs): + total = x if total is None and not out else total + x + out.append(total) + return out + + +class AccumulateTests(unittest.TestCase): + def test_plain(self): + for xs in ([], [5], list(range(10)), [-3, 7, 0, 2**40], [1.5, 2.25, -0.5], + tuple(range(20))): + self.assertEqual(list(accumulate(xs)), manual(list(xs))) + self.assertEqual(tuple(accumulate(xs)), tuple(manual(list(xs)))) + self.assertEqual(list(accumulate(xs, initial=100)), manual(list(xs), 100)) + self.assertEqual(list(accumulate([], initial=7)), [7]) + + def test_partly_taken(self): + it = accumulate([1, 2, 3, 4, 5]) + self.assertEqual(next(it), 1) + self.assertEqual(next(it), 3) + self.assertEqual(list(it), [6, 10, 15]) + self.assertEqual(list(it), []) + it = accumulate([1, 2, 3], initial=10) + self.assertEqual(next(it), 10) + self.assertEqual(list(it), [11, 13, 16]) + + def test_big_and_mixed(self): + big = [2**62, 2**62, 2**62] + self.assertEqual(list(accumulate(big)), [2**62, 2**63, 3 * 2**62]) + self.assertEqual(list(accumulate([1, 2.5, 3])), [1, 3.5, 6.5]) + self.assertEqual(list(accumulate(["a", "b", "c"])), ["a", "ab", "abc"]) + self.assertEqual(list(accumulate([[1], [2]])), [[1], [1, 2]]) + Num.adds = 0 + got = list(accumulate([Num(1), Num(2), 3])) + self.assertEqual([n.v for n in got], [1, 3, 6]) + self.assertEqual(Num.adds, 2) + with self.assertRaises(TypeError): + list(accumulate([1, "x"])) + + def test_source_exhausted(self): + src = iter([1, 2, 3]) + acc = accumulate(src) + self.assertEqual(list(acc), [1, 3, 6]) + self.assertEqual(list(src), []) + self.assertEqual(list(acc), []) + + def test_with_func(self): + self.assertEqual(list(accumulate([1, 2, 3], max)), [1, 2, 3]) + self.assertEqual(list(accumulate([3, 1, 2], min)), [3, 1, 1]) + self.assertEqual(list(accumulate([1, 2, 3], lambda a, b: a * b, initial=2)), [2, 2, 4, 12]) + + def test_many(self): + xs = list(range(100)) + want = manual(xs) + for _ in range(500): + self.assertEqual(list(accumulate(xs)), want) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_accumulate_pure_callbacks.py b/tests/regrtest/test_accumulate_pure_callbacks.py new file mode 100644 index 000000000..019af650e --- /dev/null +++ b/tests/regrtest/test_accumulate_pure_callbacks.py @@ -0,0 +1,121 @@ +"""`itertools.accumulate(xs, func)` with a callback that runs no Python +frame (`operator.add`, `max`, a small lambda): the in-place step matches +the general one for ints, floats and strs, with an initial value, at the +end, when the callback raises, for totals that aren't plain scalars and +for sources and callbacks only the general step can take.""" + +import itertools +import operator +import unittest +from fractions import Fraction +from itertools import accumulate + +N = 200 + + +def loop(it): + out = [] + for x in it: + out.append(x) + return out + + +class AccumulateCallbackTests(unittest.TestCase): + def test_operator_callbacks(self): + xs = [3, 1, 4, 1, 5, 9, 2, 6] + for _ in range(N): + self.assertEqual(list(accumulate(xs, operator.add)), [3, 4, 8, 9, 14, 23, 25, 31]) + self.assertEqual(loop(accumulate(xs, operator.mul)), [3, 3, 12, 12, 60, 540, 1080, 6480]) + self.assertEqual(list(accumulate(xs, max)), [3, 3, 4, 4, 5, 9, 9, 9]) + self.assertEqual(loop(accumulate(xs, min)), [3, 1, 1, 1, 1, 1, 1, 1]) + self.assertEqual(list(accumulate(xs, operator.sub)), [3, 2, -2, -3, -8, -17, -19, -25]) + self.assertEqual(list(accumulate(xs, operator.xor))[-1], 3 ^ 1 ^ 4 ^ 1 ^ 5 ^ 9 ^ 2 ^ 6) + + def test_lambdas(self): + xs = [1.5, 2.0, 0.5] + for _ in range(N): + self.assertEqual(list(accumulate(xs, lambda a, b: a + b)), [1.5, 3.5, 4.0]) + self.assertEqual(loop(accumulate(xs, lambda a, b: a * b)), [1.5, 3.0, 1.5]) + self.assertEqual(list(accumulate("abc", lambda a, b: a + b)), ["a", "ab", "abc"]) + self.assertEqual(list(accumulate([1, 2, 3], lambda a, b: b)), [1, 2, 3]) + k = 10 + self.assertEqual(list(accumulate([1, 2, 3], lambda a, b: a + b + k)), [1, 13, 26]) + + def test_initial_and_empty(self): + for _ in range(N): + self.assertEqual(list(accumulate([1, 2], operator.add, initial=10)), [10, 11, 13]) + self.assertEqual(list(accumulate([], operator.add, initial=7)), [7]) + self.assertEqual(list(accumulate([], operator.add)), []) + self.assertEqual(list(accumulate([5], operator.add)), [5]) + # (`initial=None` is no initial value.) + self.assertEqual(list(accumulate((), max, initial=None)), []) + self.assertEqual(list(accumulate([2, 1], max, initial=None)), [2, 2]) + + def test_big_ints_and_mixed(self): + big = 2**62 + for _ in range(N): + self.assertEqual(list(accumulate([big, big, big], operator.add)), [big, 2 * big, 3 * big]) + self.assertEqual(list(accumulate([1, 2.5, 3], operator.add)), [1, 3.5, 6.5]) + self.assertEqual(list(accumulate([True, True, 2], operator.add)), [True, 2, 4]) + self.assertEqual( + list(accumulate([Fraction(1, 2), Fraction(1, 3)], operator.add)), + [Fraction(1, 2), Fraction(5, 6)], + ) + + def test_totals_that_are_containers(self): + for _ in range(N): + rows = [[1], [2], [3]] + got = list(accumulate(rows, operator.add)) + self.assertEqual(got, [[1], [1, 2], [1, 2, 3]]) + self.assertIs(got[0], rows[0]) + self.assertEqual(list(accumulate([(1,), (2,)], operator.add)), [(1,), (1, 2)]) + sets = [{1}, {2}, {1, 3}] + self.assertEqual(list(accumulate(sets, operator.or_))[-1], {1, 2, 3}) + + def test_callback_raises_midway(self): + for _ in range(20): + it = accumulate([1, 2, "x", 4], operator.add) + self.assertEqual(next(it), 1) + self.assertEqual(next(it), 3) + with self.assertRaises(TypeError): + next(it) + it = accumulate([4, 2, 0, 1], operator.floordiv) + self.assertEqual([next(it), next(it)], [4, 2]) + with self.assertRaises(ZeroDivisionError): + next(it) + + def test_python_callbacks_and_generator_sources(self): + calls = [] + + def add(a, b): + calls.append((a, b)) + return a + b + + self.assertEqual(list(accumulate([1, 2, 3], add)), [1, 3, 6]) + self.assertEqual(calls, [(1, 2), (3, 3)]) + self.assertEqual(list(accumulate((x for x in [1, 2, 3]), operator.add)), [1, 3, 6]) + self.assertEqual(list(accumulate(map(int, "123"), operator.mul)), [1, 2, 6]) + self.assertEqual(list(accumulate(iter({"a": 1, "b": 2}), operator.add)), ["a", "ab"]) + + def test_interleaved_with_source_mutation(self): + xs = [1, 2, 3] + it = accumulate(xs, operator.add) + self.assertEqual(next(it), 1) + xs.append(10) + self.assertEqual(list(it), [3, 6, 16]) + self.assertEqual(next(it, "done"), "done") + + def test_running_total_of_instances(self): + class V: + def __init__(self, n): + self.n = n + + def __add__(self, other): + return V(self.n + other.n) + + got = list(accumulate([V(1), V(2), V(3)], operator.add)) + self.assertEqual([v.n for v in got], [1, 3, 6]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_adapter_cursor_ends.py b/tests/regrtest/test_adapter_cursor_ends.py new file mode 100644 index 000000000..e5f38b508 --- /dev/null +++ b/tests/regrtest/test_adapter_cursor_ends.py @@ -0,0 +1,177 @@ +"""The ends of `map`, `filter`, `starmap` and `groupby` over plain cursors. + +When the one source is a list's, tuple's, `str`'s, `bytes`' or range's +cursor at its end, and letting go of its sequence runs nothing, the +adapter's step reports the end natively. Each case runs hot and must +agree with CPython: the items, a source list that grows after the end +(an exhausted list iterator sees no later appends), adapters stepped again +after their end, sources holding records, sources whose items have +finalizers, and `sum` over arrays. +""" + +import array +import itertools +import operator +import unittest + +N = 500 + +deaths = [] + + +class Loud: + def __init__(self, k): + self.k = k + + def __del__(self): + deaths.append(self.k) + + +class AdapterCursorEndsTests(unittest.TestCase): + def test_map_filter_starmap_items(self): + pairs = [(1, 2), (3, 4), (5, 6)] + + def run(): + out = None + for _ in range(N): + out = ( + list(map(abs, [-1, 2, -3])), + list(filter(None, (0, 1, "", "x"))), + list(itertools.starmap(operator.mul, pairs)), + list(itertools.starmap(operator.add, [(1, 2), (3, 4)])), + list(map(str.upper, "abc")), + list(filter(lambda b: b > 1, b"\x00\x01\x02\x03")), + list(map(operator.neg, range(3))), + ) + return out + + self.assertEqual( + run(), + ([1, 2, 3], [1, "x"], [2, 12, 30], [3, 7], ["A", "B", "C"], [2, 3], [0, -1, -2]), + ) + + def test_exhausted_list_sees_no_appends(self): + def run(): + out = None + for _ in range(N): + xs = [(1, 2), (3, 4)] + m = itertools.starmap(operator.add, xs) + first = list(m) + xs.append((5, 6)) + f_src = [1, 0, 2] + f = filter(None, f_src) + ffirst = list(f) + f_src.append(3) + out = (first, list(m), next(m, "end"), ffirst, list(f)) + return out + + self.assertEqual(run(), ([3, 7], [], "end", [1, 2], [])) + + def test_groupby_ends(self): + def run(): + out = None + for _ in range(N): + out = [] + for k, g in itertools.groupby("aabbbc"): + out.append((k, list(g))) + out.append([(k, len(list(g))) for k, g in itertools.groupby((1, 1, 2))]) + out.append([k for k, _ in itertools.groupby(b"xxyz")]) + out.append([k for k, _ in itertools.groupby([])]) + return out + + self.assertEqual( + run(), + [ + ("a", ["a", "a"]), + ("b", ["b", "b", "b"]), + ("c", ["c"]), + [(1, 2), (2, 1)], + [120, 121, 122], + [], + ], + ) + + def test_groupby_grouper_after_end(self): + def run(): + out = None + for _ in range(N): + gb = itertools.groupby("aab") + k1, g1 = next(gb) + k2, g2 = next(gb) + out = (k1, list(g1), k2, list(g2), next(gb, "end"), list(g2), next(gb, "end")) + return out + + self.assertEqual(run(), ("a", [], "b", ["b"], "end", [], "end")) + + def test_loud_items_die_when_cpython_frees_them(self): + def run(): + seen = [] + for i in range(N): + del deaths[:] + xs = [Loud(1), Loud(2)] + m = map(operator.attrgetter("k"), xs) + del xs + seen = list(m) + after_end = list(deaths) + del m + seen.append(after_end) + seen.append(sorted(deaths)) + return seen + + self.assertEqual(run(), [1, 2, [2, 1], [1, 2]]) + + def test_records_with_loud_fields(self): + def run(): + out = None + for _ in range(N): + del deaths[:] + rows = [(Loud(1), 2), (Loud(3), 4)] + m = itertools.starmap(lambda a, b: a.k + b, rows) + del rows + out = (list(m), sorted(deaths)) + return out + + self.assertEqual(run(), ([3, 7], [1, 3])) + + def test_array_sum(self): + cases = [ + array.array("i", range(20)), + array.array("b", [-5, 3, 7]), + array.array("H", [65535, 1]), + array.array("q", [2**62, 2**62]), + array.array("Q", [2**63, 1]), + array.array("d", [0.1] * 10), + array.array("f", [0.5, 0.25]), + ] + + def run(): + out = None + for _ in range(N): + out = [sum(a) for a in cases] + out.append(sum(cases[0], 100)) + out.append(sum(cases[1], 0.5)) + out.append(sum(array.array("i"))) + return out + + expected = [sum(list(a)) for a in cases] + expected += [sum(range(20)) + 100, 5.5, 0] + self.assertEqual(run(), expected) + + def test_array_subclass_sum(self): + class A(array.array): + def __iter__(self): + return iter([1, 2, 3]) + + a = A("i", [10, 20]) + + def run(): + out = None + for _ in range(N): + out = sum(a) + return out + + self.assertEqual(run(), 6) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_any_all_map_native.py b/tests/regrtest/test_any_all_map_native.py new file mode 100644 index 000000000..9e543206c --- /dev/null +++ b/tests/regrtest/test_any_all_map_native.py @@ -0,0 +1,109 @@ +"""`any` and `all` over `map` and `filter` adapters that step natively: +the answer and how far the source was consumed match the general loop +when an item decides early, at the end, when the callback's result needs +the full truth test (`__bool__`, `__len__`), when the callback raises, +and when a shared iterator is consumed by both; also `str.split` with a +one-byte separator into any number of fields, and `str.isupper` / +`str.islower` on ASCII and other text.""" + +import unittest + +N = 2000 + + +class Truthy: + def __init__(self, v): + self.v = v + + def __bool__(self): + return self.v + + +class Sized: + def __init__(self, n): + self.n = n + + def __len__(self): + return self.n + + +class AnyAllMapNativeTests(unittest.TestCase): + def test_answers(self): + words = "the quick Brown fox".split() + for _ in range(N): + self.assertTrue(any(map(str.istitle, words))) + self.assertFalse(any(map(str.isupper, words))) + self.assertFalse(all(map(str.islower, words))) + self.assertTrue(all(map(str.isalpha, words))) + self.assertFalse(any(map(str.isupper, []))) + self.assertTrue(all(map(str.isupper, ()))) + + def test_consumption_stops_at_decider(self): + for _ in range(N // 10): + it = iter(["a", "B", "c", "D"]) + self.assertTrue(any(map(str.isupper, it))) + self.assertEqual(next(it), "c") + it = iter(["a", "b", "C", "d"]) + self.assertFalse(all(map(str.islower, it))) + self.assertEqual(list(it), ["d"]) + + def test_shared_map(self): + m = map(str.isupper, ["a", "B", "c", "D", "e"]) + self.assertTrue(any(m)) + self.assertEqual(list(m), [False, True, False]) + + def test_full_truth_results(self): + for _ in range(N // 10): + self.assertTrue(any(map(Truthy, [False, False, True]))) + self.assertFalse(all(map(Truthy, [True, False]))) + self.assertTrue(any(map(Sized, [0, 0, 3]))) + self.assertFalse(any(map(Sized, [0, 0]))) + self.assertTrue(any(map(len, ["", "", "x"]))) + self.assertTrue(any(map(abs, [0, -2]))) + self.assertFalse(any(map(float, ["0", "0.0"]))) + self.assertTrue(any(map(tuple, [[], [1]]))) + + def test_raises(self): + with self.assertRaises(TypeError): + any(map(str.isupper, ["a", 1])) + with self.assertRaises(ValueError): + any(map(int, ["0", "x"])) + it = iter(["a", 1, "B"]) + with self.assertRaises(TypeError): + any(map(str.isupper, it)) + self.assertEqual(list(it), ["B"]) + + def test_filter_sources(self): + for _ in range(N // 10): + self.assertTrue(any(filter(None, [0, 0, 5]))) + self.assertFalse(any(filter(None, [0, "", None]))) + self.assertTrue(all(filter(None, [0, 1, 2]))) + + def test_case_predicates(self): + cases = ["", "ABC", "AbC", "abc", "A1!", "1!", "a1", "ÀB", "àb", "Dž", "Σς", "ABÇ"] + for _ in range(N // 10): + self.assertEqual( + [s.isupper() for s in cases], + [False, True, False, False, True, False, False, True, False, False, False, True], + ) + self.assertEqual( + [s.islower() for s in cases], + [False, False, False, True, False, False, True, False, True, False, False, False], + ) + with self.assertRaises(TypeError) as cm: + "a".isupper(1) + self.assertEqual(str(cm.exception), "str.isupper() takes no arguments (1 given)") + + def test_split_one_byte(self): + for _ in range(N): + self.assertEqual("a,b,c".split(","), ["a", "b", "c"]) + self.assertEqual("".split(","), [""]) + self.assertEqual(",".split(","), ["", ""]) + self.assertEqual("a,b,c,d,e,f,g".split(","), list("abcdefg")) + self.assertEqual("a,b,c,d".split(",", 2), ["a", "b", "c,d"]) + self.assertEqual("a, b, c".split(", "), ["a", "b", "c"]) + self.assertEqual("é,ü".split(","), ["é", "ü"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_array_construction_compiled.py b/tests/regrtest/test_array_construction_compiled.py new file mode 100644 index 000000000..3f7cf939b --- /dev/null +++ b/tests/regrtest/test_array_construction_compiled.py @@ -0,0 +1,91 @@ +"""array.array(typecode) and array.array(typecode, list) from compiled +loops, for every numeric typecode: typecode, itemsize, contents, bounds +checks, and the arrays behaving as ones built by the general path +(appends, slices, equality, pickling), with what the native constructor +declines (an out-of-range or non-number item, another initializer, 'u' +and 'w', a bad typecode, a subclass, keywords) still taking the general +path, each matching CPython.""" + +import array +import pickle +import unittest +import warnings + + +class Sub(array.array): + pass + + +def build(n, code, items=None): + out = None + for i in range(n): + out = array.array(code) if items is None else array.array(code, items) + return out + + +class ArrayConstructionTests(unittest.TestCase): + def test_typecodes(self): + for code in "bBhHiIlLqQfd": + for n in (1, 400): + a = build(n, code) + self.assertEqual((a.typecode, len(a)), (code, 0)) + self.assertEqual(a.itemsize, array.array(code).itemsize) + items = [1.5, 2.0] if code in "fd" else [1, 2, 3] + b = build(n, code, items) + self.assertEqual(b.tolist(), items) + b.append(items[0]) + self.assertEqual(b[-1], items[0]) + self.assertEqual(b[1:], array.array(code, items[1:] + items[:1])) + self.assertEqual(pickle.loads(pickle.dumps(b)), b) + + def test_bounds(self): + for n in (1, 400): + self.assertEqual(build(n, "b", [-128, 127]).tolist(), [-128, 127]) + self.assertEqual(build(n, "Q", [2**64 - 1]).tolist(), [2**64 - 1]) + self.assertEqual(build(n, "q", [-(2**63)]).tolist(), [-(2**63)]) + a = build(n, "B") + with self.assertRaises(OverflowError): + a.append(256) + with self.assertRaises(OverflowError): + build(n, "H").append(-1) + with self.assertRaises(OverflowError): + build(n, "Q").append(2**64) + with self.assertRaises(OverflowError): + build(300, "b", [128]) + with self.assertRaises(TypeError): + build(300, "i", [1, "x"]) + with self.assertRaises(ValueError): + build(300, "z") + with self.assertRaises(TypeError): + build(300, "ii") + + def test_other_initializers(self): + for n in (1, 400): + self.assertEqual(build(n, "i", (1, 2)).tolist(), [1, 2]) + self.assertEqual(build(n, "i", range(3)).tolist(), [0, 1, 2]) + self.assertEqual(build(n, "B", b"ab").tolist(), [97, 98]) + self.assertEqual(build(n, "d", [1, 2]).tolist(), [1.0, 2.0]) + self.assertEqual(build(n, "w", "hi").tolist(), ["h", "i"]) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + build(3, "u") + self.assertEqual(len(caught), 3) + + def test_subclass_and_keywords(self): + def subs(n): + out = None + for i in range(n): + out = Sub("i", [1]) + return out + + for n in (1, 400): + s = subs(n) + self.assertIs(type(s), Sub) + self.assertEqual(s.tolist(), [1]) + with self.assertRaises(TypeError): + for i in range(300): + array.array("i", initializer=[1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_array_items_read_and_written_in_place.py b/tests/regrtest/test_array_items_read_and_written_in_place.py new file mode 100644 index 000000000..036fe9925 --- /dev/null +++ b/tests/regrtest/test_array_items_read_and_written_in_place.py @@ -0,0 +1,378 @@ +"""Reading, writing and appending an array's items. + +`a[i]`, `a[i] = v`, `a.append(v)`, `len(a)`, iteration and plain slices +work on the array's packed bytes directly. Each costs the same whether +the array holds a few items or a million, gives the item its typecode +describes, and refuses what CPython's array refuses: a value of the +wrong type, an int out of the item's range, an index out of range, a +resize while a view of the array is exported. +""" + +import array +import copy +import pickle +import time +import unittest +import weakref + +INT_CODES = "bBhHiIlLqQ" + + +def limits(code): + bits = 8 * array.array(code).itemsize + if code.islower(): + return -(1 << (bits - 1)), (1 << (bits - 1)) - 1 + return 0, (1 << bits) - 1 + + +class ItemTests(unittest.TestCase): + def test_every_int_typecode_round_trips_its_range(self): + for code in INT_CODES: + lo, hi = limits(code) + values = [lo, lo + 1, -1 if lo else 0, 0, 1, hi - 1, hi] + with self.subTest(code=code): + a = array.array(code, values) + self.assertEqual(len(a), len(values)) + self.assertEqual([a[i] for i in range(len(a))], values) + self.assertEqual([a[i - len(a)] for i in range(len(a))], values) + self.assertEqual(list(a), values) + self.assertEqual(a.tolist(), values) + for i, v in enumerate(reversed(values)): + a[i] = v + self.assertEqual(a.tolist(), values[::-1]) + b = array.array(code) + for v in values: + b.append(v) + self.assertEqual(b.tolist(), values) + self.assertTrue(all(type(x) is int for x in b)) + + def test_out_of_range_ints_are_refused(self): + for code in INT_CODES: + lo, hi = limits(code) + with self.subTest(code=code): + a = array.array(code, [0, 0]) + for bad in (lo - 1, hi + 1, lo - 2**70, hi + 2**70): + with self.assertRaises(OverflowError): + a[0] = bad + with self.assertRaises(OverflowError): + a.append(bad) + with self.assertRaises(OverflowError): + array.array(code, [0, bad]) + self.assertEqual(a.tolist(), [0, 0]) + + def test_wrong_types_are_refused(self): + a = array.array("i", [1, 2, 3]) + for bad in (1.5, "1", None, [1], 2 + 0j): + with self.subTest(bad=bad): + with self.assertRaises(TypeError): + a[0] = bad + with self.assertRaises(TypeError): + a.append(bad) + self.assertEqual(a.tolist(), [1, 2, 3]) + d = array.array("d", [1.0]) + for bad in ("1", None, [1.0], 1j): + with self.subTest(bad=bad): + with self.assertRaises(TypeError): + d[0] = bad + with self.assertRaises(TypeError): + d.append(bad) + self.assertEqual(d.tolist(), [1.0]) + + def test_values_that_convert(self): + class Index: + def __index__(self): + return 7 + + class Real: + def __float__(self): + return 2.5 + + a = array.array("i", [0, 0]) + a[0] = True + a[1] = Index() + a.append(Index()) + self.assertEqual(a.tolist(), [1, 7, 7]) + self.assertIs(type(a[0]), int) + d = array.array("d", [0.0, 0.0]) + d[0] = 3 + d[1] = Real() + d.append(True) + d.append(Real()) + self.assertEqual(d.tolist(), [3.0, 2.5, 1.0, 2.5]) + self.assertTrue(all(type(x) is float for x in d)) + + def test_floats(self): + d = array.array("d", [0.5, -1.25]) + d[0] = 1e300 + d.append(float("inf")) + d.append(float("-inf")) + self.assertEqual(d.tolist()[:2], [1e300, -1.25]) + self.assertEqual(d[2], float("inf")) + self.assertEqual(d[-1], float("-inf")) + nan = array.array("d", [float("nan")]) + self.assertNotEqual(nan[0], nan[0]) + f = array.array("f", [1.5, 0.1]) + self.assertEqual(f[0], 1.5) + self.assertAlmostEqual(f[1], 0.1, places=6) + self.assertNotEqual(f[1], 0.1) + f[0] = 2.25 + f.append(-0.0) + self.assertEqual(f[0], 2.25) + self.assertEqual(str(f[-1]), "-0.0") + + def test_large_unsigned_values(self): + q = array.array("Q", [2**64 - 1, 2**63, 2**63 - 1, 0]) + self.assertEqual([q[i] for i in range(4)], [2**64 - 1, 2**63, 2**63 - 1, 0]) + self.assertEqual(list(q), [2**64 - 1, 2**63, 2**63 - 1, 0]) + q[3] = 2**64 - 2 + q.append(2**63 + 5) + self.assertEqual(q[3], 2**64 - 2) + self.assertEqual(q[-1], 2**63 + 5) + self.assertEqual(sum(q), (2**64 - 1) + 2**63 + (2**63 - 1) + (2**64 - 2) + 2**63 + 5) + + def test_unicode_arrays(self): + u = array.array("w", "héllo\U0001f600") + self.assertEqual(u[1], "é") + self.assertEqual(u[-1], "\U0001f600") + self.assertEqual(list(u), list("héllo\U0001f600")) + u[0] = "J" + u.append("!") + self.assertEqual(u.tounicode(), "Jéllo\U0001f600!") + self.assertEqual(u[1:3].tounicode(), "él") + with self.assertRaises(TypeError): + u[0] = 65 + with self.assertRaises(TypeError): + u.append("ab") + + def test_index_errors(self): + a = array.array("i", [1, 2, 3]) + for bad in (3, -4, 10**9, -(10**9)): + with self.subTest(bad=bad): + with self.assertRaises(IndexError): + a[bad] + with self.assertRaises(IndexError): + a[bad] = 0 + with self.assertRaises(TypeError): + a["0"] + with self.assertRaises(TypeError): + a[1.0] + self.assertEqual(a[True], 2) + empty = array.array("i") + with self.assertRaises(IndexError): + empty[0] + with self.assertRaises(IndexError): + empty[-1] + self.assertEqual(len(empty), 0) + + +class SliceTests(unittest.TestCase): + def test_slices_match_a_list(self): + values = list(range(40)) + a = array.array("h", values) + for lo in (None, 0, 3, 17, 39, 40, 100, -1, -5, -40, -100): + for hi in (None, 0, 3, 17, 39, 40, 100, -1, -5, -40, -100): + for step in (None, 1, 2, -1, -3): + with self.subTest(lo=lo, hi=hi, step=step): + got = a[lo:hi:step] + self.assertIs(type(got), array.array) + self.assertEqual(got.typecode, "h") + self.assertEqual(got.tolist(), values[lo:hi:step]) + + def test_a_slice_is_a_copy(self): + a = array.array("i", range(10)) + b = a[2:5] + b[0] = -1 + b.append(99) + self.assertEqual(a.tolist(), list(range(10))) + self.assertEqual(b.tolist(), [-1, 3, 4, 99]) + self.assertEqual(b.itemsize, a.itemsize) + self.assertEqual(len(b), 4) + self.assertEqual(copy.copy(b), b) + self.assertEqual(pickle.loads(pickle.dumps(b)), b) + ref = weakref.ref(b) + self.assertIs(ref(), b) + self.assertEqual(sum(b), 105) + self.assertEqual(b + b, array.array("i", [-1, 3, 4, 99] * 2)) + + def test_slice_stores_from_another_array(self): + base = list(range(10)) + for lo, hi in [(2, 5), (0, 0), (10, 10), (5, 2), (-3, None), (None, 4), (0, 10)]: + for rep in ([], [70], [70, 80, 90], list(range(100, 120))): + with self.subTest(lo=lo, hi=hi, rep=rep): + a = array.array("i", base) + want = list(base) + a[lo:hi] = array.array("i", rep) + want[lo:hi] = rep + self.assertEqual(a.tolist(), want) + a = array.array("i", base) + a[1:3] = a + want = list(base) + want[1:3] = base + self.assertEqual(a.tolist(), want) + with self.assertRaises(TypeError): + a[0:1] = array.array("d", [1.0]) + + def test_subclass_instances(self): + class Samples(array.array): + def total(self): + return sum(self) + + s = Samples("d", [1.5, 2.5, 3.5]) + self.assertEqual(s[0], 1.5) + self.assertEqual(s[-1], 3.5) + s[1] = 10.0 + s.append(4.0) + self.assertEqual(len(s), 4) + self.assertEqual(s.total(), 19.0) + self.assertEqual(list(s), [1.5, 10.0, 3.5, 4.0]) + self.assertIs(type(s[1:]), array.array) + self.assertEqual(s[1:].tolist(), [10.0, 3.5, 4.0]) + + class Doubling(array.array): + def __getitem__(self, i): + return 2 * array.array.__getitem__(self, i) + + def __len__(self): + return 1 + + d = Doubling("i", [1, 2, 3]) + self.assertEqual(d[0], 2) + self.assertEqual(d[2], 6) + self.assertEqual(len(d), 1) + self.assertEqual(array.array.__len__(d), 3) + self.assertEqual(list(d), [1, 2, 3]) + + +class IteratorTests(unittest.TestCase): + def test_iteration_sees_later_appends(self): + a = array.array("i", [1, 2, 3]) + it = iter(a) + self.assertEqual(next(it), 1) + a.append(4) + self.assertEqual(list(it), [2, 3, 4]) + # Once finished, an iterator stays finished. + a.append(5) + self.assertEqual(list(it), []) + with self.assertRaises(StopIteration): + next(it) + + def test_iteration_over_a_shrinking_array(self): + a = array.array("i", range(10)) + seen = [] + for x in a: + seen.append(x) + if x == 3: + del a[5:] + self.assertEqual(seen, [0, 1, 2, 3, 4]) + + def test_loops(self): + a = array.array("l", range(5000)) + total = 0 + for x in a: + total += x + self.assertEqual(total, 12497500) + self.assertEqual(sum(a), 12497500) + self.assertEqual(max(a), 4999) + self.assertEqual([x for x in a if x % 1000 == 0], [0, 1000, 2000, 3000, 4000]) + self.assertEqual(sum(a[i] for i in range(0, 5000, 7)), sum(range(0, 5000, 7))) + self.assertIn(4999, a) + self.assertNotIn(5000, a) + self.assertEqual(a.index(4321), 4321) + self.assertEqual(a.count(17), 1) + self.assertEqual(list(reversed(a))[:3], [4999, 4998, 4997]) + + +class ExportTests(unittest.TestCase): + def test_a_view_blocks_resizes_and_sees_writes(self): + a = array.array("i", [1, 2, 3]) + view = memoryview(a) + with self.assertRaises(BufferError): + a.append(4) + with self.assertRaises(BufferError): + a[0:1] = array.array("i", [7, 8]) + with self.assertRaises(BufferError): + del a[0] + a[0] = 42 + a[1:3] = array.array("i", [5, 6]) + self.assertEqual(view.tolist(), [42, 5, 6]) + view[2] = -1 + self.assertEqual(a[2], -1) + view.release() + a.append(4) + self.assertEqual(a.tolist(), [42, 5, -1, 4]) + + def test_bytes_round_trip(self): + a = array.array("H", [1, 2, 0xFFFF]) + raw = a.tobytes() + self.assertEqual(len(raw), 6) + b = array.array("H") + b.frombytes(raw) + self.assertEqual(a, b) + self.assertEqual(bytes(a), raw) + self.assertEqual(bytes(memoryview(a)), raw) + + +class CostTests(unittest.TestCase): + """An item costs the same in a large array as in a small one.""" + + @staticmethod + def best(fn, repeat=5): + best = float("inf") + for _ in range(repeat): + start = time.perf_counter() + fn() + best = min(best, time.perf_counter() - start) + return best + + def check(self, work): + small = array.array("i", range(1_000)) + large = array.array("i", range(1_000_000)) + t_small = self.best(lambda: work(small)) + t_large = self.best(lambda: work(large)) + # (A copy of the buffer per item made the large array a thousand + # times the small one's cost.) + self.assertLess(t_large, t_small * 25 + 0.01) + + def test_reads(self): + def work(a): + total = 0 + for i in range(600): + total += a[i] + a[-1 - i] + return total + + self.check(work) + + def test_writes(self): + def work(a): + for i in range(600): + a[i] = i + a[-1 - i] = -i + + self.check(work) + + def test_slices(self): + def work(a): + total = 0 + for i in range(300): + total += len(a[i:i + 8]) + a[i:i + 2] = a[i + 2:i + 4] + return total + + self.check(work) + + def test_appends_and_iteration_prefix(self): + def work(a): + for i in range(300): + a.append(i) + it = iter(a) + total = 0 + for _ in range(300): + total += next(it) + del a[len(a) - 300:] + return total + + self.check(work) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_array_loops_namespace_probes_subclass_arith.py b/tests/regrtest/test_array_loops_namespace_probes_subclass_arith.py new file mode 100644 index 000000000..f5b04e3f2 --- /dev/null +++ b/tests/regrtest/test_array_loops_namespace_probes_subclass_arith.py @@ -0,0 +1,513 @@ +"""`for x in array` and `array.tolist()` read items off the buffer, +`hasattr`/`getattr` on a `SimpleNamespace` answer from its dictionary, +a namespace store on a global runs in compiled code, `list` and `tuple` +subclasses concatenate and repeat as their payloads, a set subclass +built from a set copies its table, and the default reduction of an +instance with `__slots__` is built natively. Each matches the general +path, and overrides stay in charge.""" + +import array +import copy +import copyreg +import pickle +import types +import unittest + +N = 300 + + +class L(list): + pass + + +class T(tuple): + pass + + +class S(set): + pass + + +class LoudAdd(list): + def __add__(self, other): + return "added" + + def __mul__(self, n): + return "times" + + def __rmul__(self, n): + return "rtimes" + + +class RightAdd(list): + def __radd__(self, other): + return "right" + + +class LoudIter(set): + def __iter__(self): + return iter([99]) + + +class Odd: + def __init__(self, v): + self.v = v + + def __hash__(self): + return 1 + + def __eq__(self, other): + return isinstance(other, Odd) and self.v == other.v + + +CFG = types.SimpleNamespace(a=1) + + +class ArrayLoops(unittest.TestCase): + def test_for_loop_matches_indexing(self): + for code in "bBhHiIlLqQfd": + a = array.array(code, range(20)) + for _ in range(N): + got = [] + for x in a: + got.append(x) + self.assertEqual(got, [a[i] for i in range(len(a))]) + self.assertEqual({type(x) for x in got}, {type(a[0])}) + + def test_empty_and_unicode(self): + for _ in range(N): + for x in array.array("i"): + self.fail("no items") + u = array.array("w", "héllo") + for _ in range(N): + got = [c for c in u] + self.assertEqual(got, list("héllo")) + self.assertEqual(u.tolist(), list("héllo")) + + def test_items_appended_during_the_loop_are_reached(self): + for _ in range(N): + a = array.array("i", [1, 2, 3]) + seen = [] + for x in a: + seen.append(x) + if len(a) < 6: + a.append(x * 10) + self.assertEqual(seen, [1, 2, 3, 10, 20, 30]) + + def test_items_removed_during_the_loop(self): + for _ in range(N): + a = array.array("i", range(10)) + seen = [] + for x in a: + seen.append(x) + if x == 3: + del a[5:] + self.assertEqual(seen, [0, 1, 2, 3, 4]) + + def test_shared_iterator_stays_exhausted(self): + for _ in range(N): + a = array.array("d", [1.5, 2.5]) + it = iter(a) + total = 0.0 + for x in it: + total += x + a.append(9.0) + self.assertEqual(list(it), []) + self.assertEqual(total, 4.0) + + def test_big_unsigned_items(self): + a = array.array("Q", [1, 2**64 - 1, 3]) + for _ in range(N): + got = [x for x in a] + self.assertEqual(got, [1, 2**64 - 1, 3]) + self.assertEqual(a.tolist(), [1, 2**64 - 1, 3]) + + def test_break_and_nested(self): + a = array.array("h", range(8)) + for _ in range(N): + pairs = 0 + for x in a: + if x == 5: + break + for y in a: + pairs += x < y + self.assertEqual(pairs, 7 + 6 + 5 + 4 + 3) + + def test_subclass_iter_override(self): + class Twice(array.array): + def __iter__(self): + for i in range(len(self)): + yield self[i] * 2 + + a = Twice("i", [1, 2, 3]) + for _ in range(N): + got = [x for x in a] + self.assertEqual(got, [2, 4, 6]) + + def test_tolist(self): + for code in "bBhHiIlLqQfd": + a = array.array(code, range(12)) + for _ in range(N): + got = a.tolist() + self.assertIs(type(got), list) + self.assertEqual(got, [a[i] for i in range(12)]) + self.assertEqual(array.array("i").tolist(), []) + with self.assertRaises(TypeError): + array.array("i").tolist(1) + + def test_iterator_type_and_pickle_state(self): + a = array.array("i", [4, 5, 6]) + it = iter(a) + next(it) + fn, args, state = it.__reduce__() + self.assertIs(fn, iter) + self.assertEqual(state, 1) + loop_types = set() + for _ in range(N): + for x in a: + loop_types.add(type(x)) + self.assertEqual(loop_types, {int}) + + +class NamespaceProbes(unittest.TestCase): + def test_hasattr(self): + ns = types.SimpleNamespace(a=1, _p=2) + hits = misses = 0 + for _ in range(N): + hits += hasattr(ns, "a") + hasattr(ns, "_p") + misses += hasattr(ns, "z") + hasattr(ns, "_q") + self.assertEqual((hits, misses), (2 * N, 0)) + for _ in range(N): + self.assertTrue(hasattr(ns, "__dict__")) + self.assertTrue(hasattr(ns, "__eq__")) + self.assertTrue(hasattr(ns, "__replace__")) + + def test_getattr_default(self): + ns = types.SimpleNamespace(a=1) + for _ in range(N): + self.assertEqual(getattr(ns, "a", None), 1) + self.assertIsNone(getattr(ns, "z", None)) + self.assertEqual(getattr(ns, "zz", 7), 7) + with self.assertRaises(AttributeError): + getattr(ns, "z") + + def test_added_and_removed_names(self): + ns = types.SimpleNamespace() + for i in range(N): + self.assertFalse(hasattr(ns, "k")) + ns.k = i + self.assertTrue(hasattr(ns, "k")) + del ns.k + + def test_generic_alias_reads_through_its_origin(self): + alias = list[int] + for _ in range(N): + self.assertTrue(hasattr(alias, "append")) + self.assertFalse(hasattr(alias, "no_such_name")) + self.assertIsNone(getattr(int | str, "no_such_name", None)) + + def test_store_on_a_global(self): + for i in range(N): + CFG.b = i + CFG.c = [i] + self.assertEqual((CFG.a, CFG.b, CFG.c), (1, N - 1, [N - 1])) + self.assertEqual(vars(CFG), {"a": 1, "b": N - 1, "c": [N - 1]}) + + def test_store_on_an_attribute_value(self): + class Holder: + pass + + h = Holder() + h.ns = types.SimpleNamespace() + for i in range(N): + h.ns.count = i + h.ns.label = "x%d" % i + self.assertEqual((h.ns.count, h.ns.label), (N - 1, "x%d" % (N - 1))) + + def test_store_releases_the_old_value(self): + import weakref + + class Node: + pass + + ns = types.SimpleNamespace() + refs = [] + for _ in range(50): + n = Node() + refs.append(weakref.ref(n)) + CFG.node = n + ns.node = n + del n + import gc + + gc.collect() + self.assertEqual(sum(r() is not None for r in refs), 1) + del CFG.node + + +class SubclassArithmetic(unittest.TestCase): + def test_list_subclass(self): + a, b = L([1, 2]), L([3]) + for _ in range(N): + r1, r2, r3, r4, r5, r6 = a + b, a + [9], [9] + a, a * 2, 2 * a, a * 0 + self.assertEqual((r1, r2, r3), ([1, 2, 3], [1, 2, 9], [9, 1, 2])) + self.assertEqual((r4, r5, r6), ([1, 2, 1, 2], [1, 2, 1, 2], [])) + for r in (r1, r2, r3, r4, r5, r6): + self.assertIs(type(r), list) + self.assertEqual((a, b), ([1, 2], [3])) + self.assertIsNot(a + L(), a) + + def test_tuple_subclass(self): + a, b = T((1, 2)), T((3,)) + for _ in range(N): + r1, r2, r3, r4, r5 = a + b, a + (9,), (9,) + a, a * 2, 2 * a + self.assertEqual((r1, r2, r3), ((1, 2, 3), (1, 2, 9), (9, 1, 2))) + self.assertEqual((r4, r5), ((1, 2, 1, 2), (1, 2, 1, 2))) + for r in (r1, r2, r3, r4, r5): + self.assertIs(type(r), tuple) + + def test_mixed_kinds_raise(self): + a, t = L([1]), T((1,)) + for bad in ( + lambda: a + t, + lambda: t + a, + lambda: a + (1,), + lambda: t + [1], + lambda: a * 1.5, + lambda: a * a, + lambda: a + 1, + lambda: 1 + t, + ): + for _ in range(5): + with self.assertRaises(TypeError): + bad() + + def test_overrides_stay_in_charge(self): + x, plain = LoudAdd([1]), L([2]) + for _ in range(N): + got = (x + plain, x * 2, 2 * x, plain + RightAdd([3]), [0] + RightAdd([3])) + self.assertEqual(got, ("added", "times", "rtimes", "right", "right")) + self.assertEqual(plain + x, [2, 1]) + + def test_negative_and_bool_counts(self): + a = L([1, 2]) + for _ in range(N): + got = (a * -1, a * True, False * a) + self.assertEqual(got, ([], [1, 2], [])) + + def test_class_change_is_seen(self): + class M(list): + pass + + m = M([1]) + for _ in range(N): + self.assertEqual(m + m, [1, 1]) + M.__add__ = lambda self, other: "late" + for _ in range(N): + self.assertEqual(m + m, "late") + + def test_namedtuple_concatenates_as_a_tuple(self): + from collections import namedtuple + + P = namedtuple("P", "x y") + p = P(1, 2) + for _ in range(N): + r = p + p + self.assertEqual(r, (1, 2, 1, 2)) + self.assertIs(type(r), tuple) + + +class SetSubclassCopies(unittest.TestCase): + def test_copy_from_sets(self): + base = set(range(20)) + s = S(base) + for _ in range(N): + a, b = S(s), S(base) + self.assertEqual((a, b), (base, base)) + self.assertIs(type(a), S) + a.add(99) + b.discard(0) + self.assertEqual((len(s), len(base)), (20, 20)) + self.assertNotIn(99, s) + + def test_reinit(self): + s = S([1, 2]) + for _ in range(N): + s.__init__({3, 4}) + self.assertEqual(s, {3, 4}) + s.__init__(s) + self.assertIn(len(s), (0, 2)) + s.__init__() + self.assertEqual(s, set()) + + def test_a_set_source_is_read_off_its_table(self): + # (As CPython's `set_update_internal` reads any set: an + # overridden `__iter__` isn't asked.) + loud = LoudIter([1, 2, 3]) + for _ in range(N): + got = S(loud) + self.assertEqual(got, {1, 2, 3}) + self.assertEqual(list(loud), [99]) + + def test_colliding_elements_survive(self): + src = {Odd(i) for i in range(6)} + for _ in range(20): + got = S(src) + self.assertEqual(len(got), 6) + self.assertIn(Odd(3), got) + self.assertNotIn(Odd(9), got) + + def test_frozenset_and_other_sources(self): + for _ in range(N): + got = (S(frozenset({1, 2})), S([1, 1, 2]), S("ab"), S({1: 2})) + self.assertEqual(got, ({1, 2}, {1, 2}, {"a", "b"}, {1})) + + +class Slotted: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x = x + self.y = y + + +class SlottedChild(Slotted): + pass + + +class Private: + __slots__ = ("__p", "q", "__weakref__") + + def __init__(self): + self.__p = 1 + self.q = 2 + + def p(self): + return self.__p + + +class Empty: + __slots__ = () + + +class OwnState: + __slots__ = ("a",) + + def __init__(self, a): + self.a = a + + def __getstate__(self): + return {"a": self.a * 10} + + def __setstate__(self, state): + self.a = state["a"] + + +class NewArgs: + __slots__ = ("a",) + + def __new__(cls, a=0): + self = object.__new__(cls) + self.a = a + return self + + def __getnewargs__(self): + return (self.a + 1,) + + +class SlottedCopies(unittest.TestCase): + def test_reduce_shape(self): + s = Slotted(1, [2]) + for _ in range(N): + r = s.__reduce_ex__(4) + self.assertEqual(r, (copyreg.__newobj__, (Slotted,), (None, {"x": 1, "y": [2]}), None, None)) + self.assertIs(r[2][1]["y"], s.y) + self.assertEqual(list(r[2][1]), ["x", "y"]) + self.assertEqual(Slotted.__slotnames__, ["x", "y"]) + + def test_copy_and_deepcopy(self): + s = Slotted(1, [2]) + for _ in range(N): + c, d = copy.copy(s), copy.deepcopy(s) + self.assertIs(type(c), Slotted) + self.assertEqual((c.x, d.x, d.y), (1, 1, [2])) + self.assertIs(c.y, s.y) + self.assertIsNot(d.y, s.y) + + def test_unset_slot_stays_unset(self): + s = Slotted(1, 2) + del s.y + for _ in range(N): + r = s.__reduce_ex__(4) + c = copy.copy(s) + self.assertEqual(r[2], (None, {"x": 1})) + self.assertFalse(hasattr(c, "y")) + del s.x + self.assertIsNone(s.__reduce_ex__(4)[2]) + + def test_values_are_read_each_time(self): + s = Slotted(0, 0) + for i in range(N): + s.x = i + self.assertEqual(s.__reduce_ex__(4)[2][1]["x"], i) + + def test_dict_and_slots(self): + s = SlottedChild(1, 2) + for _ in range(N): + r0 = s.__reduce_ex__(4) + self.assertEqual(r0[2], (None, {"x": 1, "y": 2})) + s.z = 3 + for _ in range(N): + r1 = s.__reduce_ex__(4) + c = copy.copy(s) + self.assertEqual(r1[2], ({"z": 3}, {"x": 1, "y": 2})) + self.assertEqual((c.x, c.y, c.z), (1, 2, 3)) + self.assertIsNot(c.__dict__, s.__dict__) + + def test_private_names_and_weakref_slot(self): + s = Private() + for _ in range(N): + r = s.__reduce_ex__(4) + c = copy.copy(s) + self.assertEqual(r[2], (None, {"_Private__p": 1, "q": 2})) + self.assertEqual((c.p(), c.q), (1, 2)) + + def test_empty_slots(self): + e = Empty() + for _ in range(N): + r = e.__reduce_ex__(4) + self.assertEqual(r, (copyreg.__newobj__, (Empty,), None, None, None)) + self.assertIs(type(copy.copy(e)), Empty) + + def test_own_getstate_and_getnewargs(self): + o, n = OwnState(2), NewArgs(5) + for _ in range(N): + ro, rn = o.__reduce_ex__(4), n.__reduce_ex__(4) + self.assertEqual(ro[2], {"a": 20}) + self.assertEqual(copy.copy(o).a, 20) + self.assertEqual(rn[1], (NewArgs, 6)) + self.assertEqual(copy.copy(n).a, 5) + + def test_getstate_added_later(self): + class Late: + __slots__ = ("v",) + + obj = Late() + obj.v = 1 + for _ in range(N): + self.assertEqual(obj.__reduce_ex__(4)[2], (None, {"v": 1})) + Late.__getstate__ = lambda self: "custom" + for _ in range(N): + self.assertEqual(obj.__reduce_ex__(4)[2], "custom") + + def test_pickle_round_trip(self): + s = SlottedChild("a", (1, 2)) + s.extra = [3] + for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): + for _ in range(20): + t = pickle.loads(pickle.dumps(s, proto)) + self.assertEqual((t.x, t.y, t.extra), ("a", (1, 2), [3])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_array_methods_native_halves.py b/tests/regrtest/test_array_methods_native_halves.py new file mode 100644 index 000000000..f245bf6bc --- /dev/null +++ b/tests/regrtest/test_array_methods_native_halves.py @@ -0,0 +1,345 @@ +"""`array.array`'s `pop`, `insert`, `remove`, `extend`, `reverse`, +`count`, `index`, `tobytes`, `in`, `del` and `==` have native halves for +plain arguments, and a tuple builds an array natively; a multi-name +`operator.attrgetter` reads plain attributes without a frame. Each +matches the Python method, which still serves every other shape.""" + +import array +import operator +import unittest + +N = 300 + + +class Twice(array.array): + def tolist(self): + return [x * 2 for x in super().tolist()] + + +class Popping(unittest.TestCase): + def test_pop_and_append(self): + for code in "bBhHiIlLqQfd": + a = array.array(code, range(10)) + for _ in range(N): + a.append(7) + last = a.pop() + self.assertEqual(last, 7) + self.assertEqual(a.tolist(), list(range(10))) + self.assertEqual((a.pop(0), a.pop(-2), a.pop(3)), (0, 8, 4)) + self.assertEqual(a.tolist(), [1, 2, 3, 5, 6, 7, 9]) + self.assertIs(type(a.pop()), type(array.array(code, [1])[0])) + + def test_pop_errors(self): + a = array.array("i", [1]) + a.pop() + for _ in range(5): + with self.assertRaises(IndexError): + a.pop() + a = array.array("i", [1, 2]) + for bad in (2, -3): + with self.assertRaises(IndexError): + a.pop(bad) + with self.assertRaises(TypeError): + a.pop("0") + with self.assertRaises(TypeError): + a.pop(0, 1) + self.assertEqual(a.tolist(), [1, 2]) + + def test_pop_big_unsigned(self): + a = array.array("Q", [1, 2**64 - 1]) + self.assertEqual(a.pop(), 2**64 - 1) + self.assertEqual(a.pop(), 1) + + def test_exported_buffer_refuses_resizes(self): + a = array.array("i", [1, 2, 3]) + with memoryview(a): + for op in ( + a.pop, + lambda: a.insert(0, 9), + lambda: a.remove(2), + lambda: a.extend(array.array("i", [4])), + lambda: a.__delitem__(0), + lambda: a.__delitem__(slice(0, 1)), + ): + with self.assertRaises(BufferError): + op() + a.reverse() + self.assertEqual(a.tobytes(), array.array("i", [3, 2, 1]).tobytes()) + self.assertEqual(a.tolist(), [3, 2, 1]) + self.assertEqual(a.pop(), 1) + + +class InsertRemoveDelete(unittest.TestCase): + def test_insert_positions(self): + for _ in range(N // 10): + a = array.array("i", [1, 2, 3]) + a.insert(0, 0) + a.insert(10, 9) + a.insert(-1, 8) + a.insert(-100, -1) + a.insert(2, 5) + self.assertEqual(a.tolist(), [-1, 0, 5, 1, 2, 3, 8, 9]) + + def test_insert_other_values(self): + a = array.array("d", [1.0]) + a.insert(0, 2) + a.insert(0, True) + self.assertEqual(a.tolist(), [1.0, 2.0, 1.0]) + b = array.array("b", [1]) + for bad in (200, -200, 1.5, "x"): + with self.assertRaises((OverflowError, TypeError)): + b.insert(0, bad) + self.assertEqual(b.tolist(), [1]) + + class Idx: + def __index__(self): + return 1 + + b.insert(Idx(), 7) + self.assertEqual(b.tolist(), [1, 7]) + + def test_remove(self): + for _ in range(N // 10): + a = array.array("i", [1, 2, 3, 2, 1]) + a.remove(2) + a.remove(1) + self.assertEqual(a.tolist(), [3, 2, 1]) + with self.assertRaises(ValueError): + a.remove(9) + f = array.array("d", [1.0, 2.5, 3.0]) + f.remove(1) + f.remove(2.5) + self.assertEqual(f.tolist(), [3.0]) + i = array.array("i", [1, 2]) + i.remove(2.0) + i.remove(True) + self.assertEqual(len(i), 0) + + def test_delete(self): + for _ in range(N // 10): + a = array.array("h", range(10)) + del a[0] + del a[-1] + del a[2:4] + del a[100:] + del a[5:2] + del a[::2] + self.assertEqual(a.tolist(), [2, 6, 8]) + for bad in (3, -4): + with self.assertRaises(IndexError): + del a[bad] + with self.assertRaises(TypeError): + del a["x"] + + def test_extend(self): + for _ in range(N // 10): + a = array.array("i", [1, 2]) + a.extend(array.array("i", [3])) + a.extend(a) + a.extend(a[:1]) + a.extend([7, 8]) + a.extend(iter((9,))) + self.assertEqual(a.tolist(), [1, 2, 3, 1, 2, 3, 1, 7, 8, 9]) + with self.assertRaises(TypeError): + a.extend(array.array("d", [1.0])) + u = array.array("w", "ab") + u.extend(array.array("w", "cd")) + self.assertEqual(u.tounicode(), "abcd") + + def test_reverse(self): + for code in "bBhHiIlLqQfd": + for n in (0, 1, 2, 5, 6): + a = array.array(code, range(n)) + a.reverse() + self.assertEqual(a.tolist(), list(range(n))[::-1]) + u = array.array("w", "héllo") + u.reverse() + self.assertEqual(u.tounicode(), "olléh") + + +class Searching(unittest.TestCase): + def test_contains(self): + a = array.array("i", [1, 2, 3]) + f = array.array("d", [1.0, 2.5, float("nan")]) + hits = 0 + for _ in range(N): + hits += 2 in a + hits += 2.0 in a + hits += True in a + hits += 9 not in a + hits += 2.5 in f + hits += 1 in f + hits += float("nan") not in f + hits += "x" not in a + hits += None not in a + self.assertEqual(hits, 9 * N) + self.assertIn(2**70, array.array("d", [2.0**70])) + self.assertNotIn(2**53 + 1, array.array("d", [2.0**53])) + + def test_contains_asks_other_types(self): + class Always: + def __eq__(self, other): + return True + + class Never: + def __eq__(self, other): + return False + + a = array.array("i", [1, 2, 3]) + for _ in range(N // 10): + self.assertTrue(Always() in a) + self.assertFalse(Never() in a) + self.assertFalse(Always() in array.array("i")) + + def test_count_and_index(self): + a = array.array("i", [1, 2, 3, 2, 1, 2]) + for _ in range(N): + got = (a.count(2), a.count(9), a.count(2.0), a.index(2), a.index(3), a.index(1.0)) + self.assertEqual(got, (3, 0, 3, 1, 2, 0)) + self.assertEqual((a.index(2, 2), a.index(2, 4), a.index(1, -2)), (3, 5, 4)) + self.assertEqual(a.index(2, 0, 2), 1) + for bad in (lambda: a.index(9), lambda: a.index(2, 6), lambda: a.index(3, 0, 2)): + with self.assertRaises(ValueError): + bad() + self.assertEqual(array.array("Q", [2**64 - 1, 5]).index(5), 1) + self.assertEqual(array.array("Q", [2**64 - 1, 5]).count(2**64 - 1), 1) + + def test_subclass_reads_its_buffer(self): + # (As CPython's C methods do: an overridden `tolist` isn't asked.) + t = Twice("i", [1, 2, 3]) + for _ in range(N // 10): + got = (4 in t, 3 in t, t.count(2), t.index(3), t == Twice("i", [1, 2, 3])) + self.assertEqual(got, (False, True, 1, 2, True)) + self.assertEqual(t.tolist(), [2, 4, 6]) + self.assertEqual(t.pop(), 3) + t.insert(0, 9) + t.remove(2) + t.extend(Twice("i", [5])) + t.reverse() + del t[0] + self.assertEqual(t.tolist(), [2, 18]) + self.assertIs(type(t), Twice) + + +class EqualityAndBytes(unittest.TestCase): + def test_equal(self): + a, b = array.array("i", [1, 2, 3]), array.array("i", [1, 2, 3]) + c, d = array.array("i", [1, 2]), array.array("i", [1, 2, 4]) + for _ in range(N): + got = (a == b, a != b, a == c, a != c, a == d, a == a, a != a) + self.assertEqual(got, (True, False, False, True, False, True, False)) + self.assertEqual(array.array("i"), array.array("i")) + + def test_floats_compare_by_value(self): + nan = float("nan") + a = array.array("d", [1.0, nan]) + z, nz = array.array("d", [0.0]), array.array("d", [-0.0]) + for _ in range(N): + got = (a == a, a != a, z == nz, z != nz) + self.assertEqual(got, (False, True, True, False)) + f = array.array("f", [0.5, 1.5]) + self.assertEqual(f, array.array("f", [0.5, 1.5])) + self.assertNotEqual(f, array.array("f", [0.5, 2.5])) + + def test_other_typecodes_and_types(self): + i, d = array.array("i", [1, 2]), array.array("d", [1.0, 2.0]) + for _ in range(N // 10): + got = (i == d, i != d, i == [1, 2], i != [1, 2], i == array.array("q", [1, 2])) + self.assertEqual(got, (True, False, False, True, True)) + self.assertEqual(array.array("w", "ab"), array.array("w", "ab")) + self.assertFalse(i == None) # noqa: E711 + + def test_tobytes(self): + a = array.array("i", [1, 2, 3]) + for _ in range(N): + b = a.tobytes() + self.assertIs(type(b), bytes) + self.assertEqual(len(b), 3 * a.itemsize) + c = array.array("i") + c.frombytes(b) + self.assertEqual(c, a) + self.assertEqual(array.array("d").tobytes(), b"") + self.assertEqual(array.array("w", "a").tobytes(), "a".encode("utf-32-le" if __import__("sys").byteorder == "little" else "utf-32-be")) + a.append(4) + self.assertEqual(len(b), 3 * a.itemsize) + + +class TupleConstruction(unittest.TestCase): + def test_tuple_and_list_sources(self): + for _ in range(N): + a = array.array("i", (1, 2, 3)) + b = array.array("d", (1.5, 2.5)) + c = array.array("i", ()) + d = array.array("d", (1, 2)) + self.assertEqual((a.tolist(), b.tolist(), c.tolist(), d.tolist()), ([1, 2, 3], [1.5, 2.5], [], [1.0, 2.0])) + self.assertEqual(a, array.array("i", [1, 2, 3])) + for bad in ((1, "x"), (1.5,), (2**40,)): + with self.assertRaises((TypeError, OverflowError)): + array.array("i", bad) + + +class Point: + __slots__ = ("x", "y", "z") + + def __init__(self, x, y, z): + self.x, self.y, self.z = x, y, z + + +class Record: + kind = "record" + + def __init__(self, a, b): + self.a, self.b = a, b + + @property + def total(self): + return self.a + self.b + + +class Getters(unittest.TestCase): + def test_two_and_three_names(self): + g2, g3 = operator.attrgetter("x", "y"), operator.attrgetter("z", "x", "y") + p = Point(1, 2, 3) + for _ in range(N): + a, b = g2(p), g3(p) + self.assertEqual((a, b), ((1, 2), (3, 1, 2))) + self.assertIs(type(a), tuple) + + def test_mixed_sources(self): + g = operator.attrgetter("a", "kind", "total", "b") + r = Record(1, 2) + for _ in range(N): + got = g(r) + self.assertEqual(got, (1, "record", 3, 2)) + r.kind = "own" + self.assertEqual(g(r), (1, "own", 3, 2)) + + def test_missing_and_dotted(self): + g = operator.attrgetter("x", "missing") + p = Point(1, 2, 3) + for _ in range(5): + with self.assertRaises(AttributeError): + g(p) + r = Record(Point(1, 2, 3), 0) + d = operator.attrgetter("a.x", "b", "a.z") + for _ in range(N): + got = d(r) + self.assertEqual(got, (1, 0, 3)) + + def test_values_follow_updates(self): + g = operator.attrgetter("x", "y") + p = Point(0, 0, 0) + for i in range(N): + p.x = i + p.y = [i] + self.assertEqual(g(p), (i, [i])) + + def test_as_sort_key(self): + pts = [Point(i % 3, -i, 0) for i in range(30)] + for _ in range(20): + got = sorted(pts, key=operator.attrgetter("x", "y")) + self.assertEqual([(p.x, p.y) for p in got], sorted((p.x, p.y) for p in pts)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_array_slices_and_copies.py b/tests/regrtest/test_array_slices_and_copies.py new file mode 100644 index 000000000..de96a172c --- /dev/null +++ b/tests/regrtest/test_array_slices_and_copies.py @@ -0,0 +1,128 @@ +"""Array slices, sums and copies made from their source's fields. + +A slice, `a + b` and `copy.copy(a)` build the new array from the source's +type code fields directly; each is a plain `array` of the same type code +(a subclass's too, as in CPython), independent of its source, and +a `'u'` array's slices don't warn again. Compiled code reads items, takes +slices and concatenates through the native methods' leaf halves; a bad +index, key or operand still raises CPython's error. +""" + +import array +import copy +import unittest +import warnings + + +class ArraySliceTests(unittest.TestCase): + def test_slices(self): + for tc in "bBhHiIlLqQfd": + a = array.array(tc, range(40)) + for _ in range(50): + for sl in (slice(3, 7), slice(None), slice(-5, None), slice(7, 3), slice(100, 200), + slice(None, None, 3), slice(None, None, -1), slice(-1, -10, -2)): + got = a[sl] + self.assertIs(type(got), array.array) + self.assertEqual(got.typecode, tc) + self.assertEqual(got.tolist(), a.tolist()[sl]) + self.assertEqual(array.array("i", [1, 2, 3])[1:].itemsize, array.array("i").itemsize) + + def test_independent(self): + a = array.array("i", [1, 2, 3, 4]) + b = a[1:3] + b[0] = 99 + b.append(7) + self.assertEqual(a.tolist(), [1, 2, 3, 4]) + self.assertEqual(b.tolist(), [99, 3, 7]) + c = a[:] + c.extend([5]) + self.assertEqual(len(a), 4) + e = a[3:1] + e.append(8) + self.assertEqual(e.tolist(), [8]) + + def test_ranges_carry_over(self): + b = array.array("b", [1, 2])[0:1] + with self.assertRaises(OverflowError): + b.append(200) + h = array.array("H", [1])[:] + with self.assertRaises(OverflowError): + h.append(-1) + + def test_subclass_and_sum_and_copy(self): + class A(array.array): + pass + + a = A("d", [1.5, 2.5, 3.5]) + self.assertIs(type(a[0:2]), array.array) + s = a + array.array("d", [4.5]) + self.assertIs(type(s), array.array) + self.assertEqual(s.tolist(), [1.5, 2.5, 3.5, 4.5]) + c = copy.copy(a) + self.assertIs(type(c), array.array) + self.assertEqual(c.tolist(), a.tolist()) + plain = array.array("q", [5, 6]) + d = copy.copy(plain) + d.append(7) + self.assertEqual(plain.tolist(), [5, 6]) + self.assertEqual(copy.deepcopy(plain).tolist(), [5, 6]) + with self.assertRaises(TypeError): + plain + array.array("i", [1]) + + def test_concatenation_in_loops(self): + class A(array.array): + pass + + a = array.array("h", [1, -2]) + b = array.array("h", [3]) + sub = A("h", [9]) + for _ in range(500): + self.assertEqual((a + b).tolist(), [1, -2, 3]) + self.assertEqual((a + a).tolist(), [1, -2, 1, -2]) + self.assertEqual((a + sub).tolist(), [1, -2, 9]) + self.assertIs(type(sub + a), array.array) + for other in (array.array("i", [1]), [1], b"x", 5): + with self.assertRaises(TypeError): + a + other + acc = array.array("d") + for i in range(300): + acc += array.array("d", [i]) + self.assertEqual(acc[-1], 299.0) + self.assertEqual(len(acc), 300) + u = array.array("w", "ab") + self.assertEqual((u + u).tounicode(), "abab") + + def test_items_in_loops(self): + a = array.array("l", range(-50, 50)) + total = 0 + for _ in range(100): + for i in range(len(a)): + total += a[i] + a[-1 - i] + self.assertEqual(total, -100 * 100) + f = array.array("f", [0.5, 1.5]) + self.assertEqual([f[i & 1] for i in range(1000)][-2:], [0.5, 1.5]) + caught = 0 + for i in range(3000): + try: + a[i % 101] + except IndexError: + caught += 1 + self.assertEqual(caught, sum(1 for i in range(3000) if i % 101 == 100)) + with self.assertRaises(TypeError): + a["x"] + for i in range(2000): + part = a[i % 90:i % 90 + 3] + self.assertEqual(part.tolist(), [a[(1999 % 90) + k] for k in range(3)]) + + def test_unicode_slices_warn_once(self): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + u = array.array("u", "hello") + first = len(caught) + part = u[1:4] + self.assertEqual(part.tounicode(), "ell") + self.assertEqual(len(caught), first) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_array_subscript_borrow.py b/tests/regrtest/test_array_subscript_borrow.py new file mode 100644 index 000000000..196767fbb --- /dev/null +++ b/tests/regrtest/test_array_subscript_borrow.py @@ -0,0 +1,112 @@ +"""`a[i]`, `a[i] = v` and `len(a)` of an `array.array` in hot loops. + +The fast paths read the array's buffer where the instance holds it. They +must agree with the general protocol on every typecode, on negative and +out-of-range indexes, on values that don't fit, on an array that grows or +shrinks between reads, and on a subclass. +""" + +import array +import unittest + + +class ArraySubscriptBorrow(unittest.TestCase): + def test_reads_every_typecode(self): + for code in "bBhHiIlLqQfd": + a = array.array(code, [1, 2, 3, 4, 5]) + total = 0 + for _ in range(2000): + total += a[0] + a[-1] + a[2] + len(a) + self.assertEqual(total, 2000 * (1 + 5 + 3 + 5), code) + + def test_writes_and_reads_back(self): + a = array.array("i", range(10)) + for k in range(3000): + a[k % 10] = k + a[-1] = -k + self.assertEqual(a[k % 10] if k % 10 != 9 else k, k) + self.assertEqual(a[-1], -2999) + self.assertEqual(len(a), 10) + d = array.array("d", [0.0] * 4) + for k in range(2000): + d[k % 4] = k / 2 + self.assertEqual(d.tolist(), [998.0, 998.5, 999.0, 999.5]) + + def test_out_of_range(self): + a = array.array("i", [1, 2, 3]) + for i in (3, 4, -4, 10**6, -(10**6)): + for _ in range(200): + with self.assertRaises(IndexError): + a[i] + with self.assertRaises(IndexError): + a[i] = 0 + self.assertEqual(a.tolist(), [1, 2, 3]) + + def test_values_that_dont_fit(self): + a = array.array("b", [0, 0]) + for _ in range(200): + with self.assertRaises(OverflowError): + a[0] = 200 + with self.assertRaises(TypeError): + a[1] = "x" + with self.assertRaises(TypeError): + a[1] = 1.5 + self.assertEqual(a.tolist(), [0, 0]) + u = array.array("B", [0]) + for _ in range(200): + with self.assertRaises(OverflowError): + u[0] = -1 + self.assertEqual(u[0], 0) + + def test_resized_between_reads(self): + a = array.array("l") + n = 0 + for k in range(3000): + a.append(k) + n += 1 + self.assertEqual(a[-1], k) + self.assertEqual(len(a), n) + if k % 7 == 0: + first = a[0] + a.pop(0) + n -= 1 + self.assertEqual(len(a), n) + if n: + self.assertEqual(a[0], first + 1) + self.assertEqual(a[-1], 2999) + self.assertEqual(a[0], 3000 - n) + + def test_subclass(self): + class Arr(array.array): + pass + + class Indexed(array.array): + def __getitem__(self, i): + return "own" + + def __len__(self): + return 99 + + a = Arr("h", [4, 5, 6]) + b = Indexed("h", [4, 5, 6]) + for _ in range(2000): + self.assertEqual(a[1] + a[-1] + len(a), 14) + self.assertEqual(b[1], "own") + self.assertEqual(len(b), 99) + + def test_non_int_index(self): + class Idx: + def __index__(self): + return 1 + + a = array.array("i", [7, 8, 9]) + for _ in range(500): + self.assertEqual(a[True], 8) + self.assertEqual(a[Idx()], 8) + self.assertEqual(a[1:], array.array("i", [8, 9])) + with self.assertRaises(TypeError): + a["1"] + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_async_for_in_place_steps.py b/tests/regrtest/test_async_for_in_place_steps.py new file mode 100644 index 000000000..2514fe81b --- /dev/null +++ b/tests/regrtest/test_async_for_in_place_steps.py @@ -0,0 +1,649 @@ +"""`async for` over an async generator resumes it in place. + +The loop's step (`GET_ANEXT` with the `SEND` that awaits it at once) resumes +the generator without an `asend` awaitable or a `StopIteration` to carry the +item, in the interpreter and in compiled loops alike. These tests pin what +must not change: items and their order, suspensions on an inner `await` +passing through the consumer, exceptions and the generator's end, the +"already running" guard, the first-iteration hooks, tracing, and what a +frame sees while the generator runs. +""" + +import asyncio +import sys +import types +import unittest + + +class Suspend: + """An awaitable that suspends once with `tag` and returns what's sent.""" + + def __init__(self, tag): + self.tag = tag + + def __await__(self): + got = yield self.tag + return got + + +def drive(coro, sends=None): + """Run `coro` to its end by hand: the values it suspended with and its + result. Each resume sends the next of `sends` (or the tag doubled).""" + seen = [] + value = None + try: + while True: + tag = coro.send(value) + seen.append(tag) + value = sends.pop(0) if sends else (tag, tag) + except StopIteration as stop: + return seen, stop.value + + +def run(coro): + seen, result = drive(coro) + assert seen == [], seen + return result + + +async def count(n): + for i in range(n): + yield i + + +async def count_awaiting(n): + for i in range(n): + got = await Suspend(i) + yield (i, got) + + +async def doubled(source): + async for v in source: + yield v * 2 + + +class Tracked: + log = [] + + def __init__(self, i): + self.i = i + + def __del__(self): + Tracked.log.append(self.i) + + +class AsyncForItems(unittest.TestCase): + def test_items_in_order(self): + async def main(): + out = [] + async for v in count(7): + out.append(v) + return out + + self.assertEqual(run(main()), list(range(7))) + + def test_empty_generator_and_else(self): + async def main(): + out = [] + async for v in count(0): + out.append(v) + else: + out.append("else") + return out + + self.assertEqual(run(main()), ["else"]) + + def test_break_skips_else_and_leaves_the_generator_resumable(self): + async def main(): + g = count(10) + out = [] + async for v in g: + if v == 3: + break + out.append(v) + else: + out.append("else") + async for v in g: + out.append(v) + return out + + self.assertEqual(run(main()), [0, 1, 2, 4, 5, 6, 7, 8, 9]) + + def test_hot_loop_with_work_in_the_body(self): + async def main(n): + total = 0 + odd = [] + async for v in count(n): + total += v * 2 + if v & 1: + odd.append(v) + return total, len(odd), odd[-1] + + for _ in range(3): + self.assertEqual(run(main(4000)), (4000 * 3999, 2000, 3999)) + + def test_many_short_loops(self): + async def main(n): + total = 0 + for i in range(n): + async for v in count(5): + total += v + i + return total + + self.assertEqual(run(main(3000)), sum(10 + 5 * i for i in range(3000))) + + def test_generator_wrapping_a_generator(self): + async def main(n): + total = 0 + async for v in doubled(doubled(count(n))): + total += v + return total + + for _ in range(3): + self.assertEqual(run(main(3000)), 4 * sum(range(3000))) + + def test_items_with_finalizers_die_on_time(self): + async def items(n): + for i in range(n): + yield Tracked(i) + + async def main(n): + seen = 0 + async for t in items(n): + seen += t.i + t = None + return seen + + Tracked.log = [] + self.assertEqual(run(main(3000)), sum(range(3000))) + self.assertEqual(Tracked.log, list(range(3000))) + + def test_comprehensions(self): + async def main(): + a = [v async for v in count(6)] + b = [v async for v in count(6) if v & 1] + c = {v: v * v async for v in count(4)} + d = {v % 3 async for v in count(9)} + e = [(x, y) async for x in count(2) async for y in count(2)] + return a, b, c, d, e + + self.assertEqual( + run(main()), + ( + [0, 1, 2, 3, 4, 5], + [1, 3, 5], + {0: 0, 1: 1, 2: 4, 3: 9}, + {0, 1, 2}, + [(0, 0), (0, 1), (1, 0), (1, 1)], + ), + ) + + def test_hot_comprehension(self): + async def main(n): + total = 0 + for _ in range(n): + total += sum([v async for v in count(6) if v != 2]) + return total + + self.assertEqual(run(main(2500)), 2500 * 13) + + def test_async_generator_expression(self): + async def main(): + gen = (v + 1 async for v in count(4)) + return [v async for v in gen] + + self.assertEqual(run(main()), [1, 2, 3, 4]) + + +class AsyncForSuspensions(unittest.TestCase): + def test_inner_await_passes_through_the_consumer(self): + async def main(): + out = [] + async for item in count_awaiting(3): + out.append(item) + return out + + seen, result = drive(main()) + self.assertEqual(seen, [0, 1, 2]) + self.assertEqual(result, [(0, (0, 0)), (1, (1, 1)), (2, (2, 2))]) + + def test_sent_values_reach_the_inner_await(self): + async def main(): + return [item async for item in count_awaiting(3)] + + seen, result = drive(main(), sends=["a", "b", "c"]) + self.assertEqual(seen, [0, 1, 2]) + self.assertEqual(result, [(0, "a"), (1, "b"), (2, "c")]) + + def test_several_suspensions_per_item(self): + async def gen(n): + for i in range(n): + a = await Suspend(("a", i)) + b = await Suspend(("b", i)) + yield a[0], b[0] + + async def main(n): + out = [] + async for item in gen(n): + out.append(item) + return out + + seen, result = drive(main(3)) + self.assertEqual(seen, [(k, i) for i in range(3) for k in "ab"]) + self.assertEqual(result, [(("a", i), ("b", i)) for i in range(3)]) + + def test_hot_loop_that_suspends_now_and_then(self): + async def gen(n): + for i in range(n): + if i % 500 == 0: + await Suspend(i) + yield i + + async def main(n): + total = 0 + async for v in gen(n): + total += v + return total + + seen, result = drive(main(3000)) + self.assertEqual(seen, [0, 500, 1000, 1500, 2000, 2500]) + self.assertEqual(result, sum(range(3000))) + + def test_throw_while_suspended_reaches_the_generator(self): + log = [] + + async def gen(): + try: + await Suspend("inner") + yield 1 + except KeyError as exc: + log.append(("caught", exc.args)) + yield "recovered" + finally: + log.append("finally") + + async def main(): + out = [] + async for v in gen(): + out.append(v) + return out + + coro = main() + self.assertEqual(coro.send(None), "inner") + with self.assertRaises(StopIteration) as stop: + coro.throw(KeyError("k")) + self.assertEqual(stop.exception.value, ["recovered"]) + self.assertEqual(log, [("caught", ("k",)), "finally"]) + + def test_close_while_suspended_runs_the_generators_finally(self): + log = [] + + async def gen(): + try: + await Suspend("inner") + yield 1 + finally: + log.append("finally") + + async def main(): + async for v in gen(): + log.append(v) + + coro = main() + self.assertEqual(coro.send(None), "inner") + coro.close() + self.assertEqual(log, ["finally"]) + + def test_asyncio_sleep_inside_the_generator(self): + async def gen(n): + for i in range(n): + await asyncio.sleep(0) + yield i + + async def main(): + other = [] + + async def side(): + for i in range(5): + other.append(i) + await asyncio.sleep(0) + + task = asyncio.ensure_future(side()) + got = [v async for v in gen(5)] + await task + return got, other + + self.assertEqual(asyncio.run(main()), ([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])) + + def test_cancellation_mid_iteration(self): + log = [] + + async def gen(): + try: + i = 0 + while True: + await asyncio.sleep(0) + yield i + i += 1 + finally: + log.append("gen closed") + + async def consume(): + try: + async for v in gen(): + log.append(v) + except asyncio.CancelledError: + log.append("cancelled") + raise + + async def main(): + task = asyncio.ensure_future(consume()) + for _ in range(6): + await asyncio.sleep(0) + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + return task.cancelled() + + self.assertTrue(asyncio.run(main())) + self.assertEqual(log[:2], [0, 1]) + self.assertEqual(log[-2:], ["gen closed", "cancelled"]) + + +class AsyncForEndsAndErrors(unittest.TestCase): + def test_exception_from_the_body_propagates(self): + async def gen(): + yield 1 + raise ValueError("boom") + + async def main(): + out = [] + try: + async for v in gen(): + out.append(v) + except ValueError as exc: + out.append(str(exc)) + return out + + self.assertEqual(run(main()), [1, "boom"]) + + def test_traceback_names_both_frames(self): + async def gen(): + yield 1 + raise ValueError("boom") + + async def main(): + async for v in gen(): + pass + + try: + run(main()) + except ValueError as exc: + tb = exc.__traceback__ + else: + self.fail("no ValueError") + names = [] + while tb is not None: + names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + self.assertEqual(names[-2:], ["main", "gen"]) + + def test_stop_iteration_in_the_body_is_a_runtime_error(self): + async def gen(): + yield 1 + raise StopIteration + + async def main(): + async for v in gen(): + pass + + with self.assertRaises(RuntimeError) as caught: + run(main()) + self.assertIsInstance(caught.exception.__cause__, StopIteration) + + def test_stop_async_iteration_in_the_body_is_a_runtime_error(self): + async def gen(): + yield 1 + raise StopAsyncIteration + + async def main(): + async for v in gen(): + pass + + with self.assertRaises(RuntimeError): + run(main()) + + def test_exhausted_generator_ends_the_next_loop_at_once(self): + async def main(): + g = count(2) + first = [v async for v in g] + second = [v async for v in g] + return first, second + + self.assertEqual(run(main()), ([0, 1], [])) + + def test_loop_in_try_finally(self): + log = [] + + async def main(): + try: + async for v in count(3): + log.append(v) + finally: + log.append("done") + return "ok" + + self.assertEqual(run(main()), "ok") + self.assertEqual(log, [0, 1, 2, "done"]) + + def test_generator_already_running(self): + async def gen(): + await Suspend("inner") + yield 1 + + async def consume(g): + async for v in g: + pass + + g = gen() + first = consume(g) + self.assertEqual(first.send(None), "inner") + second = consume(g) + with self.assertRaises(RuntimeError) as caught: + second.send(None) + self.assertIn("already running", str(caught.exception)) + first.close() + run(g.aclose()) + + def test_iterating_itself_from_its_own_body(self): + async def gen(): + me = holder[0] + try: + async for v in me: + pass + except (RuntimeError, ValueError) as exc: + yield type(exc).__name__ + else: + yield "no error" + + async def main(): + g = gen() + holder.append(g) + return [v async for v in g] + + holder = [] + (name,) = run(main()) + self.assertIn(name, ("RuntimeError", "ValueError")) + + def test_generator_exit_in_a_hot_loop_keeps_items_exact(self): + async def gen(n): + for i in range(n): + if i == n - 1: + raise KeyError(i) + yield i + + async def main(n): + total = 0 + try: + async for v in gen(n): + total += v + except KeyError as exc: + return total, exc.args[0] + + self.assertEqual(run(main(3000)), (sum(range(2999)), 2999)) + + +class AsyncForHooksAndFrames(unittest.TestCase): + def test_firstiter_hook_runs_once_per_generator(self): + calls = [] + old = sys.get_asyncgen_hooks() + sys.set_asyncgen_hooks(firstiter=calls.append) + try: + + async def main(): + g = count(3) + async for v in g: + pass + async for v in g: + pass + return g + + g = run(main()) + finally: + sys.set_asyncgen_hooks(*old) + self.assertEqual(len(calls), 1) + self.assertIs(calls[0], g) + + def test_firstiter_hook_error_propagates(self): + def hook(agen): + raise LookupError("no hook") + + old = sys.get_asyncgen_hooks() + sys.set_asyncgen_hooks(firstiter=hook) + try: + + async def main(): + async for v in count(3): + pass + + with self.assertRaises(LookupError): + run(main()) + finally: + sys.set_asyncgen_hooks(*old) + + def test_generator_body_sees_its_consumer(self): + async def gen(n): + for i in range(n): + caller = sys._getframe(1) + yield caller.f_code.co_name, caller.f_lineno + + async def main(n): + seen = set() + async for item in gen(n): # the line the generator reports + seen.add(item) + return seen + + line = main.__code__.co_firstlineno + 2 + for _ in range(3): + self.assertEqual(run(main(3000)), {("main", line)}) + + def test_ag_running_and_frame_while_resumed(self): + async def gen(): + g = holder[0] + yield g.ag_running, g.ag_frame is not None + + async def main(): + g = gen() + holder.append(g) + return [v async for v in g] + + holder = [] + self.assertEqual(run(main()), [(True, True)]) + + def test_tracing_sees_the_same_lines_and_results(self): + async def main(): + out = [] + async for v in count(3): + out.append(v) + return out + + events = [] + + def tracer(frame, event, arg): + if frame.f_code.co_name in ("main", "count"): + events.append((frame.f_code.co_name, event)) + return tracer + + sys.settrace(tracer) + try: + traced = run(main()) + finally: + sys.settrace(None) + self.assertEqual(traced, [0, 1, 2]) + self.assertEqual(traced, run(main())) + names = {name for name, _ in events} + self.assertEqual(names, {"main", "count"}) + self.assertEqual(sum(1 for e in events if e == ("count", "call")), 4) + + def test_class_based_iterators_still_work(self): + class Ticker: + def __init__(self, n): + self.i = 0 + self.n = n + + def __aiter__(self): + return self + + async def __anext__(self): + if self.i >= self.n: + raise StopAsyncIteration + self.i += 1 + return self.i + + async def main(n): + total = 0 + async for v in Ticker(n): + total += v + return total + + self.assertEqual(run(main(2500)), sum(range(1, 2501))) + + def test_anext_and_asend_awaitables_unchanged(self): + async def echo(): + got = yield "first" + while True: + got = yield got + + async def main(): + g = echo() + a = await anext(g) + b = await g.asend("x") + c = await g.__anext__() + await g.aclose() + return a, b, c + + self.assertEqual(run(main()), ("first", "x", None)) + + def test_types_coroutine_consumer(self): + @types.coroutine + def pause(tag): + got = yield tag + return got + + async def gen(): + for i in range(3): + got = await pause(i) + yield got + + async def main(): + return [v async for v in gen()] + + seen, result = drive(main(), sends=["x", "y", "z"]) + self.assertEqual(seen, [0, 1, 2]) + self.assertEqual(result, ["x", "y", "z"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_async_generator_method_awaitables.py b/tests/regrtest/test_async_generator_method_awaitables.py new file mode 100644 index 000000000..5eae82f7e --- /dev/null +++ b/tests/regrtest/test_async_generator_method_awaitables.py @@ -0,0 +1,279 @@ +"""An async generator's `asend`, `aclose` and `__anext__` awaitables are +made and driven in compiled code. + +`await g.asend(v)`, `await g.aclose()` and `await g.__anext__()` no longer +leave compiled code for the method call or the `await`. These tests pin +what the awaitables do: the values they complete with, the errors they +raise, the warning an awaitable dropped undriven is owed, when the +first-iteration hook runs, and that the methods read as ordinary bound +methods. +""" + +import gc +import sys +import unittest +import warnings + +N = 2500 + + +def run(coro): + try: + coro.send(None) + except StopIteration as stop: + return stop.value + raise AssertionError("coroutine suspended") + + +async def echo(): + got = yield "first" + while True: + got = yield got + + +async def count(n): + for i in range(n): + yield i + + +class Awaitables(unittest.TestCase): + def test_asend_round_trips(self): + async def main(): + g = echo() + out = [await g.asend(None)] + for v in ("a", "b", 3): + out.append(await g.asend(v)) + await g.aclose() + return out + + self.assertEqual(run(main()), ["first", "a", "b", 3]) + + def test_hot_asend_and_anext(self): + async def main(n): + g = echo() + await g.__anext__() + total = 0 + for i in range(n): + total += await g.asend(i) + await g.__anext__() + await g.aclose() + return total + + for _ in range(2): + self.assertEqual(run(main(N)), sum(range(N))) + + def test_many_short_generators(self): + async def main(n): + total = 0 + for i in range(n): + g = count(3) + total += await g.asend(None) + total += await g.__anext__() + total += await anext(g) + await g.aclose() + return total + + self.assertEqual(run(main(N)), 3 * N) + + def test_end_raises_stop_async_iteration(self): + async def main(): + g = count(1) + first = await g.asend(None) + try: + await g.asend(None) + except StopAsyncIteration: + ended = True + else: + ended = False + try: + await g.__anext__() + except StopAsyncIteration: + again = True + else: + again = False + return first, ended, again + + self.assertEqual(run(main()), (0, True, True)) + + def test_non_none_send_to_a_new_generator(self): + async def main(): + g = echo() + try: + await g.asend(5) + except TypeError as exc: + return "just-started" in str(exc) + + self.assertTrue(run(main())) + + def test_aclose_states(self): + log = [] + + async def guarded(): + try: + yield 1 + yield 2 + finally: + log.append("closed") + + async def main(): + fresh = guarded() + await fresh.aclose() + started = guarded() + await started.asend(None) + await started.aclose() + await started.aclose() + done = guarded() + async for _ in done: + pass + await done.aclose() + return len(log) + + self.assertEqual(run(main()), 2) + + def test_aclose_refused(self): + async def stubborn(): + try: + yield 1 + except GeneratorExit: + yield 2 + + async def main(): + g = stubborn() + await g.asend(None) + try: + await g.aclose() + except RuntimeError as exc: + return "ignored GeneratorExit" in str(exc) + + self.assertTrue(run(main())) + + def test_athrow(self): + async def catcher(): + while True: + try: + yield "ready" + except KeyError as exc: + yield ("caught", exc.args[0]) + + async def main(): + g = catcher() + await g.asend(None) + got = await g.athrow(KeyError("k")) + try: + await g.athrow(ValueError("out")) + except ValueError as exc: + return got, str(exc) + + self.assertEqual(run(main()), (("caught", "k"), "out")) + + def test_awaitable_cannot_be_reused(self): + async def main(): + g = echo() + aw = g.asend(None) + first = await aw + try: + await aw + except RuntimeError as exc: + return first, "reuse" in str(exc) + + self.assertEqual(run(main()), ("first", True)) + + def test_bound_methods_read_normally(self): + async def main(): + g = echo() + send = g.asend + first = await send(None) + second = await send("x") + names = (g.asend.__name__, g.aclose.__name__, g.__anext__.__name__) + owner = g.asend.__self__ is g + await g.aclose() + return first, second, names, owner + + self.assertEqual( + run(main()), ("first", "x", ("asend", "aclose", "__anext__"), True) + ) + + def test_generator_methods_absent_on_async_generators(self): + g = echo() + for name in ("send", "throw", "close", "__next__"): + self.assertFalse(hasattr(g, name), name) + run(g.aclose()) + + +class Dropped(unittest.TestCase): + def test_undriven_awaitable_warns(self): + async def main(n): + g = echo() + await g.asend(None) + for _ in range(n): + g.asend(1) + await g.aclose() + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + run(main(40)) + gc.collect() + messages = [str(w.message) for w in caught if issubclass(w.category, RuntimeWarning)] + self.assertEqual(len(messages), 40) + self.assertTrue(all("asend" in m and "never awaited" in m for m in messages)) + + def test_driven_awaitables_do_not_warn(self): + async def main(n): + g = echo() + await g.asend(None) + for i in range(n): + await g.asend(i) + await g.__anext__() + await g.aclose() + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + run(main(N)) + gc.collect() + self.assertEqual([str(w.message) for w in caught], []) + + +class Hooks(unittest.TestCase): + def test_first_iteration_hook_runs_at_the_first_method_call(self): + calls = [] + old = sys.get_asyncgen_hooks() + sys.set_asyncgen_hooks(firstiter=calls.append) + try: + + async def main(): + seen = [] + for _ in range(200): + g = count(2) + before = len(calls) + aw = g.asend(None) + seen.append(len(calls) - before) + await aw + await g.asend(None) + await g.aclose() + return seen + + seen = run(main()) + finally: + sys.set_asyncgen_hooks(*old) + self.assertEqual(seen, [1] * 200) + self.assertEqual(len(calls), 200) + + def test_tracing_gives_the_same_results(self): + async def main(): + g = echo() + out = [await g.asend(None), await g.asend("t"), await g.__anext__()] + await g.aclose() + return out + + plain = run(main()) + sys.settrace(lambda frame, event, arg: None) + try: + traced = run(main()) + finally: + sys.settrace(None) + self.assertEqual(plain, traced) + self.assertEqual(plain, ["first", "t", None]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_attrgetter_dotted_leaf.py b/tests/regrtest/test_attrgetter_dotted_leaf.py new file mode 100644 index 000000000..9d69c4886 --- /dev/null +++ b/tests/regrtest/test_attrgetter_dotted_leaf.py @@ -0,0 +1,70 @@ +"""`operator.attrgetter` with dotted names, whose leaf half reads each step +in turn: plain fields, a property or `__getattr__` midway (the full path), +a missing step's `AttributeError`, several names, and hot loops.""" + +import operator +import unittest + + +class Node: + def __init__(self, v, nxt=None): + self.v = v + self.nxt = nxt + + +class WithProp: + def __init__(self, inner): + self._inner = inner + + @property + def inner(self): + return self._inner + + +class Hook: + def __getattr__(self, name): + return Node(name) + + +class DottedAttrgetter(unittest.TestCase): + def test_plain_chain(self): + g = operator.attrgetter("nxt.nxt.v") + n = Node(1, Node(2, Node(3))) + for _ in range(400): + self.assertEqual(g(n), 3) + + def test_several_names(self): + g = operator.attrgetter("v", "nxt.v") + n = Node(1, Node(2)) + for _ in range(400): + self.assertEqual(g(n), (1, 2)) + + def test_property_and_hook_midway(self): + g = operator.attrgetter("inner.v") + h = operator.attrgetter("anything.v") + for i in range(300): + self.assertEqual(g(WithProp(Node(i))), i) + self.assertEqual(h(Hook()), "anything") + + def test_missing_step(self): + g = operator.attrgetter("nxt.v") + with self.assertRaises(AttributeError) as cm: + g(Node(1)) + self.assertIn("'NoneType' object has no attribute 'v'", str(cm.exception)) + with self.assertRaises(AttributeError): + operator.attrgetter("nope.v")(Node(1)) + + def test_builtin_values(self): + g = operator.attrgetter("real.bit_length") + for i in range(300): + self.assertEqual(g(i)(), i.bit_length()) + self.assertEqual(operator.attrgetter("__class__.__name__")(1.5), "float") + + def test_sort_key(self): + items = [Node(0, Node(k)) for k in (3, 1, 2)] + out = sorted(items, key=operator.attrgetter("nxt.v")) + self.assertEqual([x.nxt.v for x in out], [1, 2, 3]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_await_of_varargs_coroutines.py b/tests/regrtest/test_await_of_varargs_coroutines.py new file mode 100644 index 000000000..8b6184efa --- /dev/null +++ b/tests/regrtest/test_await_of_varargs_coroutines.py @@ -0,0 +1,213 @@ +"""`await f(...)` of a coroutine function that takes `*args`. + +A compiled `await` runs a coroutine function's body directly when it can; +that now covers bodies with a `*args` parameter (an +`async def __aexit__(self, *exc)`), whose surplus arguments are packed as +the frame is bound. These tests pin the binding (the tuple, defaults, no +surplus), suspensions and errors inside such a body, and the `async with` +protocol through it. +""" + +import unittest + +N = 3000 + + +class Suspend: + def __init__(self, tag): + self.tag = tag + + def __await__(self): + got = yield self.tag + return got + + +def drive(coro): + seen = [] + value = None + try: + while True: + tag = coro.send(value) + seen.append(tag) + value = ("sent", tag) + except StopIteration as stop: + return seen, stop.value + + +def run(coro): + seen, value = drive(coro) + assert seen == [], seen + return value + + +async def collect(*items): + return items + + +async def head_and_rest(a, *rest): + return a, rest + + +async def with_default(a, b=5, *rest): + return a, b, rest + + +async def pausing(tag, *rest): + got = await Suspend(tag) + return got, len(rest) + + +async def failing(*parts): + raise KeyError(parts) + + +class Manager: + def __init__(self, suppress=False): + self.suppress = suppress + self.exits = [] + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + self.exits.append(tuple(None if e is None else type(e).__name__ for e in exc[:2])) + return self.suppress + + +class VarargsCoroutines(unittest.TestCase): + def test_binding(self): + async def main(): + return ( + await collect(), + await collect(1), + await collect(1, 2, 3), + await head_and_rest(1), + await head_and_rest(1, 2, 3), + await with_default(1), + await with_default(1, 2), + await with_default(1, 2, 3, 4), + ) + + for _ in range(3): + self.assertEqual( + run(main()), + ((), (1,), (1, 2, 3), (1, ()), (1, (2, 3)), (1, 5, ()), (1, 2, ()), (1, 2, (3, 4))), + ) + + def test_hot_loop(self): + async def main(n): + total = 0 + for i in range(n): + a, rest = await head_and_rest(i, i + 1, i + 2) + total += a + sum(rest) + len(await collect(i, i)) + return total + + expected = sum(3 * i + 3 + 2 for i in range(N)) + for _ in range(2): + self.assertEqual(run(main(N)), expected) + + def test_the_tuple_is_a_fresh_tuple(self): + async def main(): + first = await collect(1, 2) + second = await collect(1, 2) + return type(first) is tuple, first == second, [x for x in first] + + self.assertEqual(run(main()), (True, True, [1, 2])) + + def test_spread_arguments(self): + async def main(n): + args = (1, 2, 3) + out = None + for _ in range(n): + out = (await collect(*args), await head_and_rest(*args), await collect(0, *args)) + return out + + self.assertEqual(run(main(500)), ((1, 2, 3), (1, (2, 3)), (0, 1, 2, 3))) + + def test_suspension_inside(self): + async def main(): + out = [] + for i in range(5): + out.append(await pausing(i, "x", "y")) + return out + + seen, value = drive(main()) + self.assertEqual(seen, [0, 1, 2, 3, 4]) + self.assertEqual(value, [(("sent", i), 2) for i in range(5)]) + + def test_errors_inside(self): + async def main(n): + caught = 0 + for i in range(n): + try: + await failing(i, "p") + except KeyError as exc: + caught += exc.args[0][0] == i + return caught + + self.assertEqual(run(main(300)), 300) + + def test_wrong_arguments(self): + async def main(): + await head_and_rest() + + with self.assertRaises(TypeError): + run(main()) + + async def keyword(): + return await head_and_rest(a=1) + + self.assertEqual(run(keyword()), (1, ())) + + def test_async_with_through_a_varargs_exit(self): + async def main(n): + m = Manager() + for _ in range(n): + async with m as got: + pass + return got is m, len(m.exits), set(m.exits) + + self.assertEqual(run(main(N)), (True, N, {(None, None)})) + + def test_async_with_exception_and_suppression(self): + async def main(suppress): + m = Manager(suppress) + reached = False + try: + async with m: + raise ValueError("inside") + reached = True + except ValueError: + return m.exits, "raised", reached + return m.exits, "suppressed", reached + + for _ in range(50): + loud = run(main(False)) + quiet = run(main(True)) + self.assertEqual(loud, ([("type", "ValueError")], "raised", False)) + self.assertEqual(quiet, ([("type", "ValueError")], "suppressed", True)) + + def test_methods_and_generators_with_varargs(self): + class Box: + async def put(self, *items): + return (self, items) + + def gen(*items): + yield from items + + async def agen(*items): + for item in items: + yield item + + async def main(): + b = Box() + owner, items = await b.put(1, 2) + return owner is b, items, list(gen(1, 2, 3)), [x async for x in agen(4, 5)] + + for _ in range(200): + got = run(main()) + self.assertEqual(got, (True, (1, 2), [1, 2, 3], [4, 5])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_batched_pairwise_cursor_steps.py b/tests/regrtest/test_batched_pairwise_cursor_steps.py new file mode 100644 index 000000000..b8618face --- /dev/null +++ b/tests/regrtest/test_batched_pairwise_cursor_steps.py @@ -0,0 +1,82 @@ +"""itertools.batched and pairwise over list and tuple cursors drained from +compiled code: full and short last batches, strict batches, a source +iterator someone else holds (exhausted at the end, so later appends to +its list stay unseen, as in CPython), a batched stopped partway and +resumed, and zip_longest and pairwise leaving a shared source exhausted; +plus builtin types called with a spread (zip(*rows), tuple(*a)) from +compiled code.""" + +import itertools +import unittest + + +def drain(n, make): + out = None + for i in range(n): + out = list(make()) + return out + + +class CursorStepTests(unittest.TestCase): + def test_batched(self): + xs = list(range(8)) + for n in (1, 300): + self.assertEqual(drain(n, lambda: itertools.batched(xs, 3)), [(0, 1, 2), (3, 4, 5), (6, 7)]) + self.assertEqual(drain(n, lambda: itertools.batched(tuple(xs), 4)), [(0, 1, 2, 3), (4, 5, 6, 7)]) + self.assertEqual(drain(n, lambda: itertools.batched([], 2)), []) + self.assertEqual(drain(n, lambda: itertools.batched(xs, 8, strict=True)), [tuple(xs)]) + with self.assertRaises(ValueError): + drain(300, lambda: itertools.batched(xs, 3, strict=True)) + + def test_batched_resume(self): + for _ in range(300): + b = itertools.batched("abcde", 2) + self.assertEqual(next(b), ("a", "b")) + self.assertEqual(list(b), [("c", "d"), ("e",)]) + self.assertEqual(list(b), []) + + def test_shared_source_exhausted(self): + for _ in range(300): + xs = [1, 2, 3, 4] + it = iter(xs) + self.assertEqual(list(itertools.batched(it, 3)), [(1, 2, 3), (4,)]) + xs.append(9) + self.assertEqual(next(it, "end"), "end") + ys = [1, 2, 3] + it = iter(ys) + self.assertEqual(list(itertools.pairwise(it)), [(1, 2), (2, 3)]) + ys.append(9) + self.assertEqual(next(it, "end"), "end") + zs = [1, 2] + it = iter(zs) + self.assertEqual(list(itertools.zip_longest(it, "abc")), [(1, "a"), (2, "b"), (None, "c")]) + zs.append(9) + self.assertEqual(next(it, "end"), "end") + + def test_pairwise(self): + xs = list(range(5)) + for n in (1, 300): + self.assertEqual(drain(n, lambda: itertools.pairwise(xs)), [(0, 1), (1, 2), (2, 3), (3, 4)]) + self.assertEqual(drain(n, lambda: itertools.pairwise([1])), []) + + def test_spread_types(self): + rows = [[1, 2, 3], [4, 5, 6]] + a = ([1, 2],) + for n in (1, 300): + self.assertEqual(drain(n, lambda: zip(*rows)), [(1, 4), (2, 5), (3, 6)]) + self.assertEqual(drain(n, lambda: zip(*())), []) + + def spread(k): + out = None + for i in range(k): + out = (tuple(*a), list(*a), set(*a), dict(*[[("x", 1)]]), zip(*rows)) + return out + + t, l, s, d, z = spread(n) + self.assertEqual((t, l, s, d, list(z)), ((1, 2), [1, 2], {1, 2}, {"x": 1}, [(1, 4), (2, 5), (3, 6)])) + with self.assertRaises(TypeError): + drain(300, lambda: zip(*[1, 2])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_big_int_text_bytes_and_methods.py b/tests/regrtest/test_big_int_text_bytes_and_methods.py new file mode 100644 index 000000000..614a27935 --- /dev/null +++ b/tests/regrtest/test_big_int_text_bytes_and_methods.py @@ -0,0 +1,241 @@ +"""Integers past 64 bits: from text, to bytes, in arithmetic, and their methods. + +`int(text, base)` of digits that don't fit a machine word, `to_bytes` of +any size, sums, differences, products, shifts and masks of a wide value +with a small one, and methods called on wide values (and on floats, +tuples and bytes) from one call site that sees several kinds of receiver. +Each result is checked against the same value built another way. +""" + +import random +import unittest + +HEX = "0123456789abcdef" + + +def by_digits(text, base): + """The value of `text` in `base`, a digit at a time.""" + v = 0 + for ch in text: + v = v * base + HEX.index(ch.lower()) + return v + + +def bytes_of(v, length, little=False): + out = [] + for _ in range(length): + out.append(v & 0xFF) + v >>= 8 + if v: + raise OverflowError("int too big to convert") + return bytes(out if little else reversed(out)) + + +class TextTests(unittest.TestCase): + def test_hex_text_of_every_length(self): + rng = random.Random(11) + for n in list(range(1, 70)) + [100, 127, 128, 129, 200, 500]: + for _ in range(8): + text = "".join(rng.choice(HEX + "ABCDEF") for _ in range(n)) + want = by_digits(text, 16) + self.assertEqual(int(text, 16), want, text) + self.assertEqual(int(text, base=16), want) + self.assertEqual(int(" " + text + "\n", 16), want) + self.assertEqual(int("-" + text, 16), -want) + self.assertEqual(int("+" + text, 16), want) + self.assertEqual(int("0x" + text, 16), want) + self.assertEqual(format(want, "x"), text.lower().lstrip("0") or "0") + + def test_boundaries(self): + cases = { + "7fffffffffffffff": 2**63 - 1, + "8000000000000000": 2**63, + "ffffffffffffffff": 2**64 - 1, + "10000000000000000": 2**64, + "0" * 40: 0, + "0" * 39 + "1": 1, + "0" * 20 + "f" * 16: 2**64 - 1, + "f" * 32: 2**128 - 1, + } + for text, want in cases.items(): + self.assertEqual(int(text, 16), want, text) + self.assertIs(type(int(text, 16)), int) + self.assertEqual(int("-8000000000000000", 16), -(2**63)) + self.assertEqual(int("-8000000000000001", 16), -(2**63) - 1) + + def test_other_bases_and_decimal(self): + rng = random.Random(12) + for base in (2, 3, 8, 10, 16, 32, 36): + digits = "0123456789abcdefghijklmnopqrstuvwxyz"[:base] + for n in (1, 13, 19, 20, 40, 64, 65, 90, 300): + text = "".join(rng.choice(digits) for _ in range(n)) + want = 0 + for ch in text: + want = want * base + digits.index(ch) + self.assertEqual(int(text, base), want, (base, text)) + self.assertEqual(int("-" + text, base), -want) + if base == 10: + self.assertEqual(int(text), want) + self.assertEqual(int(" +" + text + " "), want) + self.assertEqual(str(want), text.lstrip("0") or "0") + + def test_malformed_text_still_raises(self): + for text in ("", " ", "g", "12g4" * 10, "f" * 20 + "_", "_" + "f" * 20, "f__f" * 8, + "--" + "f" * 20, "+-" + "f" * 20, "0x", "f" * 20 + " f", "١" * 3 + "g"): + with self.assertRaises(ValueError, msg=repr(text)): + int(text, 16) + self.assertEqual(int("f_f" * 8, 16), by_digits("ff" * 8, 16)) + self.assertEqual(int("١٢٣" * 8), int("123" * 8)) + with self.assertRaises(ValueError): + int("9" * 30, 8) + + +class BytesTests(unittest.TestCase): + values = [0, 1, 255, 256, 2**63 - 1, 2**63, 2**64 - 1, 2**64, 2**127, 2**128 - 1, 2**128, + 2**200 + 12345, int("12345678123456781234567812345678", 16)] + + def test_to_bytes(self): + for v in self.values: + for length in (0, 1, 2, 7, 8, 9, 15, 16, 17, 26, 32, 64): + for little in (False, True): + order = "little" if little else "big" + try: + want = bytes_of(v, length, little) + except OverflowError: + for call in (lambda: v.to_bytes(length, order), + lambda: v.to_bytes(length, byteorder=order), + lambda: v.to_bytes(length=length, byteorder=order)): + with self.assertRaises(OverflowError): + call() + continue + self.assertEqual(v.to_bytes(length, order), want, (v, length, order)) + self.assertEqual(v.to_bytes(length, byteorder=order, signed=False), want) + self.assertEqual(v.to_bytes(length=length, byteorder=order), want) + if not little: + self.assertEqual(v.to_bytes(length), want) + self.assertEqual(int.from_bytes(want, order), v) + if want and not want[-1 if little else 0] & 0x80: + self.assertEqual(v.to_bytes(length, order, signed=True), want) + + def test_negative_and_odd_arguments(self): + for v in (-1, -(2**64), -(2**127) - 5): + with self.assertRaises(OverflowError): + v.to_bytes(32) + b = v.to_bytes(32, "big", signed=True) + self.assertEqual(int.from_bytes(b, "big", signed=True), v) + with self.assertRaises(ValueError): + (2**70).to_bytes(16, "middle") + with self.assertRaises(ValueError): + (2**70).to_bytes(-1) + self.assertEqual(True.to_bytes(2), b"\x00\x01") + self.assertEqual((0).to_bytes(0), b"") + + +class ArithmeticTests(unittest.TestCase): + def test_wide_with_small(self): + rng = random.Random(13) + for _ in range(400): + big = rng.getrandbits(rng.choice((64, 65, 100, 128, 200))) | (1 << 64) + small = rng.randrange(-(2**40), 2**40) or 7 + total = big + small + self.assertEqual(total - small, big) + self.assertEqual(small + big, total) + self.assertEqual(total - big, small) + self.assertEqual(big - small + small, big) + prod = big * small + self.assertEqual(small * big, prod) + self.assertEqual(prod // small, big) + self.assertEqual(prod % small, 0) + self.assertEqual((-big) + small, -(big - small)) + self.assertEqual(int(str(total)), total) + + def test_results_that_fit_a_word_again(self): + big = 2**64 + self.assertEqual(big - (2**64 - 5), 5) + self.assertIs(type(big - 1), int) + self.assertEqual((big + 5) - big, 5) + self.assertEqual(big + (-(2**63)), 2**63) + self.assertEqual((2**70) * 0, 0) + self.assertEqual((big - 1) + 1, big) + self.assertEqual(big - 1, 18446744073709551615) + + def test_shifts_and_masks(self): + rng = random.Random(14) + for _ in range(300): + v = rng.getrandbits(128) | (1 << 127) + text = format(v, "032x") + for shift in (0, 1, 4, 32, 48, 60, 64, 96, 124, 127, 128, 200): + self.assertEqual(v >> shift, v // (1 << shift), (v, shift)) + self.assertEqual((v >> 64) & 0xFFFF, int(text[12:16], 16)) + self.assertEqual(v & 0xFFFFFFFFFFFF, int(text[20:], 16)) + self.assertEqual(0xFF & v, int(text[30:], 16)) + self.assertEqual(v & (2**63 - 1), v % (2**63)) + self.assertEqual(v & 0, 0) + self.assertEqual((-v) & 0xFF, (256 - (v % 256)) % 256) + self.assertEqual(v & -1, v) + self.assertEqual((-v) >> 3, -((v + 7) // 8)) + self.assertEqual(v.bit_length(), len(bin(v)) - 2) + self.assertEqual((-v).bit_length(), v.bit_length()) + + +class ReceiverKindTests(unittest.TestCase): + """One call site, several kinds of builtin receiver, many times over.""" + + def test_bit_length_site(self): + values = [5, 2**70, True, 0, -(2**90), 255] + want = [3, 71, 1, 0, 91, 8] + got = [] + for i in range(6000): + got.append(values[i % 6].bit_length()) + self.assertEqual(got, want * 1000) + + def test_conjugate_and_real_sites(self): + values = [3, 2.5, 2**80, 1 + 2j, True] + want = [3, 2.5, 2**80, 1 - 2j, 1] + for i in range(5000): + self.assertEqual(values[i % 5].conjugate(), want[i % 5]) + + def test_count_and_index_sites(self): + values = [(1, 2, 1), [1, 1, 1], b"\x01\x01", bytearray(b"\x01"), range(1, 2), "1a1"] + needles = [1, 1, b"\x01", b"\x01", 1, "1"] + want = [2, 3, 2, 1, 1, 2] + for i in range(6000): + k = i % 6 + self.assertEqual(values[k].count(needles[k]), want[k], k) + for i in range(3000): + k = i % 2 + self.assertEqual(((7, 8), [8, 7])[k].index(8), 1 - k) + + def test_hex_sites(self): + values = [1.5, b"\xab", bytearray(b"\x01\x02"), 2.0] + want = [(1.5).hex(), "ab", "0102", (2.0).hex()] + for i in range(4000): + self.assertEqual(values[i % 4].hex(), want[i % 4]) + + def test_to_bytes_site(self): + values = [7, 2**100, True, 2**64 - 1] + for i in range(4000): + v = values[i % 4] + self.assertEqual(int.from_bytes(v.to_bytes(16)), int(v)) + + def test_methods_of_subclasses_and_shadows(self): + class MyInt(int): + def bit_length(self): + return -1 + + class MyTuple(tuple): + def count(self, x): + return "mine" + + values = [2**70, MyInt(2**70), 5, MyInt(5)] + want = [71, -1, 3, -1] + for i in range(4000): + self.assertEqual(values[i % 4].bit_length(), want[i % 4]) + seqs = [(1, 1), MyTuple((1, 1)), (1,)] + want = [2, "mine", 1] + for i in range(3000): + self.assertEqual(seqs[i % 3].count(1), want[i % 3]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bigint_hash_str_powmod.py b/tests/regrtest/test_bigint_hash_str_powmod.py new file mode 100644 index 000000000..2594f12ab --- /dev/null +++ b/tests/regrtest/test_bigint_hash_str_powmod.py @@ -0,0 +1,59 @@ +"""`hash`, `str` and three-argument `pow` of big integers. + +`hash(n)` folds the magnitude's words modulo `2**61 - 1`, `str(n)` +converts in base `10**9` (larger values keep the general conversion), +and `pow(b, e, m)` takes machine words for a word-size modulus and +`modpow` for a larger one. Each is checked against its definition in +Python arithmetic, over signs and word boundaries. +""" + +import random + +P = 2**61 - 1 + + +def ref_hash(n): + h = abs(n) % P + if n < 0: + h = -h + return -2 if h == -1 else h + + +def ref_str(n): + if n == 0: + return "0" + s, neg, n = [], n < 0, abs(n) + while n: + n, d = divmod(n, 10**18) + s.append("%018d" % d if n else str(d)) + return ("-" if neg else "") + "".join(reversed(s)) + + +def ref_pow(b, e, m): + r, b2 = 1 % abs(m), b % abs(m) + while e: + if e & 1: + r = r * b2 % abs(m) + e >>= 1 + b2 = b2 * b2 % abs(m) + return r + m if m < 0 and r else r + + +rng = random.Random(3) +edge = [0, 1, -1, P - 1, P, P + 1, 2 * P, -P, 2**61, 2**63, -(2**63) - 1, 2**64, 2**64 - 1, 10**9, 10**18 - 1, 3**400 + 5] +for n in edge + [rng.getrandbits(rng.randint(60, 9000)) * rng.choice([1, -1]) for _ in range(300)]: + assert hash(n) == ref_hash(n), n + assert str(n) == ref_str(n), n + assert int(str(n)) == n +for _ in range(1500): + b = rng.getrandbits(rng.choice([1, 63, 64, 65, 300])) * rng.choice([1, -1]) + e = rng.getrandbits(rng.choice([0, 1, 7, 64, 70])) + m = (rng.getrandbits(rng.choice([1, 32, 63, 64, 65, 200])) or 1) * rng.choice([1, -1]) + assert pow(b, e, m) == ref_pow(b, e, m), (b, e, m) +assert pow(3, -1, 7) == 5 +try: + pow(2, -1, 4) +except ValueError: + pass +else: + raise AssertionError("no raise") diff --git a/tests/regrtest/test_binascii_leaf_calls.py b/tests/regrtest/test_binascii_leaf_calls.py new file mode 100644 index 000000000..a3b40ab9d --- /dev/null +++ b/tests/regrtest/test_binascii_leaf_calls.py @@ -0,0 +1,45 @@ +"""binascii's encoders and decoders called positionally from compiled +loops: bytes, bytearray and str inputs, a memoryview (the full call), bad +input's errors, crc32 with and without a start value, and base64's +wrappers, each matching CPython.""" + +import base64 +import binascii +import unittest + + +def run(n, f, *args): + out = None + for i in range(n): + out = f(*args) + return out + + +class BinasciiLeafTests(unittest.TestCase): + def test_round_trips(self): + for n in (1, 300): + self.assertEqual(run(n, binascii.b2a_base64, b"hello"), b"aGVsbG8=\n") + self.assertEqual(run(n, binascii.b2a_base64, bytearray(b"hi")), b"aGk=\n") + self.assertEqual(run(n, binascii.b2a_base64, memoryview(b"hi")), b"aGk=\n") + self.assertEqual(run(n, binascii.a2b_base64, b"aGVsbG8="), b"hello") + self.assertEqual(run(n, binascii.a2b_base64, "aGk="), b"hi") + self.assertEqual(run(n, binascii.unhexlify, "6869"), b"hi") + self.assertEqual(run(n, binascii.a2b_hex, b"6869"), b"hi") + self.assertEqual(run(n, binascii.crc32, b"abc"), 891568578) + self.assertEqual(run(n, binascii.crc32, b"abc", 1), binascii.crc32(b"abc", 1)) + self.assertEqual(run(n, base64.b64encode, b"hello"), b"aGVsbG8=") + self.assertEqual(run(n, base64.b64decode, b"aGVsbG8="), b"hello") + + def test_errors(self): + with self.assertRaises(binascii.Error): + run(300, binascii.unhexlify, "zz") + with self.assertRaises(binascii.Error): + run(300, binascii.a2b_base64, b"a") + with self.assertRaises(TypeError): + run(300, binascii.b2a_base64, "text") + with self.assertRaises(ValueError): + run(300, binascii.a2b_base64, "\\u00e9") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_binop_dispatch_direct.py b/tests/regrtest/test_binop_dispatch_direct.py new file mode 100644 index 000000000..988486cba --- /dev/null +++ b/tests/regrtest/test_binop_dispatch_direct.py @@ -0,0 +1,93 @@ +"""Binary operators reached outside compiled code (`sum()`, `functools.reduce`, +`operator.add`) on instances whose class defines both the forward and the +reflected method: two instances of one class run only the forward method +(its `NotImplemented` a TypeError, never the reflected one), a number on +the left runs the instance's reflected method, an instance over a scalar +runs its forward method, and the results, errors and methods replaced +later match the general operator.""" + +import functools +import operator +import unittest + + +class N: + calls = [] + + def __init__(self, v): + self.v = v + + def __add__(self, o): + N.calls.append("add") + if isinstance(o, N): + return N(self.v + o.v) + if isinstance(o, int): + return N(self.v + o) + return NotImplemented + + def __radd__(self, o): + N.calls.append("radd") + return N(self.v + o) + + def __sub__(self, o): + return NotImplemented + + def __rsub__(self, o): + N.calls.append("rsub") + return "rsub" + + +class BinopDispatchDirect(unittest.TestCase): + def test_sum_and_reduce(self): + objs = [N(i) for i in range(10)] + for i in range(500): + N.calls.clear() + r = sum(objs, 0) + self.assertEqual(r.v, 45) + self.assertEqual(N.calls[0], "radd") + self.assertEqual(N.calls[1:], ["add"] * 9) + self.assertEqual(functools.reduce(operator.add, objs).v, 45) + self.assertEqual(operator.add(N(1), 5).v, 6) + self.assertEqual(operator.add(5, N(1)).v, 6) + + def test_errors(self): + for i in range(500): + N.calls.clear() + with self.assertRaises(TypeError) as cm: + operator.sub(N(1), N(2)) + self.assertEqual(N.calls, []) + with self.assertRaises(TypeError) as am: + operator.add(N(1), "s") + self.assertEqual(str(cm.exception), "unsupported operand type(s) for -: 'N' and 'N'") + self.assertEqual(str(am.exception), "unsupported operand type(s) for +: 'N' and 'str'") + self.assertEqual(operator.sub(3, N(1)), "rsub") + + def test_builtin_subclass(self): + class Evil(int): + def __add__(self, other): + return NotImplemented + + e = Evil(5) + out = [] + for i in range(2000): + out.append((e + 1, operator.add(e, 1), sum([e, e], 0))) + self.assertEqual(out[-1], (6, 6, 10)) + with self.assertRaises(TypeError): + operator.add(e, e) + + def test_replaced(self): + class K: + def __add__(self, o): + return 1 + + out = [] + for i in range(1000): + out.append(operator.add(K(), K())) + K.__add__ = lambda self, o: 2 + for i in range(1000): + out.append(operator.add(K(), K())) + self.assertEqual((out.count(1), out.count(2)), (1000, 1000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bisect_native_steps.py b/tests/regrtest/test_bisect_native_steps.py new file mode 100644 index 000000000..992a6d8c5 --- /dev/null +++ b/tests/regrtest/test_bisect_native_steps.py @@ -0,0 +1,50 @@ +"""`bisect` over exact lists, the scalar comparisons made natively. + +Ints, floats and strings bisect in place; an item whose comparison needs +its `__lt__` continues through it from where the native steps stopped; +`lo`/`hi` past the list raise as CPython's, and `key=` takes the general +path. Run it past the compile threshold. +""" + +import bisect + + +class K: + calls = 0 + + def __init__(self, v): + self.v = v + + def __lt__(self, other): + K.calls += 1 + o = other.v if isinstance(other, K) else other + return self.v < o + + def __gt__(self, other): + K.calls += 1 + o = other.v if isinstance(other, K) else other + return self.v > o + + +ints = list(range(0, 200, 2)) +mixed = [0, 1.5, 2, 3.5, 4, 5.5] +words = sorted("alpha beta gamma delta epsilon zeta eta theta".split()) +objs = [K(i) for i in range(0, 50, 5)] +for i in range(3000): + assert bisect.bisect(ints, 51) == 26 and bisect.bisect_left(ints, 50) == 25 + assert bisect.bisect_right(ints, 50) == 26 + assert bisect.bisect(mixed, 3) == 3 and bisect.bisect_left(mixed, 2.0) == 2 + assert bisect.bisect(words, "gamma") == words.index("gamma") + 1 + assert bisect.bisect(ints, 51, 10, 40) == 26 and bisect.bisect(ints, -1, 3) == 3 + K.calls = 0 + assert bisect.bisect(objs, 22) == 5 and K.calls > 0 + assert bisect.bisect(ints, 7, key=lambda x: x // 2) == 8 + try: + bisect.bisect([1, 2], 5, 0, 10) + except IndexError: + pass + else: + raise AssertionError("no raise") + xs = [] + bisect.insort(xs, 3); bisect.insort(xs, 1); bisect.insort(xs, 2) + assert xs == [1, 2, 3] diff --git a/tests/regrtest/test_blind_except_arith.py b/tests/regrtest/test_blind_except_arith.py new file mode 100644 index 000000000..6f0e05600 --- /dev/null +++ b/tests/regrtest/test_blind_except_arith.py @@ -0,0 +1,176 @@ +"""`except` clauses whose bodies only do arithmetic on locals. + +A clause that never looks at its exception (`except KeyError: missed += 1`) +may run without the exception being built or pushed. Its arithmetic must +give the full operation's answer: ints that overflow into big ints, floats, +mixed operands, operands with their own `__iadd__`, strings, and locals +stored twice or returned from the clause, run long enough to compile. +""" + +import unittest + +N = 20000 + + +def count_misses(d, n): + missed = 0 + for i in range(n): + try: + d[i] + except KeyError: + missed += 1 + return missed + + +def overflow(start, n): + t = start + for i in range(n): + try: + raise ValueError + except ValueError: + t += 1 + return t + + +def products(n): + t = 1 + for i in range(n): + try: + raise ValueError + except ValueError: + t = t * 3 + return t + + +def floats(n): + t = 0.0 + for i in range(n): + try: + raise ValueError + except ValueError: + t += 0.5 + t -= 0.25 + return t + + +def mixed(n): + t = 0 + for i in range(n): + try: + raise ValueError + except ValueError: + t += 0.5 + return t + + +class Acc: + def __init__(self): + self.n = 0 + + def __iadd__(self, k): + self.n += k + return self + + +def own_iadd(n): + acc = Acc() + for i in range(n): + try: + raise ValueError + except ValueError: + acc += 2 + return acc.n + + +def strings(n): + s = "" + for i in range(n): + try: + raise ValueError + except ValueError: + s += "x" + return len(s) + + +def twice(n): + a = 0 + b = 0 + for i in range(n): + try: + raise ValueError + except ValueError: + a += 1 + b = a + a = a + b + b = 1 - b + return a, b + + +def returning(d, k, base): + try: + return d[k] + except KeyError: + return base * 2 - 1 + + +def unmatched(n): + t = 0 + for i in range(n): + try: + try: + raise IndexError + except KeyError: + t += 100 + except IndexError: + t -= 1 + return t + + +class BlindArithmeticTests(unittest.TestCase): + def test_count(self): + d = {i: i for i in range(0, N, 4)} + self.assertEqual(count_misses(d, N), N - len(d)) + + def test_overflow_to_big_int(self): + start = 2**63 - N // 2 + self.assertEqual(overflow(start, N), start + N) + self.assertEqual(overflow(-(2**63), N), -(2**63) + N) + + def test_products_grow(self): + self.assertEqual(products(200), 3**200) + self.assertEqual(products(N) % 1000003, pow(3, N, 1000003)) + + def test_floats(self): + self.assertEqual(floats(N), N * 0.25) + + def test_mixed_int_float(self): + r = mixed(N) + self.assertIs(type(r), float) + self.assertEqual(r, N * 0.5) + + def test_own_iadd(self): + self.assertEqual(own_iadd(N), 2 * N) + + def test_strings(self): + self.assertEqual(strings(N), N) + + def test_stored_twice(self): + a = b = 0 + for _ in range(N): + a += 1 + b = a + a = a + b + b = 1 - b + self.assertEqual(twice(N), (a, b)) + + def test_returning(self): + d = {0: 7} + for i in range(N): + self.assertEqual(returning(d, i % 3, i), 7 if i % 3 == 0 else 2 * i - 1) + + def test_unmatched_clause_skipped(self): + self.assertEqual(unmatched(N), -N) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_blind_except_clauses.py b/tests/regrtest/test_blind_except_clauses.py new file mode 100644 index 000000000..aa29bf67b --- /dev/null +++ b/tests/regrtest/test_blind_except_clauses.py @@ -0,0 +1,1207 @@ +"""An `except` clause that can't observe the exception it catches. + +A clause that names its classes by global (or is bare), doesn't bind the +exception and only moves constants and locals (`pass`, `x = default`, +`continue`, `return -1`) is run without the exception being pushed, +matched or popped, and for a missing dict key, an index out of range or a +missing attribute without the exception being built at all. Nothing may +tell: these cases cover what the clause's body, finalizers, tracebacks, +`sys.exception()`, tracing, rebinding the class's name, and raising +callees could observe. + +The checks run at import, in the order written (several watch when objects +die), and their printed results are compared with CPython's, kept at the +end of the file: rerun with `--emit` under CPython to refresh them.""" + +import builtins +import unittest + +_lines = [] + + +def print(*args): + _lines.append(" ".join(str(a) for a in args)) + + +import sys, gc, weakref + +N = 3000 +log = [] + +def tb_names(e): + out = [] + tb = e.__traceback__ + while tb is not None: + out.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + return tuple(out) + +class Noisy: + def __init__(self, tag): + self.tag = tag + def __del__(self): + log.append(("del", self.tag, type(sys.exception()).__name__)) + +# ---- the plain shapes ------------------------------------------------------ + +def get_pass(d, k): + try: + return d[k] + except KeyError: + pass + return "miss" + +def get_assign(d, k, default): + try: + x = d[k] + except KeyError: + x = default + return x + +def get_const(d, k): + try: + x = d[k] + except KeyError: + x = 0 + return x + +def get_return(d, k): + try: + return d[k] + except KeyError: + return None + +def get_return_neg(d, k): + try: + return d[k] + except KeyError: + return -1 + +def get_return_local(d, k, default): + try: + return d[k] + except KeyError: + return default + +def get_bare(d, k): + try: + return d[k] + except: + return "bare" + +def get_exception(d, k): + try: + return d[k] + except Exception: + return "exc" + +def get_lookup(d, k): + try: + return d[k] + except LookupError: + return "lookup" + +def get_tuple(c, k): + try: + return c[k] + except (KeyError, IndexError): + return "either" + +def get_wrong(d, k): + try: + return d[k] + except ValueError: + return "wrong" + +def get_second(d, k): + try: + return d[k] + except ValueError: + return "first" + except KeyError: + return "second" + +def get_named(d, k): + try: + return d[k] + except KeyError as e: + return "named" + +def get_named_used(d, k): + try: + return d[k] + except KeyError as e: + return e.args + +def loop_continue(d, ks): + n = 0 + for k in ks: + try: + v = d[k] + except KeyError: + continue + n += v + return n + +def loop_break(d, ks): + n = 0 + for k in ks: + try: + v = d[k] + except KeyError: + break + n += v + return n + +def loop_else_finally(d, ks): + out = [] + for k in ks: + try: + v = d[k] + except KeyError: + v = -1 + else: + v += 100 + finally: + out.append(k) + out.append(v) + return out + +def index_pass(xs, i): + try: + return xs[i] + except IndexError: + pass + return "miss" + +def plain(): + d = {"a": 1, 2: 3} + xs = [10, 20] + shapes = set() + for i in range(N): + shapes.add(( + get_pass(d, "a"), get_pass(d, "b"), get_assign(d, "b", 7), get_assign(d, "a", 7), + get_const(d, "zz"), get_return(d, "zz"), get_return_neg(d, 5), get_return_local(d, 5, "dflt"), + get_bare(d, "q"), get_exception(d, "q"), get_lookup(d, "q"), get_tuple(d, "q"), + get_tuple(xs, 9), get_tuple(xs, 1), get_second(d, "q"), get_named(d, "q"), + get_named_used(d, "q"), loop_continue(d, ["a", "b", 2, "c"]), loop_break(d, ["a", "b", 2]), + tuple(loop_else_finally(d, ["a", "b"])), index_pass(xs, 5), index_pass(xs, -3), + index_pass((1, 2), 2), index_pass("ab", 2), index_pass(xs, 0), + sys.exception(), + )) + try: + get_wrong(d, "q") + except KeyError as e: + shapes.add(("wrong", e.args, tb_names(e))) + for s in sorted(shapes, key=repr): + print("plain", s) +plain() + +# ---- what a handler's body may observe ------------------------------------- + +def overwrite_finalized(d, k): + x = Noisy("local") + try: + x = d[k] + except KeyError: + x = None + log.append(("after", type(sys.exception()).__name__)) + return x + +def overwrite_shared(d, k, keep): + x = keep + try: + x = d[k] + except KeyError: + x = None + return x + +def unbound_read(d, k): + try: + x = d[k] + except KeyError: + x = y + y = 1 + return x + +def finalizers(): + d = {} + shapes = set() + keep = Noisy("kept") + for i in range(N): + del log[:] + overwrite_finalized(d, "k") + shapes.add(tuple(log)) + del log[:] + overwrite_shared(d, "k", keep) + shapes.add(tuple(log)) + try: + unbound_read(d, "k") + except UnboundLocalError as e: + shapes.add(("unbound", type(e.__context__).__name__, e.__context__.args, tb_names(e))) + del log[:] + for s in sorted(shapes, key=repr): + print("finalizers", s) +finalizers() + +# ---- exceptions with a life of their own ------------------------------------ + +class Loud(Exception): + def __del__(self): + log.append(("loud dies", self.args, type(sys.exception()).__name__)) + +class Counted(Exception): + made = 0 + def __init__(self, *args): + Counted.made += 1 + super().__init__(*args) + +def raise_loud(i): + local = Noisy("callee local") + raise Loud(i & 1) + +def catch_loud(i): + x = 0 + try: + raise_loud(i) + except Loud: + x = 5 + log.append(("past", x)) + +def catch_inline(i): + try: + raise Loud(i & 1) + except Loud: + pass + log.append("past inline") + +def catch_counted(): + try: + raise Counted(1) + except Counted: + pass + +STORED = KeyError("stored") + +def catch_stored(): + try: + raise STORED + except KeyError: + pass + +REFS = [] + +class Weak(Exception): + def __init__(self): + REFS.append(weakref.ref(self)) + +def catch_weak(refs): + try: + raise Weak() + except Weak: + pass + return REFS[-1]() is None + +def lives(): + shapes = set() + refs = [] + for i in range(N): + del log[:] + catch_loud(i) + shapes.add(("callee", tuple(log))) + del log[:] + catch_inline(i) + shapes.add(("inline", tuple(log))) + catch_counted() + catch_stored() + if i < 50: + shapes.add(("weak", catch_weak(refs))) + del log[:] + n = 0 + tb = STORED.__traceback__ + while tb is not None: + n += 1 + tb = tb.tb_next + print("counted", Counted.made, "stored tb", n, STORED.__context__) + for s in sorted(shapes, key=repr): + print("lives", s) +lives() + +# ---- handlers inside handlers ------------------------------------------------ + +def nested(d): + out = [] + try: + raise ValueError("outer") + except ValueError as outer: + try: + d["k"] + except KeyError: + pass + out.append(sys.exception() is outer) + try: + d["k"] + except KeyError: + out.append(type(sys.exception()).__name__) + out.append(sys.exception() is outer) + try: + try: + d["k"] + except KeyError: + pass + raise TypeError("inner") + except TypeError as inner: + out.append((type(inner.__context__).__name__, inner.__context__ is outer)) + out.append(sys.exception()) + return out + +def both_blind(d, xs): + try: + try: + return d["k"] + except IndexError: + return "inner" + except KeyError: + return "outer" + +def blind_in_gen(d, ks): + for k in ks: + try: + yield d[k] + except KeyError: + yield "miss" + try: + v = d[k] + except KeyError: + v = None + yield v + +def nests(): + d = {"a": 1} + shapes = set() + for i in range(N): + shapes.add(repr(nested(d))) + shapes.add(both_blind(d, [])) + shapes.add(tuple(blind_in_gen(d, ["a", "b"]))) + for s in sorted(shapes, key=repr): + print("nests", s) +nests() + +# ---- names that move --------------------------------------------------------- + +def by_global(d): + try: + return d["k"] + except Target: + return "caught" + +Target = KeyError + +def moving(): + global Target + d = {} + out = [] + def note(i, r): + if not out or out[-1][1] != r: + out.append((i, r)) + for i in range(N): + if i == N // 3: + Target = ValueError + if i == N // 3 + 50: + Target = (ValueError, LookupError) + if i == N // 3 + 100: + Target = 5 + if i == N // 3 + 150: + Target = (KeyError, 5) + if i == N // 3 + 200: + Target = KeyError + try: + r = by_global(d) + except KeyError: + r = "escaped" + except TypeError as e: + r = "TypeError: " + str(e) + note(i, r) + print("moving", out) +moving() + +def shadow_builtin(): + import builtins + d = {} + out = [] + saved = builtins.KeyError + for i in range(N): + if i == N // 2: + builtins.KeyError = ValueError + if i == N // 2 + 50: + builtins.KeyError = saved + try: + r = get_pass(d, "k") + except saved: + r = "escaped" + if not out or out[-1][1] != r: + out.append((i, r)) + builtins.KeyError = saved + print("shadow", out) +shadow_builtin() + +# ---- other raisers ----------------------------------------------------------- + +class Missing(dict): + def __missing__(self, key): + raise KeyError("from missing " + key) + +class Getter: + def __getitem__(self, key): + raise KeyError(key) + def __getattr__(self, name): + raise AttributeError(name) + +def attr_pass(o): + try: + return o.nothing + except AttributeError: + pass + return "no attr" + +def next_pass(it): + try: + return next(it) + except StopIteration: + return "done" + +def int_pass(s): + try: + return int(s) + except ValueError: + return "bad" + +def pop_pass(xs): + try: + return xs.pop() + except IndexError: + return "empty" + +def div_pass(a, b): + try: + return a // b + except ZeroDivisionError: + return "zero" + +def call_pass(f): + try: + return f() + except TypeError: + return "type" + +def unpack_pass(xs): + try: + a, b = xs + except ValueError: + a = b = None + return a, b + +class Plain: + pass + +def others(): + shapes = set() + g = Getter() + for i in range(N): + shapes.add(( + get_pass(Missing(), "k"), get_pass(g, "k"), attr_pass(g), attr_pass(Plain()), + attr_pass(5), next_pass(iter(())), next_pass(iter([4])), int_pass("x"), int_pass("12"), + pop_pass([]), pop_pass([1]), div_pass(1, 0), div_pass(7, 2), call_pass(lambda x: x), + unpack_pass([1]), unpack_pass([1, 2]), get_tuple({}, "a"), get_exception([], 3), + )) + for s in sorted(shapes, key=repr): + print("others", s) +others() + +# ---- observers --------------------------------------------------------------- + +def traced(): + events = [] + def tracer(frame, event, arg): + if frame.f_code.co_name == "get_pass": + events.append((event, frame.f_lineno - frame.f_code.co_firstlineno)) + return tracer + d = {} + for i in range(N): + get_pass(d, "k") + sys.settrace(tracer) + get_pass(d, "k") + sys.settrace(None) + for i in range(N): + get_pass(d, "k") + print("traced", events) +traced() + +def frames(): + d = {} + shapes = set() + def probe(): + try: + d["k"] + except KeyError: + pass + f = sys._getframe() + return f.f_lineno - f.f_code.co_firstlineno, sorted(f.f_locals), sys.exception() + for i in range(N): + shapes.add(repr(probe())) + print("frames", sorted(shapes)) +frames() + +def stack_items(d, seqs): + out = [] + try: + for s in seqs: + for k in s: + out.append(d[k]) + except KeyError: + pass + return out + +def gen_on_stack(d): + def g(): + try: + yield "a" + yield "b" + finally: + log.append("gen closed") + try: + for k in g(): + d[k] + except KeyError: + pass + log.append("after") + +def stacks(): + d = {"a": 1} + shapes = set() + for i in range(N): + shapes.add(tuple(stack_items(d, [["a"], ["a", "b", "a"]]))) + del log[:] + gen_on_stack(d) + shapes.add(tuple(log)) + del log[:] + for s in sorted(shapes, key=repr): + print("stacks", s) +stacks() + +# ---- raising callees under a blind clause ----------------------------------- + +class Stop(Exception): + pass + +class StopLoud(Exception): + def __del__(self): + log.append(("stoploud dies", type(sys.exception()).__name__)) + +def fail(x): + raise Stop(x) + +def fail_with_locals(tag): + a = Noisy(tag + " a") + b = Noisy(tag + " b") + raise StopLoud(tag) + +def fail_arg(n): + raise Stop + +def fail_deep(n): + if n == 0: + raise Stop(n) + return fail_deep(n - 1) + +def fail_finally(x): + try: + raise Stop(x) + finally: + log.append("finally") + +def fail_varargs(*args, **kw): + raise Stop(args) + +def fail_closure(x): + def inner(): + raise Stop(x) + return inner() + +KEPT = Stop("kept") + +def fail_kept(): + raise KEPT + +class Thing: + def __init__(self, bad=False): + if bad: + raise Stop("init") + def method(self, x): + raise Stop(x) + @property + def prop(self): + raise Stop("prop") + def __eq__(self, other): + raise Stop("eq") + __hash__ = None + +def call_pass(f, *args): + x = "before" + try: + f(*args) + except Stop: + x = "caught" + return x + +def call_direct(x): + r = 0 + try: + fail(x) + except Stop: + r = 1 + try: + fail_arg(Noisy("arg")) + except Stop: + r += 2 + log.append("between") + try: + fail_with_locals("w") + except StopLoud: + r += 4 + log.append("after loud") + try: + fail_deep(3) + except Stop: + r += 8 + try: + fail_finally(x) + except Stop: + r += 16 + try: + fail_varargs(1, 2, k=3) + except Stop: + r += 32 + try: + fail_closure(x) + except Stop: + r += 64 + try: + fail_kept() + except Stop: + r += 128 + return r + +def call_methods(t): + r = [] + try: + t.method(1) + except Stop: + r.append("method") + try: + t.prop + except Stop: + r.append("prop") + try: + t == 1 + except Stop: + r.append("eq") + try: + Thing(True) + except Stop: + r.append("init") + try: + Thing.method(t, 2) + except (Stop, TypeError): + r.append("unbound") + try: + fail(x=5) + except Stop: + r.append("kw") + return r + +def call_in_loop(n): + total = 0 + for i in range(n): + try: + fail(i) + except Stop: + continue + total += 1 + return total + +def call_returns(x): + try: + return fail(x) + except Stop: + return -1 + +def call_gen(n): + for i in range(n): + try: + fail(i) + except Stop: + pass + yield i + +def call_wrong(x): + try: + fail(x) + except KeyError: + return "wrong" + +def callees(): + shapes = set() + t = Thing() + for i in range(N): + del log[:] + r = call_direct(i & 3) + shapes.add((r, tuple(log))) + del log[:] + shapes.add(tuple(call_methods(t))) + shapes.add((call_pass(fail, 1), call_pass(len, ()), call_in_loop(3), call_returns(i & 1), + tuple(call_gen(2)), sys.exception())) + try: + call_wrong(1) + except Stop as e: + shapes.add(("wrong", e.args, tb_names(e))) + n = 0 + tb = KEPT.__traceback__ + while tb is not None: + n += 1 + tb = tb.tb_next + print("kept tb", n) + for s in sorted(shapes, key=repr): + print("callees", s) +callees() + +# ---- attribute misses --------------------------------------------------------- + +class Slotted: + __slots__ = ("a", "b") + +class Holder: + def __init__(self): + self.o = Plain() + self.s = Slotted() + +class Hooked: + def __getattr__(self, name): + if name == "yes": + return 1 + raise AttributeError(name) + +def attr_local(o): + try: + v = o.nothing + except AttributeError: + v = "miss" + return v + +def attr_chain(h): + try: + return h.o.nothing + except AttributeError: + return "chain miss" + +def attr_slot(h): + try: + return h.s.a + except AttributeError: + return "slot miss" + +def attr_temp_blind(): + x = 0 + try: + x = Noisy("temp").nothing + except AttributeError: + x = 1 + log.append(("x", x)) + return x + +def attr_deep(o, xs): + try: + return [1, xs, o.nothing] + except AttributeError: + return "deep miss" + +def attr_wrong(o): + try: + return o.nothing + except KeyError: + return "wrong" + +def attr_method(o): + try: + return o.nothing() + except AttributeError: + return "method miss" + +def attrs(): + shapes = set() + h = Holder() + p = Plain() + for i in range(N): + if i == N // 2: + p.nothing = "found" + h.o.nothing = "found too" + h.s.a = 3 + del log[:] + shapes.add((attr_local(p), attr_chain(h), attr_slot(h), attr_temp_blind(), attr_deep(Plain(), [2]), + attr_local(Hooked()), attr_local(5), attr_local(None), attr_method(Plain()), + attr_local(Slotted()), tuple(log), sys.exception())) + try: + attr_wrong(Plain()) + except AttributeError as e: + shapes.add(("wrong", e.args, e.name, type(e.obj).__name__, tb_names(e))) + for s in sorted(shapes, key=repr): + print("attrs", s) +attrs() + +# ---- raises with operands under them ------------------------------------------ + +def ident(*args): + return args + +def depth_list(d, o, xs): + try: + return [1, xs, d["k"], o] + except KeyError: + return "list" + +def depth_tuple(d, o, xs): + try: + return (xs, o, 2.5, xs[5]) + except IndexError: + return "tuple" + +def depth_binop(d, a): + try: + return a + a * d["k"] + except KeyError: + return "binop" + +def depth_call(d, o): + try: + return ident(1, o, d["k"], o.nothing) + except KeyError: + return "call key" + except AttributeError: + return "call attr" + +class Tagged: + def __del__(self): + log.append("operand dies") + +def depth_call_attr(d, o): + try: + return ident(Tagged(), o, o.nothing) + except AttributeError: + return "call attr" + +def depth_loops(d, rows): + n = 0 + for row in rows: + for k in row: + try: + n += d[k] + len(row) + except KeyError: + n -= 1 + return n + +def depth_comp(d, ks): + try: + return [d[k] for k in ks] + except KeyError: + return "comp" + +def depth_with(d): + class CM: + def __enter__(self): + return self + def __exit__(self, *exc): + log.append(("exit", exc[0].__name__ if exc[0] else None)) + return False + try: + with CM(): + d["k"] + except KeyError: + pass + return "with" + +def depth_fstring(d, o): + try: + return f"{o!r:>4}{d['k']}" + except KeyError: + return "fstring" + +def depths(): + shapes = set() + d = {"a": 1} + o = Plain() + xs = [1, 2] + for i in range(N): + del log[:] + shapes.add((depth_list(d, o, xs), depth_tuple(d, o, xs), depth_binop(d, 3), depth_call(d, o), + depth_call(d, 5), depth_call_attr(d, o), depth_loops(d, [["a", "b"], ["c", "a", "a"]]), + depth_comp(d, "ab"), depth_comp(d, "aa") == [1, 1], depth_with(d), depth_fstring(d, 7), + tuple(log), sys.exception())) + del log[:] + for s in sorted(shapes, key=repr): + print("depths", s) +depths() + +# ---- raise statements under a blind clause -------------------------------------- + +def raise_class(): + try: + raise KeyError + except KeyError: + return "class" + +def raise_inst(x): + try: + raise ValueError(x) + except ValueError: + return "inst" + +def raise_from(x): + try: + raise ValueError(x) from None + except ValueError: + return "from" + +def raise_kept(e): + try: + raise e + except ValueError: + return "kept" + +def raise_wrong(): + try: + raise KeyError + except ValueError: + return "wrong" + +def raise_base(): + try: + raise StopIteration + except Exception: + return "base" + +def raise_loud(): + x = 0 + try: + raise Loud("s") + except Loud: + x = 1 + log.append(("x", x)) + return x + +def raise_user_class(): + try: + raise Stop + except Stop: + return "user class" + +def raise_counted(): + try: + raise Counted + except Counted: + return "counted" + +def raise_group(): + try: + raise ExceptionGroup("g", [ValueError(1)]) + except ExceptionGroup: + return "group" + +def raise_in_loop(n): + t = 0 + for i in range(n): + try: + raise IndexError + except IndexError: + continue + t += 1 + return t + +def raise_nonexc(): + try: + raise 5 + except TypeError: + return "nonexc" + +def raise_in_handler(): + try: + raise ValueError("outer") + except ValueError as outer: + try: + raise KeyError + except KeyError: + pass + return sys.exception() is outer + +def raises(): + shapes = set() + kept = ValueError("kept") + before = Counted.made + for i in range(N): + del log[:] + shapes.add((raise_class(), raise_inst(i & 1), raise_from(1), raise_kept(kept), raise_base(), + raise_loud(), raise_user_class(), raise_counted(), raise_group(), raise_in_loop(3), + raise_nonexc(), raise_in_handler(), tuple(log), sys.exception())) + try: + raise_wrong() + except KeyError as e: + shapes.add(("wrong", e.args, tb_names(e))) + del log[:] + n = 0 + tb = kept.__traceback__ + while tb is not None: + n += 1 + tb = tb.tb_next + print("raises kept tb", n, kept.__context__, "counted", Counted.made - before) + for s in sorted(shapes, key=repr): + print("raises", s) +raises() + +# ---- classes named by closure variables and locals ----------------------------- + +def closures(): + class Inner(Exception): + pass + + Moving = KeyError + default = "from cell" + + def thrower(n): + if n: + raise Inner(n) + return 0 + + def by_cell(n): + try: + return thrower(n) + except Inner: + return default + + def by_moving_cell(d): + try: + return d["k"] + except Moving: + return "moving" + + def by_local(d, cls): + try: + return d["k"] + except cls: + return "local" + + def by_pair(d, cls): + try: + return d["k"] + except (cls, Inner): + return "pair" + + def by_unbound(d): + try: + return d["k"] + except Later: + return "later" + + out = [] + d = {} + for i in range(N): + if i == N // 2: + Moving = ValueError + if i == N // 2 + 50: + Moving = (ValueError, LookupError) + if i == N // 2 + 100: + default = "rebound" + try: + m = by_moving_cell(d) + except KeyError: + m = "escaped" + try: + u = by_unbound(d) + except NameError as e: + u = type(e.__context__).__name__ + try: + w = by_local(d, IndexError) + except KeyError: + w = "local escaped" + try: + x = by_local(d, 3) + except TypeError: + x = "local TypeError" + r = (by_cell(1), by_cell(0), m, u, by_local(d, KeyError), w, x, by_pair(d, LookupError), + sys.exception()) + if not out or out[-1][1] != r: + out.append((i, r)) + Later = KeyError + out.append(by_unbound(d)) + for s in out: + print("closures", s) +closures() +gc.collect() +print("done") + + +EXPECTED = r""" +plain ('wrong', ('q',), ('plain', 'get_wrong')) +plain (1, 'miss', 7, 1, 0, None, -1, 'dflt', 'bare', 'exc', 'lookup', 'either', 'either', 20, 'second', 'named', ('q',), 4, 1, ('a', 101, 'b', -1), 'miss', 'miss', 'miss', 'miss', 10, None) +finalizers ('unbound', 'KeyError', ('k',), ('finalizers', 'unbound_read')) +finalizers (('del', 'local', 'KeyError'), ('after', 'NoneType')) +finalizers () +counted 3000 stored tb 3000 None +lives ('callee', (('loud dies', (0,), 'NoneType'), ('del', 'callee local', 'NoneType'), ('past', 5))) +lives ('callee', (('loud dies', (1,), 'NoneType'), ('del', 'callee local', 'NoneType'), ('past', 5))) +lives ('inline', (('loud dies', (0,), 'NoneType'), 'past inline')) +lives ('inline', (('loud dies', (1,), 'NoneType'), 'past inline')) +lives ('weak', True) +nests [True, 'KeyError', True, ('ValueError', True), None] +nests outer +nests (1, 1, 'miss', None) +moving [(0, 'caught'), (1000, 'escaped'), (1050, 'caught'), (1100, 'TypeError: catching classes that do not inherit from BaseException is not allowed'), (1200, 'caught')] +shadow [(0, 'miss'), (1500, 'escaped'), (1550, 'miss')] +others ('miss', 'miss', 'no attr', 'no attr', 'no attr', 'done', 4, 'bad', 12, 'empty', 1, 'zero', 3, 'type', (None, None), (1, 2), 'either', 'exc') +traced [('call', 0), ('line', 1), ('line', 2), ('exception', 2), ('line', 3), ('line', 4), ('line', 5), ('return', 5)] +frames ["(6, ['d', 'f'], None)"] +stacks ('gen closed', 'after') +stacks (1, 1) +kept tb 6000 +callees ('caught', 'before', 0, -1, (0, 1), None) +callees ('method', 'prop', 'eq', 'init', 'unbound', 'kw') +callees ('wrong', (1,), ('callees', 'call_wrong', 'fail')) +callees (255, (('del', 'arg', 'NoneType'), 'between', ('stoploud dies', 'NoneType'), ('del', 'w b', 'NoneType'), ('del', 'w a', 'NoneType'), 'after loud', 'finally')) +attrs ('found', 'found too', 3, 1, 'deep miss', 'miss', 'miss', 'miss', 'method miss', 'miss', (('del', 'temp', 'NoneType'), ('x', 1)), None) +attrs ('miss', 'chain miss', 'slot miss', 1, 'deep miss', 'miss', 'miss', 'miss', 'method miss', 'miss', (('del', 'temp', 'NoneType'), ('x', 1)), None) +attrs ('wrong', ("'Plain' object has no attribute 'nothing'",), 'nothing', 'Plain', ('attrs', 'attr_wrong')) +depths ('list', 'tuple', 'binop', 'call key', 'call key', 'call attr', 9, 'comp', True, 'with', 'fstring', ('operand dies', ('exit', 'KeyError')), None) +raises kept tb 3000 None counted 3000 +raises ('class', 'inst', 'from', 'kept', 'base', 1, 'user class', 'counted', 'group', 0, 'nonexc', True, (('loud dies', ('s',), 'NoneType'), ('x', 1)), None) +raises ('wrong', (), ('raises', 'raise_wrong')) +closures (0, ('from cell', 0, 'moving', 'KeyError', 'local', 'local escaped', 'local TypeError', 'pair', None)) +closures (1500, ('from cell', 0, 'escaped', 'KeyError', 'local', 'local escaped', 'local TypeError', 'pair', None)) +closures (1550, ('from cell', 0, 'moving', 'KeyError', 'local', 'local escaped', 'local TypeError', 'pair', None)) +closures (1600, ('rebound', 0, 'moving', 'KeyError', 'local', 'local escaped', 'local TypeError', 'pair', None)) +closures later +done +""" + + +class OutputTest(unittest.TestCase): + maxDiff = None + + def test_output(self): + self.assertEqual(_lines, EXPECTED.splitlines()[1:]) + + +if __name__ == "__main__": + import sys as _sys + + if "--emit" in _sys.argv: + builtins.print("\n".join(_lines)) + else: + unittest.main() diff --git a/tests/regrtest/test_bool_clear_fromkeys_str_collect.py b/tests/regrtest/test_bool_clear_fromkeys_str_collect.py new file mode 100644 index 000000000..2babfe455 --- /dev/null +++ b/tests/regrtest/test_bool_clear_fromkeys_str_collect.py @@ -0,0 +1,87 @@ +"""bool() of plain values and containers (its constructor arm first), +list()/set()/frozenset()/tuple() of a str's characters collected +directly, container constructors from lists and tuples, list.clear +as a leaf over plain items, and dict.fromkeys over a short range, from +compiled loops: results for empty and non-empty values, non-ASCII and +astral characters, a list of instances cleared (the full path, their +finalizers running), ranges with steps, long ranges, and dict subclasses, +each matching CPython.""" + +import unittest + + +class Fin: + count = 0 + + def __del__(self): + Fin.count += 1 + + +class D(dict): + pass + + +class BuiltinBatchTests(unittest.TestCase): + def test_bool(self): + vals = [0, 1, 0.0, 2.5, "", "a", b"", None, (), (1,), [], [0], {}, {1: 2}, set(), {1}] + for i in range(300): + r = [bool(v) for v in vals] + self.assertEqual(r, [bool(v) for v in vals]) + self.assertEqual(r[:6], [False, True, False, True, False, True]) + self.assertIs(bool(frozenset()), False) + + def test_str_collect(self): + for i in range(300): + a = list("hello") + b = set("hello") + c = tuple("hé\U0001f600") + d = list("") + self.assertEqual(a, ["h", "e", "l", "l", "o"]) + self.assertEqual(b, {"h", "e", "l", "o"}) + self.assertEqual(c, ("h", "é", "\U0001f600")) + self.assertEqual(d, []) + self.assertIs(a[2], a[3]) + for i in range(300): + e = frozenset("abca") + f = set("x" * 100) + g = dict([("a", 1), ("b", 2)]) + h = list((1, 2)) + t = tuple([3, 4]) + self.assertEqual((e, f), (frozenset("abc"), {"x"})) + self.assertIs(type(e), frozenset) + self.assertEqual((g, h, t), ({"a": 1, "b": 2}, [1, 2], (3, 4))) + + def test_clear(self): + for i in range(300): + xs = [1, "a", 2.5, None, b"x"] + xs.clear() + self.assertEqual(xs, []) + Fin.count = 0 + for i in range(300): + ys = [Fin(), Fin()] + ys.clear() + self.assertEqual(Fin.count, 600) + it = iter([1, 2, 3]) + zs = [1, 2, 3] + it = iter(zs) + next(it) + zs.clear() + self.assertEqual(list(it), []) + + def test_fromkeys_range(self): + for i in range(300): + a = dict.fromkeys(range(5)) + b = dict.fromkeys(range(10, 0, -3), 0) + c = dict.fromkeys(range(100)) + d = D.fromkeys(range(3), "x") + self.assertEqual(a, {0: None, 1: None, 2: None, 3: None, 4: None}) + self.assertEqual(list(b), [10, 7, 4, 1]) + self.assertEqual(len(c), 100) + self.assertIs(type(d), D) + self.assertEqual(d, {0: "x", 1: "x", 2: "x"}) + self.assertEqual(dict.fromkeys(range(0)), {}) + self.assertEqual(list(dict.fromkeys(range(2**62, 2**62 + 2))), [2**62, 2**62 + 1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_buffer_copies_and_extends.py b/tests/regrtest/test_buffer_copies_and_extends.py new file mode 100644 index 000000000..532700cb9 --- /dev/null +++ b/tests/regrtest/test_buffer_copies_and_extends.py @@ -0,0 +1,65 @@ +"""`memoryview.tobytes`, strided gathers, and `bytearray.extend` of ints. + +A contiguous view's bytes are copied once into the result; a strided +one-dimensional view is gathered in one read of the buffer; a list or +tuple of ints in `range(256)` extends a bytearray natively, with every +other item still converted or refused as the full method does. +""" + +import unittest + + +class ToBytesTests(unittest.TestCase): + def test_contiguous_and_strided(self): + b = bytearray(range(256)) * 4 + mv = memoryview(b) + for _ in range(50): + self.assertEqual(mv.tobytes(), bytes(b)) + self.assertEqual(mv[::2].tobytes(), bytes(b[::2])) + self.assertEqual(mv[::-1].tobytes(), bytes(b[::-1])) + self.assertEqual(mv[10:100:7].tobytes(), bytes(b[10:100:7])) + self.assertEqual(mv[5:5].tobytes(), b"") + ints = mv.cast("I") + self.assertEqual(ints[::2].tobytes(), b"".join(ints[i:i + 1].tobytes() for i in range(0, len(ints), 2))) + self.assertEqual(mv.cast("H")[::-1].tolist()[:2], [0xFFFE, 0xFDFC]) + + def test_orders(self): + mv = memoryview(bytes(range(12))).cast("B", shape=[3, 4]) + self.assertEqual(mv.tobytes(), bytes(range(12))) + self.assertEqual(mv.tobytes("F"), bytes([0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11])) + with self.assertRaises(ValueError): + mv.tobytes("X") + + +class ExtendTests(unittest.TestCase): + def test_values(self): + cases = [([1, 2, 3], b"ab\x01\x02\x03"), ((4, 5), b"ab\x04\x05"), ([], b"ab"), ([255, 0], b"ab\xff\x00"), + ([True, 2], b"ab\x01\x02"), (range(3), b"ab\x00\x01\x02"), (b"xy", b"abxy")] + for _ in range(100): + for data, want in cases: + b = bytearray(b"ab") + b.extend(data) + self.assertEqual(b, want) + b = bytearray(b"ab") + b.extend(iter([7, 8])) + self.assertEqual(b, b"ab\x07\x08") + + def test_errors_leave_it_unchanged(self): + for data, exc in (([256], ValueError), ([-1], ValueError), ([1, "x"], TypeError), ([1.0], TypeError)): + b = bytearray(b"ab") + with self.assertRaises(exc): + b.extend(data) + self.assertEqual(b, b"ab") + + def test_exported(self): + b = bytearray(b"q") + v = memoryview(b) + with self.assertRaises(BufferError): + b.extend([1]) + v.release() + b.extend([1]) + self.assertEqual(b, b"q\x01") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_buffer_reads_for_ints_and_arrays.py b/tests/regrtest/test_buffer_reads_for_ints_and_arrays.py new file mode 100644 index 000000000..8e5d18169 --- /dev/null +++ b/tests/regrtest/test_buffer_reads_for_ints_and_arrays.py @@ -0,0 +1,103 @@ +"""Buffers read in place by `int.from_bytes`, `struct.iter_unpack` and +`array.fromlist`. + +`int.from_bytes` of a short bytearray or memoryview reads its bytes in +place; `struct.iter_unpack` reads its iterator's state at the class's slot +places and takes a `bytes` subclass's buffer through a view; `array` +checks a list's item types natively before packing it whole. Each must +answer as the general path does. +""" + +import array +import struct +import unittest + + +class FromBytesTests(unittest.TestCase): + def test_buffers(self): + data = bytes(range(1, 9)) + views = [data, bytearray(data), memoryview(data), memoryview(bytearray(data))] + for _ in range(500): + for v in views: + for n in range(0, 9): + for order in ("little", "big"): + self.assertEqual(int.from_bytes(v[:n], order), int.from_bytes(bytes(v[:n]), order)) + self.assertEqual(int.from_bytes(memoryview(data)[::2], "little"), int.from_bytes(data[::2], "little")) + self.assertEqual(int.from_bytes(bytearray(b"\x01\x02")), 258) + + def test_released_and_signed(self): + m = memoryview(b"\x01\x02") + m.release() + with self.assertRaises(ValueError): + int.from_bytes(m, "little") + self.assertEqual(int.from_bytes(bytearray(b"\xff"), "little", signed=True), -1) + + class Sub(int): + pass + + self.assertIs(type(Sub.from_bytes(memoryview(b"\x05"), "little")), Sub) + + +class IterUnpackTests(unittest.TestCase): + def test_formats_and_sources(self): + raw = bytes(range(256)) * 4 + for fmt in ("h", "<2H", " other.v + + +def pops(n): + got = [] + for i in range(n): + xs = [10, 20, 30, 40] + a = xs.pop(0) + b = xs.pop(-1) + c = xs.pop(1) + got.append((a, b, c, xs)) + return got[-1] + + +def pop_errors(n): + caught = 0 + for i in range(n): + xs = [1] + try: + xs.pop(5) + except IndexError as e: + caught += str(e) == "pop index out of range" + try: + xs.pop("x") + except TypeError: + caught += 1 + e = [] + try: + e.pop(0) + except IndexError as e2: + caught += str(e2) == "pop from empty list" + return caught + + +def sorts(n): + out = None + for i in range(n): + xs = [5, 3, 8, 1] + xs.sort() + ys = ["b", "a", "c"] + ys.sort() + zs = [3.5, -1.0, 2.0] + zs.sort() + ks = [K(1), K(3), K(2)] + ks.sort() + out = (xs, ys, zs, [k.v for k in ks]) + return out + + +def sort_errors(n): + caught = 0 + for i in range(n): + xs = [1, "a", 2] + try: + xs.sort() + except TypeError: + caught += 1 + return caught + + +def mixed(seq, n): + out = [] + for i in range(n): + out.append(seq.pop(0) if i % 2 == 0 else None) + return out + + +class BuiltinFastMethodSiteTests(unittest.TestCase): + def test_pop_index(self): + for n in (1, 400): + self.assertEqual(pops(n), (10, 40, 30, [20])) + + def test_pop_errors(self): + self.assertEqual(pop_errors(300), 900) + + def test_sort(self): + want = ([1, 3, 5, 8], ["a", "b", "c"], [-1.0, 2.0, 3.5], [3, 2, 1]) + for n in (1, 400): + self.assertEqual(sorts(n), want) + self.assertEqual(sort_errors(300), 300) + + def test_subclass_and_type_change(self): + def run(xs, n): + out = [] + for i in range(n): + out.append(xs.pop(0)) + xs.append(i) + return out + + self.assertEqual(run([0, 1, 2], 300)[:4], [0, 1, 2, 0]) + self.assertEqual(run(L([0, 1]), 300)[:3], ["mine", "mine", "mine"]) + + def sort_it(xs, n): + for i in range(n): + xs.sort() + return xs + + sort_it([2, 1], 300) + sub = sort_it(L([2, 1]), 3) + self.assertEqual(sub, [2, 1, "sorted", "sorted", "sorted"]) + self.assertEqual(mixed(list(range(400)), 400)[:4], [0, None, 1, None]) + + def test_str_and_set_methods(self): + def strs(n): + out = None + for i in range(n): + s = "a,b,,c" + out = (s.count(","), s.rfind(","), s.title(), s.zfill(8)) + return out + + def sets(n): + out = None + for i in range(n): + a = {1, 2, 3} + b = {2, 3} + out = (b.issubset(a), a.isdisjoint(b), sorted(a.difference(b))) + return out + + for n in (1, 400): + self.assertEqual(strs(n), (3, 4, "A,B,,C", "00a,b,,c")) + self.assertEqual(sets(n), (True, False, [1])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_builtin_key_functions.py b/tests/regrtest/test_builtin_key_functions.py new file mode 100644 index 000000000..db58322cf --- /dev/null +++ b/tests/regrtest/test_builtin_key_functions.py @@ -0,0 +1,95 @@ +"""sorted(), min() and max() with a native key function from compiled +loops: a builtin (abs, len, str.lower through the type) and a bound +method (d.get, a string's index), keys of one plain kind, ties (the first +extreme wins, the sort is stable), mixed or missing keys, reverse sorts, +empty inputs with and without a default, and a key that raises.""" + +import unittest + + +def run(n): + out = None + d = {"a": 3, "b": 1, "c": 3, "d": 0} + for i in range(n): + xs = [3, -5, 2, -2, 5] + words = ["Bb", "aa", "Cc", "AA"] + out = ( + max(d, key=d.get), + min(d, key=d.get), + sorted(d, key=d.get), + sorted(d, key=d.get, reverse=True), + max(xs, key=abs), + min(xs, key=abs), + sorted(xs, key=abs), + max(words, key=str.lower), + min(words, key=str.lower), + sorted(words, key=str.lower), + max(["x", "yyy", "zz"], key=len), + min((2.5, -1.5, 0.5), key=abs), + max([], key=abs, default="empty"), + max(["b", "a"], key="ab".index), + max([1.0, float("nan"), 3.0], key=float), + ) + return out + + +def mixed(n): + out = None + d = {"a": 1, "b": 2.5} + for i in range(n): + out = ( + max(d, key=d.get), + max(["zz", "a"], key={"a": 1, "zz": 1}.get), + sorted([1, 2.5, -3], key=abs), + ) + return out + + +def raising(n): + caught = 0 + for i in range(n): + try: + max(["a", 1], key=str.lower) + except TypeError: + caught += 1 + try: + min([], key=abs) + except ValueError: + caught += 1 + try: + max(["zz", "a"], key={"a": 1, "zz": None}.get) + except TypeError: + caught += 1 + return caught + + +class Tests(unittest.TestCase): + def test_values(self): + got = run(3000) + self.assertEqual(got, ( + "a", + "d", + ["d", "b", "a", "c"], + ["a", "c", "b", "d"], + -5, + 2, + [2, -2, 3, -5, 5], + "Cc", + "aa", + ["aa", "AA", "Bb", "Cc"], + "yyy", + 0.5, + "empty", + "b", + 3.0, + )) + + def test_mixed_keys(self): + self.assertEqual(mixed(2000), ("b", "zz", [1, 2.5, -3])) + + def test_raising(self): + self.assertEqual(raising(1000), 3000) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_builtin_keyword_halves.py b/tests/regrtest/test_builtin_keyword_halves.py new file mode 100644 index 000000000..c1f4ae2ff --- /dev/null +++ b/tests/regrtest/test_builtin_keyword_halves.py @@ -0,0 +1,109 @@ +"""Keyword calls of builtins served in place. + +`dict(a=1)`, `s.encode(encoding=...)`, `s.split(sep=..., maxsplit=...)`, +`b.decode(errors=...)`, `max(xs, default=...)` and `round(x, ndigits=...)` +take their keywords without the general keyword call when nothing they do +runs code. Every other shape, and every error, is the full call's, with +CPython's results and messages. +""" + +import unittest + + +class BuiltinKeywordTests(unittest.TestCase): + def test_dict_keywords(self): + for _ in range(300): + d = dict(a=1, b="x") + self.assertEqual(d, {"a": 1, "b": "x"}) + self.assertIs(type(d), dict) + self.assertEqual(list(d), ["a", "b"]) + self.assertEqual(dict({"z": 0}, a=1), {"z": 0, "a": 1}) + self.assertEqual(dict([("k", 2)], k=3), {"k": 3}) + + class D(dict): + pass + + self.assertIs(type(D(a=1)), D) + + def test_encode_keywords(self): + s = "héllo" + for _ in range(300): + self.assertEqual(s.encode(encoding="utf-8"), b"h\xc3\xa9llo") + self.assertEqual("abc".encode(encoding="ascii"), b"abc") + self.assertEqual(s.encode("latin-1", errors="strict"), b"h\xe9llo") + self.assertEqual(s.encode(encoding="ascii", errors="ignore"), b"hllo") + self.assertEqual(s.encode(errors="replace"), b"h\xc3\xa9llo") + with self.assertRaises(UnicodeEncodeError): + s.encode(encoding="ascii") + with self.assertRaises(LookupError): + s.encode(encoding="no-such-codec") + with self.assertRaises(TypeError): + s.encode(nope=1) + + def test_decode_keywords(self): + raw = "héllo".encode() + for _ in range(300): + self.assertEqual(raw.decode(encoding="utf-8"), "héllo") + self.assertEqual(raw.decode(errors="strict"), "héllo") + self.assertEqual(b"abc".decode(encoding="ascii"), "abc") + self.assertEqual(raw.decode("ascii", errors="ignore"), "hllo") + self.assertEqual(raw.decode(encoding="latin-1", errors="strict"), "héllo") + self.assertEqual(bytearray(b"xy").decode(errors="strict"), "xy") + with self.assertRaises(UnicodeDecodeError): + raw.decode(encoding="ascii") + with self.assertRaises(LookupError): + raw.decode(encoding="no-such-codec") + with self.assertRaises(TypeError): + raw.decode(nope=1) + self.assertEqual(b"\xff".decode(errors="replace"), "\ufffd") + + def test_min_max_round_keywords(self): + for _ in range(300): + self.assertEqual(max([3, 1, 2], default=0), 3) + self.assertEqual(min((3, 1, 2), default=0), 1) + self.assertEqual(max([], default=5), 5) + self.assertIsNone(min((), default=None)) + self.assertEqual(max([], key=None, default=1), 1) + self.assertEqual(max(["b", "a"], default=""), "b") + self.assertEqual(round(2.567, ndigits=2), 2.57) + self.assertEqual(round(number=2.5), 2) + self.assertEqual(round(7, ndigits=-1), 10) + self.assertEqual(round(2.5, ndigits=None), 2) + self.assertEqual(max(iter([4, 9]), default=0), 9) + self.assertEqual(max(["aa", "b"], key=len, default=""), "aa") + with self.assertRaises(ValueError): + max([]) + with self.assertRaises(TypeError): + max([1, "a"], default=0) + with self.assertRaises(TypeError): + round(1.5, ndigits="x") + with self.assertRaises(TypeError): + max(1, 2, default=0) + + def test_split_keywords(self): + for _ in range(300): + self.assertEqual("a b c".split(maxsplit=1), ["a", "b c"]) + self.assertEqual("a,b,c".split(sep=","), ["a", "b", "c"]) + self.assertEqual("a,b,c".split(",", maxsplit=1), ["a", "b,c"]) + self.assertEqual("a b".split(sep=None, maxsplit=-1), ["a", "b"]) + self.assertEqual("".split(sep=","), [""]) + self.assertEqual("x".split(maxsplit=0), ["x"]) + s = "only" + self.assertIs(s.split(maxsplit=3)[0], s) + with self.assertRaises(ValueError): + "a".split(sep="") + with self.assertRaises(TypeError): + "a".split(maxsplit="x") + with self.assertRaises(TypeError): + "a".split(sep=1) + with self.assertRaises(TypeError): + "a".split(nope=1) + + class S(str): + pass + + self.assertEqual(S("a b").split(maxsplit=1), ["a", "b"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_builtin_method_calls_in_hot_loops.py b/tests/regrtest/test_builtin_method_calls_in_hot_loops.py new file mode 100644 index 000000000..16683044c --- /dev/null +++ b/tests/regrtest/test_builtin_method_calls_in_hot_loops.py @@ -0,0 +1,522 @@ +"""Method calls on builtin values in hot loops. + +A loop that runs long enough is compiled twice over, and the second +compiler loads `d.pop` and calls it as two steps. For a builtin value (a +dict, list, str, set, ...) whose method needs no Python to run, the load +leaves the receiver where the bound method would go and the call runs the +method on it directly. Nothing may tell the difference: the result, the +order of evaluation, the exception and where it is raised, and what an +argument sees when it runs Python between the load and the call. + +Each case runs a loop long enough to be compiled, checks every result, +and compares with the same loop run cold (too short to compile). +""" + +import collections +import sys +import unittest + +HOT = 60_000 +COLD = 40 + + +def both(test, fn, *args): + """`fn(n, *args)` hot agrees with a cold run's prefix and returns.""" + cold = fn(COLD, *args) + hot = fn(HOT, *args) + test.assertEqual(hot[: len(cold)] if isinstance(hot, list) else None, cold if isinstance(cold, list) else None) + return hot + + +class DictMethodTests(unittest.TestCase): + def test_pop_oldest(self): + def run(n): + d = {i: str(i) for i in range(100)} + out = [] + for i in range(100, 100 + n): + d[i] = str(i) + v = d.pop(i - 100) + if i % 997 == 0 or i < 140: + out.append(v) + out.append(len(d)) + out.append(list(d)[:3]) + return out + + hot = run(HOT) + self.assertEqual(hot[-2], 100) + self.assertEqual(hot[-1], [HOT, HOT + 1, HOT + 2]) + self.assertEqual(run(COLD)[:40], hot[:40]) + + def test_pop_default_and_missing(self): + def run(n): + d = {i: i for i in range(0, 2 * n, 2)} + hits = misses = 0 + for i in range(n): + if d.pop(i, None) is None: + misses += 1 + else: + hits += 1 + return [hits, misses, len(d)] + + self.assertEqual(run(HOT), [HOT // 2, HOT // 2, HOT // 2]) + self.assertEqual(run(COLD), [COLD // 2, COLD // 2, COLD // 2]) + + def test_pop_raises_where_it_should(self): + def run(n): + d = {i: i for i in range(n)} + total = 0 + try: + for i in range(n + 5): + total += d.pop(i) + except KeyError as e: + return [total, e.args[0], len(d)] + return [total, None, len(d)] + + self.assertEqual(run(HOT), [HOT * (HOT - 1) // 2, HOT, 0]) + self.assertEqual(run(COLD), [COLD * (COLD - 1) // 2, COLD, 0]) + + def test_get_setdefault_keys_items(self): + def run(n): + d = {} + total = 0 + for i in range(n): + k = i % 50 + total += d.setdefault(k, i) + total += d.get(k, -1) + total += d.get(-1 - k, 3) + if i % 5000 == 0: + total += len(d.keys()) + len(d.values()) + len(d.items()) + return [total, len(d)] + + hot, cold = run(HOT), run(COLD) + want = 0 + d = {} + for i in range(HOT): + k = i % 50 + want += d.setdefault(k, i) + d.get(k, -1) + d.get(-1 - k, 3) + if i % 5000 == 0: + want += 3 * len(d) + self.assertEqual(hot, [want, 50]) + self.assertEqual(cold[1], 40) + + def test_argument_runs_python_between_load_and_call(self): + # The receiver's method is looked up before the argument runs; the + # argument then changes the dict the method works on. + def run(n): + d = {} + seen = [] + + def key(i): + d[i] = i * 2 + return i + + total = 0 + for i in range(n): + total += d.pop(key(i)) + if i % 9973 == 0: + seen.append(len(d)) + return [total, seen, len(d)] + + hot = run(HOT) + self.assertEqual(hot[0], HOT * (HOT - 1)) + self.assertEqual(hot[2], 0) + self.assertEqual(run(COLD)[0], COLD * (COLD - 1)) + + def test_argument_rebinds_the_receiver_name(self): + # `d.pop(f())` pops from the dict `d` named at the load, whatever + # `f` binds the name to meanwhile. + def run(n): + first = {i: "first" for i in range(n)} + second = {i: "second" for i in range(n)} + d = first + out = [] + + def swap(i): + nonlocal d + d = second if d is first else first + return i + + for i in range(n): + out.append(d.pop(swap(i))) + return [out[:6], len(first), len(second), out.count("first")] + + hot = run(HOT) + self.assertEqual(hot[0], ["first", "second"] * 3) + self.assertEqual((hot[1], hot[2], hot[3]), (HOT // 2, HOT // 2, HOT // 2)) + + def test_argument_raises_between_load_and_call(self): + def run(n): + d = {i: i for i in range(n)} + caught = 0 + total = 0 + + def key(i): + if i % 1000 == 999: + raise ValueError(i) + return i + + for i in range(n): + try: + total += d.pop(key(i)) + except ValueError: + caught += 1 + return [total, caught, len(d)] + + hot = run(HOT) + self.assertEqual(hot[1], HOT // 1000) + self.assertEqual(hot[2], HOT // 1000) + self.assertEqual(hot[0], sum(i for i in range(HOT) if i % 1000 != 999)) + + def test_receiver_kind_changes_at_one_site(self): + class Popper: + def __init__(self): + self.calls = 0 + + def pop(self, k, default=None): + self.calls += 1 + return ("popper", k) + + def run(n): + d = {i: i for i in range(n)} + p = Popper() + od = collections.OrderedDict((i, -i) for i in range(n)) + xs = list(range(n)) + out = [] + for i in range(n): + phase = (i // 7) % 4 + recv = (d, p, od, xs)[phase] + v = recv.pop(i) if phase != 3 else recv.pop() + if i % 3001 == 0 or i < 30: + out.append(v) + return [out, p.calls, len(d), len(od), len(xs)] + + hot = run(HOT) + cold = run(COLD) + self.assertEqual(hot[0][:8], [0, 1, 2, 3, 4, 5, 6, ("popper", 7)]) + self.assertEqual(cold[0][:8], hot[0][:8]) + self.assertEqual(hot[1] + (HOT - hot[2]) + (HOT - hot[3]) + (HOT - hot[4]), HOT) + + def test_missing_method_raises_at_the_load(self): + def run(n): + d = {} + order = [] + + def arg(): + order.append("arg") + return 1 + + caught = 0 + for i in range(n): + recv = d if i % 500 else 5 + try: + recv.setdefault(arg(), i) + except AttributeError: + caught += 1 + return [caught, len(order)] + + # (An int has no setdefault: the load raises before the argument runs.) + self.assertEqual(run(HOT), [HOT // 500, HOT - HOT // 500]) + + +# Loops with enough integer work around each call for the second compiler +# to take them (it leaves a loop that is all method calls to the first), +# written at module level with plain locals. Each has a reference that +# reaches the same values without a method call. + + +def pop_loop(n): + d = {i: i for i in range(100)} + acc = 0 + for i in range(100, 100 + n): + d[i] = i + a = i * 3 + 1 + b = a - i + c = (b ^ i) & 1023 + acc += d.pop(i - 100) + (a - b - c) % 7 + return acc, len(d) + + +def pop_loop_reference(n): + acc = 0 + for i in range(100, 100 + n): + a = i * 3 + 1 + b = a - i + c = (b ^ i) & 1023 + acc += (i - 100) + (a - b - c) % 7 + return acc, 100 + + +def overflow_in_argument(n, scale): + # `scale * (i + 1)` outgrows a machine word between the load of + # `d.get` and its call. + d = {i: i for i in range(64)} + acc = 0 + for i in range(n): + scale = scale * 2 + (i & 1) + k = (i * 7 + 3) & 63 + t = (k + 1) * 3 - k + acc += d.get((scale * (i + 1)) & 63, -1) + t - (t & 1) + return acc + + +def overflow_in_argument_reference(n, scale): + acc = 0 + for i in range(n): + scale = scale * 2 + (i & 1) + k = (i * 7 + 3) & 63 + t = (k + 1) * 3 - k + acc += ((scale * (i + 1)) & 63) + t - (t & 1) + return acc + + +def division_in_argument(n, bad): + # The argument divides by zero at `i == bad`, after `d.get` is loaded. + d = {i: i for i in range(64)} + acc = 0 + for i in range(n): + a = i * 5 + 2 + b = (a ^ i) & 63 + acc += d.get(b // (bad - i), -7) + a - (a & 3) + b + return acc + + +def division_in_argument_reference(n, bad): + acc = 0 + for i in range(min(n, bad)): + a = i * 5 + 2 + b = (a ^ i) & 63 + q = b // (bad - i) + acc += (q if q < 64 else -7) + a - (a & 3) + b + return acc + + +class Doubler: + def get(self, k, default): + return k * 2 + + +def changing_receivers(n, four): + # One call site, whose receiver is a dict three times in four. + acc = 0 + for i in range(n): + a = i * 3 + 1 + b = (a - i) & 15 + acc += four[i & 3].get(b, -1) + a - b + (i & 7) + return acc + + +def changing_receivers_reference(n): + acc = 0 + for i in range(n): + a = i * 3 + 1 + b = (a - i) & 15 + which = i & 3 + got = b if which == 0 else b * 2 if which == 1 else (-b if b < 8 else -1) if which == 2 else -1 + acc += got + a - b + (i & 7) + return acc + + +def changing_kinds(n, four): + # One call site over lists and tuples: two builtins of one name. + acc = 0 + for i in range(n): + a = i * 3 + 1 + b = (a - i) & 15 + o = four[i & 3] + acc += o.count(b) + a - b + (i & 7) + return acc + + +def changing_kinds_reference(n, four): + acc = 0 + for i in range(n): + a = i * 3 + 1 + b = (a - i) & 15 + acc += sum(1 for x in four[i & 3] if x == b) + a - b + (i & 7) + return acc + + +def nested_calls(n): + d = {i: i + 1 for i in range(64)} + acc = 0 + for i in range(n): + a = (i * 5 + 2) & 31 + b = (a ^ i) & 15 + acc += d.get(d.get(b, 0), -1) + a - b + (a & 3) + return acc + + +def nested_calls_reference(n): + acc = 0 + for i in range(n): + a = (i * 5 + 2) & 31 + b = (a ^ i) & 15 + acc += b + 2 + a - b + (a & 3) + return acc + + +class CompiledLoopTests(unittest.TestCase): + def test_pop_in_a_loop_with_integer_work(self): + self.assertEqual(pop_loop(HOT), pop_loop_reference(HOT)) + self.assertEqual(pop_loop(COLD), pop_loop_reference(COLD)) + + def test_argument_overflows_between_load_and_call(self): + for scale in (1, 3): + self.assertEqual( + overflow_in_argument(HOT, scale), + overflow_in_argument_reference(HOT, scale), + ) + + def test_argument_raises_between_load_and_call(self): + bad = HOT - 5000 + with self.assertRaises(ZeroDivisionError): + division_in_argument(HOT, bad) + self.assertEqual( + division_in_argument(bad, bad), + division_in_argument_reference(bad, bad), + ) + self.assertEqual( + division_in_argument(HOT, 10 * HOT), + division_in_argument_reference(HOT, 10 * HOT), + ) + + def test_one_site_many_receivers(self): + four = ({i: i for i in range(16)}, Doubler(), {i: -i for i in range(8)}, {}) + self.assertEqual(changing_receivers(HOT, four), changing_receivers_reference(HOT)) + four = ([1, 2, 3, 2], (2, 2, 5), [7], (1,)) + self.assertEqual(changing_kinds(HOT, four), changing_kinds_reference(HOT, four)) + + def test_a_call_inside_a_call(self): + self.assertEqual(nested_calls(HOT), nested_calls_reference(HOT)) + + +class OtherReceiverTests(unittest.TestCase): + def test_str_methods(self): + def run(n): + words = ["Alpha", " beta ", "GAMMA", "delta\n", "x=1"] + total = 0 + for i in range(n): + w = words[i % 5] + if w.startswith("A") or w.endswith("\n"): + total += 1 + total += len(w.strip()) + len(w.lower()) + w.find("a") + len(w.partition("=")[0]) + total += w.upper().count("A") + return [total] + + hot = run(HOT) + cold = run(COLD) + self.assertEqual(hot[0], cold[0] * (HOT // COLD)) + + def test_list_methods(self): + def run(n): + xs = [] + total = 0 + for i in range(n): + xs.append(i) + xs.insert(0, -i) + total += xs.pop() + xs.pop(0) + if i % 100 == 0: + xs.extend((i, i + 1)) + total += xs.index(i) + xs.count(i + 1) + xs.reverse() + ys = xs.copy() + ys.clear() + xs.remove(i) + total += xs.pop() + return [total, len(xs)] + + hot, cold = run(HOT), run(COLD) + self.assertEqual(hot[1], 0) + self.assertEqual(cold[1], 0) + self.assertEqual(hot[0], sum(i + 2 for i in range(0, HOT, 100))) + + def test_set_methods(self): + def run(n): + s = set() + total = 0 + for i in range(n): + s.add(i % 97) + s.discard((i * 7) % 97) + if i % 97 in s: + total += 1 + if i % 1000 == 0: + total += len(s.copy()) + s.update((1, 2, 3)) + s.remove(1) + total += s.pop() >= 0 + return [total, len(s) <= 97] + + hot, cold = run(HOT), run(COLD) + self.assertEqual(hot, run(HOT)) + self.assertTrue(hot[1] and cold[1]) + + def test_bytes_tuple_int_float(self): + def run(n): + b = b"key=value" + t = (1, 2, 3, 2) + total = 0 + for i in range(n): + total += b.find(b"=") + t.count(2) + t.index(3) + total += (i).bit_length() + (i + 0.5).is_integer() + i.to_bytes(4, "big")[3] + return [total] + + hot = run(HOT) + want = sum(3 + 2 + 2 + i.bit_length() + (i & 255) for i in range(HOT)) + self.assertEqual(hot[0], want) + + def test_bound_method_kept_in_a_local(self): + def run(n): + d = {i: i for i in range(n)} + pop = d.pop + get = d.get + total = 0 + for i in range(n): + total += get(i, 0) + pop(i) + m = d.get + total += m(i, 1) + return [total, len(d), pop.__self__ is d, pop.__name__] + + hot = run(HOT) + self.assertEqual(hot, [HOT * (HOT - 1) + HOT, 0, True, "pop"]) + + def test_keyword_and_wide_calls(self): + def run(n): + total = 0 + xs = list(range(10)) + for i in range(n): + total += int.from_bytes(i.to_bytes(4, byteorder="little"), byteorder="little") + total += len("a,b,c,d".split(",", maxsplit=i % 3)) + total += len(sorted(xs, key=None, reverse=bool(i & 1))) + total += "x".join(("a", "b")).count("x") + return [total] + + hot = run(HOT) + want = sum(i + i % 3 + 1 + 10 + 1 for i in range(HOT)) + self.assertEqual(hot[0], want) + + def test_tracing_sees_the_same_calls(self): + def run(n): + d = {i: i for i in range(n)} + total = 0 + for i in range(n): + total += d.pop(i) + return total + + run(HOT) + events = [] + + def tracer(frame, event, arg): + if event == "c_call": + events.append(arg.__name__) + + sys.setprofile(tracer) + try: + got = run(300) + finally: + sys.setprofile(None) + self.assertEqual(got, 300 * 299 // 2) + self.assertEqual(events.count("pop"), 300) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_builtin_method_keyword_positions.py b/tests/regrtest/test_builtin_method_keyword_positions.py new file mode 100644 index 000000000..2b441e573 --- /dev/null +++ b/tests/regrtest/test_builtin_method_keyword_positions.py @@ -0,0 +1,222 @@ +"""Keyword calls of builtin methods whose keywords name the next +positional parameters, run as the positional call, and `datetime`'s +`isoformat` keywords.""" + +import datetime +import unittest + +N = 300 + + +def repeat(f): + """`f()` run often enough for compiled code to take the call; every + result must be the first one.""" + first = f() + for _ in range(N): + r = f() + if r != first or type(r) is not type(first): + raise AssertionError((first, r)) + return first + + +def raises(f): + """The class and message of what `f()` raises, the same every time.""" + seen = None + for _ in range(N // 10): + try: + f() + except Exception as e: + got = (type(e), str(e)) + else: + raise AssertionError("no error") + if seen is not None and got != seen: + raise AssertionError((seen, got)) + seen = got + return seen + + +class Sub(str): + pass + + +class StrTests(unittest.TestCase): + def test_split(self): + s = "a,b,,c" + self.assertEqual(repeat(lambda: s.split(sep=",")), ["a", "b", "", "c"]) + self.assertEqual(repeat(lambda: s.split(",", maxsplit=1)), ["a", "b,,c"]) + self.assertEqual(repeat(lambda: s.split(sep=",", maxsplit=2)), ["a", "b", ",c"]) + # (A gap: `sep` omitted, `maxsplit` given.) + self.assertEqual(repeat(lambda: "a b c".split(maxsplit=1)), ["a", "b c"]) + self.assertEqual(repeat(lambda: s.rsplit(",", maxsplit=1)), ["a,b,", "c"]) + self.assertEqual(repeat(lambda: s.rsplit(sep=",")), ["a", "b", "", "c"]) + # (Out of order.) + self.assertEqual(repeat(lambda: s.split(maxsplit=1, sep=",")), ["a", "b,,c"]) + self.assertEqual(repeat(lambda: Sub("x,y").split(sep=",")), ["x", "y"]) + + def test_replace_splitlines_encode_expandtabs(self): + s = "a,b,c" + self.assertEqual(repeat(lambda: s.replace(",", ";", count=1)), "a;b,c") + self.assertEqual(repeat(lambda: s.replace(",", ";", count=0)), "a,b,c") + self.assertEqual(repeat(lambda: s.replace(",", ";", count=-1)), "a;b;c") + self.assertEqual(repeat(lambda: "x\ny\r\n".splitlines(keepends=True)), ["x\n", "y\r\n"]) + self.assertEqual(repeat(lambda: "x\ny".splitlines(keepends=False)), ["x", "y"]) + self.assertEqual(repeat(lambda: "hé".encode(encoding="utf-8")), b"h\xc3\xa9") + self.assertEqual(repeat(lambda: "hé".encode("ascii", errors="replace")), b"h?") + self.assertEqual(repeat(lambda: "hé".encode(encoding="ascii", errors="ignore")), b"h") + self.assertEqual(repeat(lambda: "hé".encode(errors="strict")), b"h\xc3\xa9") + self.assertEqual(repeat(lambda: "a\tb".expandtabs(tabsize=4)), "a b") + + def test_errors(self): + s = "a,b" + self.assertIs(raises(lambda: s.split(sep=1))[0], TypeError) + self.assertIs(raises(lambda: s.replace("a", "b", count="x"))[0], TypeError) + self.assertIs(raises(lambda: s.split(bogus=1))[0], TypeError) + self.assertIs(raises(lambda: s.split(",", sep=","))[0], TypeError) + self.assertIs(raises(lambda: s.rsplit(",", 1, maxsplit=1))[0], TypeError) + self.assertEqual( + raises(lambda: s.rsplit(",", maxsplit=1, sep=",")), + (TypeError, "rsplit() takes at most 2 arguments (3 given)"), + ) + self.assertEqual( + raises(lambda: s.split(sep=",", maxsplit=1, foo=2)), + (TypeError, "split() takes at most 2 keyword arguments (3 given)"), + ) + self.assertEqual( + raises(lambda: s.split(",", foo=2)), + (TypeError, "split() got an unexpected keyword argument 'foo'"), + ) + self.assertEqual( + raises(lambda: s.split(",", sep=",")), + (TypeError, "argument for split() given by name ('sep') and position (1)"), + ) + self.assertEqual( + raises(lambda: b"a".split(b",", sep=b",")), + (TypeError, "argument for split() given by name ('sep') and position (1)"), + ) + self.assertIs(raises(lambda: s.encode(encoding="no-such-codec"))[0], LookupError) + self.assertIs(raises(lambda: "é".encode(encoding="ascii"))[0], UnicodeEncodeError) + self.assertIs(raises(lambda: s.replace(old="a", new="b"))[0], TypeError) + + +class BytesTests(unittest.TestCase): + def test_bytes(self): + b = b"a,b,c" + self.assertEqual(repeat(lambda: b.split(sep=b",")), [b"a", b"b", b"c"]) + self.assertEqual(repeat(lambda: b.rsplit(b",", maxsplit=1)), [b"a,b", b"c"]) + self.assertEqual(repeat(lambda: b.decode(encoding="ascii")), "a,b,c") + self.assertEqual(repeat(lambda: b"\xff".decode("utf-8", errors="replace")), "�") + self.assertEqual(repeat(lambda: b"\xffa".decode(errors="ignore")), "a") + self.assertEqual(repeat(lambda: b.translate(None, delete=b",")), b"abc") + self.assertEqual(repeat(lambda: b"x\ny\n".splitlines(keepends=True)), [b"x\n", b"y\n"]) + self.assertEqual(repeat(lambda: b"a\tb".expandtabs(tabsize=2)), b"a b") + + def test_bytearray(self): + ba = bytearray(b"a,b") + self.assertEqual(repeat(lambda: ba.split(sep=b",")), [bytearray(b"a"), bytearray(b"b")]) + self.assertEqual(repeat(lambda: ba.decode(encoding="ascii")), "a,b") + self.assertEqual(repeat(lambda: ba.translate(None, delete=b",")), bytearray(b"ab")) + + def test_errors(self): + self.assertIs(raises(lambda: b"a".split(sep="a"))[0], TypeError) + self.assertIs(raises(lambda: b"\xff".decode(encoding="ascii"))[0], UnicodeDecodeError) + + +class IntTests(unittest.TestCase): + def test_to_bytes(self): + self.assertEqual(repeat(lambda: (258).to_bytes(4, byteorder="big")), b"\x00\x00\x01\x02") + self.assertEqual(repeat(lambda: (258).to_bytes(length=2, byteorder="little")), b"\x02\x01") + self.assertEqual(repeat(lambda: (-2).to_bytes(2, "big", signed=True)), b"\xff\xfe") + self.assertEqual(repeat(lambda: (-2).to_bytes(2, byteorder="big", signed=True)), b"\xff\xfe") + big = 2**100 + 5 + self.assertEqual(repeat(lambda: big.to_bytes(13, byteorder="big")), big.to_bytes(13, "big")) + self.assertEqual(repeat(lambda: True.to_bytes(1, byteorder="big")), b"\x01") + + def test_errors(self): + self.assertIs(raises(lambda: (300).to_bytes(1, byteorder="big"))[0], OverflowError) + self.assertIs(raises(lambda: (1).to_bytes(1, byteorder="middle"))[0], ValueError) + self.assertIs(raises(lambda: (-1).to_bytes(1, byteorder="big"))[0], OverflowError) + + +class DatetimeIsoformatTests(unittest.TestCase): + def test_datetime(self): + d = datetime.datetime(2020, 1, 2, 3, 4, 5, 678901) + self.assertEqual(repeat(lambda: d.isoformat(sep=" ")), "2020-01-02 03:04:05.678901") + self.assertEqual(repeat(lambda: d.isoformat(timespec="seconds")), "2020-01-02T03:04:05") + self.assertEqual(repeat(lambda: d.isoformat(" ", timespec="minutes")), "2020-01-02 03:04") + self.assertEqual( + repeat(lambda: d.isoformat(sep="_", timespec="milliseconds")), + "2020-01-02_03:04:05.678", + ) + self.assertEqual(repeat(lambda: d.isoformat(timespec="hours")), "2020-01-02T03") + self.assertEqual( + repeat(lambda: d.isoformat(timespec="microseconds", sep="T")), + "2020-01-02T03:04:05.678901", + ) + self.assertEqual(repeat(lambda: d.replace(microsecond=0).isoformat(timespec="auto")), + "2020-01-02T03:04:05") + tz = datetime.timezone(datetime.timedelta(hours=2, minutes=30)) + a = datetime.datetime(2020, 1, 2, 3, 4, 5, tzinfo=tz) + self.assertEqual(repeat(lambda: a.isoformat(sep=" ", timespec="seconds")), + "2020-01-02 03:04:05+02:30") + self.assertEqual(str(d), "2020-01-02 03:04:05.678901") + + def test_time(self): + t = datetime.time(3, 4, 5, 678901) + self.assertEqual(repeat(lambda: t.isoformat(timespec="minutes")), "03:04") + self.assertEqual(repeat(lambda: t.isoformat(timespec="milliseconds")), "03:04:05.678") + self.assertEqual(repeat(lambda: t.isoformat("seconds")), "03:04:05") + self.assertEqual(repeat(lambda: t.isoformat()), "03:04:05.678901") + self.assertEqual(repeat(lambda: str(t)), "03:04:05.678901") + tz = datetime.timezone(datetime.timedelta(hours=-5)) + a = datetime.time(3, 4, 5, tzinfo=tz) + self.assertEqual(repeat(lambda: a.isoformat(timespec="hours")), "03-05:00") + + def test_errors(self): + d = datetime.datetime(2020, 1, 2) + t = datetime.time(1, 2) + self.assertIs(raises(lambda: d.isoformat(timespec="bogus"))[0], ValueError) + self.assertIs(raises(lambda: d.isoformat(sep=None))[0], TypeError) + self.assertIs(raises(lambda: d.isoformat(sep="ab"))[0], TypeError) + self.assertIs(raises(lambda: t.isoformat(timespec="bogus"))[0], ValueError) + self.assertIs(raises(lambda: d.isoformat(bogus=1))[0], TypeError) + + def test_replace(self): + d = datetime.datetime(2020, 1, 2, 3, 4, 5) + self.assertEqual(repeat(lambda: d.replace(hour=7)), datetime.datetime(2020, 1, 2, 7, 4, 5)) + self.assertEqual(repeat(lambda: d.replace(2021, day=9)), datetime.datetime(2021, 1, 9, 3, 4, 5)) + tz = datetime.timezone.utc + a = d.replace(tzinfo=tz) + self.assertIs(repeat(lambda: a.replace(tzinfo=None)).tzinfo, None) + self.assertIs(repeat(lambda: a.replace(hour=1)).tzinfo, tz) + self.assertEqual( + repeat(lambda: d.replace(hour=0, minute=0, second=0, microsecond=0)), + datetime.datetime(2020, 1, 2), + ) + self.assertEqual(repeat(lambda: d.replace(microsecond=7)).microsecond, 7) + self.assertEqual(repeat(lambda: d.replace(day=9, year=2022)), datetime.datetime(2022, 1, 9, 3, 4, 5)) + self.assertEqual(repeat(lambda: d.replace(fold=1)).fold, 1) + self.assertEqual(repeat(lambda: d.replace(hour=2, fold=1)).fold, 1) + self.assertEqual(repeat(lambda: d.replace(tzinfo=tz).utcoffset()), datetime.timedelta(0)) + self.assertIs(raises(lambda: d.replace(hour=25))[0], ValueError) + self.assertIs(raises(lambda: d.replace(hour="x"))[0], TypeError) + self.assertIs(raises(lambda: d.replace(bogus=1))[0], TypeError) + self.assertIs(raises(lambda: d.replace(2020, year=2021))[0], TypeError) + day = datetime.date(2020, 5, 17) + self.assertEqual(repeat(lambda: day.replace(day=1)), datetime.date(2020, 5, 1)) + self.assertEqual(repeat(lambda: day.replace(month=2, day=3)), datetime.date(2020, 2, 3)) + self.assertEqual(repeat(lambda: day.replace(2021, day=4)), datetime.date(2021, 5, 4)) + self.assertIs(raises(lambda: day.replace(month=13))[0], ValueError) + + def test_astimezone(self): + utc = datetime.timezone.utc + plus2 = datetime.timezone(datetime.timedelta(hours=2)) + a = datetime.datetime(2020, 1, 2, 3, 4, 5, tzinfo=utc) + self.assertEqual(repeat(lambda: a.astimezone(tz=plus2)), + datetime.datetime(2020, 1, 2, 5, 4, 5, tzinfo=plus2)) + self.assertIs(repeat(lambda: a.astimezone(tz=plus2)).tzinfo, plus2) + self.assertEqual(repeat(lambda: a.astimezone(tz=None)), a.astimezone()) + self.assertIs(raises(lambda: a.astimezone(tz=5))[0], TypeError) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_builtin_raise_caught.py b/tests/regrtest/test_builtin_raise_caught.py new file mode 100644 index 000000000..21739ab2c --- /dev/null +++ b/tests/regrtest/test_builtin_raise_caught.py @@ -0,0 +1,67 @@ +"""Exceptions a builtin call raises, caught by compiled code's handlers. + +`[].pop()`, `{}.pop(k)`, `"abc".index("z")`, `min([])` and `next(it)` +raise in place: the code's own handler runs, with `sys.exc_info()`, the +traceback's line, `finally` and implicit chaining as CPython has them, +and an uncaught one reaches the caller. Run it past the compile +threshold. +""" + +import sys + + +def caught(xs): + try: + xs.pop() + except IndexError as e: + assert sys.exc_info()[1] is e + return ("index", str(e), e.__traceback__.tb_lineno) + finally: + xs.append(0) + return "no raise" + + +def several(d, s, it): + out = [] + for f in (lambda: d.pop("k"), lambda: s.index("z"), lambda: min([]), lambda: next(it)): + try: + f() + except (KeyError, ValueError, StopIteration) as e: + out.append(type(e).__name__) + return out + + +def chained(): + try: + try: + [].pop() + except IndexError: + {}.pop("k") + except KeyError as e: + return type(e.__context__).__name__ + + +def uncaught(): + return [].pop() + + +def caller(): + try: + uncaught() + except IndexError as e: + tb = e.__traceback__ + while tb.tb_next: + tb = tb.tb_next + return tb.tb_frame.f_code.co_name + + +line = caught.__code__.co_firstlineno + 2 +for i in range(3000): + xs = [] + assert caught(xs) == ("index", "pop from empty list", line) + assert xs == [0] + assert caught([1, 2]) == "no raise" + assert several({}, "abc", iter([])) == ["KeyError", "ValueError", "ValueError", "StopIteration"] + assert chained() == "IndexError" + assert caller() == "uncaught" + assert sys.exc_info() == (None, None, None) diff --git a/tests/regrtest/test_builtin_subclass_attr_probes.py b/tests/regrtest/test_builtin_subclass_attr_probes.py new file mode 100644 index 000000000..523690244 --- /dev/null +++ b/tests/regrtest/test_builtin_subclass_attr_probes.py @@ -0,0 +1,383 @@ +"""`hasattr`, `getattr` with a default and caught misses on instances of +built-in subclasses: the payload's methods, names nothing has, instance +and class values that arrive and leave after a site is warm, hooks, +`__slots__`, enums and named tuples all answer as the full lookup does.""" + +import collections +import enum +import unittest + + +class L(list): + pass + + +class S(str): + pass + + +class D(dict): + pass + + +class T(tuple): + pass + + +class I(int): + pass + + +class St(set): + pass + + +class OD(collections.OrderedDict): + pass + + +class DD(collections.defaultdict): + pass + + +class Cn(collections.Counter): + pass + + +class Dq(collections.deque): + pass + + +def probe(obj, name): + try: + getattr(obj, name) + caught = False + except AttributeError as e: + caught = (e.name, e.obj is obj) + return hasattr(obj, name), getattr(obj, name, "DEF") != "DEF", caught + + +class PayloadNames(unittest.TestCase): + HAS = { + L: ["append", "count", "index", "__len__", "__dict__"], + S: ["encode", "count", "index", "__len__", "__dict__"], + D: ["keys", "__len__", "__dict__"], + T: ["count", "index", "__len__", "__dict__"], + I: ["bit_length", "real", "__dict__"], + St: ["add", "__len__", "__dict__"], + OD: ["keys", "move_to_end", "__len__", "__dict__"], + DD: ["keys", "default_factory", "__len__", "__dict__"], + Cn: ["keys", "most_common", "elements", "__len__", "__dict__"], + Dq: ["append", "appendleft", "count", "index", "maxlen", "__len__", "__dict__"], + } + NAMES = [ + "encode", "append", "keys", "move_to_end", "default_factory", "most_common", + "appendleft", "bit_length", "real", "nope", "_private", "__nope__", "__len__", + "__dict__", "add", "x", "count", "index", "elements", "maxlen", + ] + + def test_every_kind(self): + for cls, has in self.HAS.items(): + obj = cls(list) if cls is DD else cls() + for _ in range(3): + for name in self.NAMES: + with self.subTest(cls=cls.__name__, name=name): + want = name in has + self.assertEqual( + probe(obj, name), + (want, want, False if want else (name, True)), + ) + + def test_dict_miss_then_kinds_that_have_the_name(self): + d, od, dd, cn = D(), OD(), DD(list), Cn() + for _ in range(3): + self.assertFalse(hasattr(d, "move_to_end")) + self.assertTrue(hasattr(od, "move_to_end")) + self.assertFalse(hasattr(d, "default_factory")) + self.assertTrue(hasattr(dd, "default_factory")) + self.assertFalse(hasattr(d, "most_common")) + self.assertTrue(hasattr(cn, "most_common")) + self.assertEqual(getattr(d, "elements", 0), 0) + self.assertTrue(callable(getattr(cn, "elements", 0))) + + def test_messages(self): + for obj, kind in [(L(), "L"), (S("s"), "S"), (D(), "D"), (T(), "T"), (I(1), "I"), (OD(), "OD"), (Dq(), "Dq")]: + for _ in range(2): + with self.assertRaises(AttributeError) as cm: + obj.nope + self.assertEqual(str(cm.exception), f"'{kind}' object has no attribute 'nope'") + self.assertEqual(cm.exception.name, "nope") + self.assertIs(cm.exception.obj, obj) + + def test_context_is_kept(self): + try: + try: + raise ValueError("ctx") + except ValueError: + L().nope + except AttributeError as e: + self.assertIsInstance(e.__context__, ValueError) + self.assertEqual(e.name, "nope") + + +class TL(list): + kind = None + + def meth(self): + return 1 + + @property + def prop(self): + return 2 + + @property + def bad(self): + raise AttributeError("bad one") + + +class ValuesArriveAndLeave(unittest.TestCase): + def test_class_and_instance_values(self): + t = TL() + for r in range(3): + self.assertEqual(getattr(t, "kind", "DEF"), None if r == 0 else "own") + self.assertTrue(hasattr(t, "meth")) + self.assertEqual(getattr(t, "prop", "DEF"), 2) + self.assertFalse(hasattr(t, "bad")) + self.assertEqual(getattr(t, "bad", "DEF"), "DEF") + self.assertEqual(hasattr(t, "late"), r == 2) + self.assertEqual(getattr(t, "inst", "DEF"), "DEF" if r == 0 else 5) + self.assertFalse(hasattr(t, "encode")) + if r == 0: + t.inst = 5 + t.kind = "own" + if r == 1: + TL.late = 7 + try: + for _ in range(2): + self.assertEqual((hasattr(t, "late"), hasattr(t, "inst")), (True, True)) + del TL.late, t.inst, t.kind + self.assertEqual( + (hasattr(t, "late"), hasattr(t, "inst"), getattr(t, "kind", "DEF")), + (False, False, None), + ) + TL.late = 9 + t.inst = 6 + t.kind = "again" + finally: + del TL.late + + def test_own_value_named_as_another_kinds_method(self): + t = TL() + for _ in range(3): + self.assertFalse(hasattr(t, "encode")) + t.encode = "mine" + self.assertEqual((hasattr(t, "encode"), getattr(t, "encode", "DEF")), (True, "mine")) + self.assertFalse(hasattr(TL(), "encode")) + del t.encode + self.assertEqual((hasattr(t, "encode"), getattr(t, "encode", "DEF")), (False, "DEF")) + + def test_base_class_gains_the_name(self): + class Base(list): + pass + + class Sub(Base): + pass + + s = Sub() + for _ in range(3): + self.assertFalse(hasattr(s, "zap")) + Base.zap = 1 + self.assertEqual((hasattr(s, "zap"), getattr(s, "zap", "DEF")), (True, 1)) + del Base.zap + self.assertEqual((hasattr(s, "zap"), getattr(s, "zap", "DEF")), (False, "DEF")) + + def test_warm_sites(self): + def caught(o, n=3000): + k = 0 + for _ in range(n): + try: + o.encode + except AttributeError: + k += 1 + return k + + def probes(o, n=3000): + k = 0 + for _ in range(n): + if not hasattr(o, "encode"): + k += 1 + if getattr(o, "encode", None) is None: + k += 1 + return k + + class Own(list): + pass + + lst = Own() + self.assertEqual((caught(lst), probes(lst)), (3000, 6000)) + self.assertEqual((caught(S("x")), probes(S("x"))), (0, 0)) + lst.encode = 1 + self.assertEqual((caught(lst), probes(lst)), (0, 0)) + del lst.encode + Own.encode = lambda self: 1 + self.assertEqual((caught(lst), probes(lst)), (0, 0)) + del Own.encode + self.assertEqual((caught(lst), probes(lst)), (3000, 6000)) + + +class Hooked(list): + def __getattr__(self, name): + if name == "magic": + return 42 + raise AttributeError("Hooked has no " + name) + + +class Overridden(str): + def __getattribute__(self, name): + if name == "special": + return "sp" + return super().__getattribute__(name) + + +class Slotted(list): + __slots__ = ("a",) + + +class AttrDict(dict): + def __getattr__(self, k): + try: + return self[k] + except KeyError: + raise AttributeError(k) + + +class Fields(list): + def __getattr__(self, k): + if k == "first": + return self[0] + raise AttributeError(k) + + +class HooksAndSlots(unittest.TestCase): + def test_hook(self): + h = Hooked() + for _ in range(3): + self.assertTrue(hasattr(h, "magic")) + self.assertFalse(hasattr(h, "nope")) + self.assertEqual(getattr(h, "nope", "DEF"), "DEF") + self.assertEqual(getattr(h, "magic", "DEF"), 42) + self.assertTrue(hasattr(h, "append")) + with self.assertRaises(AttributeError) as cm: + h.nope + self.assertEqual(str(cm.exception), "Hooked has no nope") + self.assertEqual(cm.exception.name, "nope") + self.assertIs(cm.exception.obj, h) + + def test_getattribute(self): + g = Overridden("x") + for _ in range(3): + self.assertTrue(hasattr(g, "special")) + self.assertFalse(hasattr(g, "nope")) + self.assertTrue(hasattr(g, "upper")) + self.assertEqual(getattr(g, "nope", "DEF"), "DEF") + + def test_slots(self): + sl = Slotted() + for _ in range(3): + self.assertFalse(hasattr(sl, "a")) + self.assertFalse(hasattr(sl, "b")) + self.assertEqual(getattr(sl, "a", "DEF"), "DEF") + self.assertTrue(hasattr(sl, "append")) + with self.assertRaises(AttributeError): + sl.a + with self.assertRaises(AttributeError): + sl.b + sl.a = 1 + self.assertEqual((hasattr(sl, "a"), getattr(sl, "a", "DEF")), (True, 1)) + + def test_attr_dict(self): + a = AttrDict(x=1) + f = Fields([7, 8]) + total = 0 + for _ in range(3000): + total += a.x + f.first + self.assertEqual(total, 24000) + for _ in range(3): + self.assertEqual(getattr(a, "nope", None), None) + self.assertFalse(hasattr(f, "nope")) + self.assertTrue(callable(a.keys)) + self.assertTrue(callable(f.append)) + a["late"] = 5 + self.assertEqual(a.late, 5) + del a["x"] + with self.assertRaises(AttributeError) as cm: + a.x + self.assertEqual((cm.exception.args, cm.exception.name), (("x",), "x")) + a.x = "own" + self.assertEqual(a.x, "own") + self.assertNotIn("x", a) + + def test_leaf_subscript_of_the_payload(self): + class Row(tuple): + def first(self): + return self[0] + + def tail(self): + return self[1:] + + class Table(dict): + def get_x(self): + return self["x"] + + class Odd(list): + def __getitem__(self, i): + return "odd" + + def first(self): + return self[0] + + r, t, o = Row((1, 2, 3)), Table(x=9), Odd([1]) + for _ in range(3000): + self.assertEqual(r.first(), 1) + self.assertEqual(r.tail(), (2, 3)) + self.assertEqual(t.get_x(), 9) + self.assertEqual(o.first(), "odd") + del t["x"] + with self.assertRaises(KeyError): + t.get_x() + with self.assertRaises(IndexError): + Row().first() + + +class Color(enum.IntEnum): + RED = 1 + + +class Name(enum.StrEnum): + A = "a" + + +class EnumsAndNamedTuples(unittest.TestCase): + def test_enums(self): + for _ in range(3): + self.assertTrue(hasattr(Color.RED, "value")) + self.assertTrue(hasattr(Color.RED, "bit_length")) + self.assertFalse(hasattr(Color.RED, "nope")) + self.assertEqual(getattr(Color.RED, "nope", "DEF"), "DEF") + self.assertTrue(hasattr(Name.A, "upper")) + self.assertFalse(hasattr(Name.A, "nope")) + self.assertTrue(hasattr(Name.A, "name")) + + def test_named_tuple(self): + p = collections.namedtuple("P", "x y")(1, 2) + for _ in range(3): + self.assertTrue(hasattr(p, "x")) + self.assertFalse(hasattr(p, "z")) + self.assertEqual(getattr(p, "z", "DEF"), "DEF") + self.assertTrue(hasattr(p, "count")) + self.assertTrue(hasattr(p, "_asdict")) + self.assertEqual(getattr(p, "_nope", "DEF"), "DEF") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_builtin_subclass_construct.py b/tests/regrtest/test_builtin_subclass_construct.py new file mode 100644 index 000000000..f512907e7 --- /dev/null +++ b/tests/regrtest/test_builtin_subclass_construct.py @@ -0,0 +1,97 @@ +"""Constructing subclasses of immutable built-ins in compiled code. + +`C(x)` for a class that keeps its base's `__new__` and `object.__init__`, +with `x` already of the base's type, wraps `x` itself; other arguments +convert as the base's constructor does; a class with its own `__init__` +or a `__new__` added mid-loop runs them; slots, instance dicts and the +type behave as in CPython. Run it past the compile threshold. +""" + + +class S(str): + __slots__ = ("tag",) + + +class I(int): + pass + + +class F(float): + __slots__ = () + + +class T(tuple): + pass + + +class B(bytes): + pass + + +class FS(frozenset): + pass + + +class WithInit(str): + def __init__(self, v): + self.seen = v + + +class Late(str): + pass + + +def make(n): + out = [] + for i in range(n): + s = S("key") + s.tag = i + k = I(i) + k.extra = -i + out.append((s, k, F(1.5), T((i, 2)), B(b"ab"), FS(frozenset({1})))) + return out + + +N = 3000 +for j, (s, k, f, t, b, fs) in enumerate(make(N)): + assert type(s) is S and s == "key" and s.tag == j + assert type(k) is I and k == j and k.extra == -j and k + 1 == j + 1 + assert type(f) is F and f == 1.5 + assert type(t) is T and t == (j, 2) and len(t) == 2 + assert type(b) is B and b == b"ab" + assert type(fs) is FS and fs == {1} + + +def convert(n): + out = [] + for _ in range(n): + out.append((I(True), I("7"), S(12), T([1, 2]), F(3), S(S("x")))) + return out + + +for r in convert(N): + assert r == (1, 7, "12", (1, 2), 3.0, "x") + assert type(r[0]) is I and type(r[0]) is not bool and type(r[5]) is S + + +def inits(n): + return [WithInit("v") for _ in range(n)] + + +assert all(w.seen == "v" and w == "v" for w in inits(N)) + + +def lates(n): + return [Late("a") for _ in range(n)] + + +assert lates(N)[-1] == "a" +Late.__new__ = lambda cls, v: str.__new__(cls, v * 2) +assert lates(3) == ["aa"] * 3 +try: + I(1, 2, 3) +except TypeError: + pass +else: + raise AssertionError("too many arguments") +print("ok") diff --git a/tests/regrtest/test_builtin_subclass_methods.py b/tests/regrtest/test_builtin_subclass_methods.py new file mode 100644 index 000000000..767890ed0 --- /dev/null +++ b/tests/regrtest/test_builtin_subclass_methods.py @@ -0,0 +1,59 @@ +"""Builtin methods called on instances of builtin subclasses. + +`Counter.most_common` calls `self.items()` on a `dict` subclass's +instance. Compiled code and the core loop call such a method in place +(its body unwraps the payload) instead of leaving for the generic call. +A subclass that overrides the method in Python, a view that follows its +dict, and errors keep their behavior. Items are heap objects. Run it +past the compile threshold. +""" + +import collections + + +class Item: + pass + + +class D(dict): + pass + + +class OwnItems(dict): + def items(self): + return [("own", 1)] + + +class L(list): + pass + + +class S(str): + pass + + +a, b = Item(), Item() +c = collections.Counter("aab") +for _ in range(3000): + d = D(x=a, y=b) + assert sorted(k for k, _ in d.items()) == ["x", "y"] + assert list(d.values())[0] is a and list(d.keys()) == ["x", "y"] + v = d.items() + d["z"] = 1 + assert len(v) == 3 and ("z", 1) in v + assert d.get("x") is a and d.get("q", b) is b + assert d.setdefault("w", a) is a and d.pop("w") is a + assert OwnItems(k=1).items() == [("own", 1)] + assert dict(c.items()) == {"a": 2, "b": 1} + assert c.most_common(1) == [("a", 2)] + lst = L([a]) + lst.append(b) + assert lst.pop() is b and lst.index(a) == 0 and len(lst) == 1 + s = S("a-b") + assert s.upper() == "A-B" and s.split("-") == ["a", "b"] + try: + d.pop("missing") + except KeyError: + pass + else: + raise AssertionError("no KeyError") diff --git a/tests/regrtest/test_builtin_subclass_native_lanes.py b/tests/regrtest/test_builtin_subclass_native_lanes.py new file mode 100644 index 000000000..c51e90378 --- /dev/null +++ b/tests/regrtest/test_builtin_subclass_native_lanes.py @@ -0,0 +1,250 @@ +"""Subclasses of `list`, `tuple`, `set`, `frozenset` and `dict` that +inherit `__eq__` and `__iter__`: equality, set iteration and `sum()` take +native lanes that match the general paths; overrides of `__eq__`, +`__ne__` and `__iter__` stay in charge; `sum()` over an `array.array` or +a deque matches a loop's.""" + +import array +import collections +import unittest +from collections import deque, namedtuple +from fractions import Fraction + +N = 300 + + +class L(list): + pass + + +class T(tuple): + pass + + +class S(set): + pass + + +class F(frozenset): + pass + + +class D(dict): + pass + + +class LEq(list): + def __eq__(self, other): + return "custom" + + __hash__ = None + + +class TNe(tuple): + def __ne__(self, other): + return "ne" + + +class LIter(list): + def __iter__(self): + return iter([100]) + + +class SIter(set): + def __iter__(self): + return iter([7, 7]) + + +Point = namedtuple("Point", "x y") + + +class Loud: + def __init__(self, v): + self.v = v + self.asked = 0 + + def __eq__(self, other): + self.asked += 1 + return isinstance(other, Loud) and self.v == other.v + + __hash__ = None + + +def loop(it): + out = [] + for x in it: + out.append(x) + return out + + +class EqualityTests(unittest.TestCase): + def test_sequences(self): + for _ in range(N): + self.assertTrue(L([1, 2, "a"]) == L([1, 2, "a"])) + self.assertTrue(L([1, 2]) == [1, 2]) + self.assertTrue([1, 2] == L([1, 2])) + self.assertFalse(L([1, 2]) == L([1, 3])) + self.assertFalse(L([1, 2]) == L([1, 2, 3])) + self.assertTrue(L([1, 2]) != L([2, 1])) + self.assertTrue(T((1, 2.5, "x")) == T((1, 2.5, "x"))) + self.assertTrue(T((1, 2)) == (1, 2)) + self.assertTrue((1, 2) == T((1, 2))) + self.assertFalse(T((1, 2)) != (1, 2)) + self.assertFalse(L([1, 2]) == T((1, 2))) + self.assertFalse(T((1, 2)) == [1, 2]) + self.assertTrue(L([1, 2]) != (1, 2)) + self.assertTrue(L([[1], (2, "a")]) == [[1], (2, "a")]) + self.assertTrue(T(()) == T(())) + + def test_named_tuples(self): + for _ in range(N): + self.assertEqual(Point(1, 2), Point(1, 2)) + self.assertEqual(Point(1, 2), (1, 2)) + self.assertNotEqual(Point(1, 2), Point(2, 1)) + self.assertNotEqual(Point(1, 2), [1, 2]) + self.assertEqual(Point("a", 1.5), T(("a", 1.5))) + self.assertIn(Point(1, 2), [Point(0, 0), Point(1, 2)]) + self.assertEqual([Point(1, 2), Point(3, 4)].index((3, 4)), 1) + + def test_sets_and_dicts(self): + for _ in range(N): + self.assertTrue(S({1, 2, 3}) == S({3, 2, 1})) + self.assertTrue(S({1, 2}) == {1, 2}) + self.assertTrue(S({1, 2}) == frozenset({1, 2})) + self.assertTrue(F({1, 2}) == S({1, 2})) + self.assertFalse(S({1, 2}) == S({1, 2, 3})) + self.assertTrue(S({1}) != {2}) + self.assertFalse(S({1, 2}) == [1, 2]) + self.assertTrue(D(a=1, b=2) == D(b=2, a=1)) + self.assertTrue(D(a=1) == {"a": 1}) + self.assertTrue({"a": 1} == D(a=1)) + self.assertFalse(D(a=1) == D(a=2)) + self.assertFalse(D(a=1) == L([("a", 1)])) + + def test_numbers_and_nans(self): + nan = float("nan") + for _ in range(N): + self.assertTrue(L([1, 2.0, True]) == L([1.0, 2, 1])) + self.assertTrue(T((nan,)) == T((nan,))) + self.assertFalse(T((float("nan"),)) == T((float("nan"),))) + self.assertTrue(L([Fraction(1, 2)]) == L([0.5])) + self.assertTrue(T((10**30,)) == T((10**30,))) + + def test_elements_with_eq(self): + for _ in range(50): + a, b = Loud(1), Loud(1) + self.assertTrue(L([a, 2]) == L([b, 2])) + self.assertGreater(a.asked + b.asked, 0) + self.assertFalse(T((Loud(1),)) == T((Loud(2),))) + same = Loud(5) + self.assertTrue(L([same]) == L([same])) + self.assertEqual(same.asked, 0) + + def test_overrides_stay_in_charge(self): + for _ in range(N): + self.assertEqual(LEq([1]) == LEq([1]), "custom") + self.assertEqual(LEq([1]) == [1], "custom") + self.assertEqual([1] == LEq([1]), "custom") + self.assertEqual(TNe((1,)) != TNe((1,)), "ne") + self.assertEqual(TNe((1,)) != (2,), "ne") + self.assertTrue(TNe((1,)) == (1,)) + od = collections.OrderedDict(a=1, b=2) + od2 = collections.OrderedDict(b=2, a=1) + self.assertFalse(od == od2) + self.assertTrue(collections.Counter(a=1, b=0) == collections.Counter(a=1)) + + def test_other_operands(self): + class Anything: + def __eq__(self, other): + return True + + for _ in range(50): + self.assertTrue(L([1]) == Anything()) + self.assertTrue(Anything() == T((1,))) + self.assertFalse(L([1]) == object()) + self.assertFalse(S({1}) == None) # noqa: E711 + self.assertTrue(D(a=1) != 5) + + +class IterationTests(unittest.TestCase): + def test_set_subclass_loops(self): + s = S(range(10)) + f = F("abc") + for _ in range(N): + self.assertEqual(sorted(loop(s)), list(range(10))) + self.assertEqual(sorted(loop(f)), ["a", "b", "c"]) + self.assertEqual(sorted(x for x in s if x % 2), [1, 3, 5, 7, 9]) + self.assertEqual(len(list(s)), 10) + self.assertEqual(sorted(S("hello")), ["e", "h", "l", "o"]) + self.assertEqual(loop(S()), []) + + def test_set_subclass_size_change_raises(self): + for _ in range(50): + s = S({1, 2, 3}) + with self.assertRaises(RuntimeError): + for x in s: + s.add(x + 100) + + def test_overridden_iter(self): + for _ in range(N): + self.assertEqual(loop(SIter({1, 2, 3})), [7, 7]) + self.assertEqual(list(SIter({1})), [7, 7]) + self.assertEqual(sum(SIter({1})), 14) + self.assertEqual(loop(LIter([1, 2])), [100]) + self.assertEqual(sum(LIter([1, 2])), 100) + + +class SumTests(unittest.TestCase): + def test_arrays(self): + ints = array.array("i", range(50)) + longs = array.array("q", [2**40, -(2**40), 7]) + floats = array.array("d", [0.5, 1.5, 2.0]) + small = array.array("B", [255, 255]) + for _ in range(N): + self.assertEqual(sum(ints), 1225) + self.assertEqual(sum(ints, 10), 1235) + self.assertEqual(sum(longs), 7) + self.assertEqual(sum(floats), 4.0) + self.assertEqual(sum(floats, 1), 5.0) + self.assertEqual(sum(small), 510) + self.assertEqual(sum(array.array("i")), 0) + self.assertIs(type(sum(floats)), float) + self.assertIs(type(sum(ints)), int) + + def test_deques_and_subclasses(self): + d = deque(range(10)) + d.popleft() + d.appendleft(100) + for _ in range(N): + self.assertEqual(sum(d), 145) + self.assertEqual(sum(deque([0.5, 0.25])), 0.75) + self.assertEqual(sum(L([1, 2, 3])), 6) + self.assertEqual(sum(T((1.5, 2.5))), 4.0) + self.assertEqual(sum(S({1, 2, 3}), 4), 10) + self.assertEqual(sum(L([Fraction(1, 2), Fraction(1, 2)])), 1) + self.assertEqual(sum(L([[1], [2]]), []), [1, 2]) + self.assertEqual(sum(deque([10**30, 1])), 10**30 + 1) + with self.assertRaises(TypeError): + sum(L(["a", "b"])) + with self.assertRaises(TypeError): + sum(deque(["a"])) + + def test_add_that_mutates_the_source(self): + d = deque() + + class Grow: + def __init__(self, n): + self.n = n + + def __radd__(self, other): + if self.n: + d.append(Grow(0)) + return other + 1 + + d.append(Grow(1)) + with self.assertRaises(RuntimeError): + sum(d) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_builtin_subclass_operators.py b/tests/regrtest/test_builtin_subclass_operators.py new file mode 100644 index 000000000..27590503b --- /dev/null +++ b/tests/regrtest/test_builtin_subclass_operators.py @@ -0,0 +1,66 @@ +"""Operators of builtin subclasses with Python methods, and tuple loops. + +Compiled code calls an `int` subclass's own Python `__or__` (`IntFlag`'s) +directly; a subclass that keeps `int`'s operator must still compute as an +`int`, and a reflected operand's method must still win where CPython lets +it. A loop over a fresh tuple of objects (`for flag in self, other`) +releases the tuple in place when its items live on, and must still run a +finalizer an item owes when the tuple was its last owner. Run it past the +compile threshold. +""" + +import enum + + +class Color(enum.IntFlag): + R = 1 + G = 2 + B = 4 + + +class Plain(int): + pass + + +class Loud(int): + def __or__(self, other): + return ("or", int(self), int(other)) + + def __ror__(self, other): + return ("ror", int(other), int(self)) + + +class Sub(Loud): + def __ror__(self, other): + return ("sub-ror", int(other), int(self)) + + +freed = [] + + +class Dies: + def __del__(self): + freed.append(1) + + +def pair(a, b): + n = 0 + for x in a, b: + if x is not None: + n += 1 + return n + + +for _ in range(3000): + assert Color.R | Color.G == Color(3) + assert (Color.R | Color.B) & Color.B == Color.B + assert Plain(5) | Plain(2) == 7 and type(Plain(5) | Plain(2)) is int + assert Loud(1) | Loud(2) == ("or", 1, 2) + assert Loud(1) | 4 == ("or", 1, 4) + assert Loud(1) | Sub(2) == ("sub-ror", 1, 2) + assert pair(Color.R, Color.G) == 2 + +freed.clear() +for _ in range(500): + assert pair(Dies(), Dies()) == 2 +assert len(freed) == 1000, len(freed) diff --git a/tests/regrtest/test_builtin_subclass_payload.py b/tests/regrtest/test_builtin_subclass_payload.py new file mode 100644 index 000000000..2f8310335 --- /dev/null +++ b/tests/regrtest/test_builtin_subclass_payload.py @@ -0,0 +1,126 @@ +"""Methods, `len()` and `in` on instances of builtin subclasses. + +A dict, list, set or str subclass that doesn't override a method runs +the base's own on its native payload (`Counter.get`, a list subclass's +`append`, `len(od)`, `key in counter`). An override, including one +assigned after the call sites have warmed up, still runs; views keep the +instance; errors match the base's. Run it past the compile threshold. +""" + +import collections + + +class D(dict): + pass + + +class L(list): + pass + + +class S(set): + pass + + +class T(str): + pass + + +class Tup(tuple): + pass + + +class Late(dict): + pass + + +class Own(list): + def __len__(self): + return 99 + + def __contains__(self, item): + return item == "own" + + def append(self, item): + list.append(self, item * 2) + + +def run(n): + total = 0 + for i in range(n): + d = D(a=1) + assert d.get("a") == 1 and d.get("z") is None and d.get("z", 5) == 5 + assert "a" in d and "z" not in d and len(d) == 1 + items = d.items() + d["b"] = 2 + assert list(items) == [("a", 1), ("b", 2)] and len(items) == 2 + assert list(d.keys()) == ["a", "b"] and list(d.values()) == [1, 2] + assert type(items.mapping) is type({}.items().mapping) + assert items.mapping["b"] == 2 + try: + d.get([]) + except TypeError: + pass + else: + raise AssertionError("unhashable key") + + lst = L([1, 2]) + lst.append(3) + assert lst.pop() == 3 and lst == [1, 2] and len(lst) == 2 and 2 in lst + lst.extend([4]) + lst.insert(0, 0) + lst.reverse() + assert lst == [4, 2, 1, 0] + c = lst.copy() + assert type(c) is list and c == [4, 2, 1, 0] + try: + L().pop() + except IndexError: + pass + else: + raise AssertionError("pop from empty") + + s = S({1}) + s.add(2) + s.discard(1) + assert s == {2} and len(s) == 1 and 2 in s + try: + s.remove(7) + except KeyError: + pass + else: + raise AssertionError("remove missing") + + t = T(" Ab ") + st = t.strip() + assert st == "Ab" and type(st) is str + assert t.lower() == " ab " and type(t.lower()) is str + assert t.startswith(" A") and t.find("b") == 2 and len(t) == 4 and "Ab" in t + assert T("-").join(["a", "b"]) == "a-b" and T("a b").split() == ["a", "b"] + assert len(Tup((1, 2))) == 2 and 2 in Tup((1, 2)) + + o = Own([1]) + o.append(5) + assert list.__len__(o) == 2 and o[1] == 10 + assert len(o) == 99 and "own" in o and 1 not in o + + cnt = collections.Counter("abca") + assert cnt.get("a") == 2 and "b" in cnt and len(cnt) == 3 + od = collections.OrderedDict(x=1) + assert od.get("x") == 1 and "x" in od and len(od) == 1 + + late = Late(k=1) + if i == n // 2: + Late.get = lambda self, k, default=None: "late" + Late.__len__ = lambda self: 7 + Late.__contains__ = lambda self, k: True + if i >= n // 2: + assert late.get("k") == "late" and len(late) == 7 and "q" in late + else: + assert late.get("k") == 1 and len(late) == 1 and "q" not in late + total += len(d) + len(lst) + return total + + +assert run(3000) == 6 * 3000 +print("ok") diff --git a/tests/regrtest/test_builtin_subclass_str_format.py b/tests/regrtest/test_builtin_subclass_str_format.py new file mode 100644 index 000000000..1b8c15dca --- /dev/null +++ b/tests/regrtest/test_builtin_subclass_str_format.py @@ -0,0 +1,246 @@ +"""str(), format() and f-strings of str, int and float subclass instances +(IntEnum, StrEnum, IntFlag, plain subclasses) from compiled loops: the +payload's text where the class keeps its base's methods, a spec +formatted against the payload, and every override (`__str__`, +`__repr__`, `__format__`, one added after the loop warmed up) still +taking effect, each matching CPython.""" + +import enum +import unittest + + +class I(int): + pass + + +class F(float): + pass + + +class S(str): + pass + + +class Num(enum.IntEnum): + A = 1 + B = 22 + + +class St(enum.StrEnum): + A = "a" + B = "bee" + + +class Color(enum.Enum): + RED = 1 + + +class Perm(enum.IntFlag): + R = 4 + W = 2 + + +class OwnRepr(int): + def __repr__(self): + return "OwnRepr!" + + +class OwnStr(int): + def __str__(self): + return "OwnStr!" + + +class OwnFormat(int): + def __format__(self, spec): + return "fmt:" + spec + + +class Late(int): + pass + + +def render(n, x): + out = None + for i in range(n): + out = (str(x), f"{x}", format(x), "%s" % (x,), "{}".format(x)) + return out + + +def spec(n, x, s): + out = None + for i in range(n): + out = (f"{x:>6}", format(x, s)) + return out + + +class SubclassStrFormatTests(unittest.TestCase): + def test_payload_text(self): + cases = [ + (I(5), "5"), + (I(-12), "-12"), + (F(2.5), "2.5"), + (S("x"), "x"), + (Num.B, "22"), + (St.B, "bee"), + (I(10**30), str(10**30)), + ] + for x, want in cases: + for n in (1, 400): + got = render(n, x) + self.assertEqual(got, (want,) * 5, x) + self.assertTrue(all(type(g) is str for g in got)) + + def test_specs(self): + for n in (1, 400): + self.assertEqual(spec(n, Num.B, "x"), (" 22", "16")) + self.assertEqual(spec(n, I(255), "08b"), (" 255", "11111111")) + self.assertEqual(spec(n, F(1.25), ".1f"), (" 1.25", "1.2")) + self.assertEqual(spec(n, St.B, "^7"), (" bee", " bee ")) + self.assertEqual(spec(n, S("q"), "<3"), (" q", "q ")) + with self.assertRaises(ValueError): + spec(300, St.A, "d") + + def test_overrides(self): + for n in (1, 400): + self.assertEqual(render(n, OwnRepr(3)), ("OwnRepr!",) * 5) + self.assertEqual(render(n, OwnStr(3)), ("OwnStr!",) * 5) + self.assertEqual(render(n, OwnFormat(3))[1:3], ("fmt:", "fmt:")) + self.assertEqual(render(n, OwnFormat(3))[0], "3") + self.assertEqual(render(n, Color.RED), ("Color.RED",) * 5) + self.assertEqual(render(n, Perm.R | Perm.W), ("6",) * 5) + + def test_override_added_later(self): + self.assertEqual(render(400, Late(7)), ("7",) * 5) + Late.__str__ = lambda self: "late" + try: + self.assertEqual(render(400, Late(7)), ("late",) * 5) + finally: + del Late.__str__ + Late.__format__ = lambda self, s: "F" + s + try: + self.assertEqual(render(400, Late(7))[1:3], ("F", "F")) + finally: + del Late.__format__ + self.assertEqual(render(400, Late(7)), ("7",) * 5) + + def test_join_and_percent(self): + class SS(str): + def __str__(self): + return "zzz" + + def j(n, items): + out = None + for i in range(n): + out = "-".join(items) + return out + + def pct(n, fmt, args): + out = None + for i in range(n): + out = fmt % args + return out + + for n in (1, 400): + self.assertEqual(j(n, (St.A, St.B)), "a-bee") + self.assertEqual(j(n, [S("x"), "y", St.A]), "x-y-a") + self.assertEqual(j(n, [SS("a"), SS("b")]), "a-b") + solo = j(n, [S("solo")]) + self.assertEqual(solo, "solo") + self.assertIs(type(solo), str) + self.assertEqual(pct(n, "%s", St.B), "bee") + self.assertEqual(pct(n, "%s/%s", (Num.B, I(3))), "22/3") + self.assertEqual(pct(n, "%s %%", (F(1.5),)), "1.5 %") + self.assertEqual(pct(n, "%r", (St.B,)), "") + self.assertEqual(pct(n, "%d", (Num.B,)), "22") + self.assertEqual(pct(n, "%s", (Color.RED,)), "Color.RED") + self.assertEqual(pct(n, "%s", (OwnStr(1),)), "OwnStr!") + self.assertEqual(pct(n, "%s", (SS("q"),)), "zzz") + with self.assertRaises(TypeError): + j(300, [St.A, 1]) + with self.assertRaises(TypeError): + pct(300, "%s %s", (St.A,)) + + def test_plain_enums(self): + class Shade(enum.Enum): + DARK = 1 + LIGHT = 2 + + class Mixed(int, enum.Enum): + ONE = 1 + + class Custom(enum.Enum): + X = 1 + + def __str__(self): + return "custom" + + class Bits(enum.Flag): + A = 1 + B = 2 + + for n in (1, 400): + self.assertEqual(render(n, Shade.DARK), ("Shade.DARK",) * 5) + self.assertEqual(spec(n, Shade.LIGHT, "<12"), ("Shade.LIGHT", "Shade.LIGHT ")) + self.assertEqual(render(n, Mixed.ONE), ("Mixed.ONE",) * 5) + self.assertEqual(render(n, Custom.X), ("custom",) * 5) + self.assertEqual(render(n, Bits.A | Bits.B), ("Bits.A|B",) * 5) + self.assertEqual(render(n, Bits.A), ("Bits.A",) * 5) + Shade.__name__ = "Tone" + try: + self.assertEqual(render(400, Shade.DARK), ("Tone.DARK",) * 5) + finally: + Shade.__name__ = "Shade" + Shade.__str__ = lambda self: "late" + try: + self.assertEqual(render(400, Shade.DARK), ("late",) * 5) + finally: + del Shade.__str__ + self.assertEqual(render(400, Shade.DARK), ("Shade.DARK",) * 5) + + def test_profiler_sees_enum_methods(self): + import sys + + render(400, Color.RED) + seen = [] + + def prof(frame, event, arg): + if event == "call": + seen.append(frame.f_code.co_name) + + sys.setprofile(prof) + try: + render(1, Color.RED) + finally: + sys.setprofile(None) + self.assertIn("__str__", seen) + self.assertIn("__format__", seen) + + def test_percent_temporaries(self): + dead = [] + + class DS(str): + def __del__(self): + dead.append(1) + + def f(n): + out = None + for i in range(n): + out = "%s" % DS("t") + out = "%s|%s" % (DS("u"), 1) + return out + + self.assertEqual(f(300), "u|1") + self.assertEqual(len(dead), 600) + + def test_temporaries(self): + def temp(n): + out = [] + for i in range(n): + out.append(f"{I(i)}") + return out + + self.assertEqual(temp(300), [str(i) for i in range(300)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_builtin_type_keyword_calls.py b/tests/regrtest/test_builtin_type_keyword_calls.py new file mode 100644 index 000000000..bd009e36d --- /dev/null +++ b/tests/regrtest/test_builtin_type_keyword_calls.py @@ -0,0 +1,69 @@ +"""Builtin types called with keywords that name positional parameters. + +`int(text, base=16)`, `enumerate(xs, start=1)`, `str(b, encoding=...)` +and `bytes(s, encoding=...)` take the positional call's path when the +keywords name, in order, the parameters after the positional ones. Any +other keyword shape (a positional-only parameter by keyword, keywords in +another order, unknown names) takes the full call, with CPython's results +and errors. +""" + +import unittest + + +class BuiltinTypeKeywordTests(unittest.TestCase): + def test_values(self): + for _ in range(300): + self.assertEqual(int("ff", base=16), 255) + self.assertEqual(int("101", base=2), 5) + self.assertEqual(list(enumerate("ab", start=1)), [(1, "a"), (2, "b")]) + self.assertEqual(list(enumerate(iterable="ab")), [(0, "a"), (1, "b")]) + self.assertEqual(list(enumerate(iterable="a", start=5)), [(5, "a")]) + self.assertEqual(str(b"hi", encoding="ascii"), "hi") + self.assertEqual(str(b"h\xff", "latin-1", errors="strict"), "h\xff") + self.assertEqual(str(object=5), "5") + self.assertEqual(bytes("hé", encoding="utf-8"), b"h\xc3\xa9") + self.assertEqual(bytearray("ab", encoding="ascii"), bytearray(b"ab")) + + def test_errors(self): + with self.assertRaises(TypeError): + int(x="5") + with self.assertRaises(TypeError): + int(base=16) + with self.assertRaises(ValueError): + int("zz", base=16) + self.assertEqual(list(enumerate(start=1, iterable="a")), [(1, "a")]) + with self.assertRaises(TypeError): + enumerate("a", begin=1) + with self.assertRaises(UnicodeDecodeError): + str(b"\xff", encoding="ascii") + with self.assertRaises(LookupError): + bytes("a", encoding="no-such") + with self.assertRaises(TypeError): + str(5, encoding="utf-8") + + def test_strict_zip_and_map(self): + xs, ys = [1, 2, 3], "abc" + for _ in range(300): + self.assertEqual(list(zip(xs, ys, strict=True)), [(1, "a"), (2, "b"), (3, "c")]) + self.assertEqual(list(zip(xs, ys[:2], strict=False)), [(1, "a"), (2, "b")]) + self.assertEqual(list(map(lambda a, b: a * 2 + len(b), xs, ys, strict=True)), [3, 5, 7]) + with self.assertRaises(ValueError) as cm: + list(zip(xs, ys[:2], strict=True)) + self.assertIn("zip() argument 2 is shorter than argument 1", str(cm.exception)) + with self.assertRaises(ValueError): + list(map(pow, [1, 2], [3], strict=True)) + self.assertEqual(list(zip(xs, ys, strict=1)), [(1, "a"), (2, "b"), (3, "c")]) + with self.assertRaises(TypeError): + zip(xs, nope=True) + + def test_subclasses_keep_their_call(self): + class I(int): + pass + + self.assertIs(type(I("ff", base=16)), I) + self.assertEqual(I("ff", base=16), 255) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytearray_hex_plain.py b/tests/regrtest/test_bytearray_hex_plain.py new file mode 100644 index 000000000..8eced8b44 --- /dev/null +++ b/tests/regrtest/test_bytearray_hex_plain.py @@ -0,0 +1,36 @@ +"""`bytearray.hex()` without arguments, in hot loops, matches CPython, and +the separator forms still guard the receiver as CPython's do.""" + +import unittest + + +class BytearrayHexPlain(unittest.TestCase): + def test_plain(self): + for i in range(3000): + b = bytearray(b"abc") + self.assertEqual(b.hex(), "616263") + b.append(i & 0xFF) + self.assertEqual(b.hex()[-2:], format(i & 0xFF, "02x")) + self.assertEqual(bytearray().hex(), "") + + def test_separator_forms(self): + b = bytearray(b"\x01\x02\x03\x04") + for _ in range(1000): + self.assertEqual(b.hex(":"), "01:02:03:04") + self.assertEqual(b.hex("-", 2), "0102-0304") + self.assertEqual(b.hex(sep="_", bytes_per_sep=-3), "010203_04") + + def test_resize_during_sep_len(self): + b = bytearray(b"abcd") + + class Sep(str): + def __len__(self): + b.clear() + return 1 + + with self.assertRaises(BufferError): + b.hex(Sep(":")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytearray_methods_in_hot_loops.py b/tests/regrtest/test_bytearray_methods_in_hot_loops.py new file mode 100644 index 000000000..ed180244b --- /dev/null +++ b/tests/regrtest/test_bytearray_methods_in_hot_loops.py @@ -0,0 +1,297 @@ +"""A bytearray built and read a byte at a time, in loops long enough to +be compiled. + +`b.append(n)`, `b.extend(data)`, `b.pop()`, `b[i]`, `len(b)` and +`b.decode()` give the same results however many times the loop has run, +and refuse the same things: a value that isn't a byte, a resize while a +view of the buffer is exported, an index out of range, a pop from an +empty buffer. The same holds for the neighbours that share their paths: +a byte stored through a `memoryview`, an item of a `range`, and +`slice.indices`. +""" + +import hashlib +import itertools +import unittest + +ROUNDS = 3000 + + +def build_by_append(n): + b = bytearray() + for i in range(n): + b.append(i & 0xFF) + return b + + +def build_by_extend(n, chunk): + b = bytearray() + for _ in range(n): + b.extend(chunk) + return b + + +def drain(b): + out = [] + while b: + out.append(b.pop()) + return out + + +def checksum(b): + total = 0 + for i in range(len(b)): + total += b[i] * (i & 7) + return total + + +def fill_view(view, n): + for i in range(n): + view[i] = (i * 7) & 0xFF + + +def range_total(r, n): + total = 0 + for i in range(n): + total += r[i] + r[-1 - i] + return total + + +class BuildTests(unittest.TestCase): + def test_append(self): + b = build_by_append(ROUNDS) + self.assertEqual(len(b), ROUNDS) + self.assertEqual(bytes(b), bytes(i & 0xFF for i in range(ROUNDS))) + self.assertIs(type(b), bytearray) + + def test_append_refuses_what_is_not_a_byte(self): + b = bytearray(b"ab") + for i in range(ROUNDS): + b.append(1) + for bad, error in ((256, ValueError), (-1, ValueError), (1.5, TypeError), ("a", TypeError), (None, TypeError)): + with self.subTest(bad=bad): + with self.assertRaises(error): + b.append(bad) + self.assertEqual(len(b), ROUNDS + 2) + b.append(True) + self.assertEqual(b[-1], 1) + + class Index: + def __index__(self): + return 65 + + b.append(Index()) + self.assertEqual(b[-1], 65) + + def test_extend(self): + self.assertEqual(build_by_extend(ROUNDS, b"ab"), b"ab" * ROUNDS) + self.assertEqual(build_by_extend(ROUNDS, bytearray(b"xyz")), b"xyz" * ROUNDS) + self.assertEqual(build_by_extend(50, [1, 2, 3]), bytes([1, 2, 3]) * 50) + self.assertEqual(build_by_extend(50, memoryview(b"mv")), b"mv" * 50) + self.assertEqual(build_by_extend(50, range(4)), bytes(range(4)) * 50) + self.assertEqual(build_by_extend(5, b""), b"") + b = bytearray(b"abc") + for _ in range(3): + b.extend(b) + self.assertEqual(b, b"abc" * 8) + with self.assertRaises(TypeError): + b.extend("text") + with self.assertRaises(ValueError): + b.extend([1, 256]) + with self.assertRaises(TypeError): + b.extend(5) + + def test_pop(self): + b = build_by_append(ROUNDS) + out = drain(b) + self.assertEqual(out, [i & 0xFF for i in reversed(range(ROUNDS))]) + self.assertEqual(b, b"") + with self.assertRaises(IndexError): + b.pop() + c = bytearray(b"abcd") + self.assertEqual(c.pop(0), ord("a")) + self.assertEqual(c.pop(-2), ord("c")) + self.assertEqual(c, b"bd") + with self.assertRaises(IndexError): + c.pop(5) + + def test_an_exported_buffer_is_not_resized(self): + b = bytearray(b"abc") + view = memoryview(b) + for _ in range(ROUNDS): + with self.assertRaises(BufferError): + b.append(1) + with self.assertRaises(BufferError): + b.extend(b"x") + with self.assertRaises(BufferError): + b.pop() + self.assertEqual(b, b"abc") + view.release() + b.append(1) + b.extend(b"x") + self.assertEqual(b.pop(), ord("x")) + self.assertEqual(b, b"abc\x01") + + def test_decode(self): + b = bytearray() + text = "" + for i in range(300): + b.extend(b"caf\xc3\xa9 ") + text += "café " + if i % 50 == 0: + self.assertEqual(b.decode(), text) + self.assertEqual(b.decode("utf-8"), text) + self.assertEqual(b.decode(errors="strict"), text) + self.assertEqual(len(b.decode()), 5 * 300) + b.append(0xFF) + with self.assertRaises(UnicodeDecodeError): + b.decode() + self.assertEqual(b.decode(errors="ignore"), text) + + +class ReadTests(unittest.TestCase): + def test_items_and_length(self): + b = build_by_append(ROUNDS) + self.assertEqual(checksum(b), sum((i & 0xFF) * (i & 7) for i in range(ROUNDS))) + self.assertEqual([b[-1 - i] for i in range(5)], [(ROUNDS - 1 - i) & 0xFF for i in range(5)]) + for bad in (ROUNDS, -ROUNDS - 1, 10**12): + with self.assertRaises(IndexError): + b[bad] + with self.assertRaises(TypeError): + b["0"] + self.assertEqual(b[True], 1) + total = 0 + for _ in range(ROUNDS): + total += len(b) + if len(b) > 2000: + del b[:1000] + self.assertEqual(len(b), 2000) + + def test_lengths_of_other_kinds(self): + fs = frozenset(range(37)) + total = 0 + for _ in range(ROUNDS): + total += len(fs) + self.assertEqual(total, 37 * ROUNDS) + + def test_bytes_stored_through_a_view(self): + buf = bytearray(ROUNDS) + view = memoryview(buf) + fill_view(view, ROUNDS) + self.assertEqual(buf, bytes((i * 7) & 0xFF for i in range(ROUNDS))) + for bad, error in ((256, ValueError), (-1, ValueError), ("a", TypeError), (1.5, TypeError)): + with self.subTest(bad=bad): + with self.assertRaises(error): + view[0] = bad + with self.assertRaises(IndexError): + view[ROUNDS] = 0 + self.assertEqual(buf[0], 0) + frozen = memoryview(bytes(8)) + for _ in range(100): + with self.assertRaises(TypeError): + frozen[0] = 1 + view.release() + for _ in range(100): + with self.assertRaises(ValueError): + view[0] = 1 + + def test_range_items(self): + for r in (range(ROUNDS), range(5, 5 + 3 * ROUNDS, 3), range(10 * ROUNDS, 0, -10), range(-ROUNDS, 0)): + with self.subTest(r=r): + items = list(r) + want = sum(items[i] + items[-1 - i] for i in range(ROUNDS)) + self.assertEqual(range_total(r, ROUNDS), want) + r = range(10) + for _ in range(200): + with self.assertRaises(IndexError): + r[10] + with self.assertRaises(IndexError): + r[-11] + big = range(2**70, 2**70 + 100) + self.assertEqual(sum(big[i] - 2**70 for i in range(100)), 4950) + + def test_slice_indices(self): + bounds = [None, 0, 1, 2, 5, 10, 11, -1, -2, -10, -11, 100, -100] + steps = [None, 1, 2, 3, -1, -2, -3, 100, -100] + out = [] + for a, b, c in itertools.product(bounds, bounds, steps): + for n in (0, 1, 2, 10, 11): + got = slice(a, b, c).indices(n) + out.append(got) + # What the indices mean: the items a list of that length + # gives for the slice. + self.assertEqual(list(range(n))[a:b:c], list(range(*got))) + digest = hashlib.sha256(repr(out).encode()).hexdigest() + self.assertEqual(digest, "ce3bf762ebb40629a68d9503c9bd3563c20f0a4606dab995328682a14695e21b") + self.assertEqual(slice(None, None, -1).indices(2**70), (2**70 - 1, -1, -1)) + self.assertEqual(slice(2**70, None).indices(5), (5, 5, 1)) + self.assertEqual(slice(None).indices(True), (0, 1, 1)) + with self.assertRaises(ValueError): + slice(1).indices(-1) + with self.assertRaises(ValueError): + slice(1, 2, 0).indices(5) + with self.assertRaises(TypeError): + slice("a").indices(5) + with self.assertRaises(TypeError): + slice(1).indices("5") + + +def byte_total(data): + total = 0 + for b in data: + total += b + return total + + +class IterationTests(unittest.TestCase): + def test_loops_over_bytes_and_buffers(self): + data = bytes(range(256)) * 20 + want = sum(range(256)) * 20 + for kind in (bytes, bytearray): + with self.subTest(kind=kind.__name__): + value = kind(data) + for _ in range(5): + self.assertEqual(byte_total(value), want) + self.assertEqual(sum(value), want) + self.assertEqual(max(value), 255) + self.assertEqual(min(value), 0) + self.assertEqual(max(kind(b"q")), ord("q")) + with self.assertRaises(ValueError): + max(kind()) + with self.assertRaises(ValueError): + min(kind()) + self.assertEqual(sum(kind()), 0) + self.assertEqual(sum(kind(b"ab"), 1000), 1000 + 97 + 98) + self.assertEqual(max(kind(b"abc"), default=0), 99) + self.assertEqual(max(kind(), default=-1), -1) + self.assertEqual(min(kind(b"abc"), key=lambda b: -b), 99) + self.assertEqual(max(kind(b"ab"), kind(b"b")), kind(b"b")) + self.assertTrue(all(type(b) is int for b in kind(b"xy"))) + + def test_a_buffer_that_changes_during_the_loop(self): + buf = bytearray(range(100)) + seen = [] + for b in buf: + seen.append(b) + if b == 10: + del buf[20:] + if b == 15: + buf.extend(b"\xff\xfe") + self.assertEqual(seen, list(range(20)) + [255, 254]) + buf = bytearray(b"abc") + it = iter(buf) + self.assertEqual(list(it), [97, 98, 99]) + buf.extend(b"de") + self.assertEqual(list(it), []) + buf = bytearray(b"abc") + out = [] + for i in range(ROUNDS): + for b in buf: + out.append(b) + if i == ROUNDS - 2: + buf.clear() + self.assertEqual(len(out), 3 * (ROUNDS - 1)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytearray_slice_stores_and_deletes.py b/tests/regrtest/test_bytearray_slice_stores_and_deletes.py new file mode 100644 index 000000000..87c6c1130 --- /dev/null +++ b/tests/regrtest/test_bytearray_slice_stores_and_deletes.py @@ -0,0 +1,222 @@ +"""Storing to and deleting a slice of a bytearray. + +`b[i:j] = data` and `del b[i:j]` work on the bytes themselves: a store +of the same length changes them in place, any other moves what follows +the slice once, and an extended slice (`b[::2]`) is stored byte by byte +or deleted by closing the gaps in one pass. The cost of a store or a +delete near the front depends on the bytes moved, not on a copy of the +whole buffer per byte. +""" + +import time +import unittest + +BOUNDS = (None, 0, 1, 3, 9, 20, -1, -2, -20) +STEPS = (None, 1, 2, 3, 5, -1, -2, -7) + + +def model_store(data, sl, rep): + """What `bytearray(data)[sl] = rep` leaves, on a list of ints.""" + items = list(data) + items[sl] = list(rep) + return bytes(items) + + +def model_delete(data, sl): + items = list(data) + del items[sl] + return bytes(items) + + +class SliceStoreTests(unittest.TestCase): + def test_stores_match_a_list_of_ints(self): + for src in (b"0123456789", b"", b"a"): + for start in BOUNDS: + for stop in BOUNDS: + for step in STEPS: + sl = slice(start, stop, step) + for rep in (b"", b"x", b"xyz", b"0123456789ab"): + b = bytearray(src) + try: + want = model_store(src, sl, rep) + except ValueError: + # (An empty store to an extended slice is a + # bytearray's deletion; a list refuses it + # unless the slice is empty too.) + if rep: + with self.assertRaises(ValueError): + b[sl] = rep + self.assertEqual(b, src) + else: + b[sl] = rep + self.assertEqual(bytes(b), model_delete(src, sl)) + continue + b[sl] = rep + if not rep and step not in (None, 1): + want = model_delete(src, sl) + self.assertEqual(bytes(b), want, (src, sl, rep)) + + def test_deletes_match_a_list_of_ints(self): + for src in (b"0123456789", b"", b"a", bytes(range(97))): + for start in BOUNDS: + for stop in BOUNDS: + for step in STEPS: + sl = slice(start, stop, step) + b = bytearray(src) + del b[sl] + self.assertEqual(bytes(b), model_delete(src, sl), (src, sl)) + + def test_extended_slice_size_mismatch(self): + b = bytearray(10) + with self.assertRaises(ValueError) as cm: + b[::2] = b"abc" + self.assertEqual( + str(cm.exception), "attempt to assign bytes of size 3 to extended slice of size 5" + ) + self.assertEqual(b, bytearray(10)) + + def test_other_sources(self): + b = bytearray(b"0123456789") + b[2:5] = [65, 66] + self.assertEqual(b, b"01AB56789") + b[2:4] = bytearray(b"zzz") + self.assertEqual(b, b"01zzz56789") + b[::2] = range(5) + self.assertEqual(b, bytes([0, 49, 1, 122, 2, 53, 3, 55, 4, 57])) + b[:] = memoryview(b"pq") + self.assertEqual(b, b"pq") + b[1:1] = (ord(c) for c in "xyz") + self.assertEqual(b, b"pxyzq") + with self.assertRaises(ValueError): + b[0:1] = [256] + with self.assertRaises(TypeError): + b[0:1] = ["a"] + self.assertEqual(b, b"pxyzq") + + def test_a_bytearray_stored_into_itself(self): + b = bytearray(b"0123456789") + b[1:4] = b + self.assertEqual(b, b"00123456789456789") + b = bytearray(b"abc") + b[:] = b + self.assertEqual(b, b"abc") + b[1:1] = b + self.assertEqual(b, b"aabcbc") + + def test_index_objects_as_bounds(self): + class Index: + def __init__(self, value): + self.value = value + + def __index__(self): + return self.value + + b = bytearray(b"0123456789") + b[Index(1):Index(3)] = b"Q" + self.assertEqual(b, b"0Q3456789") + del b[Index(0):Index(2)] + self.assertEqual(b, b"3456789") + del b[Index(-2):] + self.assertEqual(b, b"34567") + b[::Index(2)] = b"abc" + self.assertEqual(b, b"a4b6c") + + +class ExportedBufferTests(unittest.TestCase): + def test_a_resize_is_refused_while_a_view_is_exported(self): + b = bytearray(b"0123456789") + view = memoryview(b) + with self.assertRaises(BufferError): + b[0:2] = b"abc" + with self.assertRaises(BufferError): + del b[0:2] + with self.assertRaises(BufferError): + del b[1:1:2] + with self.assertRaises(BufferError): + b[::2] = b"" + self.assertEqual(b, b"0123456789") + # A store of the same length, and an empty plain delete, resize + # nothing. + b[0:2] = b"ab" + del b[1:1] + b[::5] = b"XY" + self.assertEqual(b, b"Xb234Y6789") + self.assertEqual(view.tobytes(), b"Xb234Y6789") + view.release() + del b[0:2] + self.assertEqual(b, b"234Y6789") + + def test_a_same_length_store_shows_through_a_view(self): + b = bytearray(1000) + view = memoryview(b) + b[100:104] = b"abcd" + self.assertEqual(bytes(view[98:106]), b"\0\0abcd\0\0") + view[200:202] = b"zz" + self.assertEqual(b[199:203], b"\0zz\0") + view.release() + + +class CostTests(unittest.TestCase): + """A store or delete costs the bytes it moves, once.""" + + @staticmethod + def best(fn, repeat=5): + best = float("inf") + for _ in range(repeat): + start = time.perf_counter() + fn() + best = min(best, time.perf_counter() - start) + return best + + def test_deleting_a_run_moves_the_tail_once(self): + def consume(run): + b = bytearray(200_000) + + def go(): + for _ in range(40): + del b[:run] + + return go + + short = self.best(consume(1)) + long = self.best(consume(64)) + # (One move per byte deleted made the 64-byte run 64 times the + # 1-byte run's cost.) + self.assertLess(long, short * 12 + 0.002) + + def test_a_small_store_does_not_copy_the_buffer(self): + def store(size): + b = bytearray(size) + + def go(): + for i in range(300): + b[8:12] = b"abcd" + b[16:20] = b"xy" + b[16:18] = b"wxyz" + + return go + + small = self.best(store(4_000)) + large = self.best(store(400_000)) + # (The large buffer's stores move 100 times the bytes, in two of + # the three stores; rebuilt as a list of ints per store, it cost + # thousands of times the small one's.) + self.assertLess(large, small * 400 + 0.05) + + def test_same_length_stores_do_not_depend_on_the_size(self): + def store(size): + b = bytearray(size) + + def go(): + for i in range(2000): + b[8:12] = b"abcd" + + return go + + small = self.best(store(1_000)) + large = self.best(store(1_000_000)) + self.assertLess(large, small * 20 + 0.01) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_affix_calls.py b/tests/regrtest/test_bytes_affix_calls.py new file mode 100644 index 000000000..5e7a47da1 --- /dev/null +++ b/tests/regrtest/test_bytes_affix_calls.py @@ -0,0 +1,50 @@ +"""`startswith` and `endswith` of `bytes` and `bytearray` agree with slicing. + +Every pairing of a `bytes` or `bytearray` receiver with a `bytes`, +`bytearray` or `memoryview` affix, empty affixes and receivers, affixes +longer than the receiver, a receiver tested against itself, tuples of +affixes, `start`/`end` windows, and the `TypeError` for a `str` or `int` +affix, run past the compile threshold. +""" + +import unittest + +DATA = [b"", b"a", b"ab", b"\x00\x01\x02", b"hello world", bytes(range(256))] +AFFIXES = [b"", b"a", b"ab", b"\x00\x01", b"world", b"hello world!", bytes(range(250, 256))] + + +class AffixTests(unittest.TestCase): + def test_pairs(self): + for _ in range(60): + for data in DATA: + for affix in AFFIXES: + head = data[: len(affix)] == affix + tail = len(affix) <= len(data) and data[len(data) - len(affix):] == affix + for recv in (data, bytearray(data)): + for a in (affix, bytearray(affix), memoryview(affix)): + self.assertEqual(recv.startswith(a), head, (recv, a)) + self.assertEqual(recv.endswith(a), tail, (recv, a)) + + def test_self_tuples_windows(self): + for _ in range(60): + ba = bytearray(b"abcabc") + self.assertTrue(ba.startswith(ba)) + self.assertTrue(ba.endswith(ba)) + self.assertTrue(b"abc".startswith((b"x", b"ab"))) + self.assertFalse(b"abc".endswith((b"x", bytearray(b"b")))) + self.assertTrue(b"abcabc".startswith(b"ca", 2)) + self.assertTrue(b"abcabc".endswith(b"ab", 0, 5)) + self.assertFalse(b"abc".startswith(b"", 4)) + + def test_errors(self): + for recv in (b"abc", bytearray(b"abc")): + with self.assertRaises(TypeError): + recv.startswith("a") + with self.assertRaises(TypeError): + recv.endswith(97) + with self.assertRaises(TypeError): + recv.startswith() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_cursor_steps.py b/tests/regrtest/test_bytes_cursor_steps.py new file mode 100644 index 000000000..848bf28da --- /dev/null +++ b/tests/regrtest/test_bytes_cursor_steps.py @@ -0,0 +1,43 @@ +"""A `bytes` iterator feeding native adapters (`map`, `filter`, `zip`, +`enumerate`, `''.join(map(...))`) steps in place; the items, partial +consumption, the iterator's state afterwards, and `urllib.parse.quote` +match the general steps.""" + +import unittest +from urllib.parse import quote, quote_from_bytes + + +class BytesCursorSteps(unittest.TestCase): + def test_map_and_join(self): + table = {b: chr(b).upper() for b in range(97, 123)} + for _ in range(300): + self.assertEqual("".join(map(table.__getitem__, b"hello")), "HELLO") + self.assertEqual(list(map(lambda b: b + 1, b"\x00\x01\xff")), [1, 2, 256]) + self.assertEqual(sum(map(int, b"abc")), 97 + 98 + 99) + + def test_filter_zip_enumerate(self): + for _ in range(300): + self.assertEqual(list(filter(None, b"\x00a\x00b")), [97, 98]) + self.assertEqual(list(zip(b"ab", b"xyz")), [(97, 120), (98, 121)]) + self.assertEqual(list(enumerate(b"hi")), [(0, 104), (1, 105)]) + + def test_partial_consumption(self): + for _ in range(300): + it = iter(b"abcdef") + m = map(chr, it) + self.assertEqual(next(m), "a") + self.assertEqual(list(zip(m, range(2))), [("b", 0), ("c", 1)]) + # zip took "d" from the map before range ended it. + self.assertEqual(next(it), ord("e")) + self.assertEqual(list(m), ["f"]) + self.assertEqual(list(it), []) + + def test_quote(self): + for i in range(500): + self.assertEqual(quote("a b/c?d=e&f"), "a%20b/c%3Fd%3De%26f") + self.assertEqual(quote_from_bytes(b"\x00\xff~"), "%00%FF~") + self.assertEqual(quote("x" * (i % 7)), "x" * (i % 7)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_from_range_and_islice_bounds.py b/tests/regrtest/test_bytes_from_range_and_islice_bounds.py new file mode 100644 index 000000000..0751326ae --- /dev/null +++ b/tests/regrtest/test_bytes_from_range_and_islice_bounds.py @@ -0,0 +1,46 @@ +"""`bytes(range(...))`, `bytearray(range(...))`, and lists of bounded +`islice` objects. + +A range of byte values converts in place; any value outside +`range(256)` must raise the same ValueError CPython raises. An `islice` +with a far bound over a short source must stop at the source's end. +""" + +import itertools +import unittest + + +class BytesFromRange(unittest.TestCase): + def test_values(self): + for _ in range(2000): + self.assertEqual(bytes(range(10)), bytes([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) + self.assertEqual(bytes(range(256))[-1], 255) + self.assertEqual(bytes(range(10, 0, -3)), b"\n\x07\x04\x01") + self.assertEqual(bytes(range(0, 300, 100)), b"\x00d\xc8") + self.assertEqual(bytes(range(5, 5)), b"") + self.assertEqual(bytearray(range(3)), bytearray(b"\x00\x01\x02")) + + def test_out_of_range(self): + for r in (range(257), range(-1, 3), range(3, -2, -1), + range(0, 400, 100), range(10**20, 10**20 + 1), + range(2**63 - 2, 2**63 + 2)): + with self.assertRaises(ValueError): + bytes(r) + with self.assertRaises(ValueError): + bytearray(r) + + +class IsliceBounds(unittest.TestCase): + def test_lists(self): + L = list(range(20)) + for _ in range(2000): + self.assertEqual(list(itertools.islice(itertools.count(), 5)), [0, 1, 2, 3, 4]) + self.assertEqual(list(itertools.islice(range(3), 10**9)), [0, 1, 2]) + self.assertEqual(list(itertools.islice(L, 2, 100, 7)), [2, 9, 16]) + self.assertEqual(list(itertools.islice(itertools.count(), 3, 3)), []) + self.assertEqual(list(itertools.islice(itertools.cycle("ab"), 1, 6, 2)), + ["b", "b", "b"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_from_text_codecs.py b/tests/regrtest/test_bytes_from_text_codecs.py new file mode 100644 index 000000000..bda48add0 --- /dev/null +++ b/tests/regrtest/test_bytes_from_text_codecs.py @@ -0,0 +1,108 @@ +"""`bytes(text, encoding[, errors])` and `bytearray(...)` of the same +arguments keep CPython's results and errors when compiled code encodes the +text directly: plain codecs and their aliases, text no codec can encode, +error handlers, subclasses, and keywords.""" + +import unittest + +N = 3000 + + +def repeat(f): + """`f()` run often enough for compiled code to take the call; every + result must be the first one, of the same type.""" + first = f() + for _ in range(N): + r = f() + if r != first or type(r) is not type(first): + raise AssertionError((first, r)) + return first + + +def raises(f): + """The class and message of what `f()` raises, the same every time.""" + seen = None + for _ in range(N // 10): + try: + f() + except Exception as e: + got = (type(e), str(e)) + else: + raise AssertionError("no error") + if seen is not None and got != seen: + raise AssertionError((seen, got)) + seen = got + return seen + + +class B(bytes): + pass + + +class BA(bytearray): + pass + + +class S(str): + pass + + +class BytesFromTextTests(unittest.TestCase): + def test_plain_codecs(self): + for enc in ("utf-8", "utf8", "UTF-8", "ascii", "latin-1", "latin1", "iso-8859-1"): + self.assertEqual(repeat(lambda: bytes("abc,1", enc)), b"abc,1", enc) + self.assertEqual(repeat(lambda: bytearray("abc,1", enc)), bytearray(b"abc,1"), enc) + self.assertEqual(repeat(lambda: bytes("h\xe9€", "utf-8")), b"h\xc3\xa9\xe2\x82\xac") + self.assertEqual(repeat(lambda: bytes("h\xe9", "latin-1")), b"h\xe9") + self.assertEqual(repeat(lambda: bytes("", "utf-8")), b"") + self.assertEqual(repeat(lambda: bytes("abc", "utf-16-le")), b"a\0b\0c\0") + self.assertEqual(repeat(lambda: bytes("abc", "cp1252")), b"abc") + + def test_fresh_bytearray(self): + a = bytearray("ab", "utf-8") + b = bytearray("ab", "utf-8") + self.assertIsNot(a, b) + a.append(0x63) + self.assertEqual((a, b), (bytearray(b"abc"), bytearray(b"ab"))) + + def test_error_handlers(self): + self.assertEqual(repeat(lambda: bytes("a\xe9b", "ascii", "ignore")), b"ab") + self.assertEqual(repeat(lambda: bytes("a\xe9b", "ascii", "replace")), b"a?b") + self.assertEqual(repeat(lambda: bytes("a€b", "latin-1", "xmlcharrefreplace")), + b"a€b") + self.assertEqual(repeat(lambda: bytes("ab", "utf-8", "strict")), b"ab") + self.assertEqual(repeat(lambda: bytes("\ud800", "utf-8", "surrogatepass")), + b"\xed\xa0\x80") + + def test_unencodable(self): + e = raises(lambda: bytes("a\xe9", "ascii")) + self.assertIs(e[0], UnicodeEncodeError) + e = raises(lambda: bytes("a€", "latin-1")) + self.assertIs(e[0], UnicodeEncodeError) + e = raises(lambda: bytearray("a€", "latin-1")) + self.assertIs(e[0], UnicodeEncodeError) + e = raises(lambda: bytes("\ud800", "utf-8")) + self.assertIs(e[0], UnicodeEncodeError) + + def test_bad_arguments(self): + self.assertIs(raises(lambda: bytes("a", "no-such-codec"))[0], LookupError) + # (A handler is looked up only when a character needs it.) + self.assertEqual(repeat(lambda: bytes("a", "ascii", "no-such-handler")), b"a") + self.assertIs(raises(lambda: bytes("a\xe9", "ascii", "no-such-handler"))[0], LookupError) + self.assertEqual(raises(lambda: bytes("a")), + (TypeError, "string argument without an encoding")) + self.assertIs(raises(lambda: bytes("a", "utf-8", "strict", 1))[0], TypeError) + self.assertIs(raises(lambda: bytes(b"a", "utf-8"))[0], TypeError) + + def test_subclasses_and_keywords(self): + self.assertEqual(repeat(lambda: B("ab", "utf-8")), B(b"ab")) + self.assertEqual(repeat(lambda: BA("ab", "utf-8")), BA(b"ab")) + self.assertEqual(repeat(lambda: bytes(S("ab"), "utf-8")), b"ab") + self.assertEqual(repeat(lambda: bytes("ab", encoding="utf-8")), b"ab") + self.assertEqual(repeat(lambda: bytes("a\xe9", encoding="ascii", errors="ignore")), b"a") + self.assertEqual(repeat(lambda: bytearray(source="ab", encoding="latin-1")), + bytearray(b"ab")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_fromhex_runs_and_join_parts.py b/tests/regrtest/test_bytes_fromhex_runs_and_join_parts.py new file mode 100644 index 000000000..888e883ca --- /dev/null +++ b/tests/regrtest/test_bytes_fromhex_runs_and_join_parts.py @@ -0,0 +1,66 @@ +"""`bytes.fromhex` decoded in runs of pairs, and `bytes.join` of +`bytearray` parts read in place. + +`fromhex` decodes whole pairs until whitespace or a non-digit; whitespace +is allowed only between pairs, and every other shape reports CPython's +error position. `b"".join` reads `bytes` and `bytearray` parts where they +are; any other part takes the general path and its error. +""" + +import unittest + + +class FromhexTests(unittest.TestCase): + def test_values(self): + for cls in (bytes, bytearray): + self.assertEqual(cls.fromhex(""), b"") + self.assertEqual(cls.fromhex("0a1B"), b"\x0a\x1b") + self.assertEqual(cls.fromhex(" ab\tcd\n"), b"\xab\xcd") + self.assertEqual(cls.fromhex("ab cd ef 01 23"), b"\xab\xcd\xef\x01\x23") + self.assertEqual(cls.fromhex("\x0bab\x0c"), b"\xab") + self.assertEqual(cls.fromhex("ab\r\ncd"), b"\xab\xcd") + self.assertEqual(cls.fromhex("AB" * 1000), b"\xab" * 1000) + self.assertEqual(cls.fromhex(bytes(range(256)).hex()), bytes(range(256))) + + def test_errors(self): + odd = "fromhex() arg must contain an even number of hexadecimal digits" + at = "non-hexadecimal number found in fromhex() arg at position %d" + cases = ( + ("abc", odd), + ("a", odd), + ("a b", at % 1), + ("zz", at % 0), + ("ab z", at % 3), + ("0g", at % 1), + ("abé", at % 2), + ) + for text, message in cases: + for cls in (bytes, bytearray): + with self.assertRaises(ValueError) as cm: + cls.fromhex(text) + self.assertEqual(str(cm.exception), message) + + +class JoinTests(unittest.TestCase): + def test_mixed_parts(self): + ba = bytearray(b"xy") + for _ in range(200): + self.assertEqual(b"-".join([b"a", bytearray(b"b"), b"c"]), b"a-b-c") + self.assertEqual(b"".join((ba, ba, b"z")), b"xyxyz") + self.assertEqual(b"ab".join([bytearray()]), b"") + self.assertEqual(b",".join([]), b"") + parts = [bytearray(b"ab")] * 2000 + self.assertEqual(len(b"".join(parts)), 4000) + self.assertIs(type(b"".join([bytearray(b"q")])), bytes) + + def test_other_parts(self): + self.assertEqual(b"".join([b"a", memoryview(b"m"), bytearray(b"q")]), b"amq") + with self.assertRaises(TypeError): + b"".join([b"a", "s"]) + with self.assertRaises(TypeError): + b"".join([b"a", 5]) + self.assertEqual(bytearray(b",").join([b"a", bytearray(b"b")]), bytearray(b"a,b")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_join_and_adapter_drains.py b/tests/regrtest/test_bytes_join_and_adapter_drains.py new file mode 100644 index 000000000..f94f1c540 --- /dev/null +++ b/tests/regrtest/test_bytes_join_and_adapter_drains.py @@ -0,0 +1,66 @@ +"""bytes.join from compiled loops (a leaf half over lists and tuples of +bytes and bytearray parts) and list() drains of native adapters (each +bulk path tried only for its own kind): joined bytes, a bytearray +separator, a generator of parts, wrong part types, and chain, accumulate, +zip, filter and map drains, each matching CPython.""" + +import itertools +import operator +import unittest + + +def joins(n, sep, parts): + out = None + for i in range(n): + out = sep.join(parts) + return out + + +def drains(n, xs): + out = None + for i in range(n): + out = ( + list(itertools.chain(xs, xs)), + list(itertools.accumulate(xs)), + list(zip(xs, xs)), + list(filter(None, xs)), + list(map(abs, xs)), + list(itertools.accumulate(xs, operator.mul, initial=2)), + ) + return out + + +class BytesJoinTests(unittest.TestCase): + def test_parts(self): + for n in (1, 300): + self.assertEqual(joins(n, b"-", [b"a", b"b", b"c"]), b"a-b-c") + self.assertEqual(joins(n, b"", (b"x", bytearray(b"y"))), b"xy") + self.assertEqual(joins(n, b", ", []), b"") + self.assertEqual(joins(n, b"+", [b"only"]), b"only") + self.assertEqual(joins(n, bytearray(b"/"), [b"a", b"b"]), bytearray(b"a/b")) + self.assertIs(type(joins(n, bytearray(b"/"), [b"a"])), bytearray) + + def test_other_iterables_and_errors(self): + self.assertEqual(joins(300, b".", (bytes([c]) for c in b"abc")), b"") + self.assertEqual(b".".join(bytes([c]) for c in b"abc"), b"a.b.c") + self.assertEqual(joins(300, b".", [memoryview(b"m"), b"n"]), b"m.n") + with self.assertRaises(TypeError): + joins(300, b".", [b"a", "b"]) + with self.assertRaises(TypeError): + joins(300, b".", [b"a", 1]) + + +class DrainTests(unittest.TestCase): + def test_drains(self): + xs = [0, -1, 2, 0, -3] + r = drains(300, xs) + self.assertEqual(r[0], xs + xs) + self.assertEqual(r[1], [0, -1, 1, 1, -2]) + self.assertEqual(r[2], [(x, x) for x in xs]) + self.assertEqual(r[3], [-1, 2, -3]) + self.assertEqual(r[4], [0, 1, 2, 0, 3]) + self.assertEqual(r[5], [2, 0, 0, 0, 0, 0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_like_values_read_in_place.py b/tests/regrtest/test_bytes_like_values_read_in_place.py new file mode 100644 index 000000000..04df99b4b --- /dev/null +++ b/tests/regrtest/test_bytes_like_values_read_in_place.py @@ -0,0 +1,318 @@ +"""Reading bytes-like values where they are. + +Indexing and storing through a `memoryview`, decoding a `bytearray`, +hashing or compressing a `bytes`, concatenating, and converting between +the bytes types read the source's bytes in place and copy them at most +once. The results are those of the general paths: every index form, every +error, and every codec outcome is unchanged. A few neighbours that take +the same kind of shortcut ride along: `range` indexing, sequence +comparison, and sets built from sets and dicts. +""" + +import hashlib +import unittest +import zlib + + +class MemoryViewItemTests(unittest.TestCase): + def test_reads(self): + data = bytes(range(256)) + for name, view in ( + ("bytes", memoryview(data)), + ("bytearray", memoryview(bytearray(data))), + ("sub-view", memoryview(b"xx" + data + b"yy")[2:-2]), + ("read-only", memoryview(bytearray(data)).toreadonly()), + ): + with self.subTest(view=name): + self.assertEqual([view[i] for i in range(256)], list(range(256))) + self.assertEqual([view[i - 256] for i in range(256)], list(range(256))) + self.assertIs(type(view[5]), int) + for bad in (256, -257, 10**9): + with self.assertRaises(IndexError): + view[bad] + with self.assertRaises(TypeError): + view["0"] + with self.assertRaises(TypeError): + view[1.0] + + def test_reads_of_other_layouts(self): + data = bytes(range(64)) + self.assertEqual(memoryview(data)[::2][3], 6) + self.assertEqual(memoryview(data)[::-1][0], 63) + self.assertEqual(memoryview(data).cast("b")[63], 63) + self.assertEqual(memoryview(bytes([200])).cast("b")[0], -56) + self.assertEqual(memoryview(data).cast("c")[65 - 64], b"\x01") + self.assertEqual(memoryview(data).cast("H")[1], int.from_bytes(data[2:4], "little")) + self.assertEqual(memoryview(data).cast("B", (8, 8))[1, 2], 10) + with self.assertRaises(NotImplementedError): + memoryview(data).cast("B", (8, 8))[1] + + def test_stores(self): + buf = bytearray(16) + view = memoryview(buf) + for i in range(16): + view[i] = i * 3 + self.assertEqual(list(buf), [i * 3 for i in range(16)]) + view[-1] = 255 + view[0] = True + self.assertEqual(buf[-1], 255) + self.assertEqual(buf[0], 1) + sub = view[4:8] + sub[1] = 99 + self.assertEqual(buf[5], 99) + for bad in (256, -1, 1.5, "a", None, b"a"): + with self.subTest(bad=bad): + with self.assertRaises((ValueError, TypeError)): + view[2] = bad + self.assertEqual(buf[2], 6) + with self.assertRaises(IndexError): + view[16] = 0 + with self.assertRaises(TypeError): + memoryview(bytes(4))[0] = 1 + with self.assertRaises(TypeError): + view.toreadonly()[0] = 1 + view.release() + with self.assertRaises(ValueError): + view[0] + with self.assertRaises(ValueError): + view[0] = 1 + + def test_run_stores(self): + buf = bytearray(b"0123456789") + view = memoryview(buf) + view[2:5] = b"abc" + view[5:7] = bytearray(b"XY") + view[7:9] = memoryview(b"--") + self.assertEqual(buf, b"01abcXY--9") + view[:] = view[::-1].tobytes() + self.assertEqual(buf, b"9--YXcba10") + view[0:4] = view[6:10] + self.assertEqual(buf, b"ba10Xcba10") + with self.assertRaises(ValueError): + view[0:2] = b"abc" + with self.assertRaises(ValueError): + view[0:2] = b"a" + view[1:1] = b"" + view[::2] = b"....." + self.assertEqual(buf, b".a.0.c.a.0") + with self.assertRaises(TypeError): + view[0:1] = "a" + + def test_loops(self): + data = bytes(i & 0xFF for i in range(5000)) + view = memoryview(data) + total = 0 + for i in range(5000): + total += view[i] + self.assertEqual(total, sum(data)) + out = bytearray(5000) + target = memoryview(out) + for i in range(5000): + target[i] = view[4999 - i] + self.assertEqual(out, data[::-1]) + for i in range(0, 4996, 4): + target[i:i + 4] = view[i:i + 4] + self.assertEqual(out[:4996], data[:4996]) + + +class DecodeTests(unittest.TestCase): + TEXTS = ("", "a", "plain ascii text", "café", "中文 and \U0001f600", "x" * 5000 + "é") + + def test_utf8_from_every_bytes_type(self): + for text in self.TEXTS: + raw = text.encode() + for name, value in ( + ("bytes", raw), + ("bytearray", bytearray(raw)), + ("memoryview", memoryview(raw)), + ): + with self.subTest(text=text[:12], source=name): + self.assertEqual(str(value, "utf-8"), text) + if name != "memoryview": + self.assertEqual(value.decode(), text) + self.assertEqual(value.decode("utf-8", "strict"), text) + self.assertEqual(value.decode(errors="replace"), text) + self.assertEqual(len(value.decode()), len(text)) + + def test_malformed_utf8(self): + for bad in (b"\xff", b"ab\xc3", b"\xed\xa0\x80", b"ok\xf8\x88\x80\x80\x80", b"\xc0\xaf"): + for kind in (bytes, bytearray): + with self.subTest(bad=bad, kind=kind.__name__): + with self.assertRaises(UnicodeDecodeError): + kind(bad).decode() + self.assertIn("�", kind(bad).decode(errors="replace")) + self.assertEqual(kind(bad).decode(errors="ignore"), bad.decode(errors="ignore")) + self.assertEqual(bytearray(b"a\xffb").decode(errors="surrogateescape"), "a\udcffb") + + def test_other_codecs(self): + self.assertEqual(bytearray(b"abc").decode("ascii"), "abc") + self.assertEqual(bytearray(b"caf\xe9").decode("latin-1"), "café") + self.assertEqual(b"abc".decode("latin-1"), "abc") + with self.assertRaises(UnicodeDecodeError): + bytearray(b"caf\xe9").decode("ascii") + self.assertEqual(bytearray("hé".encode("utf-16")).decode("utf-16"), "hé") + import codecs + + self.assertEqual(codecs.decode(bytearray(b"x\xc3\xa9"), "utf-8"), "xé") + self.assertEqual(codecs.utf_8_decode(b"x\xc3\xa9"), ("xé", 3)) + self.assertEqual(codecs.utf_8_decode(b"x\xc3", "strict", False), ("x", 1)) + self.assertEqual(codecs.ascii_decode(b"plain"), ("plain", 5)) + self.assertEqual(codecs.latin_1_decode(b"pl\xe4in"), ("pläin", 5)) + + def test_a_decoded_bytearray_is_independent(self): + buf = bytearray(b"hello") + text = buf.decode() + buf[0] = ord("J") + self.assertEqual(text, "hello") + self.assertEqual(buf.decode(), "Jello") + + +class ConversionTests(unittest.TestCase): + def test_concatenation(self): + a, b = b"abc", b"de" + self.assertEqual(a + b, b"abcde") + self.assertIs(type(a + b), bytes) + self.assertEqual(a + b"", a) + self.assertEqual(b"" + b"", b"") + self.assertEqual(bytearray(a) + b, bytearray(b"abcde")) + self.assertIs(type(bytearray(a) + b), bytearray) + self.assertEqual(a + bytearray(b), b"abcde") + self.assertIs(type(a + bytearray(b)), bytes) + big = bytes(100_000) + self.assertEqual(len(big + b"x" + big), 200_001) + self.assertEqual((big + b"x")[-1:], b"x") + with self.assertRaises(TypeError): + a + "b" + + def test_bytes_of_other_bytes_types(self): + buf = bytearray(b"mutable") + frozen = bytes(buf) + buf[0] = ord("M") + self.assertEqual(frozen, b"mutable") + self.assertIs(type(frozen), bytes) + view = memoryview(b"0123456789") + self.assertEqual(bytes(view[2:6]), b"2345") + self.assertEqual(bytes(view[::3]), b"0369") + self.assertEqual(bytes(memoryview(buf)[1:3]), b"ut") + self.assertEqual(bytes(memoryview(b"\x01\x00\x02\x00").cast("H")), b"\x01\x00\x02\x00") + self.assertEqual(bytes(bytearray()), b"") + released = memoryview(b"x") + released.release() + with self.assertRaises(ValueError): + bytes(released) + + def test_digests_agree_across_bytes_types(self): + data = bytes(range(256)) * 40 + want = hashlib.sha256(data).hexdigest() + self.assertEqual(hashlib.sha256(bytearray(data)).hexdigest(), want) + self.assertEqual(hashlib.sha256(memoryview(data)).hexdigest(), want) + h = hashlib.sha256() + h.update(data[:1000]) + h.update(bytearray(data[1000:5000])) + h.update(memoryview(data)[5000:]) + self.assertEqual(h.hexdigest(), want) + self.assertEqual(hashlib.md5(data).digest(), hashlib.md5(bytearray(data)).digest()) + self.assertEqual(hashlib.blake2b(data, key=b"k").digest(), hashlib.blake2b(bytearray(data), key=bytearray(b"k")).digest()) + with self.assertRaises(TypeError): + hashlib.sha256("text") + self.assertEqual(zlib.crc32(data), zlib.crc32(bytearray(data))) + self.assertEqual(zlib.adler32(data), zlib.adler32(memoryview(data))) + packed = zlib.compress(data) + self.assertEqual(zlib.decompress(packed), data) + self.assertEqual(zlib.decompress(bytearray(packed)), data) + self.assertEqual(zlib.compress(bytearray(data)), packed) + + def test_int_from_bytes(self): + raw = b"\x01\x02\x03\x04" + for value in (raw, bytearray(raw), memoryview(raw)): + self.assertEqual(int.from_bytes(value, "big"), 0x01020304) + self.assertEqual(int.from_bytes(value, "little"), 0x04030201) + self.assertEqual(int.from_bytes([1, 2], "big"), 258) + with self.assertRaises(TypeError): + int.from_bytes("12", "big") + + +class NeighbourTests(unittest.TestCase): + def test_range_items(self): + for r in ( + range(10), range(3, 50, 7), range(50, 3, -7), range(0), range(5, 5), range(-10, 10), + range(0, 2**62, 2**60), range(2**62, 0, -(2**60)), range(-(2**63), 2**63 - 1, 2**61), + ): + items = list(r) + with self.subTest(r=r): + for i in range(len(items)): + self.assertEqual(r[i], items[i]) + self.assertEqual(r[i - len(items)], items[i]) + for bad in (len(items), -len(items) - 1, 10**30): + with self.assertRaises(IndexError): + r[bad] + big = range(0, 2**100, 2**90) + self.assertEqual(big[3], 3 * 2**90) + self.assertEqual(range(2**64, 2**64 + 5)[-1], 2**64 + 4) + self.assertEqual(range(2**63 - 2, 2**63 + 3)[3], 2**63 + 1) + self.assertEqual(range(10)[True], 1) + self.assertIs(type(range(10)[2]), int) + + def test_lists_of_different_lengths_never_compare_items(self): + calls = [] + + class Loud: + def __eq__(self, other): + calls.append(1) + return True + + self.assertNotEqual([Loud(), 1], [Loud()]) + self.assertFalse([Loud()] == [Loud(), Loud()]) + self.assertEqual(calls, []) + self.assertEqual([Loud()], [Loud()]) + self.assertEqual(len(calls), 1) + self.assertNotEqual((Loud(), 1), (Loud(),)) + self.assertTrue((Loud(),) != (Loud(), Loud())) + self.assertNotEqual((1, 2, 3), (1, 2)) + self.assertNotEqual(("a",) * 5, ("a",) * 6) + + def test_sequence_comparisons(self): + a = list(range(1000)) + self.assertEqual(a, list(range(1000))) + self.assertNotEqual(a, list(range(999)) + [0]) + self.assertNotEqual(a, a[:-1]) + self.assertLess(a[:-1], a) + self.assertLess(a, a[:-1] + [1000]) + self.assertEqual(tuple(a), tuple(range(1000))) + self.assertGreater((1, 2, 3), (1, 2)) + self.assertEqual([1, 2.0, True, "x"], [1.0, 2, 1, "x"]) + nan = float("nan") + self.assertEqual([nan], [nan]) + self.assertNotEqual([nan], [float("nan")]) + self.assertEqual([2**70, -1], [2**70, -1]) + self.assertLess([1, 2**70], [1, 2**71]) + + def test_sets_built_from_sets_and_dicts(self): + source = {f"k{i}" for i in range(500)} | set(range(500)) + frozen = frozenset(source) + self.assertEqual(frozen, source) + self.assertIs(type(frozen), frozenset) + copy = set(frozen) + copy.add("extra") + self.assertNotIn("extra", source) + self.assertNotIn("extra", frozen) + self.assertEqual(len(copy), 1001) + self.assertIs(frozenset(frozen), frozen) + d = {i: str(i) for i in range(300)} + for i in range(0, 300, 3): + del d[i] + keys = set(d) + self.assertEqual(keys, {i for i in range(300) if i % 3}) + self.assertEqual(frozenset(d), keys) + keys.add(-1) + self.assertNotIn(-1, d) + self.assertEqual(sorted(set({1: "a", 1.0: "b", True: "c"})), [1]) + holed = set(range(100)) + for i in range(0, 100, 2): + holed.discard(i) + self.assertEqual(frozenset(holed), frozenset(range(1, 100, 2))) + self.assertEqual(hash(frozenset(holed)), hash(frozenset(range(1, 100, 2)))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_method_leaves.py b/tests/regrtest/test_bytes_method_leaves.py new file mode 100644 index 000000000..81ed1280b --- /dev/null +++ b/tests/regrtest/test_bytes_method_leaves.py @@ -0,0 +1,60 @@ +"""bytes and bytearray methods from compiled loops (leaf halves over +plain operands): results and types for bytes and bytearray receivers, +start/end arguments, None separators, errors such as index misses and +bad fill bytes, and memoryview and array operands (the full path), each +matching CPython.""" + +import array +import unittest + + +def ops(n, b): + out = None + for i in range(n): + out = ( + b.upper(), b.lower(), b.strip(), b.lstrip(b" h"), b.rstrip(), + b.count(b"l"), b.count(b"l", 3), b.rfind(b"o"), b.index(b"e"), + b.rindex(b"l", 0, 5), b.partition(b" "), b.rpartition(b"o"), + b.removeprefix(b" h"), b.removesuffix(b"d "), b.center(16, b"*"), + b.ljust(15), b.rjust(15, b"-"), b.zfill(14), b.capitalize(), + b.title(), b.swapcase(), b.isalnum(), b.isalpha(), b.isdigit(), + b.isspace(), b.islower(), b.isupper(), b.split(), b.split(b"l", 1), + b.rsplit(None, 1), b.replace(b"l", b"L"), b.replace(b"l", b"", 2), + b.splitlines(), b.expandtabs(4), + ) + return out + + +class BytesLeafTests(unittest.TestCase): + def test_bytes_and_bytearray(self): + for n in (1, 300): + r = ops(n, b" hello world ") + self.assertEqual(r[0], b" HELLO WORLD ") + self.assertEqual(r[5:8], (3, 3, 8)) + self.assertEqual(r[27], [b"hello", b"world"]) + self.assertEqual(r[28], [b" he", b"lo world "]) + self.assertEqual(r[30], b" heLLo worLd ") + self.assertEqual(r[31], b" heo world ") + a = ops(n, bytearray(b" hello world ")) + self.assertEqual([type(x).__name__ for x in a[:5]], ["bytearray"] * 5) + self.assertEqual(a[27], [bytearray(b"hello"), bytearray(b"world")]) + self.assertEqual(list(map(bytes, [x for x in a if isinstance(x, bytearray)])), + [x for x in r if isinstance(x, bytes)]) + + def test_errors_and_other_operands(self): + b = b"abc" + for i in range(300): + with self.assertRaises(ValueError): + b.index(b"z") + with self.assertRaises(TypeError): + b.center(5, b"ab") + with self.assertRaises(TypeError): + b.split("b") + self.assertEqual(b.split(memoryview(b"b")), [b"a", b"c"]) + self.assertEqual(b.replace(array.array("b", b"b"), b"X"), b"aXc") + self.assertEqual(b"a\tb".expandtabs(tabsize=2), b"a b") + self.assertEqual(b"a,b".split(sep=b","), [b"a", b"b"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_one_byte_objects_and_join.py b/tests/regrtest/test_bytes_one_byte_objects_and_join.py new file mode 100644 index 000000000..51e8cbba6 --- /dev/null +++ b/tests/regrtest/test_bytes_one_byte_objects_and_join.py @@ -0,0 +1,66 @@ +"""One-byte `bytes` objects are shared, and `bytes.join` of a list joins in place. + +As in CPython, every one-byte `bytes` result is the one object for that +byte (`bytes([97]) is b"a"`), so splitting into short pieces allocates +none. A shared object must never change: concatenation, `+=`, slicing +and `bytearray` round trips give new values and leave it alone. A +compiled `sep.join(parts)` of a list or tuple reads the parts in place; +a `bytearray` part, a non-bytes part (which raises), and other iterables +must still behave as the full call does. +""" + +import unittest + + +def joins(sep, parts, n=200): + out = None + for _ in range(n): + out = sep.join(parts) + return out + + +class OneByteTests(unittest.TestCase): + def test_identity(self): + for i in range(256): + one = bytes([i]) + self.assertIs(one, bytes([i])) + pieces = b"a b c d".split(b" ") + self.assertEqual(pieces, [b"a", b"b", b"c", b"d"]) + self.assertIs(pieces[0], bytes([97])) + self.assertIs(b"x,y".split(b",")[1], bytes([121])) + + def test_shared_objects_stay_unchanged(self): + a = bytes([97]) + b = a + b += b"z" + self.assertEqual(a, b"a") + self.assertEqual(b, b"az") + c = bytes([97]) * 3 + self.assertEqual(c, b"aaa") + self.assertEqual(bytes([97]), b"a") + ba = bytearray(bytes([98])) + ba[0] = 99 + self.assertEqual(bytes([98]), b"b") + self.assertEqual(bytes(ba), b"c") + + +class BytesJoinTests(unittest.TestCase): + def test_lists_and_tuples(self): + self.assertEqual(joins(b" ", [b"abc", b"de"]), b"abc de") + self.assertEqual(joins(b"", (b"x", b"y", b"z")), b"xyz") + self.assertEqual(joins(b"-", []), b"") + self.assertEqual(joins(b"-", [bytearray(b"q"), b"r"]), b"q-r") + + def test_errors_and_other_iterables(self): + for _ in range(100): + with self.assertRaises(TypeError): + b" ".join([b"a", "b"]) + with self.assertRaises(TypeError): + b" ".join((b"a", 1)) + self.assertEqual(joins(b",", (x for x in [b"1", b"2"]), 1), b"1,2") + self.assertEqual(joins(b",", iter([b"1", b"2"]), 1), b"1,2") + self.assertEqual(joins(b",", {b"k": 1}), b"k") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_repeat_build.py b/tests/regrtest/test_bytes_repeat_build.py new file mode 100644 index 000000000..962537867 --- /dev/null +++ b/tests/regrtest/test_bytes_repeat_build.py @@ -0,0 +1,33 @@ +"""`bytes * n` built in the result's own storage. + +One byte repeats as a fill, longer units by doubling copies; `b * 1` is +`b` itself, and an empty unit or a count of zero or less gives empty +bytes. Run it past the compile threshold, with sizes on both sides +of the compiled code's in-line limit. +""" + + +def run(n): + for i in range(n): + unit = b"ab" if i % 2 else b"x" + k = i % 9 + r = unit * k + assert r == bytes(unit[j % len(unit)] for j in range(len(unit) * k)) + assert (k * unit) == r + b = b"xyz" + assert b * 1 is b + assert b * 0 == b"" and b"" * k == b"" and b * -3 == b"" + big = b"0123456789" * 300_000 + assert len(big) == 3_000_000 and big[-11:] == b"90123456789" + assert big.count(b"0123456789") == 300_000 + assert b"\xff" * (1 << 21) == bytes([255]) * (1 << 21) + try: + b"ab" * (1 << 62) + except (MemoryError, OverflowError): + pass + else: + raise AssertionError("absurd repetition") + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_bytes_split_hex_plain.py b/tests/regrtest/test_bytes_split_hex_plain.py new file mode 100644 index 000000000..6c1799933 --- /dev/null +++ b/tests/regrtest/test_bytes_split_hex_plain.py @@ -0,0 +1,43 @@ +"""`bytes.split()`, `bytes.split(sep)` and `bytes.hex()` without options. + +These build each piece, or the digits, directly from the bytes; empty +pieces are the shared empty bytes, and a bytearray, a subclass, a +`maxsplit` or a separator for `hex` takes the general path. +""" + +assert b" a b\tc\n".split() == [b"a", b"b", b"c"] +assert b"".split() == [] and b" \t".split() == [] and b"x".split(None) == [b"x"] +assert b"a,b,,c".split(b",") == [b"a", b"b", b"", b"c"] +assert b",".split(b",") == [b"", b""] and b"".split(b",") == [b""] +assert b"a,,b,,".split(b",,") == [b"a", b"b", b""] +assert b"a,b,,c".split(b",")[2] is bytes() +assert b"a b c".split(maxsplit=1) == [b"a", b"b c"] +assert b"a,b,c".split(b",", 1) == [b"a", b"b,c"] +assert b"a b".split(sep=None) == [b"a", b"b"] and b"a,b".split(sep=b",") == [b"a", b"b"] +assert bytearray(b"a b").split() == [bytearray(b"a"), bytearray(b"b")] +assert type(bytearray(b"a,b").split(b",")[0]) is bytearray + + +class B(bytes): + pass + + +assert B(b"a b").split() == [b"a", b"b"] and type(B(b"a b").split()[0]) is bytes +try: + b"a".split(b"") +except ValueError: + pass +else: + raise AssertionError("empty separator") +try: + b"a".split("x") +except TypeError: + pass +else: + raise AssertionError("str separator") + +assert b"".hex() == "" and b"\x00\xff\x10".hex() == "00ff10" +assert bytes(range(256)).hex() == "".join(f"{i:02x}" for i in range(256)) +assert b"\x01\x02".hex(":") == "01:02" and bytearray(b"\xab").hex() == "ab" +assert B(b"\x0f").hex() == "0f" and len(b"\x7f\x80".hex()) == 4 +print("ok") diff --git a/tests/regrtest/test_bytes_split_one_byte.py b/tests/regrtest/test_bytes_split_one_byte.py new file mode 100644 index 000000000..3cf85b113 --- /dev/null +++ b/tests/regrtest/test_bytes_split_one_byte.py @@ -0,0 +1,50 @@ +"""`bytes.split` by one byte, which counts the matches to size the list and +cuts the pieces between them in one pass, keeps CPython's pieces: empty +pieces at the ends and between adjacent matches, no match, every byte a +match, high bytes, and the other separator shapes beside it.""" + +import unittest + +N = 500 + + +class BytesSplitOneByteTests(unittest.TestCase): + def check(self, data, sep): + want = [] + cur = bytearray() + for b in data: + if b == sep[0]: + want.append(bytes(cur)) + cur = bytearray() + else: + cur.append(b) + want.append(bytes(cur)) + for _ in range(N): + got = data.split(sep) + self.assertEqual(got, want) + self.assertTrue(all(type(p) is bytes for p in got)) + + def test_pieces(self): + self.check(b"The quick brown fox", b" ") + self.check(b"", b" ") + self.check(b"abc", b" ") + self.check(b" ", b" ") + self.check(b" a b ", b" ") + self.check(b",,,,", b",") + self.check(bytes(range(256)) * 3, b"\x00") + self.check(bytes(range(256)) * 3, b"\xff") + self.check(b"a\x80b\x80\x80c", b"\x80") + self.check(b"x" * 5000 + b"," + b"y" * 3, b",") + + def test_other_shapes(self): + self.assertEqual(b"a, b, c".split(b", "), [b"a", b"b", b"c"]) + self.assertEqual(b"a b c".split(), [b"a", b"b", b"c"]) + self.assertEqual(b"a b c".split(b" ", 1), [b"a", b"b c"]) + self.assertEqual(bytearray(b"a b").split(b" "), [bytearray(b"a"), bytearray(b"b")]) + self.assertEqual(b"a b".split(bytearray(b" ")), [b"a", b"b"]) + with self.assertRaises(ValueError): + b"a".split(b"") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytes_strides_repeats_translate.py b/tests/regrtest/test_bytes_strides_repeats_translate.py new file mode 100644 index 000000000..dc844fe3f --- /dev/null +++ b/tests/regrtest/test_bytes_strides_repeats_translate.py @@ -0,0 +1,116 @@ +"""Stepped slices, `bytearray` repeats and `translate` of bytes-likes. + +Slices with steps above one, from any start and stop, of bytes, +bytearrays, lists and tuples give the items a Python loop picks; a +`bytearray` times a count is a new `bytearray` (the operand unchanged); +`translate` with a table, a deletion set, or both, of `bytes` and +`bytearray` receivers, gives what a byte-by-byte loop gives, and reads +the receiver only after the table and deletion set are taken. A +memoryview's slices keep the view's format. +""" + +import unittest + + +def stepped(seq, start, stop, step): + idx = range(*slice(start, stop, step).indices(len(seq))) + return [seq[i] for i in idx] + + +class StrideTests(unittest.TestCase): + def test_slices(self): + data = bytes(range(256)) * 3 + for kind in (bytes, bytearray, list, tuple): + seq = kind(data) + for step in (2, 3, 7, 255, 1000, -2, -3): + for start, stop in ((None, None), (1, None), (5, 700), (-10, None), + (700, 5), (None, -1), (-1000, 1000), (3, 4)): + got = seq[start:stop:step] + self.assertIs(type(got), kind) + self.assertEqual(list(got), stepped(seq, start, stop, step), + (kind, start, stop, step)) + + def test_objects(self): + items = [object() for _ in range(20)] + got = items[1::3] + self.assertEqual(len(got), 7) + for a, b in zip(got, items[1::3]): + self.assertIs(a, b) + + +class RepeatTests(unittest.TestCase): + def test_bytearray_repeat(self): + ba = bytearray(b"abc") + for n in (0, 1, 2, 5, -1): + r = ba * n + self.assertIs(type(r), bytearray) + self.assertEqual(r, bytearray(b"abc" * max(n, 0))) + self.assertIsNot(r, ba) + self.assertEqual(n * ba, r) + self.assertEqual(ba, bytearray(b"abc")) + big = bytearray(range(256)) * 100 + self.assertEqual(big * 3, bytearray(bytes(range(256)) * 300)) + with self.assertRaises((MemoryError, OverflowError)): + bytearray(b"x") * (2**62) + + +class TranslateTests(unittest.TestCase): + def test_table_and_delete(self): + table = bytes(range(255, -1, -1)) + data = bytes(range(256)) * 4 + want = bytes(table[b] for b in data) + for kind in (bytes, bytearray): + recv = kind(data) + got = recv.translate(table) + self.assertIs(type(got), kind) + self.assertEqual(got, want) + self.assertEqual(recv.translate(None), data) + self.assertEqual(recv.translate(None, b"\x00\x01"), + bytes(b for b in data if b > 1)) + self.assertEqual(recv.translate(table, delete=b"\xff"), + bytes(table[b] for b in data if b != 0xff)) + self.assertEqual(recv.translate(bytearray(table), memoryview(b"ab")), + bytes(table[b] for b in data if b not in b"ab")) + with self.assertRaises(ValueError): + b"x".translate(b"short") + with self.assertRaises(TypeError): + b"x".translate(None, nonsense=b"") + + def test_receiver_read_after_table(self): + ba = bytearray(b"hello") + + class Table: + def __buffer__(self, flags): + ba.extend(b"!!") + return memoryview(bytes(range(256))) + + def __release_buffer__(self, view): + pass + + self.assertEqual(ba.translate(Table()), bytearray(b"hello!!")) + + +class MemoryviewSliceTests(unittest.TestCase): + def test_formats_kept(self): + import array + a = array.array("i", range(10)) + mv = memoryview(a) + sub = mv[2:5] + self.assertEqual(sub.format, "i") + self.assertEqual(sub.tolist(), [2, 3, 4]) + b = memoryview(b"abcdef") + self.assertEqual(b[1:3].format, "B") + self.assertEqual(bytes(b[1:5:2]), b"bd") + c = b.cast("c") + self.assertEqual(c[1:3].format, "c") + self.assertEqual(c[1:3].tolist(), [b"b", b"c"]) + ba = bytearray(b"xyz") + with memoryview(ba)[1:] as v: + self.assertEqual(v.format, "B") + v[0] = ord("Y") + self.assertEqual(ba, bytearray(b"xYz")) + ba.append(1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytesio_getvalue_shared.py b/tests/regrtest/test_bytesio_getvalue_shared.py new file mode 100644 index 000000000..f82d88401 --- /dev/null +++ b/tests/regrtest/test_bytesio_getvalue_shared.py @@ -0,0 +1,113 @@ +"""`io.BytesIO.getvalue()` hands back one bytes object until the buffer changes. + +Repeated calls on an unchanged stream share their result, and a stream made +from a bytes object returns that object. Every way of changing the buffer +(writes at the end or after a seek, `writelines`, `truncate`, re-running +`__init__`, `__setstate__`, and writes through a `getbuffer()` view) makes +the next call see the new contents. +""" + +import io +import unittest + + +class GetvalueTests(unittest.TestCase): + def test_unchanged_stream_shares(self): + f = io.BytesIO() + f.write(b"abc" * 100) + a = f.getvalue() + self.assertIs(f.getvalue(), a) + f.seek(0) + f.read(10) + self.assertIs(f.getvalue(), a) + + def test_initial_bytes(self): + data = bytes(range(256)) * 10 + f = io.BytesIO(data) + self.assertEqual(f.getvalue(), data) + self.assertIs(f.getvalue(), f.getvalue()) + + def test_writes(self): + f = io.BytesIO(b"hello world") + self.assertEqual(f.getvalue(), b"hello world") + f.seek(0) + f.write(b"J") + self.assertEqual(f.getvalue(), b"Jello world") + f.seek(0, 2) + f.write(b"!") + self.assertEqual(f.getvalue(), b"Jello world!") + f.seek(1) + f.write(b"ELLO") + self.assertEqual(f.getvalue(), b"JELLO world!") + f.writelines([b"-", b"+"]) + self.assertEqual(f.getvalue(), b"JELLO-+orld!") + f.write(b"") + self.assertEqual(f.getvalue(), b"JELLO-+orld!") + + def test_overseek_write(self): + f = io.BytesIO(b"ab") + self.assertEqual(f.getvalue(), b"ab") + f.seek(4) + f.write(b"c") + self.assertEqual(f.getvalue(), b"ab\x00\x00c") + + def test_truncate(self): + f = io.BytesIO(b"0123456789") + self.assertEqual(f.getvalue(), b"0123456789") + f.truncate(4) + self.assertEqual(f.getvalue(), b"0123") + f.seek(0) + f.write(b"ab") + f.truncate() + self.assertEqual(f.getvalue(), b"ab") + + def test_reinit(self): + f = io.BytesIO(b"first") + self.assertEqual(f.getvalue(), b"first") + f.__init__(b"later") + self.assertEqual(f.getvalue(), b"later") + f.__init__(b"") + self.assertEqual(f.getvalue(), b"") + + def test_setstate(self): + f = io.BytesIO(b"aaaa") + self.assertEqual(f.getvalue(), b"aaaa") + f.__setstate__((b"bbbb", 0, None)) + self.assertEqual(f.getvalue(), b"bbbb") + + def test_getbuffer_writes(self): + f = io.BytesIO(b"abcdef") + self.assertEqual(f.getvalue(), b"abcdef") + view = f.getbuffer() + view[0] = ord("X") + self.assertEqual(f.getvalue(), b"Xbcdef") + view[1] = ord("Y") + self.assertEqual(f.getvalue(), b"XYcdef") + del view + self.assertEqual(f.getvalue(), b"XYcdef") + with f.getbuffer() as view: + view[2] = ord("Z") + self.assertEqual(f.getvalue(), b"XYZdef") + + def test_results_are_independent(self): + f = io.BytesIO() + f.write(b"one") + a = f.getvalue() + f.write(b"two") + self.assertEqual(a, b"one") + self.assertEqual(f.getvalue(), b"onetwo") + + def test_text_wrapper_writes(self): + raw = io.BytesIO() + t = io.TextIOWrapper(raw, encoding="utf-8") + t.write("abc") + t.flush() + self.assertEqual(raw.getvalue(), b"abc") + t.write("def") + t.flush() + self.assertEqual(raw.getvalue(), b"abcdef") + t.detach() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytesio_memoryview_writes.py b/tests/regrtest/test_bytesio_memoryview_writes.py new file mode 100644 index 000000000..eb56b4d44 --- /dev/null +++ b/tests/regrtest/test_bytesio_memoryview_writes.py @@ -0,0 +1,82 @@ +"""`BytesIO.write` of memoryviews. + +Views of bytes, bytearrays and arrays, whole or sliced, of any format, +write their bytes and return the byte count; a stepped view raises +`BufferError` and a released one `ValueError`; a view of the stream's own buffer +blocks the write with `BufferError` while it lives; writes after a seek +overwrite in place. +""" + +import array +import io +import unittest + + +class MemoryviewWriteTests(unittest.TestCase): + def test_plain_views(self): + data = bytes(range(256)) + f = io.BytesIO() + mv = memoryview(data) + total = 0 + for i in range(0, 256, 16): + total += f.write(mv[i:i + 16]) + self.assertEqual(total, 256) + self.assertEqual(f.getvalue(), data) + self.assertEqual(f.write(memoryview(bytearray(b"xyz"))), 3) + self.assertEqual(f.write(memoryview(b"")), 0) + self.assertEqual(f.getvalue(), data + b"xyz") + + def test_other_layouts(self): + f = io.BytesIO() + a = array.array("i", [1, 2, 3]) + self.assertEqual(f.write(memoryview(a)), a.itemsize * 3) + self.assertEqual(f.getvalue(), a.tobytes()) + f = io.BytesIO() + with self.assertRaises(BufferError): + f.write(memoryview(b"abcdef")[::2]) + self.assertEqual(f.getvalue(), b"") + f = io.BytesIO() + self.assertEqual(f.write(memoryview(b"abcd").cast("c")), 4) + self.assertEqual(f.write(memoryview(b"abcd").cast("b")), 4) + self.assertEqual(f.getvalue(), b"abcdabcd") + + def test_seek_and_overwrite(self): + f = io.BytesIO(b"0123456789") + f.seek(2) + self.assertEqual(f.write(memoryview(b"ab")), 2) + self.assertEqual(f.getvalue(), b"01ab456789") + f.seek(12) + f.write(memoryview(b"Z")) + self.assertEqual(f.getvalue(), b"01ab456789\x00\x00Z") + + def test_errors(self): + f = io.BytesIO() + mv = memoryview(b"abc") + mv.release() + with self.assertRaises(ValueError): + f.write(mv) + g = io.BytesIO(b"hello") + view = g.getbuffer() + with self.assertRaises(BufferError): + g.write(view[:2]) + with self.assertRaises(BufferError): + g.write(b"x") + view.release() + g.seek(0, 2) + self.assertEqual(g.write(memoryview(b"!")), 1) + self.assertEqual(g.getvalue(), b"hello!") + f.close() + with self.assertRaises(ValueError): + f.write(memoryview(b"x")) + + def test_view_of_another_stream(self): + src = io.BytesIO(b"source") + dst = io.BytesIO() + with src.getbuffer() as view: + self.assertEqual(dst.write(view[1:4]), 3) + self.assertEqual(dst.getvalue(), b"our") + src.write(b"more") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytesio_reads_and_writes_in_place.py b/tests/regrtest/test_bytesio_reads_and_writes_in_place.py new file mode 100644 index 000000000..03903d5e9 --- /dev/null +++ b/tests/regrtest/test_bytesio_reads_and_writes_in_place.py @@ -0,0 +1,191 @@ +"""`io.BytesIO` reads, `readinto` and writes, at any position. + +A read copies its bytes once from the stream, `readinto` copies them +straight into the caller's buffer, and a write after a seek writes over +the bytes there, growing the stream if it runs past the end. Positions, +return values, closed streams, exported buffers and a stream read into +its own buffer behave as the documented methods do. +""" + +import io +import unittest + + +class ReadTests(unittest.TestCase): + def test_reads(self): + data = bytes(range(256)) * 4 + f = io.BytesIO(data) + self.assertEqual(f.read(10), data[:10]) + self.assertEqual(f.tell(), 10) + self.assertEqual(f.read(0), b"") + self.assertEqual(f.tell(), 10) + self.assertEqual(f.read(-1)[:5], data[10:15]) + self.assertEqual(f.tell(), len(data)) + self.assertEqual(f.read(5), b"") + f.seek(1000) + self.assertEqual(f.read(100), data[1000:]) + f.seek(5000) + self.assertEqual(f.read(4), b"") + self.assertEqual(f.tell(), 5000) + f.seek(3) + self.assertEqual(f.read(None), data[3:]) + f.seek(0) + self.assertEqual(f.read(), data) + self.assertIs(type(f.read()), bytes) + f.seek(-4, io.SEEK_END) + self.assertEqual(f.read(-7), data[-4:]) + + def test_a_read_is_a_copy(self): + f = io.BytesIO(b"abcdef") + first = f.read(3) + f.seek(0) + f.write(b"XYZ") + self.assertEqual(first, b"abc") + f.seek(0) + self.assertEqual(f.read(), b"XYZdef") + + def test_readinto(self): + data = bytes(range(100)) + f = io.BytesIO(data) + buf = bytearray(30) + self.assertEqual(f.readinto(buf), 30) + self.assertEqual(buf, data[:30]) + view = memoryview(bytearray(50)) + self.assertEqual(f.readinto(view), 50) + self.assertEqual(view.tobytes(), data[30:80]) + self.assertEqual(f.readinto(buf), 20) + self.assertEqual(buf[:20], data[80:]) + self.assertEqual(buf[20:], data[20:30]) + self.assertEqual(f.readinto(buf), 0) + self.assertEqual(f.tell(), 100) + f.seek(0) + self.assertEqual(f.readinto(bytearray()), 0) + self.assertEqual(f.tell(), 0) + with self.assertRaises(TypeError): + f.readinto(b"read-only") + with self.assertRaises(TypeError): + f.readinto(memoryview(b"read-only")) + exported = bytearray(5) + held = memoryview(exported) + self.assertEqual(f.readinto(exported), 5) + self.assertEqual(held.tobytes(), data[:5]) + held.release() + + def test_readinto_a_strided_or_released_view(self): + f = io.BytesIO(bytes(range(20))) + with self.assertRaises(TypeError): + f.readinto(memoryview(bytearray(10))[::2]) + released = memoryview(bytearray(4)) + released.release() + with self.assertRaises((TypeError, ValueError)): + f.readinto(released) + self.assertEqual(f.tell(), 0) + + def test_reading_into_the_streams_own_buffer(self): + f = io.BytesIO(b"0123456789") + view = f.getbuffer() + with self.assertRaises(BufferError): + f.write(b"x") + n = f.readinto(view[5:]) + self.assertEqual(n, 5) + self.assertEqual(bytes(view), b"0123401234") + view.release() + self.assertEqual(f.getvalue(), b"0123401234") + + def test_closed_streams(self): + f = io.BytesIO(b"abc") + f.close() + for op in (lambda: f.read(), lambda: f.read(1), lambda: f.readinto(bytearray(2)), lambda: f.write(b"x")): + with self.assertRaises(ValueError): + op() + + +class WriteTests(unittest.TestCase): + def test_appends(self): + f = io.BytesIO() + for i in range(500): + self.assertEqual(f.write(bytes([i & 0xFF]) * 3), 3) + self.assertEqual(f.tell(), 1500) + self.assertEqual(f.getvalue(), b"".join(bytes([i & 0xFF]) * 3 for i in range(500))) + self.assertEqual(f.write(b""), 0) + self.assertEqual(f.write(bytearray(b"ba")), 2) + self.assertEqual(f.write(memoryview(b"mv")), 2) + self.assertEqual(f.getvalue()[-4:], b"bamv") + + def test_writes_after_a_seek(self): + for start, data in ((0, b"XY"), (3, b"XY"), (8, b"XY"), (9, b"XY"), (10, b"XY"), (4, b"LONGER-THAN-REST")): + with self.subTest(start=start, data=data): + f = io.BytesIO(b"0123456789") + f.seek(start) + self.assertEqual(f.write(data), len(data)) + want = bytearray(b"0123456789") + want[start:start + len(data)] = data + self.assertEqual(f.getvalue(), bytes(want)) + self.assertEqual(f.tell(), start + len(data)) + f = io.BytesIO(b"abc") + f.seek(6) + f.write(b"Z") + self.assertEqual(f.getvalue(), b"abc\x00\x00\x00Z") + f = io.BytesIO(b"abcdef") + f.seek(2) + f.write(bytearray(b"--")) + self.assertEqual(f.getvalue(), b"ab--ef") + + def test_a_stream_written_into_itself(self): + f = io.BytesIO(b"abc") + f.seek(0, io.SEEK_END) + f.write(f.getvalue()) + self.assertEqual(f.getvalue(), b"abcabc") + f.seek(1) + f.write(f.getbuffer().tobytes()) + self.assertEqual(f.getvalue(), b"aabcabc") + + def test_an_exported_stream_refuses_writes(self): + f = io.BytesIO(b"abc") + view = f.getbuffer() + for data in (b"x", bytearray(b"x")): + with self.assertRaises(BufferError): + f.write(data) + f.seek(0) + with self.assertRaises(BufferError): + f.write(b"Z") + view.release() + f.write(b"Z") + self.assertEqual(f.getvalue(), b"Zbc") + + def test_wrong_types(self): + f = io.BytesIO() + with self.assertRaises(TypeError): + f.write("text") + with self.assertRaises(TypeError): + f.write(5) + self.assertEqual(f.getvalue(), b"") + + def test_loops(self): + f = io.BytesIO() + chunk = bytearray(b"0123456789abcdef") + for i in range(3000): + f.write(chunk) + if i % 500 == 499: + f.seek(0) + f.seek(0) + total = 0 + buf = bytearray(16) + while True: + n = f.readinto(buf) + if not n: + break + total += n + self.assertEqual(total, 500 * 16) + f.seek(0) + parts = [] + while True: + part = f.read(7) + if not part: + break + parts.append(part) + self.assertEqual(b"".join(parts), bytes(chunk) * 500) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytesio_tell_and_seek.py b/tests/regrtest/test_bytesio_tell_and_seek.py new file mode 100644 index 000000000..87defbfd9 --- /dev/null +++ b/tests/regrtest/test_bytesio_tell_and_seek.py @@ -0,0 +1,94 @@ +"""`BytesIO.tell()` and `seek()` keep the positions CPython keeps. + +Absolute seeks inside and past the end (a later write zero-fills the gap), +relative and end-relative seeks, `True`/`False` offsets, a negative +absolute offset (`ValueError`), an unknown whence, a closed stream, a live +`getbuffer()` view, subclasses, and `tell()` after reads, writes, +`readline` and `truncate`, run past the compile threshold. +""" + +import io +import unittest + + +class TellSeekTests(unittest.TestCase): + def test_positions(self): + for _ in range(300): + f = io.BytesIO(b"0123456789") + self.assertEqual(f.tell(), 0) + self.assertEqual(f.seek(4), 4) + self.assertEqual(f.tell(), 4) + self.assertEqual(f.read(2), b"45") + self.assertEqual(f.tell(), 6) + self.assertEqual(f.seek(0, 0), 0) + self.assertEqual(f.seek(3, 1), 3) + self.assertEqual(f.seek(-2, 2), 8) + self.assertEqual(f.seek(-100, 1), 0) + self.assertEqual(f.seek(True), 1) + self.assertEqual(f.seek(False), 0) + self.assertEqual(f.seek(20), 20) + self.assertEqual(f.read(), b"") + f.write(b"!") + self.assertEqual(f.getvalue(), b"0123456789" + b"\0" * 10 + b"!") + self.assertEqual(f.tell(), 21) + + def test_errors(self): + f = io.BytesIO(b"abc") + with self.assertRaises(ValueError): + f.seek(-1) + with self.assertRaises(ValueError): + f.seek(0, 3) + with self.assertRaises(TypeError): + f.seek(1.5) + with self.assertRaises(TypeError): + f.seek() + with self.assertRaises(OverflowError): + f.seek(2**70) + f.close() + with self.assertRaises(ValueError): + f.tell() + with self.assertRaises(ValueError): + f.seek(0) + + def test_with_view_and_lines(self): + f = io.BytesIO(b"one\ntwo\nthree\n") + view = f.getbuffer() + self.assertEqual(f.seek(4), 4) + self.assertEqual(f.readline(), b"two\n") + self.assertEqual(f.tell(), 8) + view.release() + f.seek(0) + self.assertEqual(f.readlines(), [b"one\n", b"two\n", b"three\n"]) + self.assertEqual(f.tell(), 14) + f.seek(3) + f.truncate() + self.assertEqual(f.tell(), 3) + self.assertEqual(f.getvalue(), b"one") + + def test_subclass(self): + class B(io.BytesIO): + seeks = 0 + + def seek(self, *a): + B.seeks += 1 + return super().seek(*a) + + f = B(b"abcdef") + for _ in range(100): + self.assertEqual(f.seek(2), 2) + self.assertEqual(f.tell(), 2) + self.assertEqual(B.seeks, 100) + + def test_text_layer(self): + raw = io.BytesIO("héllo\nwörld\n".encode()) + t = io.TextIOWrapper(raw, encoding="utf-8") + self.assertEqual(t.readline(), "héllo\n") + pos = t.tell() + self.assertEqual(t.readline(), "wörld\n") + t.seek(pos) + self.assertEqual(t.readline(), "wörld\n") + t.detach() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_bytesio_value_views.py b/tests/regrtest/test_bytesio_value_views.py new file mode 100644 index 000000000..eef4851fb --- /dev/null +++ b/tests/regrtest/test_bytesio_value_views.py @@ -0,0 +1,65 @@ +"""BytesIO writes and getvalue() from compiled loops (read through views +of the buffer): values after writes and seeks, the cached value reused +until a write, an exported getbuffer() view (the full path), a closed +stream, and BytesIO(initial) returning its bytes, each matching +CPython.""" + +import io +import unittest + + +def churn(n): + out = None + for i in range(n): + b = io.BytesIO() + b.write(b"ab") + b.write(b"cd") + out = (b.getvalue(), b.getvalue(), b.tell()) + return out + + +class BytesIOTests(unittest.TestCase): + def test_writes_and_values(self): + for n in (1, 300): + self.assertEqual(churn(n), (b"abcd", b"abcd", 4)) + b = io.BytesIO() + for i in range(300): + b.write(b"x") + v = b.getvalue() + self.assertEqual(v, b"x" * 300) + b.seek(1) + b.write(b"yy") + self.assertEqual(b.getvalue()[:4], b"xyyx") + b.seek(305) + b.write(b"z") + self.assertEqual(b.getvalue()[-7:], b"x\0\0\0\0\0z") + + def test_cached_and_initial(self): + init = b"seed" + b = io.BytesIO(init) + self.assertIs(b.getvalue(), init) + v1 = b.getvalue() + self.assertIs(b.getvalue(), v1) + b.seek(0, 2) + b.write(b"!") + self.assertEqual(b.getvalue(), b"seed!") + + def test_exported_and_closed(self): + b = io.BytesIO(b"abc") + m = b.getbuffer() + m[0] = ord("z") + self.assertEqual(b.getvalue(), b"zbc") + with self.assertRaises(BufferError): + b.write(b"q") + del m + b.write(b"q") + self.assertEqual(b.getvalue(), b"qbc") + b.close() + with self.assertRaises(ValueError): + b.getvalue() + with self.assertRaises(ValueError): + b.write(b"x") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_callable_instance_callbacks.py b/tests/regrtest/test_callable_instance_callbacks.py new file mode 100644 index 000000000..836e6dd05 --- /dev/null +++ b/tests/regrtest/test_callable_instance_callbacks.py @@ -0,0 +1,83 @@ +"""A callable instance (its class's Python `__call__`) as a native +adapter's callback (`map`, `filter`, `sorted`'s key) is called as its +method; the results, `*args` signatures, raises, a `__call__` replaced or +removed, and an instance `__call__` attribute (ignored, as CPython's +lookup on the type ignores it) match the general call.""" + +import unittest + + +class Adder: + def __init__(self, k): + self.k = k + self.calls = 0 + + def __call__(self, x): + self.calls += 1 + return x + self.k + + +class Var: + def __call__(self, *a): + return len(a) + + +class Raiser: + def __call__(self, x): + if x == 3: + raise KeyError(x) + return x + + +class CallableInstanceCallbacks(unittest.TestCase): + def test_map(self): + a = Adder(10) + for _ in range(300): + self.assertEqual(list(map(a, range(5))), [10, 11, 12, 13, 14]) + self.assertEqual(a.calls, 1500) + + def test_filter_and_sorted(self): + class Odd: + def __call__(self, x): + return x % 2 + + class Neg: + def __call__(self, x): + return -x + + for _ in range(300): + self.assertEqual(list(filter(Odd(), range(7))), [1, 3, 5]) + self.assertEqual(sorted([3, 1, 2], key=Neg()), [3, 2, 1]) + + def test_varargs(self): + for _ in range(300): + self.assertEqual(list(map(Var(), "ab")), [1, 1]) + self.assertEqual(list(map(Var(), "ab", "cd")), [2, 2]) + + def test_raises(self): + r = Raiser() + for _ in range(300): + out = [] + with self.assertRaises(KeyError): + for v in map(r, range(10)): + out.append(v) + self.assertEqual(out, [0, 1, 2]) + + def test_replaced_and_instance_attribute(self): + class C: + def __call__(self, x): + return "a" + + c = C() + self.assertEqual(list(map(c, range(3))), ["a"] * 3) + C.__call__ = lambda self, x: "b" + self.assertEqual(list(map(c, range(3))), ["b"] * 3) + c.__call__ = lambda x: "instance" + self.assertEqual(list(map(c, range(3))), ["b"] * 3) + del C.__call__ + with self.assertRaises(TypeError): + list(map(c, range(3))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_callable_iterator_native.py b/tests/regrtest/test_callable_iterator_native.py new file mode 100644 index 000000000..6c187e99a --- /dev/null +++ b/tests/regrtest/test_callable_iterator_native.py @@ -0,0 +1,155 @@ +"""`iter(callable, sentinel)`: the `callable_iterator` type, its steps +(CPython's `calliter_iternext`: `sentinel == result` with identity first, +a `StopIteration` from the callable ending it, a re-entrant step that +ends it), its `__reduce__`, and its use in hot loops.""" + +import collections.abc +import copy +import functools +import io +import unittest + + +class CallableIteratorType(unittest.TestCase): + def test_type(self): + it = iter(lambda: 1, 0) + self.assertEqual(type(it).__name__, "callable_iterator") + self.assertEqual(type(it).__module__, "builtins") + self.assertIs(iter(it), it) + self.assertIsInstance(it, collections.abc.Iterator) + with self.assertRaises(TypeError): + type(it)(lambda: 1, 0) + with self.assertRaises(TypeError): + iter(42, 42) + + def test_basic_and_exhaustion(self): + src = [5, 4, 3, 0, 9] + calls = [] + + def f(): + calls.append(1) + return src.pop(0) + + it = iter(f, 0) + self.assertEqual(list(it), [5, 4, 3]) + self.assertEqual(len(calls), 4) + # Spent: the callable isn't called again. + self.assertRaises(StopIteration, next, it) + self.assertEqual(len(calls), 4) + + def test_sentinel_compares_first(self): + order = [] + + class R: + def __eq__(self, o): + order.append("R") + return False + + class S: + def __eq__(self, o): + order.append("S") + return False + + vals = iter([R(), R()]) + out = [] + for x in iter(lambda: next(vals, None), S()): + if x is None: + break + out.append(x) + self.assertEqual(len(out), 2) + self.assertEqual(order, ["S", "S", "S"]) + + def test_identity_before_eq(self): + nan = float("nan") + vals = iter([1.0, 2.0, nan, 3.0]) + self.assertEqual(list(iter(lambda: next(vals), nan)), [1.0, 2.0]) + + def test_stop_iteration_from_callable(self): + vals = iter([1, 2]) + calls = [] + + def f(): + calls.append(1) + return next(vals) + + it = iter(f, object()) + self.assertEqual(list(it), [1, 2]) + self.assertEqual(len(calls), 3) + self.assertRaises(StopIteration, next, it) + self.assertEqual(len(calls), 3) + + def test_error_mid_stream_keeps_going(self): + n = [0] + + def f(): + n[0] += 1 + if n[0] == 2: + raise ValueError("boom") + return n[0] + + it = iter(f, 4) + self.assertEqual(next(it), 1) + self.assertRaises(ValueError, next, it) + self.assertEqual(list(it), [3]) + + def test_eq_raises(self): + class Bad: + def __eq__(self, o): + raise KeyError("eq") + + it = iter(lambda: 1, Bad()) + self.assertRaises(KeyError, next, it) + + def test_reentrant_exhaustion(self): + # gh-101892: a step whose call exhausted the iterator ends too. + state = {"n": 0} + + def f(): + state["n"] += 1 + if state["n"] == 1: + self.assertEqual(list(it), []) + return 7 + return 0 + + it = iter(f, 0) + self.assertEqual(list(it), []) + + def test_reduce_and_copy(self): + src = [1, 2, 0] + it = iter(src.pop, 1) + r = it.__reduce__() + self.assertIs(r[0], iter) + self.assertEqual(r[1][1], 1) + c = copy.copy(it) + self.assertEqual(type(c).__name__, "callable_iterator") + self.assertEqual(list(c), [0, 2]) + spent = iter([1, 0].pop, 1) + self.assertEqual(list(spent), [0]) + self.assertEqual(spent.__reduce__(), (iter, ((),))) + + def test_read_chunks(self): + f = io.BytesIO(b"abcdefghij") + chunks = list(iter(functools.partial(f.read, 4), b"")) + self.assertEqual(chunks, [b"abcd", b"efgh", b"ij"]) + + def test_hot_loops(self): + def g(): + return 1 + + total = 0 + for _ in range(400): + src = [3, 2, 1, 0] + total += sum(iter(src.pop, 3)) + c = 0 + for x in iter(g, 0): + c += x + if c == 3: + break + total += c + it = iter([1, 2, 0, 3]).__next__ + total += sum(x for x in iter(it, 0)) + self.assertEqual(total, 400 * (3 + 3 + 3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_capi_unicode_codec_entry_points.py b/tests/regrtest/test_capi_unicode_codec_entry_points.py new file mode 100644 index 000000000..62368b133 --- /dev/null +++ b/tests/regrtest/test_capi_unicode_codec_entry_points.py @@ -0,0 +1,132 @@ +"""The `PyUnicode_*` codec, wide-character and path-converter entry points. + +Wheels call these directly (charset_normalizer's mypyc build calls +`PyUnicode_DecodeUTF32`); a missing one is a symbol lookup error at the +first call. Each is reached through `ctypes.pythonapi` and checked against +what the matching Python-level codec gives. +""" + +import ctypes +import pathlib +import unittest + +api = ctypes.pythonapi +P = ctypes.POINTER + + +def fn(name, restype, *argtypes): + f = getattr(api, name) + f.restype = restype + f.argtypes = list(argtypes) + return f + + +TEXT = "h\xe9€\U0001d11e" + + +class WideDecoders(unittest.TestCase): + def test_utf32(self): + f = fn("PyUnicode_DecodeUTF32", ctypes.py_object, ctypes.c_char_p, + ctypes.c_ssize_t, ctypes.c_char_p, P(ctypes.c_int)) + data = TEXT.encode("utf-32") + bo = ctypes.c_int(0) + self.assertEqual(f(data, len(data), None, ctypes.byref(bo)), TEXT) + self.assertEqual(bo.value, -1) + self.assertEqual(f(data[4:], len(data) - 4, None, None), TEXT) + be = TEXT.encode("utf-32-be") + bo = ctypes.c_int(1) + self.assertEqual(f(be, len(be), None, ctypes.byref(bo)), TEXT) + with self.assertRaises(UnicodeDecodeError): + f(b"\x00\x00\x11\x00", 4, None, None) + self.assertEqual(f(b"\x00\x00\x11\x00", 4, b"replace", None), "�") + + def test_utf16_stateful(self): + f = fn("PyUnicode_DecodeUTF16Stateful", ctypes.py_object, ctypes.c_char_p, + ctypes.c_ssize_t, ctypes.c_char_p, P(ctypes.c_int), P(ctypes.c_ssize_t)) + data = "ab\U0001d11e".encode("utf-16-be") + bo = ctypes.c_int(1) + used = ctypes.c_ssize_t(-1) + self.assertEqual(f(data[:-1], len(data) - 1, None, ctypes.byref(bo), ctypes.byref(used)), "ab") + self.assertEqual(used.value, 4) + self.assertEqual(f(data, len(data), None, ctypes.byref(bo), ctypes.byref(used)), "ab\U0001d11e") + self.assertEqual(used.value, len(data)) + g = fn("PyUnicode_DecodeUTF16", ctypes.py_object, ctypes.c_char_p, + ctypes.c_ssize_t, ctypes.c_char_p, P(ctypes.c_int)) + with self.assertRaises(UnicodeDecodeError): + g(data[:-1], len(data) - 1, None, ctypes.byref(ctypes.c_int(1))) + + def test_utf32_stateful_and_utf7(self): + f = fn("PyUnicode_DecodeUTF32Stateful", ctypes.py_object, ctypes.c_char_p, + ctypes.c_ssize_t, ctypes.c_char_p, P(ctypes.c_int), P(ctypes.c_ssize_t)) + data = TEXT.encode("utf-32-le") + used = ctypes.c_ssize_t() + self.assertEqual(f(data[:-2], len(data) - 2, None, ctypes.byref(ctypes.c_int(-1)), ctypes.byref(used)), TEXT[:-1]) + self.assertEqual(used.value, len(data) - 4) + u7 = fn("PyUnicode_DecodeUTF7", ctypes.py_object, ctypes.c_char_p, ctypes.c_ssize_t, ctypes.c_char_p) + data = TEXT.encode("utf-7") + self.assertEqual(u7(data, len(data), None), TEXT) + + def test_escapes(self): + u = fn("PyUnicode_DecodeUnicodeEscape", ctypes.py_object, ctypes.c_char_p, ctypes.c_ssize_t, ctypes.c_char_p) + self.assertEqual(u(b"a\\n\\u20ac", 9, None), "a\n€") + r = fn("PyUnicode_DecodeRawUnicodeEscape", ctypes.py_object, ctypes.c_char_p, ctypes.c_ssize_t, ctypes.c_char_p) + self.assertEqual(r(b"a\\n\\u20ac", 9, None), "a\\n€") + + +class Encoders(unittest.TestCase): + def test_as_strings(self): + for name, codec in (("UTF16", "utf-16"), ("UTF32", "utf-32"), + ("UnicodeEscape", "unicode_escape"), + ("RawUnicodeEscape", "raw_unicode_escape")): + f = fn("PyUnicode_As%sString" % name, ctypes.py_object, ctypes.py_object) + self.assertEqual(f(TEXT + "\n"), (TEXT + "\n").encode(codec), name) + fn("PyUnicode_GetDefaultEncoding", ctypes.c_char_p) + self.assertEqual(api.PyUnicode_GetDefaultEncoding(), b"utf-8") + + def test_wide_char(self): + w = fn("PyUnicode_AsWideChar", ctypes.c_ssize_t, ctypes.py_object, ctypes.c_void_p, ctypes.c_ssize_t) + need = w(TEXT, None, 0) + units = len(TEXT) + (ctypes.sizeof(ctypes.c_wchar) == 2) + self.assertEqual(need, units + 1) + buf = (ctypes.c_wchar * need)() + self.assertEqual(w(TEXT, buf, need), units) + self.assertEqual(ctypes.wstring_at(buf), TEXT) + short = (ctypes.c_wchar * 2)("x", "y") + self.assertEqual(w("abc", short, 1), 1) + self.assertEqual(short[1], "y") + ws = fn("PyUnicode_AsWideCharString", ctypes.c_void_p, ctypes.py_object, P(ctypes.c_ssize_t)) + n = ctypes.c_ssize_t() + p = ws("hi\0x", ctypes.byref(n)) + self.assertEqual(n.value, 4) + self.assertEqual(ctypes.wstring_at(p, 4), "hi\0x") + fn("PyMem_Free", None, ctypes.c_void_p)(p) + with self.assertRaises(ValueError): + ws("hi\0x", None) + + +class PathConverters(unittest.TestCase): + def convert(self, name, arg): + f = fn("PyUnicode_" + name, ctypes.c_int, ctypes.py_object, ctypes.c_void_p) + slot = ctypes.c_void_p(0) + rc = f(arg, ctypes.addressof(slot)) + rep = fn("PyObject_Repr", ctypes.py_object, ctypes.c_void_p)(slot.value) + f.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + self.assertEqual(f(None, ctypes.addressof(slot)), 1) + self.assertIsNone(slot.value) + return rc, rep + + def test_converters(self): + self.assertEqual(self.convert("FSConverter", pathlib.Path("/tmp/\xe9")), + (0x20000, repr(b"/tmp/\xc3\xa9"))) + self.assertEqual(self.convert("FSConverter", b"/b"), (0x20000, repr(b"/b"))) + self.assertEqual(self.convert("FSDecoder", b"/tmp/x"), (0x20000, repr("/tmp/x"))) + self.assertEqual(self.convert("FSDecoder", pathlib.Path("q")), (0x20000, repr("q"))) + f = fn("PyUnicode_FSConverter", ctypes.c_int, ctypes.py_object, ctypes.c_void_p) + with self.assertRaises(ValueError): + f(b"a\0b", ctypes.addressof(ctypes.c_void_p())) + with self.assertRaises(TypeError): + f(3, ctypes.addressof(ctypes.c_void_p())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_chain_generator_drain.py b/tests/regrtest/test_chain_generator_drain.py new file mode 100644 index 000000000..0c4246258 --- /dev/null +++ b/tests/regrtest/test_chain_generator_drain.py @@ -0,0 +1,65 @@ +"""`list(chain(...))` drains a generator source whole, as `list(gen)` +does, then moves on; results, the chain's state after a raise, partly +consumed sources, and other sources match CPython.""" + +import itertools +import unittest + + +def gen(n, start=0): + for i in range(start, start + n): + yield i + + +class Boom(Exception): + pass + + +def raising(): + yield 1 + yield 2 + raise Boom + + +class ChainGeneratorDrain(unittest.TestCase): + def test_mixed_sources(self): + for _ in range(200): + self.assertEqual(list(itertools.chain(gen(3), gen(2, 10))), [0, 1, 2, 10, 11]) + self.assertEqual(list(itertools.chain([7], gen(2), (8, 9), gen(1, 5), "ab")), + [7, 0, 1, 8, 9, 5, "a", "b"]) + self.assertEqual(list(itertools.chain.from_iterable(gen(2, k) for k in (0, 10))), + [0, 1, 10, 11]) + self.assertEqual(list(itertools.chain(gen(0), gen(0), [1])), [1]) + self.assertEqual(list(itertools.chain({"k": 1}, gen(1))), ["k", 0]) + + def test_raise_then_resume(self): + c = itertools.chain(raising(), gen(2, 5)) + with self.assertRaises(Boom): + list(c) + self.assertEqual(list(c), [5, 6]) + + def test_partly_consumed(self): + g = gen(5) + next(g) + c = itertools.chain(g, [9]) + self.assertEqual(next(c), 1) + self.assertEqual(list(c), [2, 3, 4, 9]) + self.assertEqual(list(g), []) + + def test_finally_runs(self): + log = [] + + def g(): + try: + yield 1 + yield 2 + finally: + log.append("done") + for _ in range(50): + log.clear() + self.assertEqual(list(itertools.chain(g(), [3])), [1, 2, 3]) + self.assertEqual(log, ["done"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_chain_over_adapters.py b/tests/regrtest/test_chain_over_adapters.py new file mode 100644 index 000000000..a3639ef24 --- /dev/null +++ b/tests/regrtest/test_chain_over_adapters.py @@ -0,0 +1,231 @@ +"""`itertools.chain` over `map` and `filter` sources, consumed whole. + +`list(chain(map(f, xs), map(g, ys)))` drains each `map` or `filter` source +as `list(map(f, xs))` drains one, in place of a general step per item. +These tests pin the order of items and of callback calls, what a raise +part-way leaves behind, a chain that was stepped before it is drained, +and chains that share or contain one another. +""" + +import itertools +import unittest +from operator import attrgetter, itemgetter + +N = 300 + + +class Point: + def __init__(self, x): + self.x = x + + +def double(v): + return v * 2 + + +class ChainOverAdapters(unittest.TestCase): + def test_order_of_items(self): + pairs = [(i, -i) for i in range(N)] + points = [Point(i) for i in range(N)] + got = list( + itertools.chain( + map(itemgetter(0), pairs), + [("plain",)], + map(attrgetter("x"), points), + filter(None, range(5)), + (v for v in "ab"), + map(double, range(3)), + map(str.upper, ["x", "y"]), + filter(str.isdigit, ["1", "a", "2"]), + ) + ) + want = ( + list(range(N)) + + [("plain",)] + + list(range(N)) + + [1, 2, 3, 4, "a", "b", 0, 2, 4, "X", "Y", "1", "2"] + ) + self.assertEqual(got, want) + + def test_other_consumers(self): + pairs = [(i, -i) for i in range(N)] + make = lambda: itertools.chain(map(itemgetter(0), pairs), map(itemgetter(1), pairs)) # noqa: E731 + for _ in range(30): + self.assertEqual(sum(make()), 0) + self.assertEqual(tuple(make())[N - 1 : N + 2], (N - 1, 0, -1)) + self.assertEqual(len(set(make())), 2 * N - 1) + self.assertEqual(sorted(make())[0], 1 - N) + self.assertEqual(max(make()), N - 1) + self.assertEqual([v for v in make()][:3], [0, 1, 2]) + self.assertEqual( + list(itertools.chain.from_iterable([map(double, [1, 2]), map(double, [3])])), + [2, 4, 6], + ) + self.assertEqual(list(itertools.islice(make(), N - 1, N + 1)), [N - 1, 0]) + + def test_order_of_calls(self): + log = [] + + def note(tag): + def f(v): + log.append((tag, v)) + return v + + return f + + def keep(v): + log.append(("keep", v)) + return v % 2 + + got = list(itertools.chain(map(note("a"), [1, 2]), filter(keep, [3, 4, 5]), map(note("b"), [6]))) + self.assertEqual(got, [1, 2, 3, 5, 6]) + self.assertEqual( + log, + [("a", 1), ("a", 2), ("keep", 3), ("keep", 4), ("keep", 5), ("b", 6)], + ) + + def test_a_raise_part_way(self): + def boom(v): + if v == 3: + raise KeyError(v) + return v * 2 + + chain = itertools.chain(map(boom, [1, 3, 4]), [8], map(boom, [5])) + with self.assertRaises(KeyError): + list(chain) + self.assertEqual(list(chain), [8, 8, 10]) + self.assertEqual(list(chain), []) + + def stops(v): + if v == 2: + raise StopIteration + return v + + self.assertEqual(list(itertools.chain(map(stops, [1, 2, 3]), [9])), [1, 9]) + + def test_stepped_then_drained(self): + pairs = [(i,) for i in range(6)] + chain = itertools.chain(map(itemgetter(0), pairs), map(itemgetter(0), pairs)) + self.assertEqual((next(chain), next(chain)), (0, 1)) + self.assertEqual(list(chain), [2, 3, 4, 5, 0, 1, 2, 3, 4, 5]) + first = map(double, [1, 2, 3]) + chain = itertools.chain(first, [7]) + self.assertEqual(next(first), 2) + self.assertEqual(list(chain), [4, 6, 7]) + self.assertEqual(list(first), []) + + def test_shared_and_nested(self): + shared = map(double, range(4)) + chain = itertools.chain(shared, shared, [9]) + self.assertEqual(list(chain), [0, 2, 4, 6, 9]) + inner = itertools.chain(map(double, [1]), [5]) + outer = itertools.chain(inner, map(double, [2]), inner) + self.assertEqual(list(outer), [2, 5, 4]) + source = iter([1, 2, 3, 4]) + chain = itertools.chain(map(double, source), map(str, source)) + self.assertEqual(list(chain), [2, 4, 6, 8]) + empty = itertools.chain(map(double, []), filter(None, []), map(double, ())) + self.assertEqual(list(empty), []) + + +class Flaky: + """An iterator over 1..5 whose second step raises `KeyError`.""" + + def __init__(self): + self.i = 0 + + def __iter__(self): + return self + + def __next__(self): + self.i += 1 + if self.i == 2: + raise KeyError("flaky") + if self.i > 5: + raise StopIteration + return self.i + + +def boom(v): + if v == 2: + raise KeyError(v) + return v + + +def consume(it, how): + """What `it` gives before it raises, consumed one of three ways.""" + got = [] + try: + if how == "for": + for v in it: + got.append(v) + elif how == "list": + got = list(it) + else: + while True: + got.append(next(it)) + except KeyError: + got.append("KeyError") + except StopIteration: + pass + return got + + +class AfterASourceRaises(unittest.TestCase): + """An adapter whose source (or callback) raised: most go on from the + next item when stepped again; a few are over for good.""" + + def check(self, make, first, rest): + for how in ("for", "list", "next"): + it = make() + got = consume(it, how) + if how == "list": + self.assertEqual(got, ["KeyError"], how) + else: + self.assertEqual(got, first + ["KeyError"], how) + self.assertEqual(list(it), rest, how) + + def test_chain(self): + self.check(lambda: itertools.chain(Flaky(), [9]), [1], [3, 4, 5, 9]) + self.check(lambda: itertools.chain([0], Flaky(), [9]), [0, 1], [3, 4, 5, 9]) + self.check(lambda: itertools.chain(map(boom, [1, 2, 3]), [9]), [1], [3, 9]) + self.check(lambda: itertools.chain(filter(boom, [1, 2, 3]), [9]), [1], [3, 9]) + self.check(lambda: itertools.chain.from_iterable([Flaky(), [9]]), [1], [3, 4, 5, 9]) + + def test_chain_whose_sources_raise(self): + def sources(): + yield [1] + raise KeyError("sources") + + self.check(lambda: itertools.chain.from_iterable(sources()), [1], []) + chain = itertools.chain([1], 5, [2]) + with self.assertRaises(TypeError): + list(chain) + self.assertEqual(list(chain), []) + + def test_adapters_that_go_on(self): + self.check(lambda: zip(Flaky(), range(10)), [(1, 0)], [(3, 1), (4, 2), (5, 3)]) + self.check(lambda: zip(range(10), Flaky()), [(0, 1)], [(2, 3), (3, 4), (4, 5)]) + self.check(lambda: enumerate(Flaky()), [(0, 1)], [(1, 3), (2, 4), (3, 5)]) + self.check(lambda: map(str, Flaky()), ["1"], ["3", "4", "5"]) + self.check(lambda: filter(None, Flaky()), [1], [3, 4, 5]) + self.check(lambda: itertools.accumulate(Flaky()), [1], [4, 8, 13]) + self.check(lambda: itertools.compress(Flaky(), [1] * 5), [1], [3, 4, 5]) + self.check(lambda: itertools.takewhile(lambda v: v < 5, Flaky()), [1], [3, 4]) + self.check(lambda: itertools.dropwhile(lambda v: v < 1, Flaky()), [1], [3, 4, 5]) + self.check(lambda: itertools.filterfalse(lambda v: v > 4, Flaky()), [1], [3, 4]) + self.check(lambda: itertools.starmap(boom, [(1,), (2,), (3,)]), [1], [3]) + self.check(lambda: itertools.tee(Flaky())[0], [1], [3, 4, 5]) + + def test_adapters_that_end(self): + self.check(lambda: itertools.islice(Flaky(), 10), [1], []) + self.check(lambda: itertools.islice(Flaky(), 0, 10, 2), [1], []) + self.check(lambda: itertools.islice(itertools.cycle(Flaky()), 8), [1], []) + self.check(lambda: itertools.pairwise(Flaky()), [], []) + self.check(lambda: itertools.batched(Flaky(), 2), [], []) + self.check(lambda: itertools.zip_longest(Flaky(), [7]), [(1, 7)], []) + self.check(lambda: itertools.zip_longest([7, 8, 9], Flaky()), [(7, 1)], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_chain_pure_steps.py b/tests/regrtest/test_chain_pure_steps.py new file mode 100644 index 000000000..d070e41c3 --- /dev/null +++ b/tests/regrtest/test_chain_pure_steps.py @@ -0,0 +1,79 @@ +"""`islice` over `chain` steps without the interpreter. + +A `chain` whose current source is a list or tuple cursor, or whose next +source is a list or tuple with items, steps in place for a one-source +adapter (`islice`), moving to the next source as the general step does. +Sources it can't step (generators, iterators held elsewhere, empty +sequences) keep the general step, and the results match it. +""" + +import unittest +from itertools import chain, islice + +N = 3000 + + +class ChainPureStepTests(unittest.TestCase): + def test_sequence_sources(self): + L = [1, 2, 3] + for _ in range(N): + a = list(islice(chain(L, L), 4)) + b = list(islice(chain([], (7,), [], [8, 9]), 5)) + c = list(islice(chain(L, "ab", range(2)), 9)) + self.assertEqual(a, [1, 2, 3, 1]) + self.assertEqual(b, [7, 8, 9]) + self.assertEqual(c, [1, 2, 3, "a", "b", 0, 1]) + + def test_partial_reads_resume(self): + for _ in range(N): + c = chain([1], [2], [3]) + r = [list(islice(c, 2)), list(islice(c, 2))] + self.assertEqual(r, [[1, 2], [3]]) + self.assertEqual(list(c), []) + + def test_shared_iterator_source(self): + for _ in range(N): + it = iter([5, 6]) + c = chain(it, [7]) + first = list(islice(c, 1)) + mid = next(it) + rest = list(c) + self.assertEqual((first, mid, rest), ([5], 6, [7])) + + def test_mutated_source(self): + M = [1, 2] + c = chain(M, M) + self.assertEqual((next(c), next(c)), (1, 2)) + M.append(3) + self.assertEqual(list(islice(c, 5)), [3, 1, 2, 3]) + + def test_generator_and_from_iterable_sources(self): + def g(): + yield 1 + yield 2 + + for _ in range(N): + a = list(islice(chain(g(), [3], g()), 10)) + b = list(islice(chain.from_iterable([[1], [], (2, 3)]), 10)) + self.assertEqual(a, [1, 2, 3, 1, 2]) + self.assertEqual(b, [1, 2, 3]) + + def test_released_items_finalize(self): + dead = [] + + class D: + def __del__(self): + dead.append(1) + + def f(): + c = chain([D()], [1]) + return list(islice(c, 2)) + + for _ in range(50): + r = f() + del r + self.assertEqual(len(dead), 50) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_chainmap_contains_chain_str.py b/tests/regrtest/test_chainmap_contains_chain_str.py new file mode 100644 index 000000000..5365bb9ff --- /dev/null +++ b/tests/regrtest/test_chainmap_contains_chain_str.py @@ -0,0 +1,62 @@ +"""`key in ChainMap` over exact dicts decided natively (its native +__contains__), and itertools.chain draining str sources in bulk, from +compiled loops: keys in the first, a later, or no map, an int key, keys +with a Python __hash__/__eq__ (the full path), maps that aren't dicts, +a ChainMap subclass overriding __contains__, maps changed after warm-up, +and chains of lists, tuples, strs (non-ASCII too) and empty strs, each +matching CPython.""" + +import collections +import itertools +import unittest + + +class Key: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, Key) and self.v == other.v + + +class Never(collections.ChainMap): + def __contains__(self, key): + return False + + +class ChainMapTests(unittest.TestCase): + def test_contains(self): + cm = collections.ChainMap({"a": 1}, {"b": 2, 3: 4}) + for i in range(300): + r = ("a" in cm, "b" in cm, 3 in cm, "z" in cm, 4 in cm) + self.assertEqual(r, (True, True, True, False, False)) + k = collections.ChainMap({Key(1): 1}, {}) + for i in range(300): + r2 = (Key(1) in k, Key(2) in k) + self.assertEqual(r2, (True, False)) + u = collections.ChainMap({"a": 1}, collections.UserDict({"q": 1})) + for i in range(300): + r3 = ("q" in u, "x" in u) + self.assertEqual(r3, (True, False)) + n = Never({"a": 1}) + for i in range(300): + r4 = "a" in n + self.assertFalse(r4) + cm.maps[1]["new"] = 0 + self.assertIn("new", cm) + cm.maps.append({"late": 1}) + self.assertIn("late", cm) + + def test_chain_str(self): + for i in range(300): + r = list(itertools.chain([1], (2,), "ab", "", "hé")) + s = list(itertools.chain.from_iterable(["xy", [3]])) + self.assertEqual(r, [1, 2, "a", "b", "h", "é"]) + self.assertEqual(s, ["x", "y", 3]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_checksums_read_buffers_in_place.py b/tests/regrtest/test_checksums_read_buffers_in_place.py new file mode 100644 index 000000000..10cc5449d --- /dev/null +++ b/tests/regrtest/test_checksums_read_buffers_in_place.py @@ -0,0 +1,56 @@ +"""`zlib.crc32`/`adler32` and `hashlib` over buffers read in place. + +A `bytes`, `bytearray` or contiguous `memoryview` is read where it is; a +released view raises `ValueError` and a strided one `BufferError`, as +CPython's `PyBUF_SIMPLE` consumers do. `adler32` reduces per block (and its +starting value even for no data). +""" + +import hashlib +import unittest +import zlib + + +DATA = bytes(range(256)) * 300 + + +class ChecksumTests(unittest.TestCase): + def sources(self): + return [DATA, bytearray(DATA), memoryview(DATA), memoryview(bytearray(DATA))[7:]] + + def test_crc32_and_adler32(self): + expected = [(zlib.crc32(bytes(s)), zlib.adler32(bytes(s))) for s in self.sources()] + for _ in range(20): + got = [(zlib.crc32(s), zlib.adler32(s)) for s in self.sources()] + self.assertEqual(got, expected) + self.assertEqual(zlib.crc32(b"hello", 12345), zlib.crc32(b"lo", zlib.crc32(b"hel", 12345))) + self.assertEqual(zlib.adler32(b"hello"), 0x062C0215) + self.assertEqual(zlib.adler32(b"", 0xFFFFFFFF), 917518) + self.assertEqual(zlib.adler32(b"", 65530), 9) + self.assertEqual(zlib.adler32(b"\xff" * 100000, 0xFFF0FFF0), zlib.adler32(b"\xff" * 50000, zlib.adler32(b"\xff" * 50000, 0xFFF0FFF0))) + + def test_hashes(self): + want = hashlib.sha256(DATA).hexdigest() + for s in self.sources()[:3]: + self.assertEqual(hashlib.sha256(s).hexdigest(), want) + h = hashlib.sha256() + h.update(s[:1000]) + h.update(s[1000:]) + self.assertEqual(h.hexdigest(), want) + self.assertEqual(hashlib.md5(bytearray(b"abc")).hexdigest(), "900150983cd24fb0d6963f7d28e17f72") + + def test_buffer_errors(self): + released = memoryview(b"x") + released.release() + strided = memoryview(bytearray(b"abcdef"))[::2] + for f in (zlib.crc32, zlib.adler32, hashlib.md5, lambda v: hashlib.sha1().update(v), zlib.compress): + with self.assertRaises(ValueError): + f(released) + with self.assertRaises(BufferError): + f(strided) + with self.assertRaises(TypeError): + zlib.crc32("text") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_class_attr_reads_through_instances.py b/tests/regrtest/test_class_attr_reads_through_instances.py new file mode 100644 index 000000000..8fdccdd13 --- /dev/null +++ b/tests/regrtest/test_class_attr_reads_through_instances.py @@ -0,0 +1,92 @@ +"""Class attributes read through instances from compiled loops (memoized +per class version, now ahead of the slow lanes, and for module values +too): ints, strings, a module, a range, a bytearray, an instance +attribute that shadows later, the class attribute reassigned, a +subclass overriding it, slotted classes, several classes at one site, +and a class with __getattribute__, each matching CPython.""" + +import posixpath +import unittest + + +class A: + LIMIT = 10 + NAME = "a" + mod = posixpath + span = range(3) + buf = bytearray(b"x") + + def limit(self): + return self.LIMIT + + def mod_sep(self): + return self.mod.sep + + +class B(A): + LIMIT = 20 + + +class S: + __slots__ = ("v",) + mod = posixpath + LIMIT = 5 + + def get(self): + return self.mod, self.LIMIT + + +class G: + LIMIT = 1 + + def __getattribute__(self, name): + if name == "LIMIT": + return 99 + return object.__getattribute__(self, name) + + +def reads(n, objs): + out = [] + for i in range(n): + for o in objs: + out.append((o.LIMIT, o.mod is posixpath)) + return out[-len(objs):] + + +class ClassAttrTests(unittest.TestCase): + def test_values(self): + a, b, s = A(), B(), S() + for i in range(300): + r = (a.limit(), a.NAME, a.mod_sep(), a.span, a.buf, b.limit(), s.get()) + self.assertEqual(r[:5], (10, "a", "/", range(3), bytearray(b"x"))) + self.assertEqual(r[5], 20) + self.assertEqual(r[6], (posixpath, 5)) + self.assertEqual(reads(300, [a, b, s]), [(10, True), (20, True), (5, True)]) + + def test_shadow_and_reassign(self): + a = A() + for i in range(300): + v = a.limit() + a.LIMIT = 7 + self.assertEqual(a.limit(), 7) + del a.LIMIT + self.assertEqual(a.limit(), 10) + A.LIMIT = 11 + try: + self.assertEqual(a.limit(), 11) + self.assertEqual(B().limit(), 20) + finally: + A.LIMIT = 10 + a.mod = None + with self.assertRaises(AttributeError): + a.mod_sep() + + def test_getattribute(self): + g = G() + for i in range(300): + v = g.LIMIT + self.assertEqual(v, 99) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_class_call_mapping.py b/tests/regrtest/test_class_call_mapping.py new file mode 100644 index 000000000..6deace01c --- /dev/null +++ b/tests/regrtest/test_class_call_mapping.py @@ -0,0 +1,66 @@ +"""`cls(*args, **kwargs)` of a plain class with a Python `__init__`. + +`dataclasses.replace` ends in `self.__class__(**changes)`. The core loop +and compiled code bind the mapping's keywords to `__init__` and run it +inline, as a keyword call's construction runs; the mapping is left as it +was, and a binding the fast path can't make (an unexpected or repeated +name) raises the generic call's `TypeError`. Items are heap objects. Run +it past the compile threshold. +""" + +import dataclasses + + +class Item: + pass + + +class P: + def __init__(self, a, b=2, *, c=3): + self.a, self.b, self.c = a, b, c + + +class K: + def __init__(self, a, **rest): + self.a, self.rest = a, rest + + +@dataclasses.dataclass +class Pt: + x: object + y: int = 0 + tags: list = dataclasses.field(default_factory=list) + + +def make(cls, *args, **kwargs): + return cls(*args, **kwargs) + + +def build(cls, kw): + return cls(**kw) + + +item = Item() +for _ in range(3000): + kw = {"a": item, "c": 5} + p = build(P, kw) + assert p.a is item and p.b == 2 and p.c == 5 and kw == {"a": item, "c": 5} + p = make(P, item, c=7) + assert p.a is item and p.b == 2 and p.c == 7 + k = build(K, {"a": 1, "z": item}) + assert k.a == 1 and k.rest == {"z": item} + try: + build(P, {"a": 1, "zz": 2}) + except TypeError as e: + assert "zz" in str(e), e + else: + raise AssertionError("no TypeError") + try: + make(P, 1, a=2) + except TypeError as e: + assert "a" in str(e), e + else: + raise AssertionError("no TypeError") + pt = Pt(item, 2) + q = dataclasses.replace(pt, y=5) + assert q.x is item and q.y == 5 and q.tags == [] and q is not pt diff --git a/tests/regrtest/test_class_link_tuples.py b/tests/regrtest/test_class_link_tuples.py new file mode 100644 index 000000000..07c62a38d --- /dev/null +++ b/tests/regrtest/test_class_link_tuples.py @@ -0,0 +1,94 @@ +"""`cls.__mro__` and `cls.__bases__` read as one tuple each. + +As in CPython, `C.__mro__ is C.__mro__`: the class keeps the tuple while +its links stay the same, a `__bases__` assignment gives new ones, and a +class whose tuples were read is still collected once nothing else holds +it. A tuple subclass passed to `type()` as the bases is kept as given. +""" + +import gc +import unittest +import weakref + +N = 3000 + + +class A: + pass + + +class B: + pass + + +def links(c): + return c.__mro__, c.__bases__ + + +class ClassLinkTupleTests(unittest.TestCase): + def test_identity(self): + class C(A): + pass + + first = links(C) + for _ in range(N): + r = links(C) + self.assertIs(r[0], first[0]) + self.assertIs(r[1], first[1]) + self.assertEqual(r, ((C, A, object), (A,))) + self.assertIs(int.__mro__, int.__mro__) + self.assertEqual(object.__bases__, ()) + + def test_bases_assignment(self): + class D(A): + pass + + before = links(D) + out = [] + for i in range(N): + if i == N // 2: + D.__bases__ = (B,) + out.append(links(D)) + self.assertEqual(out[0], before) + self.assertEqual(out[-1], ((D, B, object), (B,))) + self.assertIsNot(out[-1][0], before[0]) + self.assertIs(out[-1][0], D.__mro__) + # The tuple read before the assignment keeps what it held. + self.assertEqual(before[0], (D, A, object)) + + def test_collected(self): + refs = [] + for i in range(200): + K = type("K%d" % i, (A,), {}) + links(K) + refs.append(weakref.ref(K)) + del K + gc.collect() + self.assertEqual(sum(r() is not None for r in refs), 0) + + def test_held_tuple_keeps_class(self): + K = type("Held", (A,), {}) + mro = K.__mro__ + r = weakref.ref(K) + del K + gc.collect() + self.assertIsNotNone(r()) + self.assertIs(mro[0], r()) + del mro + gc.collect() + self.assertIsNone(r()) + + def test_tuple_subclass_bases(self): + class T(tuple): + pass + + bases = T((A,)) + K = type("K", bases, {}) + for _ in range(500): + b = K.__bases__ + self.assertIs(b, bases) + self.assertEqual(K.__mro__, (K, A, object)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_class_method_site.py b/tests/regrtest/test_class_method_site.py new file mode 100644 index 000000000..cba38f430 --- /dev/null +++ b/tests/regrtest/test_class_method_site.py @@ -0,0 +1,131 @@ +"""Method loads on a user class receiver (`C.s(x)`, `C.make()`). + +Compiled code remembers a class's plain function, static method or class +method at the site while the class's and its metaclass's versions hold; +reassigning the attribute, swapping a static method for a class method, +another class at the site, a metaclass that reads attributes itself or +defines the name (as a data descriptor or a method the class's entry +overrides), and a descriptor with its own `__get__` all behave as +in CPython. Run it past the compile threshold. +""" + + +class C: + @staticmethod + def s(x): + return ("s", x) + + @classmethod + def make(cls): + return ("make", cls.__name__) + + def plain(x): + return ("plain", x) + + +class Sub(C): + pass + + +class Meta(type): + def __getattribute__(cls, name): + if name == "s": + return lambda x: ("meta", x) + return super().__getattribute__(name) + + +class M(metaclass=Meta): + @staticmethod + def s(x): + return ("s", x) + + +class Shadow(type): + def s(cls, x): + return ("shadow", x) + + +class N(metaclass=Shadow): + pass + + +class Desc: + calls = 0 + + def __get__(self, obj, cls): + Desc.calls += 1 + return lambda x: ("desc", Desc.calls, x) + + +class D: + s = Desc() + + +def run(n, k): + out = [] + for i in range(n): + out.append((k.s(i), k.make(), k.plain(i))) + return out + + +N_ = 2000 +assert run(N_, C)[-1] == (("s", N_ - 1), ("make", "C"), ("plain", N_ - 1)) +assert run(N_, Sub)[-1] == (("s", N_ - 1), ("make", "Sub"), ("plain", N_ - 1)) + + +def swap(n): + out = [] + for i in range(n): + out.append(C.s(i)) + return out + + +assert swap(N_)[-1] == ("s", N_ - 1) +C.s = classmethod(lambda cls, x: ("cm", cls.__name__, x)) +assert swap(5)[-1] == ("cm", "C", 4) +C.s = staticmethod(lambda x: ("new", x)) +assert swap(5)[-1] == ("new", 4) +C.s = lambda x: ("fn", x) +assert swap(5)[-1] == ("fn", 4) +Meta.s = 1 # an unrelated metaclass change +del C.s +try: + swap(1) +except AttributeError: + pass +else: + raise AssertionError("deleted attribute") + + +def via(k, n): + out = [] + for i in range(n): + out.append(k.s(i)) + return out + + +assert via(M, N_)[-1] == ("meta", N_ - 1) +assert via(N, N_)[-1] == ("shadow", N_ - 1) +r = via(D, N_) +assert r[-1] == ("desc", N_, N_ - 1) and Desc.calls == N_ + + +# A metaclass method of the same name: the class's own entry wins until +# it goes, and then the metaclass's answers, bound to the class. +class MetaFn(type): + def s(cls, x): + return ("metafn", cls.__name__, x) + + +class Q(metaclass=MetaFn): + @staticmethod + def s(x): + return ("q", x) + + +assert via(Q, N_)[-1] == ("q", N_ - 1) +del Q.s +assert via(Q, 5)[-1] == ("metafn", "Q", 4) +Q.s = staticmethod(lambda x: ("again", x)) +assert via(Q, 5)[-1] == ("again", 4) +print("ok") diff --git a/tests/regrtest/test_class_name_and_method_attr_reads.py b/tests/regrtest/test_class_name_and_method_attr_reads.py new file mode 100644 index 000000000..84e8cfb14 --- /dev/null +++ b/tests/regrtest/test_class_name_and_method_attr_reads.py @@ -0,0 +1,133 @@ +"""`cls.__qualname__` and a bound method's attributes, compiled and not. + +A site that reads a class's `__name__`, `__qualname__` or `__module__` +remembers the string for the class's version; assigning `__qualname__` +moves the version, so the site reads the new name. A bound method's +`__self__`, `__func__`, `__name__`, `__qualname__` and `__doc__` read +directly: names a decorator patched onto the function, builtin methods' +qualified names, and metaclasses that answer the names themselves behave +as before. +""" + +import functools +import unittest + +N = 3000 + + +class Plain: + """plain doc""" + + def method(self): + """method doc""" + + +class Meta(type): + @property + def __module__(cls): + return "meta-module" + + +class ByMeta(metaclass=Meta): + pass + + +def renamed(f): + @functools.wraps(f) + def inner(*a): + return f(*a) + + inner.__name__ = "patched" + return inner + + +class Wrapped: + @renamed + def original(self): + pass + + +def qual(c): + return c.__qualname__ + + +class ClassNameTests(unittest.TestCase): + def test_qualname_assignment(self): + class C: + pass + + out = [] + for i in range(N): + if i == N // 2: + C.__qualname__ = "Outer.C" + out.append((qual(C), C.__name__)) + self.assertEqual(out[0][0], "ClassNameTests.test_qualname_assignment..C") + self.assertEqual(out[-1], ("Outer.C", "C")) + self.assertIs(qual(C), qual(C)) + + def test_name_assignment_and_mixed_classes(self): + class A: + pass + + class B: + pass + + out = [] + for i in range(N): + if i == N // 2: + A.__name__ = "Renamed" + out.append(((A, B)[i % 2]).__name__) + self.assertEqual(out[:2], ["A", "B"]) + self.assertEqual(out[-2:], ["Renamed", "B"]) + + def test_metaclass_names(self): + for _ in range(N): + r = (ByMeta.__module__, ByMeta.__name__, qual(int), qual(Plain)) + self.assertEqual(r, ("meta-module", "ByMeta", "int", "Plain")) + + +class BoundMethodAttrTests(unittest.TestCase): + def test_python_method(self): + p = Plain() + m = p.method + for _ in range(N): + r = (m.__self__, m.__func__, m.__name__, m.__qualname__, m.__doc__) + self.assertEqual(r, (p, Plain.method, "method", "Plain.method", "method doc")) + + def test_patched_function_names(self): + m = Wrapped().original + for _ in range(N): + r = (m.__name__, m.__qualname__) + self.assertEqual(r, ("patched", "Wrapped.original")) + + def test_builtin_methods(self): + lst = [] + app = lst.append + fk = dict.fromkeys + for _ in range(N): + r = (app.__self__ is lst, app.__name__, app.__qualname__, fk.__qualname__) + self.assertEqual(r, (True, "append", "list.append", "dict.fromkeys")) + + def test_classmethod_and_mixed_receivers(self): + class K: + @classmethod + def make(cls): + return cls + + def inst(self): + pass + + k = K() + ms = [K.make, k.inst, len, Plain().method] + out = [] + for i in range(N): + m = ms[i % 4] + out.append(m.__name__) + self.assertEqual(out[:4], ["make", "inst", "len", "method"]) + self.assertIs(K.make.__self__, K) + with self.assertRaises(AttributeError): + k.inst.no_such_attr + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_class_read_last_reference.py b/tests/regrtest/test_class_read_last_reference.py new file mode 100644 index 000000000..5f79d383e --- /dev/null +++ b/tests/regrtest/test_class_read_last_reference.py @@ -0,0 +1,45 @@ +"""`x.__class__` of a temporary that dies at the read. + +`super(C, obj).__class__` reads the class of a proxy nothing else holds. +Compiled code reads it and releases the proxy in place; a temporary with a +finalizer dies at the read too, and its `__del__` runs before the next +statement, as CPython runs it. Run it past the compile threshold. +""" + +log = [] + + +class D: + def __del__(self): + log.append("del") + + +class B: + def m(self): + return "B.m" + + +class C(B): + def m(self): + return super().m() + "+C" + + +def proxies(o): + for _ in range(3000): + assert super(C, o).__class__ is super + s = super(C, o) + assert s.m() == "B.m" and s.__self__ is o and s.__thisclass__ is C + assert s.__self_class__ is C + + +def temporaries(): + for _ in range(3000): + del log[:] + cls = D().__class__ + log.append("after") + assert cls is D and log == ["del", "after"], log + + +proxies(C()) +temporaries() +assert C().m() == "B.m+C" diff --git a/tests/regrtest/test_class_value_stores_keep_lookups.py b/tests/regrtest/test_class_value_stores_keep_lookups.py new file mode 100644 index 000000000..6fe9657f0 --- /dev/null +++ b/tests/regrtest/test_class_value_stores_keep_lookups.py @@ -0,0 +1,323 @@ +"""A class attribute store that only replaces a value keeps the class's +name lookups. + +The MRO lookup cache holds where each name resolves, not what it resolves +to, so a store that replaces the value of an entry a class already has +(`Counter.count += 1`, `Config.mode = "b"`) no longer empties it. These +tests pin what must still be seen at once: the new value everywhere, and +every change to where a name resolves (a name added or deleted on any class +of the MRO, a base swapped, a descriptor taking a plain value's place). +""" + +import unittest + +N = 3000 + + +class ValueStores(unittest.TestCase): + def test_counter_per_instance(self): + class Counted: + count = 0 + + def __init__(self, v): + Counted.count += 1 + self.v = v + + def get(self): + return self.v + self.count + + total = 0 + for i in range(N): + total += Counted(i).get() + self.assertEqual(Counted.count, N) + self.assertEqual(total, sum(i + i + 1 for i in range(N))) + + def test_constructor_that_names_its_own_class(self): + class Scaled: + base = 3 + made = [] + + def __init__(self, v): + self.v = v + Scaled.base + if v == N - 1: + Scaled.made.append(self) + + class Linked: + head = None + + def __init__(self, v): + self.v = v + self.prev = Linked.head + Linked.head = self + + total = 0 + for i in range(N): + total += Scaled(i).v + Linked(i) + self.assertEqual(total, sum(range(N)) + 3 * N) + self.assertEqual([s.v for s in Scaled.made], [N + 2]) + self.assertEqual((Linked.head.v, Linked.head.prev.v), (N - 1, N - 2)) + Scaled.base = 10 + self.assertEqual(Scaled(1).v, 11) + + def test_new_values_seen_through_instances_and_subclasses(self): + class Base: + level = 0 + name = "base" + + def read(self): + return self.level, self.name + + class Child(Base): + pass + + c = Child() + for i in range(N): + Base.level = i + Base.name = "n%d" % (i & 3) + got = (c.read(), Child.level, Base.level, getattr(c, "level")) + self.assertEqual(got, ((N - 1, "n%d" % ((N - 1) & 3)), N - 1, N - 1, N - 1)) + + def test_through_class_object_and_type(self): + class Tot: + total = 0 + + def add(self, x): + self.__class__.total += x + type(self).total += 1 + + t = Tot() + for i in range(N): + t.add(i) + self.assertEqual(Tot.total, sum(range(N)) + N) + + def test_setattr_and_vars(self): + class Cfg: + a = 1 + b = 2 + + c = Cfg() + for i in range(200): + setattr(Cfg, "b", i) + got = (getattr(c, "b"), vars(Cfg)["b"], Cfg.__dict__["a"]) + self.assertEqual(got, (199, 199, 1)) + + +class ShapeChanges(unittest.TestCase): + def churn(self, cls, name): + for i in range(50): + setattr(cls, name, i) + + def test_subclass_gains_and_loses_the_name(self): + class Base: + x = "base" + + class Child(Base): + pass + + c = Child() + self.churn(Base, "x") + self.assertEqual(c.x, 49) + Child.x = "child" + self.assertEqual((c.x, Child.x, Base.x), ("child", "child", 49)) + self.churn(Base, "x") + self.churn(Child, "x") + self.assertEqual((c.x, Base.x), (49, 49)) + Child.x = "mine" + del Child.x + self.assertEqual((c.x, hasattr(Child, "x"), "x" in vars(Child)), (49, True, False)) + + def test_earlier_base_gains_the_name(self): + class A: + pass + + class B: + x = "b" + + class C(A, B): + pass + + c = C() + self.churn(B, "x") + self.assertEqual(c.x, 49) + A.x = "a" + self.assertEqual((c.x, C.x), ("a", "a")) + self.churn(A, "x") + self.churn(B, "x") + self.assertEqual(c.x, 49) + B.x = "b again" + del A.x + self.assertEqual((c.x, C.x), ("b again", "b again")) + + def test_absent_names_appear(self): + class Thing: + present = 1 + + t = Thing() + for i in range(50): + Thing.present = i + self.assertFalse(hasattr(t, "later")) + self.assertFalse(hasattr(Thing, "later")) + Thing.later = "now" + self.assertEqual((t.later, Thing.later), ("now", "now")) + del Thing.later + self.assertFalse(hasattr(t, "later")) + + def test_entries_shift_when_an_earlier_one_is_deleted(self): + class Cfg: + a = 1 + b = 2 + c = 3 + + o = Cfg() + self.churn(Cfg, "c") + self.assertEqual((o.a, o.b, o.c), (1, 2, 49)) + del Cfg.a + self.assertEqual((o.b, o.c, hasattr(o, "a")), (2, 49, False)) + Cfg.d = 4 + Cfg.a = "back" + self.churn(Cfg, "b") + self.assertEqual((o.a, o.b, o.c, o.d), ("back", 49, 49, 4)) + + def test_descriptor_takes_a_plain_values_place_and_back(self): + class Shape: + size = 1 + + def area(self): + return "first" + + s = Shape() + s.__dict__["size"] = "instance" + self.churn(Shape, "size") + self.assertEqual(s.size, "instance") + Shape.size = property(lambda self: "property") + self.assertEqual(s.size, "property") + Shape.size = 7 + self.assertEqual(s.size, "instance") + del s.__dict__["size"] + self.assertEqual(s.size, 7) + for i in range(50): + Shape.area = lambda self, i=i: i + got = s.area() + self.assertEqual(got, 49) + Shape.area = staticmethod(lambda: "static") + self.assertEqual(s.area(), "static") + + def test_methods_follow_changes_between_value_stores(self): + class Base: + ticks = 0 + + def step(self): + return "base" + + class Kid(Base): + def step(self): + return "kid" + + def call(o): + return o.step() + + k = Kid() + seen = [] + for i in range(N): + Base.ticks = i + Kid.ticks = -i + if i == N // 2: + Kid.step = lambda self: "patched" + elif i == N // 2 + 50: + del Kid.step + elif i == N // 2 + 100: + Base.step = lambda self: "new base" + elif i == N // 2 + 150: + k.step = lambda: "instance" + elif i == N // 2 + 200: + del k.step + got = call(k) + if not seen or seen[-1] != got: + seen.append(got) + self.assertEqual(seen, ["kid", "patched", "base", "new base", "instance", "new base"]) + + def test_kind_changes_of_a_plain_value(self): + class Slot: + mark = "text" + + def read(self): + return self.mark + + s = Slot() + seen = [] + for value in ("a", "b", 1, 2, None, None, 2.5, (1,), [1], "back", len, Slot.read, 7): + for _ in range(60): + Slot.mark = value + got = s.read() + seen.append(got if not callable(got) else got.__name__) + self.assertEqual( + seen, ["a", "b", 1, 2, None, None, 2.5, (1,), [1], "back", "len", "read", 7] + ) + s.mark = "own" + Slot.mark = "class" + self.assertEqual(s.read(), "own") + + def test_bases_swapped(self): + class One: + tag = "one" + + class Two: + tag = "two" + + class User(One): + pass + + u = User() + self.churn(One, "tag") + self.assertEqual(u.tag, 49) + User.__bases__ = (Two,) + self.assertEqual(u.tag, "two") + self.churn(Two, "tag") + self.churn(One, "tag") + self.assertEqual(u.tag, 49) + Two.tag = "two again" + self.assertEqual(u.tag, "two again") + + def test_metaclass_attribute_and_class_attribute(self): + class Meta(type): + shared = "meta" + + class Klass(metaclass=Meta): + pass + + self.assertEqual(Klass.shared, "meta") + self.churn(Meta, "shared") + self.assertEqual(Klass.shared, 49) + Klass.shared = "class" + self.assertEqual(Klass.shared, "class") + self.churn(Klass, "shared") + self.assertEqual((Klass.shared, Meta.shared), (49, 49)) + del Klass.shared + Meta.shared = "meta again" + self.assertEqual(Klass.shared, "meta again") + + def test_special_names_still_take_effect(self): + class Num: + def __init__(self, v): + self.v = v + + def __len__(self): + return self.v + + scale = 1 + + n = Num(3) + for i in range(100): + Num.scale = i + Num.__len__ = lambda self, i=i: self.v + i + got = len(n) + self.assertEqual(got, 102) + Num.__eq__ = lambda self, other: True + self.assertTrue(n == object()) + Num.__eq__ = lambda self, other: False + self.assertFalse(n == n) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_class_value_via_field_site.py b/tests/regrtest/test_class_value_via_field_site.py new file mode 100644 index 000000000..5b693a9c2 --- /dev/null +++ b/tests/regrtest/test_class_value_via_field_site.py @@ -0,0 +1,120 @@ +"""Class values read through instances in compiled pure helpers. + +A helper like `ipaddress`'s `__contains__` reads `self.version`, a class +constant, at a site whose field cache holds only instances' own fields. +The site answers from the class value it read for the class's version. +Each case runs hot and must agree with CPython: instances that later +shadow the name, classes whose value changes, subclasses that override +it, two classes at one site, object-valued constants, and `ip in net`. +""" + +import ipaddress +import unittest + +N = 3000 + + +class V4: + version = 4 + tag = "four" + + def __init__(self, ip): + self.ip = ip + + +class V6: + __slots__ = ("ip",) + version = 6 + tag = "six" + + def __init__(self, ip): + self.ip = ip + + +class V4Sub(V4): + version = 44 + + +def same(a, b): + return a.version == b.version + + +def info(a): + return (a.version, a.tag) + + +class ClassValueViaFieldSiteTests(unittest.TestCase): + def test_constants_and_two_classes(self): + a, b, c = V4(1), V4(2), V6(3) + + def run(): + out = None + for i in range(N): + out = (same(a, b), same(a, c), same(c, c), info(a), info(c)) + return out + + self.assertEqual(run(), (True, False, True, (4, "four"), (6, "six"))) + + def test_instance_shadows_later(self): + a = V4(1) + + def run(): + out = [] + for i in range(N): + if i == N // 2: + a.version = 5 + a.tag = "shadow" + out.append(info(a)) + return out[0], out[-1] + + self.assertEqual(run(), ((4, "four"), (5, "shadow"))) + del a.version + + def test_class_value_changes(self): + class K: + version = 1 + + k = K() + + def read(o): + return o.version + + def run(): + out = [] + for i in range(N): + if i == N // 2: + K.version = 2 + out.append(read(k)) + return out[0], out[-1] + + self.assertEqual(run(), (1, 2)) + + def test_subclass_override(self): + a, s = V4(1), V4Sub(2) + + def run(): + out = None + for i in range(N): + out = (info(a), info(s), same(a, s)) + return out + + self.assertEqual(run(), ((4, "four"), (44, "four"), False)) + + def test_ipaddress_contains(self): + net = ipaddress.ip_network("10.0.0.0/8") + net6 = ipaddress.ip_network("fe80::/10") + ip4 = ipaddress.ip_address("10.1.2.3") + out4 = ipaddress.ip_address("11.1.2.3") + ip6 = ipaddress.ip_address("fe80::1") + + def run(): + out = None + for i in range(N): + out = (ip4 in net, out4 in net, ip6 in net, ip6 in net6, ip4 in net6) + return out + + self.assertEqual(run(), (True, False, False, True, False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_cmp_to_key_and_slot_callables.py b/tests/regrtest/test_cmp_to_key_and_slot_callables.py new file mode 100644 index 000000000..a84a52b1c --- /dev/null +++ b/tests/regrtest/test_cmp_to_key_and_slot_callables.py @@ -0,0 +1,124 @@ +"""`functools.cmp_to_key`, and calls of callables held in `__slots__`. + +`cmp_to_key(f)` returns a key factory that makes no class per call; its +keys compare through `f`, keep `.obj`, take `obj` by keyword, report the +signature `(obj)`, are unhashable, and fail against other objects. +Compiled code calls `self.fn(...)` of a function a `__slots__` member +holds without leaving; an unset member, a member assigned a new callable, +a subclass that shadows the name with a method, and a class whose layout +changes behave as before. +""" + +import collections.abc +import functools +import inspect +import unittest + +N = 3000 + + +class Holder: + __slots__ = ("fn", "other") + + def __init__(self, fn): + self.fn = fn + + def run(self, x): + return self.fn(x) + + +class Shadow(Holder): + def __init__(self): + pass + + def fn(self, x): + return ("method", x) + + +class CmpToKeyTests(unittest.TestCase): + def test_sorting(self): + for _ in range(N // 10): + r = sorted(range(10), key=functools.cmp_to_key(lambda a, b: b - a)) + s = sorted([5, "3", 7, 2, "0"], key=functools.cmp_to_key(lambda x, y: int(x) - int(y))) + self.assertEqual(r, list(range(9, -1, -1))) + self.assertEqual(s, ["0", 2, "3", 5, 7]) + + def test_key_objects(self): + def cmp1(x, y): + return (x > y) - (x < y) + + key = functools.cmp_to_key(mycmp=cmp1) + self.assertEqual(key(obj=3), key(obj=3)) + self.assertGreater(key(3), key(1)) + self.assertLessEqual(key(1), key(1)) + self.assertEqual(key(50).obj, 50) + self.assertEqual(str(inspect.signature(key)), "(obj)") + with self.assertRaises((TypeError, AttributeError)): + key(3) > 1 + with self.assertRaises((TypeError, AttributeError)): + 1 < key(3) + with self.assertRaises(TypeError): + hash(key(10)) + self.assertNotIsInstance(key(1), collections.abc.Hashable) + with self.assertRaises(TypeError): + functools.cmp_to_key() + with self.assertRaises(TypeError): + key() + + def test_raising_cmp(self): + def bad(x, y): + raise ZeroDivisionError + + key = functools.cmp_to_key(bad) + for _ in range(200): + with self.assertRaises(ZeroDivisionError): + key(3) > key(1) + with self.assertRaises(ZeroDivisionError): + sorted([3, 1, 2], key=key) + + +class SlotCallableTests(unittest.TestCase): + def test_slot_function(self): + h = Holder(lambda x: x * 2) + for i in range(N): + r = h.run(i) + self.assertEqual(r, (N - 1) * 2) + + def test_reassigned_and_unset(self): + h = Holder(len) + out = [] + for i in range(N): + if i == N // 2: + h.fn = str + out.append(h.run([1, 2])) + self.assertEqual((out[0], out[-1]), (2, "[1, 2]")) + e = Holder.__new__(Holder) + for _ in range(200): + with self.assertRaises(AttributeError): + e.run(1) + + def test_shadowing_subclass(self): + items = [Holder(lambda x: ("slot", x)), Shadow()] + out = [] + for i in range(N): + out.append(items[i % 2].run(i)) + self.assertEqual(out[:2], [("slot", 0), ("method", 1)]) + + def test_mixed_receivers(self): + class Plain: + def __init__(self, fn): + self.fn = fn + + def run(self, x): + return self.fn(x) + + items = [Holder(abs), Plain(abs), Holder(lambda x: -x)] + out = [] + for i in range(N): + out.append(items[i % 3].run(-i)) + self.assertEqual(out[:3], [0, 1, 2]) + self.assertEqual(out[-3:], [N - 3, N - 2, N - 1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_cmp_to_key_direct_sort.py b/tests/regrtest/test_cmp_to_key_direct_sort.py new file mode 100644 index 000000000..587519b2b --- /dev/null +++ b/tests/regrtest/test_cmp_to_key_direct_sort.py @@ -0,0 +1,76 @@ +"""sorted() and list.sort() with key=functools.cmp_to_key(mycmp) compare +the items through mycmp directly: stable order, reverse, a mycmp result +that is not an int (its own < 0 decides), an error from mycmp, a mycmp +that mutates the list being sorted, and a key class that stays immutable, +each matching CPython.""" + +import functools +import unittest + + +def three_way(a, b): + return (a > b) - (a < b) + + +class Res: + def __init__(self, v): + self.v = v + + def __lt__(self, other): + return self.v < other + + +class CmpToKeySortTests(unittest.TestCase): + def test_order_and_stability(self): + xs = [(1, "a"), (0, "b"), (1, "c"), (0, "d")] + k = functools.cmp_to_key(lambda a, b: a[0] - b[0]) + for _ in range(300): + self.assertEqual(sorted(xs, key=k), [(0, "b"), (0, "d"), (1, "a"), (1, "c")]) + self.assertEqual( + sorted(xs, key=k, reverse=True), [(1, "a"), (1, "c"), (0, "b"), (0, "d")] + ) + ys = list(range(20, 0, -1)) + ys.sort(key=functools.cmp_to_key(three_way)) + self.assertEqual(ys, list(range(1, 21))) + + def test_non_int_result(self): + k = functools.cmp_to_key(lambda a, b: Res(a - b)) + self.assertEqual(sorted([3, 1, 2], key=k), [1, 2, 3]) + k = functools.cmp_to_key(lambda a, b: float(a - b)) + self.assertEqual(sorted([3, 1, 2], key=k), [1, 2, 3]) + + def test_error(self): + calls = [] + + def bad(a, b): + calls.append((a, b)) + raise ValueError("no") + + with self.assertRaises(ValueError): + sorted([1, 2, 3], key=functools.cmp_to_key(bad)) + self.assertEqual(len(calls), 1) + self.assertEqual(sorted([5], key=functools.cmp_to_key(bad)), [5]) + + def test_mutation(self): + L = [3, 2, 1] + + def mut(a, b): + L.append(0) + return a - b + + with self.assertRaises(ValueError): + L.sort(key=functools.cmp_to_key(mut)) + + def test_wrappers(self): + k = functools.cmp_to_key(three_way) + self.assertTrue(k(1) < k(2)) + self.assertTrue(k(2) >= k(2)) + with self.assertRaises(TypeError): + type(k).__call__ = None + with self.assertRaises(TypeError): + type(k(1)).__lt__ = None + self.assertEqual(sorted([2, 1], key=k), [1, 2]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_codec_memo_and_inplace_stdlib_natives.py b/tests/regrtest/test_codec_memo_and_inplace_stdlib_natives.py new file mode 100644 index 000000000..c96ac44f6 --- /dev/null +++ b/tests/regrtest/test_codec_memo_and_inplace_stdlib_natives.py @@ -0,0 +1,287 @@ +"""`codecs.lookup` remembers the codec of each spelling it has resolved, +and more native functions run in place from compiled code: the +`datetime` class methods, `os.path`'s and `re`'s helpers, `os.walk`, +`time.strptime`, the tokenizer, `string.Formatter`'s parsers, +`contextvars.copy_context`, the XML parser and serializer, and the event +loop's bookkeeping. Each behaves as before in a hot loop: results, +errors, and the Python code a native calls back into, which still sees +the frames that called it.""" + +import asyncio +import codecs +import contextvars +import io +import os +import pathlib +import re +import string +import sys +import tempfile +import time +import tokenize +import unittest +import xml.etree.ElementTree as ET +from datetime import date, datetime, timedelta, timezone +from datetime import time as dtime + +N = 300 + + +class CodecMemo(unittest.TestCase): + def test_spellings_share_one_codec(self): + # (The registry keeps one codec per normalised name: case and + # punctuation don't make another.) + for _ in range(N): + a = codecs.lookup("utf-8") + b = codecs.lookup("UTF-8") + c = codecs.lookup("Utf_8") + self.assertIs(a, b) + self.assertIs(a, c) + self.assertEqual(a.name, "utf-8") + self.assertEqual(codecs.lookup("UTF8").name, "utf-8") + self.assertEqual(codecs.lookup("latin-1").name, codecs.lookup("iso8859-1").name) + + def test_errors_are_not_remembered(self): + for _ in range(20): + with self.assertRaises(LookupError): + codecs.lookup("no-such-codec-x") + with self.assertRaises(ValueError): + codecs.lookup("utf-8\0") + with self.assertRaises(TypeError): + codecs.lookup(8) + with self.assertRaises(TypeError): + codecs.lookup(b"utf-8") + + def test_registered_search_function(self): + calls = [] + info = codecs.lookup("utf-8") + mine = codecs.CodecInfo(info.encode, info.decode, name="mine-x") + + def search(name): + calls.append(name) + return mine if name == "mine_x" else None + + with self.assertRaises(LookupError): + codecs.lookup("mine-x") + codecs.register(search) + try: + for _ in range(N): + got = codecs.lookup("Mine-X") + self.assertIs(got, mine) + self.assertEqual(calls.count("mine_x"), 1) + self.assertEqual("é".encode("mine-x"), b"\xc3\xa9") + finally: + codecs.unregister(search) + for _ in range(5): + with self.assertRaises(LookupError): + codecs.lookup("Mine-X") + self.assertEqual(codecs.lookup("utf-8").name, "utf-8") + self.assertIs(codecs.lookup("utf-8"), codecs.lookup("UTF-8")) + + def test_many_spellings(self): + names = ["utf-8", "UTF-8", "utf8", "U8", "latin-1", "ascii", "cp1252", "utf-16", "UTF_16_LE"] + firsts = [codecs.lookup(n) for n in names] + for i in range(400): + with self.assertRaises(LookupError): + codecs.lookup("missing-%d" % i) + for n, first in zip(names, firsts): + self.assertIs(codecs.lookup(n), first) + + def test_str_subclass_name(self): + class Name(str): + pass + + for _ in range(20): + self.assertIs(codecs.lookup(Name("utf-8")), codecs.lookup("utf-8")) + + +class Fussy: + """A path whose `__fspath__` looks at who called it.""" + + seen = None + + def __init__(self, path): + self.path = path + + def __fspath__(self): + Fussy.seen = sys._getframe(1).f_code.co_name + return self.path + + +class InPlaceNatives(unittest.TestCase): + def test_datetime_class_methods(self): + class D(datetime): + pass + + for i in range(N): + got = ( + datetime.fromtimestamp(86400 * i, timezone.utc).day, + datetime.fromisoformat("2024-05-17T01:02:03").second, + datetime.combine(date(2024, 5, 17), dtime(1, 2)).minute, + date.fromordinal(738000 + i).toordinal(), + type(D.now()), type(D.fromtimestamp(0, timezone.utc)), type(D.combine(date(2024, 1, 1), dtime(0))), + ) + self.assertLess(abs(datetime.now() - datetime.now()), timedelta(seconds=5)) + self.assertEqual(date.today(), datetime.now().date()) + self.assertEqual(got, (1 + (N - 1) % 31 if N <= 31 else got[0], 3, 2, 738000 + N - 1, D, D, D)) + for _ in range(5): + with self.assertRaises(ValueError): + datetime.fromisoformat("nope") + with self.assertRaises(TypeError): + datetime.fromtimestamp("x") + with self.assertRaises(TypeError): + datetime.combine(1, 2) + with self.assertRaises((ValueError, OverflowError)): + date.fromordinal(0) + + def test_path_helpers(self): + for _ in range(N): + got = ( + os.path.normpath("a//b/../c/./d"), + os.path.normpath(Fussy("x/../y")), + pathlib.PurePosixPath("/usr//lib/../x.py").parts, + os.path.splitroot("/a/b") if hasattr(os.path, "splitroot") else None, + ) + self.assertEqual(got[0], os.path.join("a", "c", "d")) + self.assertEqual(got[1], "y") + self.assertEqual(got[2], ("/", "usr", "lib", "..", "x.py")) + self.assertEqual(Fussy.seen, "test_path_helpers") + for _ in range(5): + with self.assertRaises(TypeError): + os.path.normpath(5) + + def test_regex_entries(self): + for i in range(N): + p = re.compile(r"(\w+)-(\d+)") + m = p.match("item-%d" % i) + got = (m.group(1), int(m.group(2)), re.match(rb"a+", b"aaab").end(), + re.search("x", "abc"), re.compile("a", re.I).match("A").group()) + self.assertEqual(got, ("item", N - 1, 3, None, "A")) + for _ in range(5): + with self.assertRaises(re.error): + re.compile("(") + with self.assertRaises(TypeError): + re.compile(r"a").match(5) + + def test_walk(self): + with tempfile.TemporaryDirectory() as root: + os.makedirs(os.path.join(root, "a", "b")) + for name in ("x.txt", os.path.join("a", "y.txt"), os.path.join("a", "b", "z.txt")): + with open(os.path.join(root, name), "w") as f: + f.write("x") + errors = [] + for _ in range(60): + seen = [] + for top, dirs, files in os.walk(root): + dirs.sort() + seen.append((os.path.relpath(top, root), sorted(files))) + for _top, _dirs, _files in os.walk(os.path.join(root, "missing"), onerror=errors.append): + self.fail("nothing to walk") + self.assertEqual(seen, [(".", ["x.txt"]), ("a", ["y.txt"]), (os.path.join("a", "b"), ["z.txt"])]) + self.assertEqual(len(errors), 60) + self.assertIsInstance(errors[0], OSError) + pruned = [] + for top, dirs, files in os.walk(root): + pruned.append(os.path.relpath(top, root)) + dirs[:] = [] + self.assertEqual(pruned, ["."]) + + def test_strptime(self): + for _ in range(N): + t = time.strptime("2024-05-17 13:45", "%Y-%m-%d %H:%M") + self.assertEqual((t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min), (2024, 5, 17, 13, 45)) + for _ in range(5): + with self.assertRaises(ValueError): + time.strptime("nope", "%Y") + + def test_tokenizer(self): + src = "x = 1 + 2\nprint(x)\n" + for _ in range(60): + toks = [t.string for t in tokenize.generate_tokens(io.StringIO(src).readline)] + self.assertEqual(toks[:5], ["x", "=", "1", "+", "2"]) + + def bad_readline(): + lines.append(sys._getframe(1).f_code.co_name) + if len(lines) > 1: + raise RuntimeError("no more") + return "y = (\n" + + for _ in range(20): + lines = [] + with self.assertRaises(RuntimeError): + list(tokenize.generate_tokens(bad_readline)) + self.assertEqual(len(lines), 2) + + def test_formatter(self): + fmt = string.Formatter() + + class Shouty(string.Formatter): + def format_field(self, value, spec): + return super().format_field(value, spec).upper() + + for i in range(N): + got = (fmt.format("{0} {name!r:>6}|{0:03d}", i, name="x"), + fmt.format("{a[k]}-{b.real}", a={"k": 1}, b=2), + Shouty().format("{}:{x}", "a", x="b")) + self.assertEqual(got, ("%d 'x'|%03d" % (N - 1, N - 1), "1-2", "A:B")) + for _ in range(5): + with self.assertRaises(ValueError): + fmt.format("{") + with self.assertRaises(KeyError): + fmt.format("{missing}") + with self.assertRaises(IndexError): + fmt.format("{3}", 1) + with self.assertRaises(ValueError): + fmt.format("{} {0}", 1) + + def test_copy_context(self): + var = contextvars.ContextVar("v", default=0) + var.set(5) + for i in range(N): + ctx = contextvars.copy_context() + ctx.run(var.set, i) + other = contextvars.copy_context() + self.assertEqual((var.get(), ctx[var], other[var]), (5, N - 1, 5)) + self.assertIsNot(ctx, other) + with self.assertRaises(TypeError): + contextvars.copy_context(1) + + def test_xml_round_trip(self): + chunks = [] + + class Sink: + def write(self, data): + chunks.append(sys._getframe(1).f_code.co_name) + return len(data) + + for i in range(60): + root = ET.fromstring("t" % i) + text = ET.tostring(root, encoding="unicode") + ET.ElementTree(root).write(Sink(), encoding="unicode") + self.assertEqual(text, 't') + self.assertTrue(chunks) + for _ in range(5): + with self.assertRaises(ET.ParseError): + ET.fromstring("") + + def test_event_loop_runs(self): + async def work(x): + await asyncio.sleep(0) + return x * 2 + + async def agen(): + yield 1 + yield 2 + + async def drain(): + return [v async for v in agen()] + + for i in range(30): + got = (asyncio.run(work(i)), asyncio.run(drain())) + self.assertEqual(got, (58, [1, 2])) + with self.assertRaises(RuntimeError): + asyncio.get_running_loop() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_collect_range_iter.py b/tests/regrtest/test_collect_range_iter.py new file mode 100644 index 000000000..9abd371b7 --- /dev/null +++ b/tests/regrtest/test_collect_range_iter.py @@ -0,0 +1,35 @@ +"""`list()`, `tuple()` and `sorted()` of a range's iterator +(`reversed(range(n))`, `iter(range(...))` partly consumed): the ints at +once, in order, negative and large steps, an empty rest, values near the +64-bit limits, and the iterator left exhausted as stepping it leaves it.""" + +import sys +import unittest + + +class CollectRangeIter(unittest.TestCase): + def test_values(self): + for i in range(2000): + r = (list(reversed(range(20))), tuple(iter(range(3, 30, 7))), list(reversed(range(10, -10, -3))), + sorted(reversed(range(5))), list(iter(range(0)))) + self.assertEqual(r[0], list(range(19, -1, -1))) + self.assertEqual(r[1], (3, 10, 17, 24)) + self.assertEqual(r[2], [-8, -5, -2, 1, 4, 7, 10]) + self.assertEqual(r[3], [0, 1, 2, 3, 4]) + self.assertEqual(r[4], []) + + def test_partial_and_exhausted(self): + it = iter(range(10)) + next(it) + next(it) + self.assertEqual(list(it), list(range(2, 10))) + self.assertEqual(list(it), []) + with self.assertRaises(StopIteration): + next(it) + big = sys.maxsize + self.assertEqual(list(iter(range(big - 3, big))), [big - 3, big - 2, big - 1]) + self.assertEqual(list(reversed(range(-big - 1, -big + 2))), [-big + 1, -big, -big - 1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_builtin_errors.py b/tests/regrtest/test_compiled_builtin_errors.py new file mode 100644 index 000000000..e1f012abd --- /dev/null +++ b/tests/regrtest/test_compiled_builtin_errors.py @@ -0,0 +1,864 @@ +"""Errors a warm loop raises without leaving compiled code: a built-in +method's (`str.index`, `list.pop`, `dict.pop`, ...) on a local or a stack +receiver, a number operator's (a zero divisor, a negative shift count, zero +to a negative power), `len()` of an object without a length, `next()` at +the end of a plain iterator and a failing `assert`. Each keeps the type, +arguments, message, traceback and context the full call gives it, releases +its temporaries before the handler runs, and reaches a caller's handler or +a `finally` on the way. `str(e)` and `format(e)` of an exception follow +the class's own `__str__` and `__format__` as they come and go.""" + +import sys +import unittest + +N = 3000 + + +def trace(e): + out = [] + tb = e.__traceback__ + while tb is not None: + code = tb.tb_frame.f_code + out.append((code.co_name, tb.tb_lineno - code.co_firstlineno)) + tb = tb.tb_next + return out + + +def loop(fn, *args): + last = None + count = 0 + for i in range(N): + try: + fn(*args) + except Exception as e: + count += 1 + last = e + return count, last + + +def m_index(s, x): + return s.index(x) + + +def m_rindex(s, x): + return s.rindex(x) + + +def m_find(s, x): + return s.find(x) + + +def m_rfind(s, x): + return s.rfind(x) + + +def m_count(s, x): + return s.count(x) + + +def m_strip(s, x): + return s.strip(x) + + +def m_lstrip(s, x): + return s.lstrip(x) + + +def m_rstrip(s, x): + return s.rstrip(x) + + +def m_list_remove(xs, x): + xs.remove(x) + + +def m_list_index(xs, x): + return xs.index(x) + + +def m_pop(xs): + return xs.pop() + + +def m_pop_key(d, k): + return d.pop(k) + + +def m_set_remove(s, k): + s.remove(k) + + +def m_split(s, sep): + return s.split(sep) + + +def m_join(s, xs): + return s.join(xs) + + +def m_startswith(s, p): + return s.startswith(p) + + +def m_replace(s, a, b): + return s.replace(a, b) + + +def m_format(s, a): + return s.format(a) + + +def m_get(d, k): + return d.get(k) + + +def m_encode(s): + return s.encode("ascii") + + +class Box: + def __init__(self): + self.s = "abc" + self.xs = [1, 2, 3] + self.d = {"a": 1} + self.e = [] + + +def st_index(b): + return b.s.index("z") + + +def st_const(): + return "abc".index("z") + + +def st_remove(b): + b.xs.remove(9) + + +def st_pop(b): + return b.e.pop() + + +def st_pop_key(b): + return b.d.pop("zz") + + +def st_fresh_list(): + return [].pop() + + +def st_fresh_dict(): + return {}.pop("k") + + +def st_nested(b): + return b.s.upper().index("z") + + +class BuiltinMethodErrors(unittest.TestCase): + def check(self, fn, args, kind, eargs, text=None): + count, e = loop(fn, *args) + self.assertEqual(count, N) + self.assertIs(type(e), kind) + self.assertEqual(e.args, eargs) + if text is None: + text = eargs[0] + self.assertEqual(str(e), text) + self.assertEqual(trace(e), [("loop", 5), (fn.__name__, 1)]) + self.assertIsNone(e.__context__) + self.assertIsNone(e.__cause__) + + def test_local_receivers(self): + self.check(m_index, ("abc", "z"), ValueError, ("substring not found",)) + self.check(m_rindex, ("abc", "z"), ValueError, ("substring not found",)) + self.check(m_list_remove, ([1, 2, 3], 9), ValueError, ("list.remove(x): x not in list",)) + self.check(m_list_index, ([1, 2, 3], 9), ValueError, ("list.index(x): x not in list",)) + self.check(m_pop, ([],), IndexError, ("pop from empty list",)) + self.check(m_pop_key, ({"a": 1}, "zz"), KeyError, ("zz",), "'zz'") + self.check(m_set_remove, ({1, 2}, 9), KeyError, (9,), "9") + self.check(m_pop, (set(),), KeyError, ("pop from an empty set",), "'pop from an empty set'") + self.check(m_split, ("a,b", ""), ValueError, ("empty separator",)) + self.check( + m_join, (",", [1, 2]), TypeError, ("sequence item 0: expected str instance, int found",) + ) + self.check( + m_format, + ("{} {}", 1), + IndexError, + ("Replacement index 1 out of range for positional args tuple",), + ) + self.check( + m_encode, + ("caf\xe9",), + UnicodeEncodeError, + ("ascii", "caf\xe9", 3, 4, "ordinal not in range(128)"), + "'ascii' codec can't encode character '\\xe9' in position 3: ordinal not in range(128)", + ) + + def test_argument_errors(self): + for fn, name in ((m_index, "index"), (m_rindex, "rindex"), (m_find, "find"), (m_rfind, "rfind"), (m_count, "count")): + with self.subTest(name): + self.check(fn, ("abc", 5), TypeError, (name + "() argument 1 must be str, not int",)) + self.check(fn, ("abc", None), TypeError, (name + "() argument 1 must be str, not None",)) + self.check(m_strip, ("abc", 5), TypeError, ("strip arg must be None or str",)) + self.check(m_lstrip, ("abc", 5), TypeError, ("lstrip arg must be None or str",)) + self.check(m_rstrip, ("abc", 5), TypeError, ("rstrip arg must be None or str",)) + self.check( + m_startswith, + ("abc", 5), + TypeError, + ("startswith first arg must be str or a tuple of str, not int",), + ) + self.check( + m_replace, ("abc", "a", 5), TypeError, ("replace() argument 2 must be str, not int",) + ) + self.check( + m_get, + ({}, []), + TypeError, + ("cannot use 'list' as a dict key (unhashable type: 'list')",), + ) + + def test_stack_receivers(self): + b = Box() + self.check(st_index, (b,), ValueError, ("substring not found",)) + self.check(st_const, (), ValueError, ("substring not found",)) + self.check(st_remove, (b,), ValueError, ("list.remove(x): x not in list",)) + self.check(st_pop, (b,), IndexError, ("pop from empty list",)) + self.check(st_pop_key, (b,), KeyError, ("zz",), "'zz'") + self.check(st_fresh_list, (), IndexError, ("pop from empty list",)) + self.check(st_fresh_dict, (), KeyError, ("k",), "'k'") + self.check(st_nested, (b,), ValueError, ("substring not found",)) + self.assertEqual((b.s, b.xs, b.d, b.e), ("abc", [1, 2, 3], {"a": 1}, [])) + + def test_handler_in_the_loop(self): + def run(s, x): + n = 0 + for i in range(N): + try: + s.index(x) + except ValueError: + n += 1 + return n + + self.assertEqual(run("abc", "z"), N) + self.assertEqual(run("abc", "b"), 0) + + def test_site_that_mostly_succeeds(self): + out = [] + s = "hello world" + for i in range(N): + try: + out.append(s.index("w" if i % 7 else "?")) + except ValueError as e: + out.append(str(e)) + self.assertEqual(out.count("substring not found"), len(range(0, N, 7))) + self.assertEqual(out.count(6), N - len(range(0, N, 7))) + + def test_temporaries_released_before_the_handler(self): + log = [] + + class Temp: + def __init__(self, i): + self.i = i + + def __del__(self): + log.append(self.i) + + late = None + for i in range(N): + try: + [Temp(i)].index(5) + except ValueError: + if len(log) != i + 1 and late is None: + late = i + self.assertIsNone(late) + self.assertEqual(log, list(range(N))) + + def test_caller_handlers_and_finally(self): + def no_handler(s): + return s.index("q") + 1 + + def with_finally(s, out): + try: + return s.index("q") + finally: + out.append(1) + + n = 0 + out = [] + for i in range(N): + try: + no_handler("abc") + except ValueError: + n += 1 + try: + with_finally("abc", out) + except ValueError: + n += 1 + self.assertEqual((n, len(out)), (2 * N, N)) + + def test_context_of_an_error_in_a_handler(self): + last = None + for i in range(N): + try: + try: + "abc".index("z") + except ValueError: + [].pop() + except IndexError as e: + last = e + self.assertIs(type(last.__context__), ValueError) + self.assertEqual(last.__context__.args, ("substring not found",)) + self.assertEqual(last.args, ("pop from empty list",)) + + +def floordiv(a, b): + return a // b + + +def truediv(a, b): + return a / b + + +def mod(a, b): + return a % b + + +def lshift(a, b): + return a << b + + +def rshift(a, b): + return a >> b + + +def power(a, b): + return a**b + + +def ifloordiv(a, b): + a //= b + return a + + +def itruediv(a, b): + a /= b + return a + + +def imod(a, b): + a %= b + return a + + +def dm(a, b): + return divmod(a, b) + + +BIG = int("1" + "0" * 30) + + +class NumberOperatorErrors(unittest.TestCase): + def check(self, fn, a, b, kind, message): + count, e = loop(fn, a, b) + self.assertEqual(count, N, (fn.__name__, a, b)) + self.assertIs(type(e), kind, (fn.__name__, a, b)) + self.assertEqual(e.args, (message,), (fn.__name__, a, b)) + self.assertEqual(trace(e), [("loop", 5), (fn.__name__, 1)]) + self.assertIsNone(e.__context__) + + def test_zero_divisors(self): + for fn in (floordiv, truediv, mod, ifloordiv, itruediv, imod, dm): + for a, b in ((1, 0), (1.5, 0), (1, 0.0), (2.5, 0.0), (True, False), (0, 0), (BIG, 0), (1, False)): + self.check(fn, a, b, ZeroDivisionError, "division by zero") + self.assertEqual(loop(fn, 7, 2)[0], 0) + + def test_operand_types(self): + for fn, sym in ( + (floordiv, "//"), + (truediv, "/"), + (ifloordiv, "//="), + (itruediv, "/="), + (dm, "divmod()"), + ): + self.check( + fn, None, 0, TypeError, "unsupported operand type(s) for %s: 'NoneType' and 'int'" % sym + ) + self.check(fn, "a", 0, TypeError, "unsupported operand type(s) for %s: 'str' and 'int'" % sym) + self.check(mod, None, 0, TypeError, "unsupported operand type(s) for %: 'NoneType' and 'int'") + self.check(mod, "a", 0, TypeError, "not all arguments converted during string formatting") + + def test_shift_counts(self): + for a, b in ((1, -1), (True, -3), (0, -1), (1 << 70, -1)): + self.check(lshift, a, b, ValueError, "negative shift count") + self.check(rshift, a, b, ValueError, "negative shift count") + self.assertEqual(loop(lshift, 1, 3)[0], 0) + self.assertEqual(lshift(1, 3), 8) + self.check(lshift, 1.0, -1, TypeError, "unsupported operand type(s) for <<: 'float' and 'int'") + self.check(rshift, 1.0, -1, TypeError, "unsupported operand type(s) for >>: 'float' and 'int'") + + def test_zero_to_a_negative_power(self): + for a, b in ((0, -1), (False, -2), (0.0, -1), (0, -1.5)): + self.check(power, a, b, ZeroDivisionError, "zero to a negative power") + self.assertEqual(loop(power, 0, 0)[0], 0) + self.assertEqual(power(2, -1), 0.5) + + def test_handler_in_the_loop(self): + n = 0 + t = 0 + msg = None + for i in range(N): + try: + t += 1 // (i % 3) + except ZeroDivisionError as e: + n += 1 + msg = str(e) + self.assertEqual((n, t, msg), (N // 3, N // 3, "division by zero")) + + def test_raised_in_a_callee(self): + def callee(a, b): + return a // b + + n = 0 + t = 0 + for i in range(N): + try: + t += callee(i, i % 4) + except ZeroDivisionError: + n += 1 + self.assertEqual(n, N // 4) + self.assertEqual(t, sum(i // (i % 4) for i in range(N) if i % 4)) + + def test_finally_on_the_way(self): + out = [] + for i in range(50): + try: + try: + 1 % (i - i) + finally: + out.append(i) + except ZeroDivisionError as e: + out.append(str(e)) + self.assertEqual(len(out), 100) + self.assertEqual(out[-2:], [49, "division by zero"]) + + def test_values_below_the_operands(self): + log = [] + + class Temp: + def __init__(self, i): + self.i = i + + def __del__(self): + log.append(self.i) + + def __add__(self, other): + return other + + n = 0 + late = None + for i in range(N): + try: + x = [i, i + 1][0] + (i + 1) // (i - i) + except ZeroDivisionError: + n += 1 + try: + x = Temp(i) + (i + 1) % (i - i) + except ZeroDivisionError: + if len(log) != i + 1 and late is None: + late = i + self.assertEqual(n, N) + self.assertIsNone(late) + self.assertEqual(len(log), N) + + +def length(x): + return len(x) + + +def gen(): + yield 1 + + +class NoLen: + pass + + +class MetaLen(type): + def __len__(cls): + return 7 + + +class WithMeta(metaclass=MetaLen): + pass + + +class BadLen: + def __len__(self): + return -1 + + +class LenErrors(unittest.TestCase): + def test_objects_without_a_length(self): + for name, v in ( + ("int", 5), + ("int", BIG), + ("float", 2.5), + ("bool", True), + ("NoneType", None), + ("function", length), + ("builtin_function_or_method", len), + ("generator", gen()), + ("NoLen", NoLen()), + ("type", NoLen), + ("module", sys), + ("complex", 1j), + ("slice", slice(1)), + ): + with self.subTest(name): + count, e = loop(length, v) + self.assertEqual(count, N) + self.assertIs(type(e), TypeError) + self.assertEqual(e.args, ("object of type '%s' has no len()" % name,)) + self.assertEqual(trace(e), [("loop", 5), ("length", 1)]) + + def test_lengths_that_answer(self): + self.assertEqual(loop(length, [1, 2])[0], 0) + self.assertEqual(loop(length, WithMeta)[0], 0) + self.assertEqual((length([1, 2]), length(WithMeta)), (2, 7)) + count, e = loop(length, BadLen()) + self.assertEqual(count, N) + self.assertIs(type(e), ValueError) + self.assertEqual(e.args, ("__len__() should return >= 0",)) + + +class NextAtTheEnd(unittest.TestCase): + def test_plain_iterators(self): + def makers(): + yield lambda: iter([]) + yield lambda: iter(()) + yield lambda: iter(range(0)) + yield lambda: iter("") + yield lambda: iter(b"") + yield lambda: iter({}) + yield lambda: iter(set()) + + for make in makers(): + it = make() + n = 0 + last = None + for i in range(N): + try: + next(it) + except StopIteration as e: + n += 1 + last = e + self.assertEqual(n, N) + self.assertEqual(last.args, ()) + self.assertIsNone(last.value) + self.assertEqual(str(last), "") + self.assertEqual([name for name, _ in trace(last)], ["test_plain_iterators"]) + + def test_default_and_items_first(self): + def run(it): + out = [] + for i in range(N): + try: + out.append(next(it)) + except StopIteration: + out.append("end") + return out + + out = run(iter([1, 2, 3])) + self.assertEqual(out[:5], [1, 2, 3, "end", "end"]) + self.assertEqual(out.count("end"), N - 3) + out = run(iter(range(2))) + self.assertEqual(out[:4], [0, 1, "end", "end"]) + it = iter("ab") + got = [next(it, None) for i in range(N)] + self.assertEqual(got[:4], ["a", "b", None, None]) + self.assertEqual(got.count(None), N - 2) + + def test_list_grown_after_its_iterator_ended(self): + # An exhausted list iterator stays exhausted. + xs = [1] + it = iter(xs) + seen = [] + for i in range(N): + try: + seen.append(next(it)) + except StopIteration: + if i == 10: + xs.append(2) + self.assertEqual(seen, [1]) + + def test_end_in_a_callee(self): + def take(it): + return next(it) + + it = iter(()) + count, e = loop(take, it) + self.assertEqual(count, N) + self.assertIs(type(e), StopIteration) + self.assertEqual(trace(e), [("loop", 5), ("take", 1)]) + + +class FailingAssert(unittest.TestCase): + def test_message_and_bare(self): + def with_message(x): + assert x, "bad value" + + def with_object(x): + assert x, (1, [2]) + + def bare(x): + assert x + + count, e = loop(with_message, 0) + self.assertEqual(count, N) + self.assertIs(type(e), AssertionError) + self.assertEqual(e.args, ("bad value",)) + self.assertEqual(trace(e), [("loop", 5), ("with_message", 1)]) + count, e = loop(with_object, 0) + self.assertEqual((count, e.args), (N, ((1, [2]),))) + count, e = loop(bare, 0) + self.assertEqual((count, e.args, str(e)), (N, (), "")) + self.assertEqual(loop(with_message, 1)[0], 0) + + def test_handler_in_the_loop(self): + n = 0 + texts = set() + for i in range(N): + try: + assert i % 2, "even %d" % (i % 4) + except AssertionError as e: + n += 1 + texts.add(str(e)) + self.assertEqual(n, N // 2) + self.assertEqual(sorted(texts), ["even 0", "even 2"]) + + def test_assertion_error_rebound(self): + # The name is read from the builtins at the raise, never the + # module's own. + def check(x): + assert x, "m" + + for _ in range(N): + try: + check(0) + except AssertionError: + pass + g = check.__globals__ + g["AssertionError"] = ValueError + try: + with self.assertRaises(sys.modules["builtins"].AssertionError): + check(0) + finally: + del g["AssertionError"] + + +class MyErr(Exception): + pass + + +class MyStr(Exception): + def __str__(self): + return "custom:" + str(self.args) + + +class MyFmt(Exception): + def __format__(self, spec): + return "fmt" + + +class MyKey(KeyError): + pass + + +class MyRepr(Exception): + def __repr__(self): + return "R" + + +class Arg: + def __str__(self): + return "arg-str" + + def __repr__(self): + return "arg-repr" + + +class Init(Exception): + def __init__(self, a, b): + super().__init__(a) + self.b = b + + +def texts(e): + out = None + for i in range(N): + out = (str(e), "%s" % (e,), f"{e}", format(e), f"{e!s}", f"{e!r}") + return out + + +class ExceptionText(unittest.TestCase): + def same(self, e, text, rep): + self.assertEqual(texts(e), (text, text, text, text, text, rep), rep) + + def test_base_str(self): + self.same(ValueError("x"), "x", "ValueError('x')") + self.same(ValueError(), "", "ValueError()") + self.same(ValueError(1, 2), "(1, 2)", "ValueError(1, 2)") + self.same(ValueError(5), "5", "ValueError(5)") + self.same(ValueError(None), "None", "ValueError(None)") + self.same(ValueError(2.5), "2.5", "ValueError(2.5)") + self.same(ValueError("x", "y"), "('x', 'y')", "ValueError('x', 'y')") + self.same(ValueError(b"b"), "b'b'", "ValueError(b'b')") + self.same(ValueError(Arg()), "arg-str", "ValueError(arg-repr)") + self.same(ValueError((1, 2)), "(1, 2)", "ValueError((1, 2))") + self.same(ValueError([1]), "[1]", "ValueError([1])") + self.same(MyErr("m"), "m", "MyErr('m')") + self.same(MyErr(), "", "MyErr()") + self.same(MyRepr("r"), "r", "R") + self.same(Init("a", "b"), "a", "Init('a')") + self.same(BaseException("b"), "b", "BaseException('b')") + self.same(StopIteration(3), "3", "StopIteration(3)") + self.same(SystemExit(2), "2", "SystemExit(2)") + self.same(KeyboardInterrupt(), "", "KeyboardInterrupt()") + + def test_key_errors(self): + self.same(KeyError("k"), "'k'", "KeyError('k')") + self.same(KeyError(), "", "KeyError()") + self.same(KeyError(1, 2), "(1, 2)", "KeyError(1, 2)") + self.same(KeyError(5), "5", "KeyError(5)") + self.same(KeyError(Arg()), "arg-repr", "KeyError(arg-repr)") + self.same(MyKey("k"), "'k'", "MyKey('k')") + self.same(MyKey(), "", "MyKey()") + self.same(LookupError("l"), "l", "LookupError('l')") + self.same(IndexError("i"), "i", "IndexError('i')") + + def test_own_str_and_format(self): + self.assertEqual( + texts(MyStr("s")), + ("custom:('s',)", "custom:('s',)", "custom:('s',)", "custom:('s',)", "custom:('s',)", "MyStr('s')"), + ) + self.assertEqual(texts(MyFmt("f")), ("f", "f", "fmt", "fmt", "f", "MyFmt('f')")) + + def test_kinds_with_their_own_text(self): + self.same(OSError(5, "failed"), "[Errno 5] failed", "OSError(5, 'failed')") + self.same(OSError("plain"), "plain", "OSError('plain')") + self.same( + FileNotFoundError(2, "nf", "path"), + "[Errno 2] nf: 'path'", + "FileNotFoundError(2, 'nf')", + ) + self.same( + UnicodeDecodeError("utf-8", b"\xff", 0, 1, "bad"), + "'utf-8' codec can't decode byte 0xff in position 0: bad", + "UnicodeDecodeError('utf-8', b'\\xff', 0, 1, 'bad')", + ) + self.same( + SyntaxError("msg", ("f.py", 1, 2, "text")), + "msg (f.py, line 1)", + "SyntaxError('msg', ('f.py', 1, 2, 'text'))", + ) + self.same( + ExceptionGroup("g", [ValueError(1)]), + "g (1 sub-exception)", + "ExceptionGroup('g', [ValueError(1)])", + ) + self.same(AttributeError("a", name="n", obj=1), "a", "AttributeError('a')") + self.same(ImportError("i", name="mod", path="p"), "i", "ImportError('i')") + + def test_class_gaining_and_losing_its_dunders(self): + class Shift(Exception): + pass + + def text(e): + return str(e), f"{e}" + + e = Shift("s") + for _ in range(N): + self.assertEqual(text(e), ("s", "s")) + Shift.__str__ = lambda self: "one" + for _ in range(N): + self.assertEqual(text(e), ("one", "one")) + Shift.__str__ = lambda self: "two" + self.assertEqual(text(e), ("two", "two")) + del Shift.__str__ + self.assertEqual(text(e), ("s", "s")) + Shift.__format__ = lambda self, spec: "F" + self.assertEqual(text(e), ("s", "F")) + del Shift.__format__ + self.assertEqual(text(e), ("s", "s")) + e.args = ("t", "u") + self.assertEqual(text(e), ("('t', 'u')", "('t', 'u')")) + e.args = () + self.assertEqual(text(e), ("", "")) + + def test_base_class_gaining_str(self): + class Base(Exception): + pass + + class Leaf(Base): + pass + + class Key(KeyError): + pass + + e = Leaf("x") + k = Key("x") + for _ in range(N): + self.assertEqual((str(e), str(k)), ("x", "'x'")) + Base.__str__ = lambda self: "base" + self.assertEqual(str(e), "base") + del Base.__str__ + self.assertEqual(str(e), "x") + Key.__str__ = lambda self: "key" + self.assertEqual(str(k), "key") + del Key.__str__ + self.assertEqual(str(k), "'x'") + + def test_text_in_a_handler(self): + out = set() + for i in range(N): + try: + if i % 3 == 0: + raise ValueError("bad %d" % (i % 5)) + elif i % 3 == 1: + {}["k%d" % (i % 4)] + else: + int("x%d" % (i % 2)) + except (ValueError, KeyError) as e: + out.add(str(e)) + self.assertEqual( + sorted(out), + [ + "'k0'", + "'k1'", + "'k2'", + "'k3'", + "bad 0", + "bad 1", + "bad 2", + "bad 3", + "bad 4", + "invalid literal for int() with base 10: 'x0'", + "invalid literal for int() with base 10: 'x1'", + ], + ) + + def test_args_changed_between_reads(self): + e = ValueError("a") + seen = [] + for i in range(50): + seen.append(str(e)) + e.args = ("a%d" % i,) if i % 2 else () + self.assertEqual(seen[:4], ["a", "", "a1", ""]) + self.assertEqual(seen[-1], "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_callback_frame_order.py b/tests/regrtest/test_compiled_callback_frame_order.py new file mode 100644 index 000000000..19ae2fb45 --- /dev/null +++ b/tests/regrtest/test_compiled_callback_frame_order.py @@ -0,0 +1,171 @@ +"""The frame stack seen from a compiled callback of a native loop. + +A function with a loop is compiled after a few calls and then entered +directly from `map`, `sorted`, `max` and the like, with no frame of its +own until something looks. Its caller may still be waiting to be put on +the frame stack at that point. These tests pin what a look finds once +the callback is compiled: `sys._getframe()` is the callback's own frame, +its `f_back` is the caller, the locals are the callback's, and the +caller's frame is still the caller's afterwards. +""" + +import functools +import sys +import traceback +import unittest + +ROUNDS = 300 + + +def own_frame(v, off=1): + t = 0 + for k in range(3): + t += v + off + f = sys._getframe() + return f.f_code.co_name, sorted(f.f_locals), f.f_back.f_code.co_name + + +def own_frame_kwonly(v, *, off=1): + t = 0 + for k in range(3): + t += v + off + f = sys._getframe() + return f.f_code.co_name, f.f_locals["off"], f.f_back.f_code.co_name + + +def stack_names(v): + t = 0 + for k in range(3): + t += v + return [s.name for s in traceback.extract_stack(limit=3)] + + +def back_locals(v): + t = 0 + for k in range(3): + t += v + return sys._getframe(1).f_locals.get("marker"), t + + +def raising(v, *, div=0): + t = 0 + for k in range(3): + t += v + return t // div + + +class FrameOrder(unittest.TestCase): + def test_own_frame_from_map(self): + def caller(): + return list(map(own_frame, [1, 2])) + + want = ("own_frame", ["f", "k", "off", "t", "v"], "caller") + for _ in range(ROUNDS): + self.assertEqual(caller(), [want, want]) + + def test_own_frame_with_a_keyword_only_parameter(self): + def caller(): + return list(map(own_frame_kwonly, [1, 2])) + + def caller_partial(): + return sorted([1, 2], key=functools.partial(own_frame_kwonly, off=5)) + + for _ in range(ROUNDS): + self.assertEqual(caller(), [("own_frame_kwonly", 1, "caller")] * 2) + self.assertEqual(caller_partial(), [1, 2]) + + def test_other_native_loops(self): + def by_sorted(): + return sorted([2, 1], key=lambda v: own_frame(v)[2]) + + def by_max(): + return max([1, 2], key=lambda v: len(own_frame(v)[1])) + + def by_filter(): + return list(filter(lambda v: own_frame(v)[0] == "own_frame", [1, 2])) + + def by_key(): + seen = [] + + def key(v): + t = 0 + for k in range(3): + t += v + seen.append(sys._getframe().f_back.f_code.co_name) + return t + + return sorted([3, 1, 2], key=key), seen + + for _ in range(ROUNDS): + self.assertEqual(by_sorted(), [2, 1]) + self.assertEqual(by_max(), 1) + self.assertEqual(by_filter(), [1, 2]) + self.assertEqual(by_key(), ([1, 2, 3], ["by_key"] * 3)) + + def test_the_stack_walk_is_in_order(self): + def caller(): + return list(map(stack_names, [1, 2])) + + want = ["test_the_stack_walk_is_in_order", "caller", "stack_names"] + for _ in range(ROUNDS): + self.assertEqual(caller(), [want, want]) + + def test_the_callers_locals_are_the_callers(self): + def caller(): + marker = "mine" + out = list(map(back_locals, [1, 2])) + return out, sys._getframe().f_code.co_name, marker + + for _ in range(ROUNDS): + self.assertEqual( + caller(), ([("mine", 3), ("mine", 6)], "caller", "mine") + ) + + def test_the_caller_is_itself_afterwards(self): + def caller(): + before = sys._getframe().f_code.co_name + list(map(own_frame, [1])) + after = sys._getframe() + return before, after.f_code.co_name, after.f_back.f_code.co_name + + for _ in range(ROUNDS): + self.assertEqual( + caller(), ("caller", "caller", "test_the_caller_is_itself_afterwards") + ) + + def test_tracebacks_name_every_frame(self): + def caller(): + return list(map(raising, [1, 2])) + + for _ in range(ROUNDS): + try: + caller() + except ZeroDivisionError as e: + names = [s.name for s in traceback.extract_tb(e.__traceback__)] + self.assertEqual( + names, ["test_tracebacks_name_every_frame", "caller", "raising"] + ) + + def test_nested_native_loops(self): + def inner(v): + t = 0 + for k in range(3): + t += v + f = sys._getframe() + return f.f_code.co_name, f.f_back.f_code.co_name, f.f_back.f_back.f_code.co_name + + def middle(v): + t = 0 + for k in range(2): + t += v + return list(map(inner, [v]))[0] + + def outer(): + return list(map(middle, [1, 2])) + + for _ in range(ROUNDS): + self.assertEqual(outer(), [("inner", "middle", "outer")] * 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_ctor_container_stores.py b/tests/regrtest/test_compiled_ctor_container_stores.py new file mode 100644 index 000000000..ef1b32651 --- /dev/null +++ b/tests/regrtest/test_compiled_ctor_container_stores.py @@ -0,0 +1,117 @@ +"""Containers stored into fresh instances by compiled constructors. + +A framed `__init__` entered from compiled code finds room for its class's +names and appends its stores in line; a store of a container into an +instance the collector doesn't track yet tracks it first. Cycles made +through such stores must be collected, `gc.is_tracked` must agree with +CPython, and attribute order and values must be the usual ones. +""" + +import gc +import unittest +import weakref + + +class Node: + def __init__(self, value, parent=None): + self.value = value + self.children = [] + self.parent = parent + if parent is not None: + parent.children.append(self) + + +class Holder: + def __init__(self, x): + self.x = x + self.items = [x] + self.meta = {"x": x} + + +class Pair: + def __init__(self, a, b): + self.a = a + self.b = b + + +class Named: + __slots__ = ("name", "big", "ref", "__weakref__") + + def __init__(self, i): + self.name = "n%d" % i + self.big = (1 << 80) + i + + +class NamedDict: + def __init__(self, i): + self.name = "n%d" % i + self.big = (1 << 80) + i + self.z = complex(i, 1) + self.ref = None + + +class CtorContainerStoreTests(unittest.TestCase): + def test_values_and_order(self): + for i in range(5000): + h = Holder(i) + self.assertEqual(list(vars(h)), ["x", "items", "meta"]) + self.assertEqual((h.x, h.items, h.meta), (i, [i], {"x": i})) + + def test_tracked_like_cpython(self): + for i in range(5000): + h = Holder(i) + self.assertTrue(gc.is_tracked(h)) + for i in range(5000): + p = Pair(i, [i]) + self.assertTrue(gc.is_tracked(p)) + + def test_cycles_collected(self): + refs = [] + for i in range(5000): + root = Node(i) + Node(i + 1, root) + refs.append(weakref.ref(root)) + del root + gc.collect() + self.assertEqual(sum(r() is not None for r in refs), 0) + + def test_self_cycle_via_container(self): + refs = [] + for i in range(5000): + h = Holder(i) + h.items.append(h) + refs.append(weakref.ref(h)) + del h + gc.collect() + self.assertEqual(sum(r() is not None for r in refs), 0) + + def test_atomic_stores_then_cycles(self): + # Strings, big ints and complex numbers leave a fresh instance + # untracked; a later container that closes a cycle still gets it + # collected. + for cls in (Named, NamedDict): + refs = [] + for i in range(5000): + o = cls(i) + self.assertEqual((o.name, o.big), ("n%d" % i, (1 << 80) + i)) + if i % 2: + o.ref = [o] + refs.append(weakref.ref(o)) + del o + gc.collect() + self.assertEqual(sum(r() is not None for r in refs), 0) + self.assertTrue(gc.is_tracked(cls(1))) + + def test_shared_containers(self): + shared = [] + made = [] + for i in range(5000): + p = Pair(shared, i) + made.append(p) + self.assertTrue(all(p.a is shared for p in made)) + shared.append(1) + self.assertEqual(made[-1].a, [1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_exception_init_entry.py b/tests/regrtest/test_compiled_exception_init_entry.py new file mode 100644 index 000000000..5777fa40a --- /dev/null +++ b/tests/regrtest/test_compiled_exception_init_entry.py @@ -0,0 +1,94 @@ +"""Exception classes with a Python `__init__`, built from compiled code. + +Warm callers allocate the exception with its `args` seeded from the call, +as `BaseException.__new__` seeds them, and enter `__init__` directly; a +`super().__init__(...)` that reaches `BaseException.__init__` stores the +new `args` in place. `args`, `str()`, a `StopIteration`'s `value`, +attributes, tracebacks and errors must all keep CPython's behavior. +""" + +import unittest + + +class AppError(Exception): + def __init__(self, msg, code): + super().__init__(msg) + self.code = code + + +class NoSuper(Exception): + def __init__(self, a, b=2): + self.total = a + b + + +class Rewrites(ValueError): + def __init__(self, *parts): + super().__init__("-".join(parts), len(parts)) + + +class Stop(StopIteration): + def __init__(self, v): + super().__init__(v * 2) + + +class Fails(Exception): + def __init__(self, v): + if v < 0: + raise TypeError("negative") + super().__init__(v) + + +class ExceptionInitEntryTests(unittest.TestCase): + def test_super_init(self): + for i in range(3000): + e = AppError("boom", i) + self.assertEqual((e.args, e.code, str(e)), (("boom",), i, "boom")) + self.assertIsNone(e.__traceback__) + + def test_args_seeded_without_super(self): + for i in range(3000): + e = NoSuper(i) + self.assertEqual((e.args, e.total), ((i,), i + 2)) + e = NoSuper(i, 5) + self.assertEqual((e.args, e.total), ((i, 5), i + 5)) + + def test_rewritten_args(self): + for i in range(3000): + e = Rewrites("a", str(i)) + self.assertEqual(e.args, ("a-%d" % i, 2)) + self.assertIsInstance(e, ValueError) + + def test_stop_iteration_value(self): + for i in range(3000): + e = Stop(i) + self.assertEqual((e.value, e.args), (2 * i, (2 * i,))) + + def test_raise_and_catch(self): + caught = 0 + for i in range(3000): + try: + raise AppError("x", i) + except AppError as e: + caught += e.code == i + self.assertEqual(e.__traceback__.tb_frame.f_code.co_name, "test_raise_and_catch") + self.assertEqual(caught, 3000) + + def test_errors(self): + for i in range(3000): + self.assertEqual(Fails(i).args, (i,)) + with self.assertRaisesRegex(TypeError, "negative"): + Fails(-1) + with self.assertRaises(TypeError): + AppError("only one") + with self.assertRaises(TypeError): + NoSuper() + + def test_heap_arguments(self): + for i in range(3000): + payload = [i] + e = AppError(payload, None) + self.assertIs(e.args[0], payload) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_field_replace_refs.py b/tests/regrtest/test_compiled_field_replace_refs.py new file mode 100644 index 000000000..a2b9ae843 --- /dev/null +++ b/tests/regrtest/test_compiled_field_replace_refs.py @@ -0,0 +1,104 @@ +"""Compiled attribute stores that replace an object. + +A compiled `obj.attr = value` that replaces another object releases the +old one in place when another owner keeps it, and through the general +path when it was the last reference (its finalizer runs at once, in +every tier). A site that first added the attribute replaces it in place +on later passes. Reference counts, finalizers, `__dict__` order and the +stored values stay right. +""" + +import sys +import unittest + +N = 3000 + + +class Node: + pass + + +class Dying: + deaths = [] + + def __init__(self, n): + self.n = n + + def __del__(self): + Dying.deaths.append(self.n) + + +class FieldReplaceTests(unittest.TestCase): + def test_shared_old_values(self): + nodes = [Node() for _ in range(50)] + for x in nodes: + x.ref = x + keep = [Node() for _ in range(50)] + base = [sys.getrefcount(k) for k in keep] + for i in range(N // 10): + for x, k in zip(nodes, keep): + x.ref = k + for x in nodes: + x.ref = x + del x, k + self.assertEqual([sys.getrefcount(k) for k in keep], base) + self.assertTrue(all(x.ref is x for x in nodes)) + for x, k in zip(nodes, keep): + x.ref = k + del x, k + self.assertEqual([sys.getrefcount(k) for k in keep], [b + 1 for b in base]) + + def test_last_reference_finalizes(self): + Dying.deaths.clear() + holder = Node() + holder.d = Dying(-1) + for i in range(N): + holder.d = Dying(i) + self.assertEqual(len(Dying.deaths), i + 1) + self.assertEqual(Dying.deaths[:3], [-1, 0, 1]) + self.assertEqual(holder.d.n, N - 1) + + def test_mixed_values(self): + n = Node() + n.v = 0 + objs = ["s", 1.5, (1, 2), [3], None, 7, n] + for i in range(N): + n.v = objs[i % len(objs)] + self.assertIs(n.v, objs[(N - 1) % len(objs)]) + self.assertEqual(sys.getrefcount(objs[3]), sys.getrefcount([3]) + 2) + + + def test_add_then_replace(self): + nodes = [Node() for _ in range(50)] + + def mark(v): + for x in nodes: + x.seen = v + x.prev = x + + for i in range(N // 10): + mark(i) + self.assertTrue(all(x.seen == N // 10 - 1 and x.prev is x for x in nodes)) + self.assertEqual(sys.getrefcount(nodes[0]), sys.getrefcount(nodes[1])) + del nodes[3].seen + mark(-1) + self.assertEqual(list(nodes[3].__dict__), ["prev", "seen"]) + self.assertEqual(list(nodes[4].__dict__), ["seen", "prev"]) + + def test_replace_finalizes_in_loops(self): + Dying.deaths.clear() + holders = [Node() for _ in range(20)] + + def fill(k): + for h in holders: + h.d = Dying(k) + + fill(0) + for k in range(1, N // 10): + fill(k) + self.assertEqual(len(Dying.deaths), 20 * k) + self.assertEqual(sorted(set(Dying.deaths))[:2], [0, 1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_framed_init_entry.py b/tests/regrtest/test_compiled_framed_init_entry.py new file mode 100644 index 000000000..894c074bf --- /dev/null +++ b/tests/regrtest/test_compiled_framed_init_entry.py @@ -0,0 +1,185 @@ +"""Constructors whose `__init__` runs in a frame, entered from compiled code. + +Once a class's calls settle on an `__init__` that is neither store-only nor +a leaf, compiled callers allocate the instance and enter the `__init__` +directly, as they call a function. The instance, `__init__`'s errors and +return value, defaults, closures, redefinitions and subclasses must all +keep CPython's behavior while that path is warm. +""" + +import gc +import sys +import unittest + + +def helper(x): + return x + + +class Point: + __slots__ = ("x", "y", "n") + + def __init__(self, x, y=0): + self.x = x + self.y = helper(y) + self.n = len(str(x)) + + +class Plain: + def __init__(self, a, b): + self.a = a + self.b = helper(b) + self.total = a + b + + +class Sub(Plain): + pass + + +class Raises: + def __init__(self, v): + if v < 0: + raise ValueError(v) + self.v = helper(v) + + +class ReturnsValue: + def __init__(self, v): + self.v = helper(v) + if v == 7: + return 1 + + +def make_closure_class(k): + class Closed: + def __init__(self, v): + self.v = helper(v) + k + + return Closed + + +class Escapes: + seen = [] + + def __init__(self, v): + self.v = helper(v) + Escapes.seen.append(self) + + +class Recurse: + def __init__(self, n): + self.child = Recurse(n - 1) if n else None + self.n = helper(n) + + +class FramedInitEntryTests(unittest.TestCase): + def test_instances_and_defaults(self): + for i in range(3000): + p = Point(i) + self.assertIs(type(p), Point) + self.assertEqual((p.x, p.y, p.n), (i, 0, len(str(i)))) + q = Point(i, i + 1) + self.assertEqual(q.y, i + 1) + r = Plain(i, 2) + self.assertEqual((r.a, r.b, r.total), (i, 2, i + 2)) + + def test_subclass(self): + for i in range(3000): + s = Sub(i, 1) + self.assertIs(type(s), Sub) + self.assertEqual(s.total, i + 1) + p = Plain(i, 1) + self.assertIs(type(p), Plain) + + def test_errors_in_init(self): + for i in range(3000): + self.assertEqual(Raises(i).v, i) + try: + Raises(-5) + except ValueError as e: + exc = e + else: + self.fail("no ValueError") + self.assertEqual(exc.args, (-5,)) + tb = exc.__traceback__ + names = [] + while tb is not None: + names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + self.assertEqual(names[-1], "__init__") + + def test_init_returning_a_value(self): + for i in range(3000): + if i != 7: + self.assertEqual(ReturnsValue(i).v, i) + with self.assertRaisesRegex(TypeError, "__init__"): + ReturnsValue(7) + + def test_wrong_argument_count(self): + for i in range(3000): + Plain(i, i) + with self.assertRaises(TypeError): + Plain(1) + with self.assertRaises(TypeError): + Plain(1, 2, 3) + + def test_closures(self): + for k in range(3): + cls = make_closure_class(k) + for i in range(2000): + self.assertEqual(cls(i).v, i + k) + + def test_redefined_init(self): + class Box: + def __init__(self, v): + self.v = helper(v) + + for i in range(3000): + self.assertEqual(Box(i).v, i) + + def other(self, v): + self.v = helper(v) * 2 + + Box.__init__ = other + for i in range(3000): + self.assertEqual(Box(i).v, 2 * i) + + def new(cls, v): + inst = object.__new__(cls) + inst.made = True + return inst + + Box.__new__ = new + b = Box(5) + self.assertTrue(b.made) + self.assertEqual(b.v, 10) + + def test_instances_escape_and_die(self): + Escapes.seen.clear() + for i in range(3000): + Escapes(i) + self.assertEqual([e.v for e in Escapes.seen], list(range(3000))) + Escapes.seen.clear() + gc.collect() + + def test_recursion(self): + for _ in range(300): + r = Recurse(10) + depth = 0 + while r is not None: + depth += 1 + r = r.child + self.assertEqual(depth, 11) + limit = sys.getrecursionlimit() + with self.assertRaises(RecursionError): + Recurse(limit + 100) + + def test_keyword_and_star_calls(self): + args = (1, 2) + for i in range(3000): + self.assertEqual(Plain(*args).total, 3) + self.assertEqual(Plain(a=i, b=1).total, i + 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_loop_stays_compiled.py b/tests/regrtest/test_compiled_loop_stays_compiled.py new file mode 100644 index 000000000..1888fd0eb --- /dev/null +++ b/tests/regrtest/test_compiled_loop_stays_compiled.py @@ -0,0 +1,160 @@ +"""Operations compiled loops now finish in place: set algebra whose result +is discarded or stored, iterating an io.StringIO (and a closed one's +ValueError), Counter.most_common(n), and copy.deepcopy of plain trees, +a method whose first call changes its class (a lazily set class +attribute), and string.Template.substitute, each giving CPython's +results and errors, with the general path still taking what the native +one declines (user objects, a subclass, a memo).""" + +import collections +import copy +import io +import unittest + + +class K: + def __init__(self, k): + self.k = k + + def __eq__(self, o): + return isinstance(o, K) and self.k == o.k + + def __hash__(self): + return hash(self.k) + + +class SubCounter(collections.Counter): + pass + + +def set_ops(n, a, b): + out = None + for i in range(n): + a | b + x = a | b + y = a & b + z = a - b + w = a ^ b + out = (x, y, z, w) + return out + + +def lines(n, text): + out = None + for i in range(n): + got = [] + for line in io.StringIO(text): + got.append(line) + out = got + return out + + +def ranks(n, c, k): + out = None + for i in range(n): + out = c.most_common(k) + return out + + +def deep(n, x): + out = None + for i in range(n): + out = copy.deepcopy(x) + return out + + +class Lazy: + ready = False + + def __init__(self, v): + self.v = v + + def get(self): + if not Lazy.ready: + Lazy.ready = True + return self.v + + +def lazy_calls(n): + total = 0 + o = Lazy(2) + for i in range(n): + total += o.get() + return total + + +class CompiledLoopTests(unittest.TestCase): + def test_method_after_class_change(self): + self.assertEqual(lazy_calls(500), 1000) + Lazy.get = lambda self: -1 + self.assertEqual(lazy_calls(300), -300) + + def test_template(self): + import string + + t = string.Template("$a and ${b}") + out = None + for i in range(400): + out = t.substitute(a=i, b="x") + self.assertEqual(out, "399 and x") + with self.assertRaises(KeyError): + for i in range(300): + t.substitute(a=1) + + def test_set_ops(self): + for n in (1, 400): + self.assertEqual(set_ops(n, {1, 2}, {2, 3}), ({1, 2, 3}, {2}, {1}, {1, 3})) + x, y, z, w = set_ops(n, frozenset({1, 2}), {2, 3}) + self.assertIs(type(x), frozenset) + self.assertEqual((x, y, z, w), ({1, 2, 3}, {2}, {1}, {1, 3})) + ks = set_ops(n, {K(1), K(2)}, {K(2)}) + self.assertEqual(len(ks[0]), 2) + self.assertEqual(ks[1], {K(2)}) + with self.assertRaises(TypeError): + set_ops(300, {1}, [1]) + + def test_stringio_lines(self): + for n in (1, 400): + self.assertEqual(lines(n, "a,1\nb,2\nc"), ["a,1\n", "b,2\n", "c"]) + self.assertEqual(lines(n, ""), []) + + def closed(n): + caught = 0 + for i in range(n): + f = io.StringIO("x\n") + f.close() + try: + for line in f: + pass + except ValueError: + caught += 1 + return caught + + self.assertEqual(closed(300), 300) + + def test_most_common(self): + c = collections.Counter("abracadabra") + for n in (1, 400): + self.assertEqual(ranks(n, c, 2), [("a", 5), ("b", 2)]) + self.assertEqual(ranks(n, c, 0), []) + self.assertEqual(ranks(n, SubCounter("aab"), 1), [("a", 2)]) + self.assertEqual(ranks(n, collections.Counter({"x": 1.5, "y": 2}), 1), [("y", 2)]) + + def test_deepcopy(self): + tree = {"a": [1, 2, (3, "x")], "b": {"c": None}} + for n in (1, 400): + got = deep(n, tree) + self.assertEqual(got, tree) + self.assertIsNot(got, tree) + self.assertIsNot(got["a"], tree["a"]) + k = K(1) + mixed = deep(n, [k, [k]]) + self.assertIs(mixed[0], mixed[1][0]) + self.assertIsNot(mixed[0], k) + shared = [1] + both = deep(300, [shared, shared]) + self.assertIs(both[0], both[1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_module_scope_names.py b/tests/regrtest/test_compiled_module_scope_names.py new file mode 100644 index 000000000..9a5ff5e6b --- /dev/null +++ b/tests/regrtest/test_compiled_module_scope_names.py @@ -0,0 +1,162 @@ +"""Module-scope loops in compiled code: `LOAD_NAME` and `STORE_NAME`. + +A module's body (or `exec(code, g)`) reads names from its globals, then +the builtins, and binds them in its globals. Compiled loops cache those +reads; rebinding, shadowing a builtin, deleting a name, a separate +namespace (`exec(code, g, l)`, a class body) and finalizers of displaced +values must all behave as CPython's interpreter does. +""" + +import unittest + +N = 20000 +H = N // 2 + + +def run(src, g=None, l=None): + g = {} if g is None else g + src = src.replace("NN", str(N)).replace("HH", str(H)) + code = compile(src, "", "exec") + if l is None: + exec(code, g) + else: + exec(code, g, l) + return g + + +class ModuleScopeNameTests(unittest.TestCase): + def test_reads_and_stores(self): + g = run( + "total = 0\n" + "items = [1, 2, 3]\n" + "for i in range(NN):\n" + " total += len(items) + i\n" + " last = i\n" + ) + self.assertEqual(g["total"], 3 * N + sum(range(N))) + self.assertEqual(g["last"], N - 1) + + def test_shadow_builtin_mid_loop(self): + g = run( + "out = []\n" + "for i in range(NN):\n" + " if i == HH:\n" + " len = lambda x: -1\n" + " out.append(len('ab'))\n" + "del len\n" + "after = len('abc')\n" + ) + self.assertEqual(g["out"][:H], [2] * H) + self.assertEqual(g["out"][H:], [-1] * (N - H)) + self.assertEqual(g["after"], 3) + + def test_rebinding_global_read(self): + g = run( + "k = 1\n" + "acc = 0\n" + "for i in range(NN):\n" + " acc += k\n" + " k = i % 3\n" + ) + expect = 1 + sum(i % 3 for i in range(N - 1)) + self.assertEqual(g["acc"], expect) + + def test_deleted_name_raises(self): + g = run( + "x = 5\n" + "seen = 0\n" + "for i in range(NN):\n" + " if i == HH:\n" + " del x\n" + " try:\n" + " seen += x\n" + " except NameError as e:\n" + " msg = str(e)\n" + " break\n" + ) + self.assertEqual(g["seen"], 5 * H) + self.assertEqual(g["msg"], "name 'x' is not defined") + + def test_custom_builtins(self): + g = {"__builtins__": {"len": lambda x: 7, "range": range}} + run( + "s = 0\n" + "for i in range(NN):\n" + " s += len(i)\n", + g, + ) + self.assertEqual(g["s"], 7 * N) + + def test_separate_locals(self): + g = {"base": 10} + l = {} + run( + "acc = 0\n" + "for i in range(NN):\n" + " acc += base\n" + "base = -1\n", + g, + l, + ) + self.assertEqual(l["acc"], 10 * N) + self.assertEqual(l["base"], -1) + self.assertEqual(g["base"], 10) + self.assertNotIn("acc", g) + + def test_class_body_loop(self): + g = run( + "class C:\n" + " total = 0\n" + " for i in range(NN):\n" + " total += i\n" + " names = [n for n in ('a', 'b')]\n" + ) + C = g["C"] + self.assertEqual(C.total, sum(range(N))) + self.assertEqual(C.i, N - 1) + self.assertEqual(C.names, ["a", "b"]) + self.assertNotIn("total", g) + + def test_finalizers_of_displaced_values(self): + log = [] + + class Noisy: + def __init__(self, n): + self.n = n + + def __del__(self): + log.append(self.n) + + run( + "for i in range(NN):\n" + " obj = Noisy(i)\n" + "del obj\n", + {"Noisy": Noisy}, + ) + self.assertEqual(log, list(range(N))) + + def test_functions_and_classes_in_loop(self): + g = run( + "made = []\n" + "for i in range(NN):\n" + " def f(x, i=i):\n" + " return x + i\n" + " made.append(f(1))\n" + "class K:\n" + " pass\n" + "objs = [K() for _ in range(10)]\n" + ) + self.assertEqual(g["made"], [1 + i for i in range(N)]) + self.assertEqual(len(g["objs"]), 10) + + def test_globals_and_vars_agree(self): + g = run( + "for i in range(NN):\n" + " globals()['mirror'] = i\n" + " seen = mirror\n" + ) + self.assertEqual((g["mirror"], g["seen"]), (N - 1, N - 1)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_plan_releases_code.py b/tests/regrtest/test_compiled_plan_releases_code.py new file mode 100644 index 000000000..7491dd2bb --- /dev/null +++ b/tests/regrtest/test_compiled_plan_releases_code.py @@ -0,0 +1,88 @@ +"""A callback's code object dies with its function, however hot it ran. + +A function that native code calls often enough (`max(xs, key=f)`, `map`, +`len(obj)`) has its frameless plan compiled. The compiled plan belongs to +the code object and must not hold a counted reference back to it, or the +two keep each other alive after the last function over that code is gone. +""" + +import gc +import unittest +import weakref + +CALLS = 30_000 + + +def make(source, name): + namespace = {} + exec(source, namespace) + return namespace[name] + + +class CodeIsCollected(unittest.TestCase): + def check(self, f, drive): + code = weakref.ref(f.__code__) + func = weakref.ref(f) + drive(f) + self.assertIsNotNone(code()) + del f + for _ in range(3): + gc.collect() + self.assertIsNone(func()) + self.assertIsNone(code()) + + def test_a_key_function(self): + xs = list(range(20)) + + def drive(f): + for _ in range(CALLS // 20): + self.assertEqual(max(xs, key=f), 12) + + self.check(make("def key(v):\n return (v * 3 + 1) % 19\n", "key"), drive) + + def test_a_mapped_function(self): + xs = list(range(20)) + + def drive(f): + for _ in range(CALLS // 20): + self.assertEqual(sum(map(f, xs)), 210) + + self.check(make("def step(v):\n return v + 1\n", "step"), drive) + + def test_a_method_reached_through_len(self): + source = ( + "class Box:\n" + " def __init__(self):\n" + " self.items = [1, 2, 3]\n" + " def __len__(self):\n" + " return len(self.items)\n" + ) + cls = make(source, "Box") + box = cls() + code = weakref.ref(cls.__len__.__code__) + for _ in range(CALLS): + self.assertEqual(len(box), 3) + del box, cls + for _ in range(3): + gc.collect() + self.assertIsNone(code()) + + def test_a_callback_that_calls_a_helper(self): + namespace = {} + exec( + "def helper(v):\n return v * 2\n" + "def key(v):\n return helper(v) % 7\n", + namespace, + ) + codes = [weakref.ref(namespace[n].__code__) for n in ("helper", "key")] + xs = list(range(20)) + for _ in range(CALLS // 20): + self.assertEqual(min(xs, key=namespace["key"]), 0) + namespace.clear() + for _ in range(3): + gc.collect() + self.assertEqual([c() for c in codes], [None, None]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_property_init_entry.py b/tests/regrtest/test_compiled_property_init_entry.py new file mode 100644 index 000000000..041aeb6d8 --- /dev/null +++ b/tests/regrtest/test_compiled_property_init_entry.py @@ -0,0 +1,118 @@ +"""Classes whose `__init__` stores through a property setter, built from +compiled code. + +Such an `__init__` never fills the instance's own attribute positions, so +warm callers stop trying a store-only build and a leaf evaluation and +enter it framed. The setter must still run for every store, validation +errors must propagate, and a class that later drops the property must +store plainly again. +""" + +import unittest + + +class Celsius: + def __init__(self, v): + self.v = v + + @property + def v(self): + return self._v + + @v.setter + def v(self, value): + if value < -273: + raise ValueError("below absolute zero") + self._v = value + + +class Counted: + made = 0 + + def __init__(self, x, y=1): + self.x = x + self.y = y + + @property + def x(self): + return self._x + + @x.setter + def x(self, value): + Counted.made += 1 + self._x = value * 2 + + +class Desc: + def __set_name__(self, owner, name): + self.name = "_" + name + + def __get__(self, obj, owner=None): + return self if obj is None else getattr(obj, self.name) + + def __set__(self, obj, value): + setattr(obj, self.name, [value]) + + +class UsesDesc: + d = Desc() + + def __init__(self, d): + self.d = d + + +class Later: + def __init__(self, v): + self.v = v + + +class PropertyInitEntryTests(unittest.TestCase): + def test_setter_runs(self): + for i in range(3000): + c = Celsius(i) + self.assertEqual((c.v, c._v), (i, i)) + self.assertNotIn("v", vars(c)) + + def test_setter_errors(self): + for i in range(3000): + Celsius(i) + with self.assertRaisesRegex(ValueError, "absolute zero"): + Celsius(-300) + for i in range(3000): + if i % 1000 == 999: + with self.assertRaises(ValueError): + Celsius(-1000) + else: + self.assertEqual(Celsius(i).v, i) + + def test_setter_side_effects(self): + before = Counted.made + for i in range(3000): + c = Counted(i) + self.assertEqual((c.x, c.y), (2 * i, 1)) + self.assertEqual(Counted.made - before, 3000) + + def test_custom_data_descriptor(self): + payload = object() + for i in range(3000): + u = UsesDesc(payload) + self.assertEqual(u.d, [payload]) + self.assertEqual(vars(u), {"_d": [payload]}) + + def test_property_added_later(self): + for i in range(3000): + self.assertEqual(vars(Later(i)), {"v": i}) + Later.v = property(lambda self: self._v * 10, + lambda self, value: setattr(self, "_v", value)) + try: + for i in range(3000): + o = Later(i) + self.assertEqual((o.v, vars(o)), (10 * i, {"_v": i})) + finally: + del Later.v + for i in range(3000): + self.assertEqual(vars(Later(i)), {"v": i}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_store_ctor_entry.py b/tests/regrtest/test_compiled_store_ctor_entry.py new file mode 100644 index 000000000..e035d3717 --- /dev/null +++ b/tests/regrtest/test_compiled_store_ctor_entry.py @@ -0,0 +1,154 @@ +"""Store-only constructors built by compiled code's class dispatch. + +A class whose `__init__` only stores its parameters and constants is +stamped at its version once compiled code builds one, and later calls +build the instance from the class's slot. Changes to the class, its +`__init__` or its code, unused and last-reference arguments, defaults and +finalizers must all behave as CPython's calls do. +""" + +import gc +import unittest + + +class Point: + def __init__(self, x, y=0): + self.x = x + self.y = y + + +class Tagged: + def __init__(self, value, unused): + self.value = value + self.kind = "tagged" + + +class Tracked: + freed = 0 + + def __del__(self): + Tracked.freed += 1 + + +class Mutable: + def __init__(self, a): + self.a = a + + +class Meta(type): + calls = 0 + + def __call__(cls, *args, **kwargs): + Meta.calls += 1 + return super().__call__(*args, **kwargs) + + +class Plain: + def __init__(self, a): + self.a = a + + +class StoreCtorEntryTests(unittest.TestCase): + def test_values_and_defaults(self): + for i in range(3000): + p = Point(i) + self.assertEqual((p.x, p.y), (i, 0)) + q = Point(i, -i) + self.assertEqual(vars(q), {"x": i, "y": -i}) + + def test_heap_arguments(self): + for i in range(3000): + items = [i] + p = Point(items, items) + self.assertIs(p.x, items) + self.assertIs(p.y, items) + for i in range(3000): + p = Point([i]) + self.assertEqual(p.x, [i]) + + def test_unused_last_reference_released(self): + Tracked.freed = 0 + for i in range(3000): + t = Tagged(i, Tracked()) + self.assertEqual((t.value, t.kind), (i, "tagged")) + gc.collect() + self.assertEqual(Tracked.freed, 3000) + + def test_stored_last_reference_kept(self): + Tracked.freed = 0 + keep = [] + for i in range(3000): + keep.append(Point(Tracked())) + self.assertEqual(Tracked.freed, 0) + del keep + gc.collect() + self.assertEqual(Tracked.freed, 3000) + + def test_class_changes(self): + for i in range(3000): + self.assertEqual(vars(Mutable(i)), {"a": i}) + + def init(self, a): + self.b = a * 2 + + old = Mutable.__init__ + Mutable.__init__ = init + try: + for i in range(3000): + self.assertEqual(vars(Mutable(i)), {"b": 2 * i}) + finally: + Mutable.__init__ = old + for i in range(3000): + self.assertEqual(vars(Mutable(i)), {"a": i}) + + def test_code_replaced(self): + class C: + def __init__(self, a): + self.a = a + + def other(self, a): + self.z = -a + + for i in range(3000): + self.assertEqual(vars(C(i)), {"a": i}) + C.__init__.__code__ = other.__code__ + for i in range(3000): + self.assertEqual(vars(C(i)), {"z": -i}) + + def test_metaclass_assigned_later(self): + class K(metaclass=Meta): + def __init__(self, a): + self.a = a + + Meta.calls = 0 + for i in range(3000): + self.assertEqual(K(i).a, i) + self.assertEqual(Meta.calls, 3000) + + def test_errors(self): + for i in range(3000): + Plain(i) + with self.assertRaises(TypeError): + Plain() + with self.assertRaises(TypeError): + Plain(1, 2) + for i in range(3000): + if i % 1000 == 0: + with self.assertRaises(TypeError): + Plain(i, i) + else: + self.assertEqual(Plain(i).a, i) + + def test_subclass_shares_init(self): + class Sub(Point): + pass + + for i in range(3000): + s = Sub(i, 1) + self.assertIs(type(s), Sub) + self.assertEqual((s.x, s.y), (i, 1)) + self.assertIs(type(Point(i)), Point) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_subscript_raises.py b/tests/regrtest/test_compiled_subscript_raises.py new file mode 100644 index 000000000..e9b593cd1 --- /dev/null +++ b/tests/regrtest/test_compiled_subscript_raises.py @@ -0,0 +1,183 @@ +"""Subscript misses raised from compiled code with values pending below. + +A dict's missing key or a sequence's index out of range raised while other +values wait on the stack (`t += d[k]`, `f(x, d[k])`, `[a, d[k]]`) is +raised in compiled code: the pending values are written out on the miss +path only. The handler must see the usual exception (class, args, +traceback line), the pending values must be released exactly once, and a +raise with no handler must reach the caller. A leaf `__exit__` that +suppresses (`contextlib.suppress`) must keep its meaning once compiled code +calls it directly. +""" + +import contextlib +import unittest +import weakref + +N = 20000 + + +class Box: + def __init__(self, v): + self.v = v + + +def augmented(d, n): + t = 0 + missed = 0 + for i in range(n): + try: + t += d[i] + except KeyError: + missed += 1 + return t, missed + + +def as_argument(d, n): + out = [] + missed = 0 + for i in range(n): + try: + out.append((i, d[i])) + except KeyError as e: + missed += 1 + last = e + return len(out), missed, last.args + + +def in_display(xs, n): + missed = 0 + k = 0 + for i in range(n): + try: + k += len([i, xs[i], i]) + except IndexError: + missed += 1 + return k, missed + + +def in_string(s, n): + missed = 0 + for i in range(n): + try: + c = "" + s[i] + except IndexError as e: + missed += 1 + msg = str(e) + return missed, msg + + +def line_of_raise(d, n): + lines = set() + for i in range(n): + try: + x = 1 + d[i] # the raising line + except KeyError as e: + tb = e.__traceback__ + lines.add(tb.tb_lineno - tb.tb_frame.f_code.co_firstlineno) + return lines + + +def never_added(d, n): + # The addition never runs: its result's local has no type evidence. + missed = 0 + for i in range(n): + try: + x = 1 + d[i] + except KeyError: + missed += 1 + return missed + + +def unhandled(d, i): + return 1 + d[i] + + +def pending_objects(d, n): + # The pending value below the subscript is an object: released once. + refs = [] + for i in range(n): + b = Box(i) + refs.append(weakref.ref(b)) + try: + pair = (b, d[i]) + except KeyError: + pass + del b + return sum(r() is not None for r in refs) + + +class Leaf: + def __init__(self, *exc): + self.exc = exc + + def __enter__(self): + return self + + def __exit__(self, t, v, tb): + return t is not None and issubclass(t, self.exc) + + +def suppressing(n, cm_factory): + d = {} + hit = 0 + for i in range(n): + with cm_factory(KeyError): + hit += d[i] + hit += 1 + return hit + + +def propagating(n): + d = {} + caught = 0 + for i in range(n): + try: + with Leaf(IndexError): + hit = d[i] + except KeyError as e: + caught += e.args == (i,) + return caught + + +class SubscriptRaiseTests(unittest.TestCase): + def test_augmented(self): + d = {i: i for i in range(0, N, 3)} + self.assertEqual(augmented(d, N), (sum(d.values()), N - len(d))) + + def test_as_argument(self): + d = {i: i for i in range(0, N, 2)} + self.assertEqual(as_argument(d, N), (len(d), N - len(d), (N - 1,))) + + def test_index_errors(self): + xs = list(range(N // 2)) + self.assertEqual(in_display(xs, N), (3 * (N // 2), N - N // 2)) + self.assertEqual(in_display(tuple(xs), N), (3 * (N // 2), N - N // 2)) + self.assertEqual(in_string("abc", N), (N - 3, "string index out of range")) + + def test_traceback_line(self): + self.assertEqual(line_of_raise({}, N), {4}) + + def test_store_never_reached(self): + self.assertEqual(never_added({}, N), N) + + def test_unhandled(self): + d = {} + for i in range(N): + with self.assertRaises(KeyError) as cm: + unhandled(d, i) + self.assertEqual(cm.exception.args, (i,)) + + def test_pending_objects_released(self): + self.assertEqual(pending_objects({}, N), 0) + + def test_suppress(self): + self.assertEqual(suppressing(N, contextlib.suppress), N) + self.assertEqual(suppressing(N, Leaf), N) + + def test_exit_returning_false_propagates(self): + self.assertEqual(propagating(N), N) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_varargs_direct_entry.py b/tests/regrtest/test_compiled_varargs_direct_entry.py new file mode 100644 index 000000000..e4e438321 --- /dev/null +++ b/tests/regrtest/test_compiled_varargs_direct_entry.py @@ -0,0 +1,151 @@ +"""Compiled code entering functions that take `*args` directly. + +Once such a function (with neither `**kwargs` nor keyword-only parameters) +is warm, compiled callers bind its arguments themselves: the surplus moves +into the `*args` tuple, missing positionals take their defaults, and an +empty tuple stands in when nothing is left over. Methods, closures, +recursion, errors and constructors whose `__init__` takes `*args` must +all keep CPython's behavior. +""" + +import gc +import sys +import unittest +import weakref + + +def star(*args): + return args + + +def first(x, *rest): + return (x, rest) + + +def defaulted(x, y=10, *rest): + return (x, y, rest) + + +def raises(*args): + if args and args[0] < 0: + raise ValueError(args) + return len(args) + + +def depth(n, *acc): + if n == 0: + return acc + return depth(n - 1, n, *acc) + + +def make_closure(k): + def inner(*args): + return sum(args) + k + + return inner + + +class Item: + pass + + +class Methods: + def __init__(self, base): + self.base = base + + def add(self, *args): + return self.base + sum(args) + + +class Collect: + def __init__(self, *args): + self.args = args + self.n = len(args) + + +class Mixed: + def __init__(self, a, *rest): + self.a = a + self.rest = rest + if a < 0: + raise ValueError(a) + + +class VarargsDirectEntryTests(unittest.TestCase): + def test_counts(self): + for i in range(3000): + self.assertEqual(star(), ()) + self.assertEqual(star(i), (i,)) + self.assertEqual(star(i, 1, 2, 3, 4, 5, 6, 7, 8, 9), (i, 1, 2, 3, 4, 5, 6, 7, 8, 9)) + self.assertEqual(first(i), (i, ())) + self.assertEqual(first(i, 1), (i, (1,))) + + def test_defaults(self): + for i in range(3000): + self.assertEqual(defaulted(i), (i, 10, ())) + self.assertEqual(defaulted(i, 2), (i, 2, ())) + self.assertEqual(defaulted(i, 2, 3, 4), (i, 2, (3, 4))) + with self.assertRaises(TypeError): + defaulted() + + def test_heap_items_survive(self): + for _ in range(3000): + a, b = Item(), [1, 2] + got = star(a, b, "x" * 3) + self.assertIs(got[0], a) + self.assertIs(got[1], b) + obj = Item() + ref = weakref.ref(obj) + kept = star(obj) + del obj + gc.collect() + self.assertIsNotNone(ref()) + del kept + gc.collect() + self.assertIsNone(ref()) + + def test_errors(self): + for i in range(3000): + self.assertEqual(raises(i, i), 2) + with self.assertRaises(ValueError) as cm: + raises(-1, 2) + self.assertEqual(cm.exception.args, ((-1, 2),)) + + def test_recursion(self): + for _ in range(300): + self.assertEqual(depth(5), (1, 2, 3, 4, 5)) + with self.assertRaises(RecursionError): + depth(sys.getrecursionlimit() + 100) + + def test_closures_and_methods(self): + fns = [make_closure(k) for k in range(3)] + m = Methods(100) + for i in range(3000): + for k, f in enumerate(fns): + self.assertEqual(f(i, 1), i + 1 + k) + self.assertEqual(m.add(), 100) + self.assertEqual(m.add(i, 1), 101 + i) + + def test_constructors(self): + for i in range(3000): + c = Collect(i, "a") + self.assertEqual((c.args, c.n), ((i, "a"), 2)) + self.assertEqual(Collect().args, ()) + m = Mixed(i, 1, 2) + self.assertEqual((m.a, m.rest), (i, (1, 2))) + self.assertEqual(Mixed(i).rest, ()) + with self.assertRaises(ValueError): + Mixed(-1, 2) + with self.assertRaises(TypeError): + Mixed() + + def test_keyword_and_spread_calls(self): + args = (1, 2, 3) + for i in range(3000): + self.assertEqual(star(*args), args) + self.assertEqual(first(x=i), (i, ())) + self.assertEqual(Collect(*args).n, 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compiled_with_loops.py b/tests/regrtest/test_compiled_with_loops.py new file mode 100644 index 000000000..286e0ce49 --- /dev/null +++ b/tests/regrtest/test_compiled_with_loops.py @@ -0,0 +1,148 @@ +"""Loops around `with` blocks, in functions whose other loops tier 2 takes. + +Tier 2 never compiles a `with` block. A loop it carved out for one goes to +the frame JIT at the loop's first trigger, whether tier 2 compiled nothing +for the function or compiled its other loops. Whichever runs the loop, the +context manager's protocol must hold: `__enter__`'s result bound, `__exit__` +called once per pass with the exception (or `None`s), a true return +suppressing it, and `break`, `continue` and `return` leaving through +`__exit__`. +""" + +import unittest + +N = 30000 + + +class Counter: + def __init__(self, suppress=False): + self.enters = 0 + self.exits = 0 + self.seen = [] + self.suppress = suppress + + def __enter__(self): + self.enters += 1 + return self.enters + + def __exit__(self, typ, val, tb): + self.exits += 1 + if typ is not None: + self.seen.append(typ) + return self.suppress + + +def plain(n): + cm = Counter() + t = 0 + for i in range(n): + with cm as k: + t += k - i + return t, cm.enters, cm.exits + + +def after_numeric(n): + # Tier 2 compiles the first loop; the second stays its to leave. + t = 0 + for i in range(50000): + t += i + cm = Counter() + for i in range(n): + with cm: + t += 1 + return t, cm.exits + + +def nested_numeric(n): + cm = Counter() + t = 0 + for j in range(n // 50): + for i in range(50): + t += i + with cm: + t += 1 + return t, cm.exits + + +def suppressing(n): + cm = Counter(suppress=True) + hit = 0 + for i in range(n): + with cm: + if i % 7 == 0: + raise ValueError(i) + hit += 1 + return hit, cm.exits, len(cm.seen) + + +def propagating(n): + cm = Counter() + caught = 0 + for i in range(n): + try: + with cm: + if i % 5 == 0: + raise KeyError(i) + except KeyError: + caught += 1 + return caught, cm.exits, len(cm.seen) + + +def leaving(n): + cm = Counter() + t = 0 + for i in range(n): + with cm: + if i % 3 == 0: + continue + if i == n - 1: + break + t += 1 + return t, cm.enters, cm.exits + + +def returning(n): + cm = Counter() + for i in range(n): + with cm: + if i == n - 10: + return i, cm.enters, cm.exits + return None + + +class CompiledWithLoopTests(unittest.TestCase): + def test_plain(self): + self.assertEqual(plain(N), (N, N, N)) + + def test_after_numeric(self): + self.assertEqual(after_numeric(N), (sum(range(50000)) + N, N)) + + def test_nested_numeric(self): + self.assertEqual(nested_numeric(N), (sum(range(50)) * (N // 50) + N // 50, N // 50)) + + def test_suppressing(self): + raised = len(range(0, N, 7)) + self.assertEqual(suppressing(N), (N - raised, N, raised)) + + def test_propagating(self): + raised = len(range(0, N, 5)) + self.assertEqual(propagating(N), (raised, N, raised)) + + def test_leaving(self): + skipped = len(range(0, N, 3)) + last_skipped = (N - 1) % 3 == 0 + expected_t = N - skipped - (0 if last_skipped else 1) + self.assertEqual(leaving(N), (expected_t, N, N)) + + def test_returning(self): + # The `return` inside the block runs before its own `__exit__`. + self.assertEqual(returning(N), (N - 10, N - 9, N - 10)) + + def test_repeated_calls(self): + for _ in range(3): + self.assertEqual(plain(N // 3), (N // 3, N // 3, N // 3)) + self.assertEqual(after_numeric(N // 3), (sum(range(50000)) + N // 3, N // 3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_compress_bisect_key_odict_ctor.py b/tests/regrtest/test_compress_bisect_key_odict_ctor.py new file mode 100644 index 000000000..340fb16b1 --- /dev/null +++ b/tests/regrtest/test_compress_bisect_key_odict_ctor.py @@ -0,0 +1,106 @@ +"""itertools.compress stepped in place, bisect with a key called in +place, and OrderedDict built from pairs or a dict, from compiled loops: +selectors of every plain kind and of other kinds, the same iterator as +both arguments, unequal lengths, keys that are itemgetters, lambdas and +raising functions, insort with a key, and OrderedDict order, duplicate +keys, mixed and non-plain keys, a subclass and the profile of a class +whose __init__ changed, each matching CPython.""" + +import bisect +import collections +import itertools +import operator +import unittest + + +def compress(n, data, sel): + out = None + for i in range(n): + out = list(itertools.compress(data, sel)) + return out + + +class CompressTests(unittest.TestCase): + def test_selectors(self): + for n in (1, 300): + self.assertEqual(compress(n, [1, 2, 3, 4], [1, 0, 1, 0]), [1, 3]) + self.assertEqual(compress(n, "abcd", [True, None, 2, False]), ["a", "c"]) + self.assertEqual(compress(n, (1, 2, 3), [1, 1]), [1, 2]) + self.assertEqual(compress(n, [1, 2], [1, 1, 1]), [1, 2]) + self.assertEqual(compress(n, range(5), [0, "", "x", [], [0]]), [2, 4]) + self.assertEqual(compress(n, [], []), []) + + def test_same_iterator(self): + for _ in range(300): + it = iter([1, 0, 2, 1, 3, 0]) + self.assertEqual(list(itertools.compress(it, it)), [2]) + + def test_partial_then_resume(self): + for _ in range(300): + c = itertools.compress([1, 2, 3, 4], [1, 1, 0, 1]) + self.assertEqual(next(c), 1) + self.assertEqual(list(c), [2, 4]) + + +def bisects(n, xs, x, key): + out = None + for i in range(n): + out = (bisect.bisect_left(xs, x, key=key), bisect.bisect_right(xs, x, key=key)) + return out + + +class BisectKeyTests(unittest.TestCase): + def test_keys(self): + xs = [(1, "a"), (3, "b"), (3, "c"), (5, "d")] + for n in (1, 300): + self.assertEqual(bisects(n, xs, 3, operator.itemgetter(0)), (1, 3)) + self.assertEqual(bisects(n, xs, 4, lambda t: t[0]), (3, 3)) + self.assertEqual(bisects(n, ["a", "bb", "ccc"], 2, len), (1, 2)) + + def bad(t): + raise RuntimeError("key") + + with self.assertRaises(RuntimeError): + bisects(300, xs, 3, bad) + + def test_insort_key(self): + for _ in range(300): + xs = [(1, "a"), (5, "d")] + bisect.insort(xs, (3, "x"), key=operator.itemgetter(0)) + self.assertEqual(xs, [(1, "a"), (3, "x"), (5, "d")]) + + +class Sub(collections.OrderedDict): + pass + + +def ods(n, arg, cls=collections.OrderedDict): + out = None + for i in range(n): + out = cls(arg) + return out + + +class OrderedDictCtorTests(unittest.TestCase): + def test_pairs_and_dicts(self): + for n in (1, 300): + o = ods(n, [("b", 1), ("a", 2), (3, "c")]) + self.assertEqual(list(o.items()), [("b", 1), ("a", 2), (3, "c")]) + o.move_to_end("b") + self.assertEqual(list(o), ["a", 3, "b"]) + self.assertEqual(list(ods(n, (("x", 1), ("x", 2)))), ["x"]) + self.assertEqual(ods(n, (("x", 1), ("x", 2)))["x"], 2) + self.assertEqual(list(ods(n, {"q": 1, 2: 3}).items()), [("q", 1), (2, 3)]) + self.assertEqual(list(ods(n, [(1.5, "f"), ((1, 2), "t")])), [1.5, (1, 2)]) + self.assertEqual(list(ods(n, [["k", "v"]])), ["k"]) + s = ods(n, [("z", 0)], Sub) + self.assertIs(type(s), Sub) + self.assertEqual(list(s), ["z"]) + with self.assertRaises(ValueError): + ods(300, [("a", 1, 2)]) + with self.assertRaises(TypeError): + ods(300, [1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_consecutive_field_accesses.py b/tests/regrtest/test_consecutive_field_accesses.py new file mode 100644 index 000000000..ed88aeca4 --- /dev/null +++ b/tests/regrtest/test_consecutive_field_accesses.py @@ -0,0 +1,241 @@ +"""Several accesses of one object's fields in a row each see the object as it is. + +A compiled loop that reads and writes several fields of the same local +checks that object's layout once and reuses the check for the accesses +that follow. Anything in between that can change the object (a store of +a new attribute, a store that replaces a non-scalar value, a call, a +rebinding of the local, an alias) must be seen by the next access. +""" + +import unittest + +N = 4000 + + +class P: + def __init__(self, a=1, b=2.0, c=3): + self.a = a + self.b = b + self.c = c + + def tick(self): + self.a += 1 + return self.a + + +class S: + __slots__ = ("a", "b", "c") + + def __init__(self, a=1, b=2.0, c=3): + self.a = a + self.b = b + self.c = c + + +def reads(p, n): + total = 0 + for _ in range(n): + total += p.a + p.c + total += p.c - p.a + return total + + +def read_write(p, n): + for _ in range(n): + p.b = p.b + 0.5 + p.a = p.a + p.c + p.c = p.c + 1 + return p.a, p.b, p.c + + +def two_receivers(p, q, n): + total = 0 + for _ in range(n): + total += p.a + q.a + p.c = q.c + 1 + q.c = p.c + 1 + total += p.c + q.c + return total + + +def with_ticks(p, n): + total = 0 + for _ in range(n): + total += p.a + total += p.tick() + total += p.a + p.c + return total + + +def new_attribute_between(p, n): + total = 0 + for i in range(n): + total += p.a + if i == n // 2: + p.extra = i # a new name: the instance's values move + total += p.c + return total + + +def heap_store_between(p, n): + total = 0 + for i in range(n): + total += p.a + p.b = [i] # replaces a float with a list, then back + total += p.c + p.b = 2.5 + total += p.a + return total + + +def rebinding_between(p, q, n): + total = 0 + for i in range(n): + x = p + total += x.a + x = q + total += x.a + total += x.c + return total + + +def call_between(p, n, f): + total = 0 + for i in range(n): + total += p.a + f(p, i) + total += p.a + p.c + return total + + +def lane_change_between(p, n): + total = 0.0 + for i in range(n): + total += p.c + p.c = p.c + 1 + total += p.a + return total + + +class ConsecutiveAccessTests(unittest.TestCase): + kinds = (P, S) + + def test_reads(self): + for cls in self.kinds: + self.assertEqual(reads(cls(5, 2.0, 7), N), N * (12 + 2)) + + def test_reads_and_writes(self): + for cls in self.kinds: + p = cls() + a, b, c = read_write(p, N) + self.assertEqual(b, 2.0 + 0.5 * N) + self.assertEqual(c, 3 + N) + self.assertEqual(a, 1 + sum(3 + k for k in range(N))) + + def test_two_receivers_and_aliases(self): + for cls in self.kinds: + p, q = cls(), cls(10, 0.0, 0) + got = two_receivers(p, q, N) + want = 0 + pc, qc = 3, 0 + for _ in range(N): + want += 1 + 10 + pc = qc + 1 + qc = pc + 1 + want += pc + qc + self.assertEqual(got, want) + # The same object under both names. + r = cls(1, 0.0, 0) + got = two_receivers(r, r, N) + want = 0 + c = 0 + for _ in range(N): + want += 2 + c = c + 1 + c = c + 1 + want += 2 * c + self.assertEqual(got, want) + + def test_method_updates_between_reads(self): + p = P() + got = with_ticks(p, N) + want = 0 + a = 1 + for _ in range(N): + want += a + a += 1 + want += a + want += a + 3 + self.assertEqual(got, want) + + def test_new_attribute_between_reads(self): + p = P() + self.assertEqual(new_attribute_between(p, N), N * 4) + self.assertEqual(p.extra, N // 2) + for k in range(40): + setattr(p, "more%d" % k, k) + self.assertEqual(new_attribute_between(p, N), N * 4) + + def test_heap_store_between_reads(self): + for cls in self.kinds: + p = cls() + self.assertEqual(heap_store_between(p, N), N * 5) + self.assertEqual(p.b, 2.5) + + def test_rebinding_between_reads(self): + for cls in self.kinds: + self.assertEqual(rebinding_between(cls(1, 0.0, 2), cls(10, 0.0, 20), N), N * 31) + self.assertEqual(rebinding_between(P(1, 0.0, 2), S(10, 0.0, 20), N), N * 31) + + def test_call_between_reads(self): + def grow(p, i): + if i % 1000 == 999: + setattr(p, "g%d" % i, i) + p.a += 1 + + def dict_view(p, i): + if i == 10: + p.__dict__["c"] = 100 + + p = P() + got = call_between(p, N, grow) + self.assertEqual(got, sum((1 + i) + (2 + i) + 3 for i in range(N))) + p = P() + got = call_between(p, N, dict_view) + self.assertEqual(got, sum(1 + 1 + (3 if i < 10 else 100) for i in range(N))) + + class Other: + a = 7 + c = 9 + + def swap_class(p, i): + if i == N // 2: + p.__class__ = Q + + class Q(P): + pass + + p = P() + self.assertEqual(call_between(p, N, swap_class), N * 5) + self.assertIs(type(p), Q) + + def test_lane_change_between_reads(self): + for cls in self.kinds: + p = cls(1, 0.0, 0) + self.assertEqual(lane_change_between(p, N), sum(range(N)) + N) + p.c = 0.5 + self.assertEqual(lane_change_between(p, N), sum(k + 0.5 for k in range(N)) + N) + + def test_deleted_then_restored(self): + for cls in self.kinds: + p = cls() + self.assertEqual(reads(p, N), N * (4 + 2)) + del p.c + with self.assertRaises(AttributeError): + reads(p, 3) + p.c = 4 + self.assertEqual(reads(p, N), N * (5 + 3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_container_binops_in_hot_loops.py b/tests/regrtest/test_container_binops_in_hot_loops.py new file mode 100644 index 000000000..f9fe9cc99 --- /dev/null +++ b/tests/regrtest/test_container_binops_in_hot_loops.py @@ -0,0 +1,102 @@ +"""Container operators, `len(range)` and `dict(mapping, **kw)` in hot loops. + +Loops that tier 2 compiles run `list + list`, `tuple + tuple`, +`dict | dict`, set algebra and `bytes + bytes` without the general +operator dispatch when no Python code is involved; operands that need it +(a key with a Python `__eq__`, a subclass, a reflected operator) still +take it. `len()` of a range and `dict(mapping, **kw)` have direct paths. +""" + +import unittest + +N = 4000 + + +class Key: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, Key) and self.v == other.v + + +class MyList(list): + def __add__(self, other): + return "mine" + + +class Radd: + def __radd__(self, other): + return "radd" + + +class ContainerBinopTests(unittest.TestCase): + def test_plain_operands(self): + L = [1, 2, 3] + D = {"a": 1, "b": 2} + for i in range(N): + a = L + [i] + b = (1, 2) + (i,) + c = D | {"q": i} + d = {1, 2} | {i} + e = {1, 2, 3} & {2, i} + f = {1, 2, 3} - {2} + g = {1, 2} ^ {2, 3} + h = b"ab" + b"cd" + self.assertEqual(a, [1, 2, 3, N - 1]) + self.assertEqual(b, (1, 2, N - 1)) + self.assertEqual(c, {"a": 1, "b": 2, "q": N - 1}) + self.assertEqual(list(c), ["a", "b", "q"]) + self.assertEqual(d, {1, 2, N - 1}) + self.assertEqual(e, {2}) + self.assertEqual((f, g, h), ({1, 3}, {1, 3}, b"abcd")) + self.assertEqual(L, [1, 2, 3]) + self.assertEqual(D, {"a": 1, "b": 2}) + + def test_python_keys_and_subclasses(self): + k1, k2 = Key(1), Key(1) + ml = MyList([1]) + r = Radd() + for i in range(N): + a = {k1: "x"} | {k2: "y"} + b = {k1} | {k2} + c = ml + [2] + d = [1] + r + self.assertEqual(len(a), 1) + self.assertEqual(a[k1], "y") + self.assertEqual(len(b), 1) + self.assertEqual((c, d), ("mine", "radd")) + + def test_errors(self): + for i in range(N // 10): + with self.assertRaises(TypeError): + [1] + (2,) + with self.assertRaises(TypeError): + {"a": 1} | [1] + with self.assertRaises(TypeError): + {1} | [1] + + def test_range_len_and_dict_kw(self): + base = {"a": 1} + for i in range(N): + n = (len(range(10, 100, 3)), len(range(i)), len(range(5, 0, -2)), len(range(3, 3))) + d = dict(base, z=i) + e = dict({"k": 1}.items(), a=2) + f = dict(z=i) + self.assertEqual(n, (30, N - 1, 3, 0)) + self.assertEqual(d, {"a": 1, "z": N - 1}) + self.assertEqual(list(d), ["a", "z"]) + self.assertEqual(e, {"k": 1, "a": 2}) + self.assertEqual(f, {"z": N - 1}) + self.assertEqual(base, {"a": 1}) + with self.assertRaises(OverflowError): + len(range(10 ** 30)) + self.assertEqual(dict(base, a=5), {"a": 5}) + self.assertEqual(dict({1: "x"}, a=5), {1: "x", "a": 5}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_container_cycle_tracking.py b/tests/regrtest/test_container_cycle_tracking.py new file mode 100644 index 000000000..16c8adf35 --- /dev/null +++ b/tests/regrtest/test_container_cycle_tracking.py @@ -0,0 +1,95 @@ +"""Cycles through lists and dicts made by builtins are collected. + +Each maker's container is given an object that refers back to it; the +collector must find every such cycle. `list.copy()`, `dir()`, +`json.loads`, `re.findall`, `dict.fromkeys`, `dict | dict`, a list's `+` +and `*`, and a function's `**kwargs` built their containers without +registering them, so these cycles were never collected. A `**kwargs` dict +that only ever feeds a `**` spread can't escape its call and isn't +registered; one that leaves through another local, a closure or +`locals()` is. +""" + +import copy +import gc +import json +import re +import weakref + + +class Node: + pass + + +def kwargs(**k): + return k + + +def kwargs_via_local(**k): + other = k + return other + + +def kwargs_via_closure(**k): + return (lambda: k)() + + +def kwargs_via_locals(**k): + return locals()["k"] + + +def merged(*a, **k): + return dict(**k) + + +LISTS = { + "split": lambda: "a,b".split(","), + "copy": lambda: [1, 2].copy(), + "sorted": lambda: sorted([2, 1]), + "slice": lambda: [1, 2, 3][0:2], + "slice_step": lambda: [1, 2, 3][::2], + "concat": lambda: [1] + [2], + "repeat": lambda: [1] * 2, + "dir": lambda: dir(), + "json": lambda: json.loads("[1, 2]"), + "findall": lambda: re.findall("a", "aa"), + "deepcopy": lambda: copy.deepcopy([1, 2]), + "enumerate": lambda: list(enumerate((1, 2))), +} +DICTS = { + "literal": lambda: {"a": 1}, + "copy": lambda: {"a": 1}.copy(), + "fromkeys": lambda: dict.fromkeys("ab"), + "fromkeys_list": lambda: dict.fromkeys(["a", "b"]), + "fromkeys_dict": lambda: dict.fromkeys({"a": 1}), + "union": lambda: {"a": 1} | {"b": 2}, + "json": lambda: json.loads('{"a": 1}'), + "kwargs": lambda: kwargs(a=1), + "kwargs_empty": lambda: kwargs(), + "kwargs_via_local": lambda: kwargs_via_local(a=1), + "kwargs_via_closure": lambda: kwargs_via_closure(), + "kwargs_via_locals": lambda: kwargs_via_locals(), + "merged": lambda: merged(a=1), +} + + +def check(makers, put): + bad = [] + for name, make in makers.items(): + dead = [] + for i in range(60): + c = make() + node = Node() + put(c, node) + node.ref = c + weakref.finalize(node, dead.append, i) + del c, node + gc.collect() + if len(dead) != 60: + bad.append((name, len(dead))) + return bad + + +assert check(LISTS, lambda c, n: c.append(n)) == [] +assert check(DICTS, lambda c, n: c.__setitem__("n", n)) == [] +print("ok") diff --git a/tests/regrtest/test_container_dunder_lanes.py b/tests/regrtest/test_container_dunder_lanes.py new file mode 100644 index 000000000..03f23b6d6 --- /dev/null +++ b/tests/regrtest/test_container_dunder_lanes.py @@ -0,0 +1,122 @@ +"""Hot-loop paths for container methods read as values and for a few +bytes and str methods. + +`d.__getitem__` and the other container dunders read in compiled code +must bind as the full read binds them; `map(d.__getitem__, xs)` must +call a subclass's `__missing__` for a miss, in order, and raise what the +lookup raises; `b.endswith(tuple)` must reject a tuple item that isn't +bytes-like and accept other buffers; `s.expandtabs()` must keep its +columns across tabs, newlines and tab sizes. +""" + +import unittest + + +class Quoter(dict): + def __init__(self): + self.missed = [] + + def __missing__(self, b): + self.missed.append(b) + r = chr(b) if b < 128 else "%{:02X}".format(b) + self[b] = r + return r + + +class Key: + def __hash__(self): + return hash(1) + + def __eq__(self, other): + return other == 1 + + +def reads(x): + return (x.__contains__, x.__len__, x.__iter__) + + +class ContainerDunderLanes(unittest.TestCase): + def test_bound_dunders(self): + d, lst, st, s = {"a": 1}, [1, 2], {3}, "ab" + for _ in range(3000): + g = d.__getitem__ + self.assertEqual(g("a"), 1) + self.assertIs(g.__self__, d) + self.assertEqual(lst.__getitem__(1), 2) + d.__setitem__("b", 2) + d.__delitem__("b") + self.assertTrue(st.__contains__(3)) + self.assertEqual(s.__len__(), 2) + for x in (d, lst, st, s): + c, n, it = reads(x) + self.assertIs(c.__self__, x) + self.assertEqual(n(), len(x)) + self.assertEqual(list(it()), list(x)) + self.assertEqual(type(d.__getitem__).__name__, "builtin_function_or_method") + + def test_map_getitem(self): + q = Quoter() + for i in range(2000): + data = bytes([97, 32, 47 + i % 3, 200]) + got = "".join(map(q.__getitem__, data)) + self.assertEqual(got, "".join(chr(b) if b < 128 else "%C8" for b in data)) + self.assertEqual(sorted(q.missed), [32, 47, 48, 49, 97, 200]) + plain = {1: "one", 2: "two"} + for _ in range(500): + self.assertEqual(list(map(plain.__getitem__, [1, 2, 1])), ["one", "two", "one"]) + with self.assertRaises(KeyError): + list(map(plain.__getitem__, [1, 3])) + odd = {Key(): "k", 2: "two"} + self.assertEqual(list(map(odd.__getitem__, [1, 2])), ["k", "two"]) + it = iter([1, 2, 3]) + with self.assertRaises(KeyError): + list(map(plain.__getitem__, it)) + self.assertEqual(list(it), []) + + def test_bytes_endswith_tuple(self): + for i in range(3000): + name = b"file%d.txt" % i + self.assertTrue(name.endswith((b".py", b".txt"))) + self.assertFalse(name.endswith((b".py", b".c"))) + self.assertTrue(name.startswith((b"x", b"file"))) + self.assertTrue(name.endswith((bytearray(b"txt"), memoryview(b"t")))) + self.assertTrue(bytearray(name).endswith((b".txt",))) + self.assertTrue(b"a.txt".endswith((b".txt", "str"))) + with self.assertRaises(TypeError): + b"a.txt".endswith(("str", b".txt")) + with self.assertRaises(TypeError): + b"a.txt".endswith((b".py", 1)) + self.assertFalse(b"abc".endswith(())) + + def test_expandtabs(self): + cases = ["a\tb\tc", "\t", "ab\ncd\te", "x\r\ty", "no tabs", "é\tx", "a\t\tb"] + for _ in range(1000): + for t in cases: + for size in (8, 4, 1, 0, -3): + want = "".join(_expand(t, size)) + self.assertEqual(t.expandtabs(size), want) + self.assertEqual(t.expandtabs(tabsize=size), want) + self.assertEqual(t.expandtabs(), "".join(_expand(t, 8))) + with self.assertRaises(TypeError): + "a".expandtabs(size=4) + with self.assertRaises(TypeError): + "a".expandtabs(4, tabsize=4) + + +def _expand(t, size): + col = 0 + for ch in t: + if ch == "\t": + pad = size - col % size if size > 0 else 0 + col += pad + yield " " * pad + elif ch in "\r\n": + col = 0 + yield ch + else: + col += 1 + yield ch + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_container_method_kernels.py b/tests/regrtest/test_container_method_kernels.py new file mode 100644 index 000000000..20a4be763 --- /dev/null +++ b/tests/regrtest/test_container_method_kernels.py @@ -0,0 +1,107 @@ +"""Container methods that compiled code runs in place. + +`dict.pop`, `dict.copy`, `set.copy` and `list.remove` run as kernels or +leaf bodies when nothing they touch can run Python code, and decline to +the full call otherwise. These loops check both sides of that line. +""" + +import unittest + +N = 3000 + + +class Key: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, Key) and other.v == self.v + + +class Loose: + def __init__(self, v): + self.v = v + + def __eq__(self, other): + return getattr(other, "v", other) == self.v + + def __repr__(self): + return f"Loose({self.v})" + + +class DictPopCopyTests(unittest.TestCase): + def test_pop(self): + class DD(dict): + pass + + for i in range(N): + d = {"a": 1, "b": 2, 3: 4, Key(1): 5} + r = (d.pop("a"), d.pop("zz", None), d.pop(3), d.pop(Key(1)), + d.pop(2.0, "f"), list(d)) + dd = DD(x=i) + r2 = (dd.pop("x"), dd) + self.assertEqual(r, (1, None, 4, 5, "f", ["b"])) + self.assertEqual(r2, (N - 1, {})) + with self.assertRaises(KeyError) as cm: + {}.pop("missing") + self.assertEqual(cm.exception.args, ("missing",)) + with self.assertRaises(TypeError) as cm: + {}.pop() + self.assertEqual(str(cm.exception), "pop expected at least 1 argument, got 0") + + def test_copy(self): + class DD(dict): + pass + + d = {"a": 1} + s = {1, 2} + for i in range(N): + c = d.copy() + c["n"] = i + t = s.copy() + t.add(3) + sub = DD(x=1).copy() + self.assertEqual((d, c, s, t), ({"a": 1}, {"a": 1, "n": N - 1}, {1, 2}, {1, 2, 3})) + self.assertIs(type(sub), dict) + with self.assertRaises(TypeError) as cm: + {}.copy(1) + self.assertEqual(str(cm.exception), "dict.copy() takes no arguments (1 given)") + + +class ListRemoveTests(unittest.TestCase): + def test_native_and_python_equality(self): + for i in range(N): + items = [1, "a", 2.0, 3, None, Loose(5)] + items.remove(3) + items.remove("a") + items.remove(2) + items.remove(None) + items.remove(5) + self.assertEqual(items, [1]) + mixed = [Loose(1), 2] + mixed.remove(2) + self.assertEqual(repr(mixed), "[Loose(1)]") + with self.assertRaises(ValueError) as cm: + [1].remove(99) + self.assertEqual(str(cm.exception), "list.remove(x): x not in list") + + def test_removed_item_finalizes_promptly(self): + events = [] + + class D: + def __del__(self): + events.append("del") + + for i in range(N): + items = [D() if i == N - 1 else 0, 7] + items.remove(items[0]) + if i == N - 1: + events.append("after") + self.assertEqual(events, ["del", "after"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_container_ops_compiled.py b/tests/regrtest/test_container_ops_compiled.py new file mode 100644 index 000000000..75f67703c --- /dev/null +++ b/tests/regrtest/test_container_ops_compiled.py @@ -0,0 +1,131 @@ +"""Dict union and equality, set and keys-view comparisons, keys-view +algebra, and bytes repetition and formatting in compiled code. + +Plain keys and values take the native paths; a key or value with a +Python `__eq__` takes the full path, which runs it. Results that are heap +values keep compiled code from leaving at the next instruction. Run it +past the compile threshold. +""" + + +class E: + eqs = 0 + + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + E.eqs += 1 + return isinstance(other, E) and self.v == other.v + + +nan = float("nan") + + +def dicts(n): + d1 = {"a": 1, "b": [1, 2]} + d2 = {"b": 3, "c": 4} + for _ in range(n): + u = d1 | d2 + assert u == {"a": 1, "b": 3, "c": 4} and list(u) == ["a", "b", "c"] + assert u is not d1 and d1 == {"a": 1, "b": [1, 2]} + assert d1 | {} == d1 and {} | d2 == d2 + assert {"x": 1, "y": 2} == {"y": 2, "x": 1} + assert {"x": 1} != {"x": 1.5} and {"x": 1} == {"x": 1.0} + assert {"x": 1} != {"y": 1} and {"x": 1} != {"x": 1, "y": 2} + assert {"x": {"y": (1, [2])}} == {"x": {"y": (1, [2])}} + d = {"n": nan} + assert d == d and d != {"n": float("nan")} + assert {"n": nan} == {"n": nan} + E.eqs = 0 + assert {"e": E(1)} == {"e": E(1)} and E.eqs == 1 + assert {E(1): 1} == {E(1): 1} and E.eqs >= 2 + + +def sets(n): + s = {"a", "c"} + f = frozenset({"a", "c", "d"}) + for i in range(n): + assert s <= {"a", "c", "d"} and s < f and not s > f and f >= s + assert not {"a", "z"} <= {"a", "c", "d"} + assert s == frozenset({"c", "a"}) and s != f + assert {1, 2} == {2.0, 1} and {i} <= {i, i + 1} + E.eqs = 0 + assert {E(1)} <= {E(1), E(2)} and E.eqs >= 1 + + +def views(n): + d = {"a": 1, "b": 2, 1: 3} + k = d.keys() + for _ in range(n): + r = k & {"a", "z"} + assert r == {"a"} and type(r) is set + assert k | {"z"} == {"a", "b", 1, "z"} and type(k | frozenset()) is set + assert k - {"a"} == {"b", 1} and k ^ {"a", "z"} == {"b", 1, "z"} + assert k & frozenset({"b"}) == {"b"} and type(k & frozenset()) is set + # (A tie keeps the view's element, as `set.intersection(view)`.) + tie = k & {1.0, "a", "b"} + assert tie == {1, "a", "b"} and [x for x in tie if x == 1][0].__class__ is int + bigger = d.keys() & {1.0} + assert [type(x) for x in bigger] == [float] + E.eqs = 0 + assert {E(1): 0}.keys() & {E(1)} == {E(1)} and E.eqs >= 1 + + +def keys_compare(n): + d = {"a": 1, "b": 2} + k = d.keys() + e = {"x": 1}.keys() + for _ in range(n): + assert k == {"a", "b"} and k != {"a"} and {"a", "b"} == k and k == frozenset("ab") + assert k <= {"a", "b", "c"} and k < {"a", "b", "c"} and not k < {"a", "b"} + assert k >= {"a"} and k > {"a"} and not k > {"a", "b"} and {"a"} < k + assert {"a", "b", "c"} > k and k == {"b": 0, "a": 0}.keys() and k != e and not k <= e + assert d.items() == {("a", 1), ("b", 2)} and d.values() != {1, 2} + assert {1: 0}.keys() == {1.0} and {1: 0}.keys() == {True} + E.eqs = 0 + assert {E(1): 0}.keys() == {E(1)} and E.eqs >= 1 + + +def byte_ops(n): + bs = b"ab" + for i in range(n): + assert bs * 3 == b"ababab" and 2 * bs == b"abab" + assert bs * 0 == b"" and bs * -1 == b"" + assert b"%d-%s" % (i, b"x") == b"%d-x" % i + assert b"%x" % 255 == b"ff" and b"%%%d" % 5 == b"%5" + assert b"%5d" % 3 == b" 3" + try: + b"%d" % "s" + except TypeError: + pass + else: + raise AssertionError("bytes %d of a str") + try: + b"%d %d" % (1,) + except TypeError: + pass + else: + raise AssertionError("too few arguments") + + +for f in (dicts, sets, views, keys_compare, byte_ops): + f(1500) + +# Self-referential dicts compare by identity first, and two distinct +# ones recurse until the full path raises. +a = {} +a["a"] = a +assert a == a +b = {} +b["a"] = b +try: + a == b +except RecursionError: + pass +else: + raise AssertionError("expected RecursionError") +print("ok") diff --git a/tests/regrtest/test_container_release_paths.py b/tests/regrtest/test_container_release_paths.py new file mode 100644 index 000000000..2dcde88f4 --- /dev/null +++ b/tests/regrtest/test_container_release_paths.py @@ -0,0 +1,116 @@ +"""Releasing dicts, lists and tuples, and refilling the tuple free list. + +A dying dict or list gives its shared items up with plain decrements and +drops the ones it owns last, in order; deeply nested ones still free +without overflowing the stack. Objects with `__del__` die when their last +container does, in CPython's order. A tuple a loop builds and drops +reuses one allocation, as CPython's free list does. +""" + +import gc +import sys +import unittest + +N = 3000 + + +class Noted: + log = [] + + def __init__(self, name): + self.name = name + + def __del__(self): + Noted.log.append(self.name) + + +class DictReleaseTests(unittest.TestCase): + def test_shared_and_owned_values(self): + keys = ["k%d" % i for i in range(20)] + shared = [object() for _ in range(20)] + before = [sys.getrefcount(k) for k in keys] + for _ in range(N): + d = dict(zip(keys, shared)) + c = d.copy() + c["own"] = [1, 2, 3] + del d, c + self.assertEqual([sys.getrefcount(k) for k in keys], before) + + def test_death_order(self): + Noted.log = [] + d = {"a": Noted("a"), 1: Noted("one"), "b": Noted("b")} + del d + gc.collect() + self.assertEqual(Noted.log, ["a", "one", "b"]) + Noted.log = [] + keep = Noted("kept") + d = {"x": keep, "y": Noted("y"), "z": keep} + del d + self.assertEqual(Noted.log, ["y"]) + del keep + self.assertEqual(Noted.log, ["y", "kept"]) + + def test_deep_nesting(self): + d = {} + for _ in range(200000): + d = {"next": d, 1: "x"} + del d + + def test_drained_dict(self): + d = {i: str(i) for i in range(50)} + items = list(d.items()) + self.assertEqual(items[7], (7, "7")) + d.clear() + self.assertEqual(len(d), 0) + e = dict.fromkeys("abc", []) + self.assertEqual(sorted(e), ["a", "b", "c"]) + + +class ListReleaseTests(unittest.TestCase): + def test_shared_strings(self): + strs = tuple("s%d" % i for i in range(100)) + before = [sys.getrefcount(s) for s in strs[:5]] + for _ in range(N): + lst = list(strs) + lst.append("tail") + del lst + self.assertEqual([sys.getrefcount(s) for s in strs[:5]], before) + + def test_death_order_with_shared_items(self): + Noted.log = [] + keep = Noted("kept") + lst = [keep, Noted("first"), "shared", keep, Noted("second")] + del lst + # (CPython releases a list's items last first; the order of the + # two deaths isn't what this checks.) + self.assertEqual(sorted(Noted.log), ["first", "second"]) + del keep + self.assertEqual(Noted.log[-1], "kept") + self.assertEqual(len(Noted.log), 3) + + def test_deep_nesting(self): + lst = [] + for _ in range(200000): + lst = [lst, "x"] + del lst + + +class TuplePoolTests(unittest.TestCase): + def test_reused_address(self): + ids = list(map(id, ((i, i) for i in range(10)))) + self.assertEqual(len(set(ids)), 1) + + def test_pairs_hold_their_items(self): + out = [] + for i, pair in enumerate(enumerate("abcdef" * 50)): + out.append(pair) + self.assertEqual(out[:2], [(0, "a"), (1, "b")]) + self.assertEqual(len(set(map(id, out))), len(out)) + d = {"k%d" % i: i for i in range(10)} + for _ in range(N): + items = [kv for kv in d.items()] + self.assertEqual(items[3], ("k3", 3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_container_repr_items.py b/tests/regrtest/test_container_repr_items.py new file mode 100644 index 000000000..517cfa3ff --- /dev/null +++ b/tests/regrtest/test_container_repr_items.py @@ -0,0 +1,22 @@ +"""Container reprs append plain items in place. + +Ints (both extremes), bools, `None` and printable ASCII strings without a +quote or backslash are written directly; strings that need escaping or +the other quote, non-ASCII text, floats and nested containers render as +before. +""" + +items = ["", "a b", "it's", 'say "hi"', "back\\slash", "tab\t", "é", "\x7f", + "~", " ", "\n", "x'y\"z", 0, -1, 2**63 - 1, -2**63, 10**20, True, + False, None, 1.5, -0.0, (1,), [], {}] +expected_list = ( + "['', 'a b', \"it's\", 'say \"hi\"', 'back\\\\slash', 'tab\\t', 'é', " + "'\\x7f', '~', ' ', '\\n', 'x\\'y\"z', 0, -1, 9223372036854775807, " + "-9223372036854775808, 100000000000000000000, True, False, None, 1.5, " + "-0.0, (1,), [], {}]" +) +assert repr(items) == expected_list, repr(items) +assert repr(tuple(items)) == "(" + expected_list[1:-1] + ")" +assert str({"k": 1, 2: None, "it's": False}) == "{'k': 1, 2: None, \"it's\": False}" +assert repr((5,)) == "(5,)" and repr([]) == "[]" and repr({}) == "{}" +print("ok") diff --git a/tests/regrtest/test_container_subclass_super_init.py b/tests/regrtest/test_container_subclass_super_init.py new file mode 100644 index 000000000..06aed064f --- /dev/null +++ b/tests/regrtest/test_container_subclass_super_init.py @@ -0,0 +1,59 @@ +"""`super().__init__(...)` in a `list`, `set` or `dict` subclass's `__init__`. + +Compiled code calls the container's own `__init__` body in place, so the +body must still iterate its argument through the interpreter (a generator, +a class with `__iter__` that raises), check its argument count and the +items' hashability, and replace what the container held before. Run it +past the compile threshold. +""" + + +class L(list): + def __init__(self, *args, **kw): + super().__init__(*args, **kw) + self.extra = 1 + + +class S(set): + def __init__(self, *args): + super().__init__(*args) + + +class D(dict): + def __init__(self, *args, **kw): + super().__init__(*args, **kw) + + +def gen(): + yield 1 + yield 2 + + +class Raises: + def __iter__(self): + raise ValueError("boom") + + +for _ in range(3000): + lst = L(gen()) + assert lst == [1, 2] and lst.extra == 1, lst + assert L((x for x in range(3))) == [0, 1, 2] + assert L() == [] + assert S([1, 2, 2]) == {1, 2} + assert D([("a", 1)], b=2) == {"a": 1, "b": 2} + for bad, exc, text in ( + (lambda: L(1), TypeError, "not iterable"), + (lambda: L([1], [2]), TypeError, "at most 1 argument"), + (lambda: S([[1]]), TypeError, "unhashable"), + (lambda: L(Raises()), ValueError, "boom"), + ): + try: + bad() + except exc as e: + assert text in str(e), e + else: + raise AssertionError("no error") + +again = L([5]) +again.__init__([7, 8]) +assert again == [7, 8], again diff --git a/tests/regrtest/test_containers_shared_across_blocking_calls.py b/tests/regrtest/test_containers_shared_across_blocking_calls.py new file mode 100644 index 000000000..d348f48cd --- /dev/null +++ b/tests/regrtest/test_containers_shared_across_blocking_calls.py @@ -0,0 +1,180 @@ +"""A container one thread is using while it blocks stays usable from others. + +A comparison or a `repr` that a container operation calls can block (a +sleep, a lock, a write), which gives the GIL to another thread in the +middle of that operation. The other thread's operations on the same +container then finish, with the results CPython gives: none of them +hangs waiting for the first thread while holding the GIL, and none is +lost. +""" + +import collections +import threading +import time +import unittest + +PAUSE = 0.15 +entered = threading.Event() + + +class Slow: + """Hashes alike with every other `Slow`; equality and `repr` block.""" + + def __repr__(self): + entered.set() + time.sleep(PAUSE) + return "slow" + + def __hash__(self): + return 1 + + def __eq__(self, other): + entered.set() + time.sleep(PAUSE) + return self is other + + +def slow_key(v): + entered.set() + time.sleep(PAUSE) + return v + + +class BlockedOperationTests(unittest.TestCase): + def both(self, holder, poke): + """`holder()` in one thread and, once it blocks, `poke()` in another.""" + entered.clear() + results = {} + + def a(): + try: + results["holder"] = holder() + except Exception as e: + results["holder"] = type(e) + + def b(): + self.assertTrue(entered.wait(10)) + try: + results["poke"] = poke() + except Exception as e: + results["poke"] = type(e) + + ta = threading.Thread(target=a, daemon=True) + tb = threading.Thread(target=b, daemon=True) + ta.start() + tb.start() + ta.join(30) + tb.join(30) + self.assertFalse(ta.is_alive(), "the blocked operation never finished") + self.assertFalse(tb.is_alive(), "the other thread's operation never finished") + return results + + def test_set_add_during_a_membership_test(self): + k1, k2 = Slow(), Slow() + s = {k1} + r = self.both(lambda: k2 in s, lambda: s.add(5)) + self.assertEqual(r, {"holder": False, "poke": None}) + self.assertEqual(len(s), 2) + self.assertIn(5, s) + + def test_set_discard_and_update_during_a_membership_test(self): + k1, k2 = Slow(), Slow() + s = {k1, 7} + r = self.both(lambda: k2 in s, lambda: s.discard(7)) + self.assertEqual(r["holder"], False) + self.assertNotIn(7, s) + r = self.both(lambda: k2 in s, lambda: s.add("x")) + self.assertIn("x", s) + self.assertEqual(len(s), 2) + + def test_several_threads_add_during_one_membership_test(self): + k1, k2 = Slow(), Slow() + s = {k1} + entered.clear() + found = [] + holder = threading.Thread(target=lambda: found.append(k2 in s), daemon=True) + holder.start() + self.assertTrue(entered.wait(10)) + adders = [threading.Thread(target=s.add, args=(i,), daemon=True) for i in range(8)] + for t in adders: + t.start() + for t in adders + [holder]: + t.join(30) + self.assertFalse(t.is_alive()) + self.assertEqual(found, [False]) + self.assertEqual(len(s), 9) + self.assertTrue(all(i in s for i in range(8))) + + def test_list_operations_during_a_count(self): + k1, k2 = Slow(), Slow() + lst = [k1, 2] + r = self.both(lambda: lst.count(k2), lambda: lst.append(9)) + self.assertEqual(r, {"holder": 0, "poke": None}) + self.assertEqual(lst[1:], [2, 9]) + r = self.both(lambda: lst.index(2), lambda: lst.pop()) + self.assertEqual(r, {"holder": 1, "poke": 9}) + self.assertEqual(len(lst), 2) + + def test_list_length_and_append_during_a_repr(self): + lst = [Slow(), 2, 3] + r = self.both(lambda: repr(lst), lambda: len(lst)) + self.assertEqual(r, {"holder": "[slow, 2, 3]", "poke": 3}) + r = self.both(lambda: repr(lst)[:6], lambda: lst.append(4)) + self.assertEqual(r["holder"], "[slow,") + self.assertEqual(lst[1:], [2, 3, 4]) + + def test_dict_stores_during_a_lookup_and_a_store(self): + k1, k2 = Slow(), Slow() + d = {k1: 1} + r = self.both(lambda: d.get(k2), lambda: d.__setitem__("x", 3)) + self.assertEqual(r, {"holder": None, "poke": None}) + self.assertEqual((len(d), d["x"]), (2, 3)) + r = self.both(lambda: d.__setitem__(k2, 2), lambda: d.__setitem__("y", 4)) + self.assertEqual((len(d), d["y"]), (4, 4)) + r = self.both(lambda: d.get(Slow()), lambda: len(d)) + self.assertEqual(r["poke"], 4) + + def test_deque_append_during_a_count(self): + k1, k2 = Slow(), Slow() + dq = collections.deque([k1, 2]) + r = self.both(lambda: dq.count(k2), lambda: dq.append(7)) + self.assertIs(r["holder"], RuntimeError) + self.assertEqual(list(dq)[1:], [2, 7]) + + def test_list_append_during_sorts(self): + lst = [3, 1, 2] + r = self.both(lambda: sorted(lst, key=slow_key), lambda: lst.append(0)) + self.assertEqual(r["holder"], [1, 2, 3]) + self.assertEqual(lst, [3, 1, 2, 0]) + r = self.both(lambda: lst.sort(key=slow_key), lambda: lst.append(-1)) + self.assertIs(r["holder"], ValueError) + + def test_a_busy_thread_beside_a_blocked_operation(self): + # The blocked thread gets the GIL back from a thread that never + # blocks, though it holds its container the whole time. + k1, k2 = Slow(), Slow() + s = {k1} + stop = False + spins = [0] + + def spin(): + while not stop: + spins[0] += 1 + + t = threading.Thread(target=spin, daemon=True) + t.start() + try: + t0 = time.monotonic() + for _ in range(5): + self.assertFalse(k2 in s) + took = time.monotonic() - t0 + finally: + stop = True + t.join(30) + self.assertFalse(t.is_alive()) + self.assertGreater(spins[0], 0) + self.assertLess(took, 20) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_contains_delitem_direct.py b/tests/regrtest/test_contains_delitem_direct.py new file mode 100644 index 000000000..31de77f01 --- /dev/null +++ b/tests/regrtest/test_contains_delitem_direct.py @@ -0,0 +1,176 @@ +"""Compiled `in` / `not in` tests call a class's Python `__contains__` +directly, and compiled `del obj[k]` its Python `__delitem__`; the +answers (a non-`bool` answer's truth included, a `__bool__` there too), +raises (caught in the frame or past it), the operands' lifetimes, and +methods replaced later match the general operators.""" + +import unittest +import weakref + + +class Bag: + def __init__(self, *items): + self.items = dict.fromkeys(items) + self.calls = 0 + + def __contains__(self, x): + self.calls += 1 + return x in self.items + + def __delitem__(self, k): + self.calls += 1 + del self.items[k] + + +class Answer: + def __init__(self, v): + self.v = v + + def __bool__(self): + return self.v + + +class Odd: + def __contains__(self, x): + if x == "raise": + raise KeyError(x) + if x == "answer": + return Answer(False) + return x if isinstance(x, int) else [] + + +class Tracked: + deleted = 0 + + def __del__(self): + Tracked.deleted += 1 + + +class ContainsDelitemDirect(unittest.TestCase): + def test_contains(self): + b = Bag("a", "b") + n = 0 + for i in range(3000): + if "a" in b: + n += 1 + if "z" in b: + n += 100 + if "z" not in b: + n += 1 + self.assertEqual(n, 6000) + self.assertEqual(b.calls, 9000) + + def test_contains_values(self): + b = Bag("a") + for i in range(2000): + self.assertIs("a" in b, True) + self.assertIs("q" not in b, True) + key = "a" if i % 2 else "b" + self.assertEqual(key in b, i % 2 == 1) + + def test_non_bool_answers(self): + o = Odd() + for i in range(1000): + self.assertIs(3 in o, True) + self.assertIs(0 in o, False) + self.assertIs("s" in o, False) + self.assertIs("s" not in o, True) + self.assertIs("answer" in o, False) + self.assertIs("answer" not in o, True) + + def test_contains_raises(self): + o = Odd() + n = 0 + for i in range(1000): + try: + if "raise" in o: + n += 100 + except KeyError: + n += 1 + self.assertEqual(n, 1000) + + def check(c, x): + return x in c + + for i in range(1000): + with self.assertRaises(KeyError): + check(o, "raise") + self.assertTrue(check(o, 1)) + + def test_delitem(self): + for _ in range(300): + b = Bag(*range(10)) + for k in range(0, 10, 2): + del b[k] + self.assertEqual(list(b.items), [1, 3, 5, 7, 9]) + self.assertEqual(b.calls, 5) + + def test_delitem_raises(self): + b = Bag() + n = 0 + for i in range(1000): + try: + del b[i] + except KeyError: + n += 1 + self.assertEqual(n, 1000) + + def drop(c, k): + del c[k] + return "after" + + for i in range(1000): + b.items[i] = i + self.assertEqual(drop(b, i), "after") + with self.assertRaises(KeyError): + drop(b, i) + + def test_lifetimes(self): + b = Bag() + for i in range(500): + b.items["t"] = Tracked() + del b["t"] + self.assertGreaterEqual(Tracked.deleted, 500) + t = Tracked() + r = weakref.ref(t) + b.items["t"] = t + del t + self.assertIsNotNone(r()) + del b["t"] + self.assertIsNone(r()) + probe = Tracked() + pr = weakref.ref(probe) + for i in range(500): + probe in b + del probe + self.assertIsNone(pr()) + + def test_replaced(self): + class C: + def __contains__(self, x): + return True + + def __delitem__(self, k): + self.last = k + + c = C() + n = 0 + for i in range(1000): + if i in c: + n += 1 + del c[i] + self.assertEqual((n, c.last), (1000, 999)) + C.__contains__ = lambda self, x: False + C.__delitem__ = lambda self, k: setattr(self, "last", -k) + for i in range(1000): + if i in c: + n += 100 + del c[i] + self.assertEqual((n, c.last), (1000, -999)) + del C.__contains__ + with self.assertRaises(TypeError): + 1 in c + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_contains_pure_eq.py b/tests/regrtest/test_contains_pure_eq.py new file mode 100644 index 000000000..c8751cc0e --- /dev/null +++ b/tests/regrtest/test_contains_pure_eq.py @@ -0,0 +1,119 @@ +"""`x in d`, `x in s` and `d.get(x)` of an instance whose class's Python +`__hash__` and `__eq__` evaluate frameless settle an equal but distinct +stored key in place; the answers, `not in`, hash collisions between +unequal keys, stored keys of other classes and kinds, an `__eq__` with +effects (called once per comparison, as CPython calls it), and an +`__eq__` that raises match the general lookup.""" + +import unittest + + +class P: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x = x + self.y = y + + def __hash__(self): + return hash((self.x, self.y)) + + def __eq__(self, o): + return isinstance(o, P) and self.x == o.x and self.y == o.y + + +class Collide: + def __init__(self, v): + self.v = v + + def __hash__(self): + return 11 + + def __eq__(self, o): + return isinstance(o, Collide) and self.v == o.v + + +class Counted: + eqs = 0 + + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, o): + Counted.eqs += 1 + return isinstance(o, Counted) and self.v == o.v + + +class Boom: + def __hash__(self): + return 5 + + def __eq__(self, o): + raise ValueError("eq") + + +class ContainsPureEq(unittest.TestCase): + def test_dict_and_sets(self): + d = {P(i, -i): i for i in range(20)} + s = set(d) + fs = frozenset(d) + for _ in range(200): + for i in range(25): + k = P(i, -i) + self.assertEqual(k in d, i < 20) + self.assertEqual(k in s, i < 20) + self.assertEqual(k in fs, i < 20) + self.assertEqual(k not in d, i >= 20) + self.assertEqual(d.get(k), i if i < 20 else None) + self.assertEqual(d.get(k, "dflt"), i if i < 20 else "dflt") + + def test_collisions(self): + d = {Collide(i): i for i in range(6)} + s = set(d) + for _ in range(300): + self.assertIn(Collide(4), d) + self.assertNotIn(Collide(9), d) + self.assertIn(Collide(0), s) + self.assertNotIn(Collide(-1), s) + self.assertEqual(d.get(Collide(5)), 5) + self.assertIsNone(d.get(Collide(7))) + + def test_mixed_stored_keys(self): + d = {P(1, 2): "p", hash((1, 2)): "int", "s": 1} + s = {P(1, 2), hash((1, 2))} + for _ in range(300): + self.assertIn(P(1, 2), d) + self.assertEqual(d.get(P(1, 2)), "p") + self.assertIn(P(1, 2), s) + self.assertNotIn(P(2, 1), d) + self.assertIn(hash((1, 2)), d) + + def test_eq_with_effects(self): + d = {Counted(i): i for i in range(5)} + s = set(d) + Counted.eqs = 0 + for _ in range(300): + self.assertIn(Counted(3), d) + self.assertIn(Counted(2), s) + self.assertEqual(d.get(Counted(1)), 1) + self.assertEqual(Counted.eqs, 900) + + def test_eq_raises(self): + b1 = Boom() + d = {b1: 1} + s = {b1} + for _ in range(300): + self.assertIn(b1, d) + with self.assertRaises(ValueError): + Boom() in d + with self.assertRaises(ValueError): + Boom() in s + with self.assertRaises(ValueError): + d.get(Boom()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_contextvar_get_compiled.py b/tests/regrtest/test_contextvar_get_compiled.py new file mode 100644 index 000000000..11bf06ca2 --- /dev/null +++ b/tests/regrtest/test_contextvar_get_compiled.py @@ -0,0 +1,58 @@ +"""ContextVar.get from compiled loops (an exact var's state read in +place): defaults given to the var and to get, LookupError for a var with +neither, values set and reset, values inside copy_context().run, and +values seen from another thread, each matching CPython.""" + +import contextvars +import threading +import unittest + +A = contextvars.ContextVar("a", default=1) +B = contextvars.ContextVar("b") + + +def gets(n, var, *default): + out = None + for i in range(n): + out = var.get(*default) + return out + + +class ContextVarGetTests(unittest.TestCase): + def test_defaults_and_errors(self): + for n in (1, 300): + self.assertEqual(gets(n, A), 1) + self.assertEqual(gets(n, B, "dflt"), "dflt") + with self.assertRaises(LookupError): + gets(n, B) + + def test_set_reset_and_contexts(self): + tok = A.set(5) + try: + self.assertEqual(gets(300, A), 5) + + def inner(): + A.set(9) + return gets(300, A) + + self.assertEqual(contextvars.copy_context().run(inner), 9) + self.assertEqual(gets(300, A), 5) + finally: + A.reset(tok) + self.assertEqual(gets(300, A), 1) + + def test_other_thread(self): + tok = A.set(7) + try: + seen = [] + th = threading.Thread(target=lambda: seen.append(gets(300, A))) + th.start() + th.join() + self.assertEqual(seen, [1]) + self.assertEqual(gets(300, A), 7) + finally: + A.reset(tok) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_counter_most_common_native.py b/tests/regrtest/test_counter_most_common_native.py new file mode 100644 index 000000000..1a583cbf7 --- /dev/null +++ b/tests/regrtest/test_counter_most_common_native.py @@ -0,0 +1,70 @@ +"""`Counter.most_common(n)` of plain int counts, natively. + +An exact `Counter` whose counts are all ints (or bools) gives its `n` +largest `(key, count)` pairs as `heapq.nlargest(n, self.items(), +key=itemgetter(1))` does: largest first, equal counts in insertion order. +Other counts, subclasses, a non-int `n`, and any call a trace hook watches +take the Python method. +""" + +import collections +import heapq +import operator +import sys +import unittest + + +def expected(c, n): + return heapq.nlargest(n, c.items(), key=operator.itemgetter(1)) + + +class MostCommonTests(unittest.TestCase): + def test_orders(self): + words = "the quick brown fox jumps over the lazy dog the fox".split() + c = collections.Counter(words) + for _ in range(100): + for n in (0, 1, 2, 3, 5, 50, -1): + self.assertEqual(c.most_common(n), expected(c, n)) + self.assertEqual(c.most_common(), sorted(c.items(), key=operator.itemgetter(1), reverse=True)) + ties = collections.Counter({"b": 2, "a": 2, "c": 2, "z": 3}) + self.assertEqual(ties.most_common(3), [("z", 3), ("b", 2), ("a", 2)]) + self.assertEqual(collections.Counter("abracadabra").most_common(3), [("a", 5), ("b", 2), ("r", 2)]) + neg = collections.Counter({"x": -1, "y": 0, "z": True}) + self.assertEqual(neg.most_common(2), expected(neg, 2)) + big = collections.Counter({i: i % 7 for i in range(500)}) + self.assertEqual(big.most_common(10), expected(big, 10)) + self.assertEqual(collections.Counter().most_common(3), []) + + def test_other_shapes(self): + f = collections.Counter({"a": 1.5, "b": 2}) + self.assertEqual(f.most_common(1), [("b", 2)]) + + class C(collections.Counter): + def items(self): + return [("only", 1)] + + self.assertEqual(C(a=3).most_common(1), [("only", 1)]) + c = collections.Counter("aab") + with self.assertRaises(TypeError): + c.most_common("2") + self.assertEqual(c.most_common(True), [("a", 2)]) + + def test_trace_sees_the_python_method(self): + seen = [] + + def tracer(frame, event, arg): + if event == "call": + seen.append(frame.f_code.co_name) + return None + + c = collections.Counter("aabbc") + sys.settrace(tracer) + try: + c.most_common(2) + finally: + sys.settrace(None) + self.assertIn("nlargest", seen) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_counter_runs_and_zip_views.py b/tests/regrtest/test_counter_runs_and_zip_views.py new file mode 100644 index 000000000..79bc003c7 --- /dev/null +++ b/tests/regrtest/test_counter_runs_and_zip_views.py @@ -0,0 +1,82 @@ +"""Counter(list) and Counter(tuple) count a run of plain keys under one +view of the dict, and list(zip(...)) of list and tuple cursors reads them +in place: counts and first-seen order, keys whose __eq__ runs Python +partway through, non-int counts already present, Counter.update over a +dict subclass, zips of unequal lengths with shared and partly consumed +cursors, each matching CPython.""" + +import collections +import unittest + + +class Key: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, Key) and self.v == other.v + + +class CounterRunTests(unittest.TestCase): + def test_counts_and_order(self): + words = "b a b c a b".split() + for i in range(300): + c = collections.Counter(words) + t = collections.Counter(tuple(words)) + self.assertEqual(c, {"b": 3, "a": 2, "c": 1}) + self.assertEqual(list(c), ["b", "a", "c"]) + self.assertEqual(t, c) + self.assertEqual(collections.Counter([1, 2, 1, True, 2.0]), {1: 3, 2: 2}) + + def test_mixed_keys(self): + k = Key(1) + items = ["x", "y", k, "x", Key(1), 3, 3] + c = collections.Counter(items) + self.assertEqual(c["x"], 2) + self.assertEqual(c[k], 2) + self.assertEqual(c[3], 2) + self.assertEqual(list(c), ["x", "y", k, 3]) + + def test_existing_counts(self): + c = collections.Counter({"a": 1.5, "b": 2}) + c.update(["b", "a", "b", "z"]) + self.assertEqual(c, {"a": 2.5, "b": 4, "z": 1}) + self.assertIsInstance(c["a"], float) + c.update(("z", "z")) + self.assertEqual(c["z"], 3) + + def test_subclass(self): + class C(collections.Counter): + pass + + c = C("abca") + c.update(["a", "q"]) + self.assertEqual(c, {"a": 3, "b": 1, "c": 1, "q": 1}) + + +class ZipViewTests(unittest.TestCase): + def test_lengths_and_cursors(self): + a = [1, 2, 3, 4] + b = (5, 6) + for i in range(300): + r = list(zip(a, b)) + m = list(zip(*[[1, 2], [3, 4], [5, 6]])) + self.assertEqual(r, [(1, 5), (2, 6)]) + self.assertEqual(m, [(1, 3, 5), (2, 4, 6)]) + x, y = iter(a), iter(b) + next(x) + self.assertEqual(list(zip(x, y)), [(2, 5), (3, 6)]) + self.assertEqual(list(x), []) + x, y = iter(b), iter(a) + self.assertEqual(list(zip(x, y)), [(5, 1), (6, 2)]) + self.assertEqual(list(y), [3, 4]) + s = iter(a) + self.assertEqual(list(zip(s, s)), [(1, 2), (3, 4)]) + self.assertEqual(list(zip([], a)), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_csv_reader_for_loops.py b/tests/regrtest/test_csv_reader_for_loops.py new file mode 100644 index 000000000..5f92ea147 --- /dev/null +++ b/tests/regrtest/test_csv_reader_for_loops.py @@ -0,0 +1,118 @@ +"""`for row in csv.reader(...)` loops that keep and step the reader in place. + +Compiled code keeps the reader itself for the loop (its `__iter__` +returns it) and reads each record as its `__next__` would, the end +reported with no `StopIteration`. Each case runs hot and must agree with +CPython: the records and `line_num`, records spanning lines, readers +stepped by hand between loop steps, readers resumed after a `break`, +text streams, and dialects. +""" + +import csv +import io +import unittest + +N = 400 + + +class CsvReaderForLoopTests(unittest.TestCase): + def test_records_and_line_num(self): + lines = ["a,b,c", "1,2,3", '"x, y",z,'] + + def run(): + out = None + for _ in range(N): + r = csv.reader(lines) + out = [] + for row in r: + out.append((r.line_num, row)) + out.append(r.line_num) + return out + + self.assertEqual( + run(), + [(1, ["a", "b", "c"]), (2, ["1", "2", "3"]), (3, ["x, y", "z", ""]), 3], + ) + + def test_record_spanning_lines(self): + lines = ['a,"multi', 'line",b', "c,d"] + + def run(): + out = None + for _ in range(N): + r = csv.reader(lines) + out = [(row, r.line_num) for row in r] + return out + + self.assertEqual(run(), [(["a", "multiline", "b"], 2), (["c", "d"], 3)]) + + def test_next_between_steps_and_resume(self): + lines = ["%d,%d" % (i, i * i) for i in range(6)] + + def run(): + out = None + for _ in range(N): + r = csv.reader(lines) + out = [] + for row in r: + out.append(row[0]) + out.append(next(r)[1]) + if row[0] == "2": + break + for row in r: + out.append(row) + out.append(next(r, "end")) + return out + + self.assertEqual(run(), ["0", "1", "2", "9", ["4", "16"], ["5", "25"], "end"]) + + def test_text_stream(self): + text = "h1,h2\r\nv1,v2\r\nv3,v4\r\n" + + def run(): + out = None + for _ in range(N): + out = [row for row in csv.reader(io.StringIO(text, newline=""))] + return out + + self.assertEqual(run(), [["h1", "h2"], ["v1", "v2"], ["v3", "v4"]]) + + def test_dialects(self): + lines = ["a;b;'c;d'", "1;2;3"] + + def run(): + out = None + for _ in range(N): + out = list(csv.reader(lines, delimiter=";", quotechar="'")) + out += [row for row in csv.reader(["1,2"], quoting=csv.QUOTE_NONNUMERIC)] + return out + + self.assertEqual(run(), [["a", "b", "c;d"], ["1", "2", "3"], [1.0, 2.0]]) + + def test_errors_inside_loop(self): + def run(): + caught = 0 + for _ in range(N): + try: + for row in csv.reader(["ok", 5]): + pass + except csv.Error: + caught += 1 + return caught + + self.assertEqual(run(), N) + + def test_dict_reader(self): + lines = ["k,v", "a,1", "b,2"] + + def run(): + out = None + for _ in range(N): + out = [(d["k"], d["v"]) for d in csv.DictReader(lines)] + return out + + self.assertEqual(run(), [("a", "1"), ("b", "2")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_csv_reader_plain_lines.py b/tests/regrtest/test_csv_reader_plain_lines.py new file mode 100644 index 000000000..e26f02760 --- /dev/null +++ b/tests/regrtest/test_csv_reader_plain_lines.py @@ -0,0 +1,175 @@ +"""The csv reader over a list or tuple of lines, a `StringIO` or a text file +yields what it yields over a generator of the same lines. + +Lines of plain and quoted fields are split directly and other one-line +records run through the parser in place; records that span +lines, lines the parser raises on, non-string items, and the quoting styles +that convert fields take the full path, as do records that run past a +stream's buffered block. Rows, errors, `line_num` and the stream's `tell()` +agree, past the compile threshold. +""" + +import csv +import io +import os +import tempfile +import unittest + +LINES = [ + "abc,12,3.5,hello world,x\n", + "a,b,c", + "a,b,\r\n", + ",,\r", + "\n", + "", + "one\n", + "x\ty;z\n", + 'p,"q,r",s\n', + 'p,q"r,s\n', + "p\\,q,r\n", + "héllo,wörld,日本\n", + "a,,b\n", + "a,b\nc\n", + "a,b\rc\n", + "a,b\n\n", + " a, b ,c \n", + "1,2.5,,x\n", + '"",""""\n', + '"a""b","c""",d\r\n', + '"a"b,c\n', + '"a\rb",c\n', + 'x,"y"\n', + '"x",\n', + '"x","y"', + 'a"b",c\n', + '"é,""ü""",日\n', + '"q"\r\r\n', + '"abc""\n', +] + +DIALECTS = [ + {}, + {"delimiter": "\t"}, + {"delimiter": ";"}, + {"quoting": csv.QUOTE_ALL}, + {"quoting": csv.QUOTE_NONE, "escapechar": "\\"}, + {"quoting": csv.QUOTE_NONE, "quotechar": None}, + {"escapechar": "\\"}, + {"quotechar": "'"}, + {"skipinitialspace": True}, + {"strict": True}, + {"quoting": csv.QUOTE_NONNUMERIC}, + {"quoting": csv.QUOTE_STRINGS}, + {"quoting": csv.QUOTE_NOTNULL}, + {"delimiter": "é"}, + {"doublequote": False}, + {"doublequote": False, "escapechar": "\\"}, + {"quotechar": "é"}, +] + + +def outcome(reader): + out = [] + while True: + try: + row = next(reader) + except StopIteration: + return out + except Exception as e: # noqa: BLE001 - compared below + out.append((type(e).__name__, str(e), reader.line_num)) + return out + out.append((row, reader.line_num)) + + +class PlainLineTests(unittest.TestCase): + def check(self, lines, **kw): + want = outcome(csv.reader((line for line in lines), **kw)) + self.assertEqual(outcome(csv.reader(list(lines), **kw)), want, (lines, kw)) + self.assertEqual(outcome(csv.reader(tuple(lines), **kw)), want, (lines, kw)) + + def test_each_line(self): + for _ in range(30): + for kw in DIALECTS: + for line in LINES: + self.check([line, "z,y\n", line], **kw) + + def test_known_rows(self): + for _ in range(200): + r = csv.reader(["a,b,c\n", "1,,3\r\n", "x,\n", "\n", 'q,"w,e"\n', "é,ü"]) + self.assertEqual(list(r), [["a", "b", "c"], ["1", "", "3"], ["x", ""], [], + ["q", "w,e"], ["é", "ü"]]) + self.assertEqual(r.line_num, 6) + + def test_records_across_lines(self): + for _ in range(50): + for kw in DIALECTS: + self.check(['a,"multi\n', 'line",x\n', "b,c\n"], **kw) + self.check(['"open\n'], **kw) + self.check(['"x"y,z\n', '"a""b",c\n', '"q"\n'], **kw) + self.check(["a\\\n", "b,c\n"], **kw) + + def test_bad_items(self): + r = csv.reader(["a,b\n", 7, "c\n"]) + self.assertEqual(next(r), ["a", "b"]) + with self.assertRaises(csv.Error): + next(r) + self.assertEqual(next(r), ["c"]) + + def test_field_limit(self): + old = csv.field_size_limit(8) + try: + for _ in range(50): + self.check(["abcdefgh\n", "abcdefghi\n", "a,bcdefgh\n"]) + with self.assertRaises(csv.Error): + list(csv.reader(["abcdefghi\n"])) + self.assertEqual(list(csv.reader(["abcdefgh\n"])), [["abcdefgh"]]) + finally: + csv.field_size_limit(old) + + def test_list_changes(self): + lines = ["a,b\n", "c,d\n"] + r = csv.reader(lines) + self.assertEqual(next(r), ["a", "b"]) + lines.append("e\n") + lines[1] = 'x,"y"\n' + self.assertEqual(list(r), [["x", "y"], ["e"]]) + self.assertEqual(r.line_num, 3) + + def test_streams(self): + parts = [] + for i in range(3000): + if i % 7 == 0: + parts.append('%d,"multi\nline %d",x\r\n' % (i, i)) + elif i % 5 == 0: + parts.append('%d,"q,""%d""",y\n' % (i, i)) + elif i % 11 == 0: + parts.append("\n") + else: + parts.append("%d,plain %d,é\n" % (i, i)) + text = "".join(parts) + for newline in ("", None): + want = outcome(csv.reader(line for line in io.StringIO(text, newline=newline))) + self.assertEqual(outcome(csv.reader(io.StringIO(text, newline=newline))), want) + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "rows.csv") + with open(path, "w", encoding="utf-8", newline="") as f: + f.write(text) + with open(path, encoding="utf-8", newline=newline) as f: + self.assertEqual(outcome(csv.reader(f)), want) + with open(path, encoding="utf-8", newline=newline) as f: + r = csv.reader(f) + next(r) + next(r) + with self.assertRaises(OSError): + f.tell() + self.assertEqual(f.readline(), "2,plain 2,é\n") + + def test_dict_reader(self): + lines = ["k,v\n"] + ["%d,%d\n" % (i, i * i) for i in range(500)] + rows = list(csv.DictReader(lines)) + self.assertEqual(rows[7], {"k": "7", "v": "49"}) + self.assertEqual(len(rows), 500) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_csv_rows_and_fspath.py b/tests/regrtest/test_csv_rows_and_fspath.py new file mode 100644 index 000000000..ea8c39a09 --- /dev/null +++ b/tests/regrtest/test_csv_rows_and_fspath.py @@ -0,0 +1,68 @@ +"""csv readers over lists and tuples from compiled loops (the first row, +line_num, the end, a caller-held source iterator left exhausted, a +record spanning lines, a non-str line's error), and os.fspath of +pathlib paths (before and after their string is cached, a subclass +overriding __fspath__ or __str__), each matching CPython.""" + +import csv +import os +import pathlib +import unittest + + +class Odd(pathlib.PurePosixPath): + def __fspath__(self): + return "odd" + + +class Shout(pathlib.PurePosixPath): + def __str__(self): + return "SHOUT" + + +class CsvFspathTests(unittest.TestCase): + def test_rows(self): + lines = ["a,b", "1,2"] + for _ in range(300): + r = csv.reader(lines) + self.assertEqual(r.line_num, 0) + self.assertEqual(next(r), ["a", "b"]) + self.assertEqual(r.line_num, 1) + self.assertEqual(list(r), [["1", "2"]]) + self.assertEqual(r.line_num, 2) + with self.assertRaises(StopIteration): + next(r) + self.assertEqual(list(csv.reader(("x",))), [["x"]]) + self.assertEqual(list(csv.reader(['"a\n', 'b",c'])), [["a\nb", "c"]]) + + def test_held_source(self): + for _ in range(300): + src = ["a"] + it = iter(src) + self.assertEqual(list(csv.reader(it)), [["a"]]) + src.append("b") + self.assertEqual(next(it, "end"), "end") + + def test_bad_line(self): + with self.assertRaises(csv.Error): + for _ in range(300): + list(csv.reader(["a", 1])) + + def test_fspath(self): + def run(n, p): + out = None + for i in range(n): + out = os.fspath(p) + return out + + for n in (1, 300): + p = pathlib.PurePosixPath("/usr", "lib") + self.assertEqual(run(n, p), "/usr/lib") + self.assertEqual(run(n, pathlib.PurePosixPath("/x")), "/x") + self.assertEqual(run(n, Odd("/y")), "odd") + self.assertEqual(run(n, Shout("/z")), "SHOUT") + self.assertEqual(run(n, pathlib.Path("/tmp")), "/tmp") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_csv_rows_of_plain_values.py b/tests/regrtest/test_csv_rows_of_plain_values.py new file mode 100644 index 000000000..7322489d6 --- /dev/null +++ b/tests/regrtest/test_csv_rows_of_plain_values.py @@ -0,0 +1,85 @@ +"""`csv.writer.writerow` of rows of strings, numbers, bools and `None`. + +Lists and tuples of plain values write what CPython writes under every +quoting mode; a bool is `True` or `False`, quoted under +`QUOTE_NONNUMERIC` only as a number would be; a row with an object whose +`__str__` changes the row being written sees the change, as iterating it +live does; any iterable is a row; a non-iterable is a `csv.Error`. +""" + +import csv +import io +import unittest + + +def write(rows, **kw): + f = io.StringIO() + w = csv.writer(f, **kw) + for row in rows: + w.writerow(row) + return f.getvalue() + + +ROWS = [ + [1, "text", 1.5], + (0, -7, 2**40, 1e300, -0.0, float("inf")), + [True, False, None, ""], + ["a,b", 'q"uote', "line\nbreak", " space "], + [], + [None], + [""], +] + + +class PlainRowTests(unittest.TestCase): + def test_modes(self): + expected = { + csv.QUOTE_MINIMAL: ( + '1,text,1.5\r\n0,-7,1099511627776,1e+300,-0.0,inf\r\n' + 'True,False,,\r\n"a,b","q""uote","line\nbreak", space \r\n' + '\r\n""\r\n""\r\n' + ), + csv.QUOTE_ALL: ( + '"1","text","1.5"\r\n"0","-7","1099511627776","1e+300","-0.0","inf"\r\n' + '"True","False","",""\r\n"a,b","q""uote","line\nbreak"," space "\r\n' + '\r\n""\r\n""\r\n' + ), + csv.QUOTE_NONNUMERIC: ( + '1,"text",1.5\r\n0,-7,1099511627776,1e+300,-0.0,inf\r\n' + 'True,False,"",""\r\n"a,b","q""uote","line\nbreak"," space "\r\n' + '\r\n""\r\n""\r\n' + ), + } + for mode, want in expected.items(): + self.assertEqual(write(ROWS, quoting=mode), want, mode) + got = write([[1, "a", None, ""], ["b"]], quoting=csv.QUOTE_STRINGS) + self.assertEqual(got, '1,"a",,""\r\n"b"\r\n') + got = write([[1, "a", None, ""]], quoting=csv.QUOTE_NOTNULL) + self.assertEqual(got, '"1","a",,""\r\n') + with self.assertRaises(csv.Error): + write([[None]], quoting=csv.QUOTE_NONE) + + def test_live_iteration(self): + row = [1, None, 3] + + class Grow: + def __str__(self): + row.append("added") + return "g" + + row[1] = Grow() + self.assertEqual(write([row]), "1,g,3,added\r\n") + + def test_other_iterables(self): + self.assertEqual(write([(x for x in (1, 2)), range(3), "ab"]), "1,2\r\n0,1,2\r\na,b\r\n") + with self.assertRaises(csv.Error): + write([5]) + + def test_round_trip(self): + rows = [[str(i), "text", "1.5"] for i in range(300)] + text = write(rows) + self.assertEqual(list(csv.reader(io.StringIO(text))), rows) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_ctor_keyword_binding.py b/tests/regrtest/test_ctor_keyword_binding.py new file mode 100644 index 000000000..47cd60027 --- /dev/null +++ b/tests/regrtest/test_ctor_keyword_binding.py @@ -0,0 +1,63 @@ +"""Constructor calls with keyword arguments from compiled code. + +Compiled code binds `C(a, b=x)` straight into `__init__`'s locals by a +permutation of the keywords it remembers per function and names tuple. +These loops check other keyword orders, keyword-only parameters with +defaults, reassigned defaults, and the errors for a missing or +unexpected keyword. +""" + +import unittest + +N = 3000 + + +class P: + def __init__(self, name, kind, *, default=None, annotation="ann"): + self.r = (name, kind, default, annotation) + + +class Q: + def __init__(self, a, b=2, c=3): + self.r = (a, b, c) + + +class CtorKeywordTests(unittest.TestCase): + def test_orders_and_defaults(self): + for i in range(N): + r = (P("a", 1, default=i).r, P("b", 2, annotation=i).r, + P("c", 3, annotation=1, default=2).r, P(kind=4, name="d").r, + Q(1, c=i).r, Q(c=5, a=6).r) + self.assertEqual(r, (("a", 1, N - 1, "ann"), ("b", 2, None, N - 1), + ("c", 3, 2, 1), ("d", 4, None, "ann"), + (1, 2, N - 1), (6, 2, 5))) + + def test_reassigned_defaults(self): + class R: + def __init__(self, a, *, k=1, j=2): + self.r = (a, k, j) + + for i in range(N): + r = R(i, j=0).r + self.assertEqual(r, (N - 1, 1, 0)) + R.__init__.__kwdefaults__ = {"k": 10, "j": 20} + for i in range(N): + r = R(i, j=0).r + self.assertEqual(r, (N - 1, 10, 0)) + R.__init__.__kwdefaults__ = None + with self.assertRaises(TypeError): + R(1, j=0) + + def test_errors(self): + for i in range(N): + Q(1, b=i) + with self.assertRaises(TypeError): + Q(b=1) + with self.assertRaises(TypeError): + Q(1, d=1) + with self.assertRaises(TypeError): + P("x", 1, default=1, default2=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dataclass_asdict_native.py b/tests/regrtest/test_dataclass_asdict_native.py new file mode 100644 index 000000000..1591e1be4 --- /dev/null +++ b/tests/regrtest/test_dataclass_asdict_native.py @@ -0,0 +1,150 @@ +"""dataclasses.asdict over trees of plain values, nested dataclasses and +exact containers, from compiled loops: fresh copies of every container, +fields in order, ClassVar and InitVar left out, and the Python path still +taking what the native copy declines (a namedtuple, a set, an enum, a +custom dict_factory, a slots dataclass, a deleted field, a property +field, a cycle, a profiler watching), each matching CPython.""" + +import collections +import dataclasses +import enum +import sys +import unittest +from typing import ClassVar + + +@dataclasses.dataclass +class Inner: + a: int + b: str = "x" + + +@dataclasses.dataclass +class Outer: + name: str + inner: Inner + items: list = dataclasses.field(default_factory=list) + meta: dict = dataclasses.field(default_factory=dict) + pair: tuple = (1, 2) + count: ClassVar[int] = 0 + flag: bool = False + ratio: float = 0.5 + blob: bytes = b"" + nothing: object = None + + +NT = collections.namedtuple("NT", "p q") + + +class Color(enum.Enum): + RED = 1 + + +@dataclasses.dataclass +class Mixed: + nt: NT + tags: set + color: Color + + +@dataclasses.dataclass(slots=True) +class Slotted: + a: int + b: list + + +@dataclasses.dataclass +class WithInit: + a: int + scale: dataclasses.InitVar[int] = 1 + + def __post_init__(self, scale): + self.a *= scale + + +def copies(n, obj, **kw): + out = None + for i in range(n): + out = dataclasses.asdict(obj, **kw) + return out + + +class AsdictTests(unittest.TestCase): + def test_plain_tree(self): + inner = Inner(1) + o = Outer("o", inner, [Inner(2, "y"), [3, (4, Inner(5))]], {"k": Inner(6), 7: [8]}) + want = { + "name": "o", + "inner": {"a": 1, "b": "x"}, + "items": [{"a": 2, "b": "y"}, [3, (4, {"a": 5, "b": "x"})]], + "meta": {"k": {"a": 6, "b": "x"}, 7: [8]}, + "pair": (1, 2), + "flag": False, + "ratio": 0.5, + "blob": b"", + "nothing": None, + } + for n in (1, 300): + got = copies(n, o) + self.assertEqual(got, want) + self.assertEqual(list(got), list(want)) + self.assertIsNot(got["items"], o.items) + self.assertIsNot(got["meta"][7], o.meta[7]) + self.assertIs(type(got["pair"]), tuple) + + def test_declined_shapes(self): + m = Mixed(NT(1, Inner(2)), {1, 2}, Color.RED) + for n in (1, 300): + got = copies(n, m) + self.assertEqual(got, {"nt": NT(1, {"a": 2, "b": "x"}), "tags": {1, 2}, "color": Color.RED}) + self.assertIs(type(got["nt"]), NT) + self.assertIsNot(got["tags"], m.tags) + got = copies(n, Inner(1), dict_factory=collections.OrderedDict) + self.assertIs(type(got), collections.OrderedDict) + s = Slotted(1, [2]) + self.assertEqual(copies(n, s), {"a": 1, "b": [2]}) + self.assertEqual(copies(n, WithInit(2, 3)), {"a": 6}) + + def test_deleted_field_and_cycle(self): + i = Inner(1) + del i.a + with self.assertRaises(AttributeError): + copies(300, i) + o = Outer("c", Inner(1)) + o.items.append(o.items) + with self.assertRaises(RecursionError): + copies(1, o) + + def test_property_field(self): + @dataclasses.dataclass + class P: + x: int + + P.x = property(lambda self: 42, lambda self, v: None) + p = P(1) + self.assertEqual(copies(300, p), {"x": 42}) + + def test_errors(self): + with self.assertRaises(TypeError): + dataclasses.asdict(Inner) + with self.assertRaises(TypeError): + dataclasses.asdict(3) + + def test_profiler_sees_python_copy(self): + copies(300, Inner(1)) + seen = [] + + def prof(frame, event, arg): + if event == "call": + seen.append(frame.f_code.co_name) + + sys.setprofile(prof) + try: + dataclasses.asdict(Inner(1)) + finally: + sys.setprofile(None) + self.assertIn("_asdict_inner", seen) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_datetime_time_values_native.py b/tests/regrtest/test_datetime_time_values_native.py new file mode 100644 index 000000000..e271f4197 --- /dev/null +++ b/tests/regrtest/test_datetime_time_values_native.py @@ -0,0 +1,441 @@ +"""`datetime.time` values are built, read, hashed, compared and formatted +natively; `datetime.time()`, `timetz()`, `combine()`, `date.fromordinal()` +and `str()` of the date types run natively; dates and times hash natively +as dict keys; a field of a date held in a global is read in compiled code; +`setattr()` stores into a `__slots__` member in place. Each matches the +Python implementation, and every other shape still reaches it.""" + +import copy +import pickle +import unittest +import weakref +from datetime import date, datetime, time, timedelta, timezone + +N = 300 + +UTC = timezone.utc +PLUS1 = timezone(timedelta(hours=1)) +MINUS5 = timezone(timedelta(hours=-5, minutes=-30)) + +G_DATE = date(2024, 5, 17) +G_DT = datetime(2024, 5, 17, 13, 45, 12, 99) +G_TIME = time(13, 45, 12, 99) + + +class Holder: + def __init__(self): + self.d = G_DATE + self.t = G_TIME + + +class MyTime(time): + pass + + +class LoudDate(date): + def __hash__(self): + return 7 + + +class TimeConstruction(unittest.TestCase): + def test_positional_and_keyword_forms(self): + for _ in range(N): + a = time(1, 2, 3, 4) + b = time(hour=1, minute=2, second=3, microsecond=4) + c = time(1, 2, second=3, microsecond=4, fold=1) + d = time() + e = time(23, 59, 59, 999999, UTC) + f = time(7, tzinfo=PLUS1) + self.assertEqual((a.hour, a.minute, a.second, a.microsecond), (1, 2, 3, 4)) + self.assertEqual(a, b) + self.assertEqual((c.fold, a.fold), (1, 0)) + self.assertEqual((d.hour, d.minute, d.second, d.microsecond, d.tzinfo), (0, 0, 0, 0, None)) + self.assertIs(e.tzinfo, UTC) + self.assertIs(f.tzinfo, PLUS1) + self.assertIs(type(a), time) + self.assertEqual(repr(a), "datetime.time(1, 2, 3, 4)") + self.assertEqual(repr(c), "datetime.time(1, 2, 3, 4, fold=1)") + + def test_errors_are_the_constructors(self): + for bad in ((24,), (0, 60), (0, 0, 60), (0, 0, 0, 1000000), (-1,)): + for _ in range(5): + with self.assertRaises(ValueError): + time(*bad) + for _ in range(5): + with self.assertRaises(ValueError): + time(1, fold=2) + with self.assertRaises(TypeError): + time("1") + with self.assertRaises(TypeError): + time(1.5) + with self.assertRaises(TypeError): + time(1, 2, 3, 4, "utc") + with self.assertRaises(TypeError): + time(1, 2, 3, 4, None, 1) + with self.assertRaises(TypeError): + time(1, hour=2) + with self.assertRaises(TypeError): + time(1, nope=2) + + def test_other_argument_types(self): + class I(int): + pass + + class Idx: + def __index__(self): + return 9 + + for _ in range(N): + a, b, c = time(True, False), time(I(3), I(4)), time(Idx()) + self.assertEqual((a.hour, a.minute, b.hour, b.minute, c.hour), (1, 0, 3, 4, 9)) + + def test_subclass_and_pickle(self): + for _ in range(N): + m = MyTime(1, 2, 3) + self.assertIs(type(m), MyTime) + self.assertEqual(m, time(1, 2, 3)) + t = time(1, 2, 3, 4, PLUS1, fold=1) + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + u = pickle.loads(pickle.dumps(t, proto)) + self.assertEqual((u, u.tzinfo, u.microsecond), (t, PLUS1, 4)) + self.assertEqual(copy.copy(t), t) + self.assertEqual(copy.deepcopy(t), t) + + def test_fields_are_read_only(self): + t = time(1, 2, 3) + with self.assertRaises(AttributeError): + t.hour = 5 + self.assertEqual(t.hour, 1) + + def test_replace(self): + t = time(1, 2, 3, 4, UTC) + for _ in range(N): + u, v = t.replace(hour=5), t.replace(tzinfo=None, fold=1) + self.assertEqual((u.hour, u.minute, u.tzinfo), (5, 2, UTC)) + self.assertEqual((v.tzinfo, v.fold, v.second), (None, 1, 3)) + + +class TimeHashAndCompare(unittest.TestCase): + def test_hash(self): + a, b = time(1, 2, 3, 4), time(1, 2, 3, 4, fold=1) + for _ in range(N): + ha, hb, hc = hash(a), hash(b), hash(time(1, 2, 3, 4)) + self.assertEqual(ha, hb) + self.assertEqual(ha, hc) + self.assertEqual(ha, a.__hash__()) + self.assertEqual(ha, hash(bytes([1, 2, 3, 0, 0, 4]))) + self.assertNotEqual(hash(time(1, 2, 3, 5)), ha) + + def test_hash_with_zones(self): + for _ in range(N): + hu, hp = hash(time(1, 2, 3, tzinfo=UTC)), hash(time(2, 2, 3, tzinfo=PLUS1)) + # (Equal values hash equal; what an aware time's hash is built + # from differs between CPython's C and Python implementations.) + self.assertEqual(hp, hu) + self.assertEqual(time(2, 2, 3, tzinfo=PLUS1), time(1, 2, 3, tzinfo=UTC)) + self.assertEqual(hu, time(1, 2, 3, tzinfo=UTC).__hash__()) + late = time(0, 30, tzinfo=PLUS1) + self.assertEqual(hash(late), late.__hash__()) + self.assertEqual(hash(late), hash(time(0, 30, tzinfo=PLUS1))) + + def test_as_dict_and_set_keys(self): + d = {time(1, 2): "a", time(3, 4): "b"} + s = {time(1, 2), time(3, 4, tzinfo=UTC)} + hits = 0 + for _ in range(N): + hits += d[time(1, 2)] == "a" + hits += time(3, 4) in d + hits += time(1, 2) in s + hits += time(4, 4, tzinfo=PLUS1) in s + hits += time(9) not in s + self.assertEqual(hits, 5 * N) + + def test_compare(self): + a, b = time(1, 2, 3), time(1, 2, 4) + for _ in range(N): + got = (a < b, a <= b, a > b, a >= b, a == b, a != b, a == time(1, 2, 3)) + self.assertEqual(got, (True, True, False, False, False, True, True)) + self.assertEqual(time(1, fold=1), time(1)) + self.assertEqual(sorted([b, a, time(0, 59)]), [time(0, 59), a, b]) + self.assertEqual(max(a, b), b) + + def test_compare_zones(self): + u, p = time(1, 2, 3, tzinfo=UTC), time(2, 2, 3, tzinfo=PLUS1) + m = time(1, 2, 3, tzinfo=MINUS5) + for _ in range(N): + got = (u == p, u < p, u <= p, u < m, u == m, u == time(1, 2, 3, tzinfo=UTC)) + self.assertEqual(got, (True, False, True, True, False, True)) + naive = time(1, 2, 3) + for _ in range(5): + self.assertFalse(naive == u) + self.assertTrue(naive != u) + with self.assertRaises(TypeError): + naive < u + + def test_compare_other_types(self): + t = time(1) + for _ in range(5): + self.assertFalse(t == 1) + self.assertTrue(t != "01:00:00") + self.assertFalse(t == G_DT) + with self.assertRaises(TypeError): + t < 1 + with self.assertRaises(TypeError): + t >= G_DATE + self.assertTrue(MyTime(1) == t) + self.assertTrue(t <= MyTime(1)) + + +class TimeText(unittest.TestCase): + def test_isoformat_and_str(self): + cases = [ + (time(1, 2, 3), "01:02:03"), + (time(1, 2, 3, 4), "01:02:03.000004"), + (time(23, 59), "23:59:00"), + (time(1, 2, 3, tzinfo=UTC), "01:02:03+00:00"), + (time(1, 2, 3, 4, MINUS5), "01:02:03.000004-05:30"), + (time(1, 2, 3, tzinfo=timezone(timedelta(seconds=3661))), "01:02:03+01:01:01"), + ] + for t, want in cases: + for _ in range(N // 10): + got = (t.isoformat(), str(t), "%s" % t, f"{t}") + self.assertEqual(got, (want, want, want, want)) + + def test_timespec_forms(self): + t = time(1, 2, 3, 4567) + for _ in range(N): + got = ( + t.isoformat("hours"), + t.isoformat(timespec="minutes"), + t.isoformat("milliseconds"), + t.isoformat(timespec="microseconds"), + ) + self.assertEqual(got, ("01", "01:02", "01:02:03.004", "01:02:03.004567")) + with self.assertRaises(ValueError): + t.isoformat("days") + self.assertEqual(MyTime(1, 2).isoformat(), "01:02:00") + + +class DatetimeParts(unittest.TestCase): + def test_time_and_timetz(self): + aware = datetime(2024, 5, 17, 13, 45, 12, 99, PLUS1, fold=1) + for _ in range(N): + a, b, c, d = G_DT.time(), G_DT.timetz(), aware.time(), aware.timetz() + self.assertEqual(a, time(13, 45, 12, 99)) + self.assertEqual((a.tzinfo, b.tzinfo, c.tzinfo), (None, None, None)) + self.assertIs(d.tzinfo, PLUS1) + self.assertEqual((c.fold, d.fold, a.fold), (1, 1, 0)) + self.assertIs(type(a), time) + self.assertEqual(d, time(13, 45, 12, 99, PLUS1)) + + def test_combine(self): + t, tz = time(1, 2, 3, 4), time(1, 2, 3, 4, PLUS1, fold=1) + for _ in range(N): + a = datetime.combine(G_DATE, t) + b = datetime.combine(G_DATE, tz) + c = datetime.combine(G_DT, t) + d = datetime.combine(G_DATE, tz, None) + e = datetime.combine(G_DATE, t, tzinfo=UTC) + self.assertEqual(a, datetime(2024, 5, 17, 1, 2, 3, 4)) + self.assertEqual((b.tzinfo, b.fold, b.hour), (PLUS1, 1, 1)) + self.assertEqual(c, a) + self.assertIsNone(d.tzinfo) + self.assertIs(e.tzinfo, UTC) + self.assertIs(type(a), datetime) + for bad in ((1, t), (G_DATE, 1), (G_DATE, G_DT)): + with self.assertRaises(TypeError): + datetime.combine(*bad) + + class Sub(datetime): + pass + + self.assertIs(type(Sub.combine(G_DATE, t)), Sub) + + def test_fromordinal(self): + n = G_DATE.toordinal() + for i in range(N): + d = date.fromordinal(n + (i & 7)) + self.assertEqual(d, G_DATE + timedelta(days=(N - 1) & 7)) + self.assertIs(type(d), date) + self.assertEqual(date.fromordinal(1), date.min) + self.assertEqual(date.fromordinal(date.max.toordinal()), date.max) + self.assertEqual(datetime.fromordinal(n), datetime(2024, 5, 17)) + self.assertIs(type(datetime.fromordinal(n)), datetime) + for bad in (0, -5, date.max.toordinal() + 1): + with self.assertRaises((ValueError, OverflowError)): + date.fromordinal(bad) + with self.assertRaises(TypeError): + date.fromordinal("1") + + def test_str(self): + aware = datetime(2024, 5, 17, 1, 2, 3, tzinfo=MINUS5) + for _ in range(N): + got = (str(G_DATE), str(G_DT), str(aware), "%s|%s" % (G_DATE, G_DT), f"{G_DATE}") + self.assertEqual( + got, + ( + "2024-05-17", + "2024-05-17 13:45:12.000099", + "2024-05-17 01:02:03-05:30", + "2024-05-17|2024-05-17 13:45:12.000099", + "2024-05-17", + ), + ) + + class T(datetime): + def isoformat(self, sep="T", timespec="auto"): + return "mine" + sep + + self.assertEqual(str(T(2024, 1, 2)), "mine ") + + +class HashedDateValues(unittest.TestCase): + def test_hash_matches_the_method(self): + td = timedelta(days=3, seconds=17, microseconds=5) + aware = datetime(2024, 5, 17, 13, tzinfo=PLUS1) + for v in (G_DATE, G_DT, G_TIME, td, aware, date.min, datetime.max, timedelta(0)): + for _ in range(N // 10): + h = hash(v) + self.assertEqual(h, v.__hash__()) + self.assertEqual(h, hash(copy.copy(v))) + self.assertEqual(h, hash(pickle.loads(pickle.dumps(v)))) + + def test_equal_values_hash_equal(self): + a = datetime(2024, 5, 17, 13, tzinfo=PLUS1) + b = datetime(2024, 5, 17, 12, tzinfo=UTC) + for _ in range(N): + ha, hb = hash(a), hash(b) + self.assertEqual(a, b) + self.assertEqual(ha, hb) + self.assertEqual(hash(timedelta(hours=24)), hash(timedelta(days=1))) + self.assertEqual(hash(date(2024, 5, 17)), hash(G_DATE)) + + def test_dict_and_set_keys(self): + days = {date(2024, 5, d): d for d in range(1, 29)} + stamps = {datetime(2024, 5, 17, h) for h in range(24)} + spans = {timedelta(hours=h): h for h in range(24)} + total = 0 + for i in range(N): + d = 1 + i % 28 + total += days[date(2024, 5, d)] == d + total += date(2024, 6, d) not in days + total += datetime(2024, 5, 17, i % 24) in stamps + total += spans[timedelta(minutes=60 * (i % 24))] == i % 24 + total += days.get(G_DATE) == 17 + self.assertEqual(total, 5 * N) + + def test_subclass_hash_is_its_own(self): + d = {LoudDate(2024, 5, 17): "loud"} + for _ in range(N): + h = hash(LoudDate(2024, 5, 17)) + self.assertEqual(h, 7) + self.assertEqual(d[LoudDate(2024, 5, 17)], "loud") + self.assertNotEqual(hash(G_DATE), 7) + + +class FieldsOfHeldValues(unittest.TestCase): + def test_global_and_attribute_receivers(self): + h = Holder() + total = 0 + for _ in range(N): + total += G_DATE.year + G_DATE.month + G_DATE.day + total += G_DT.hour + G_DT.minute + G_DT.second + G_DT.microsecond + total += G_TIME.hour + G_TIME.minute + G_TIME.second + G_TIME.microsecond + G_TIME.fold + total += h.d.year + h.t.hour + self.assertEqual(total, N * (2024 + 5 + 17 + 13 + 45 + 12 + 99 + 13 + 45 + 12 + 99 + 2024 + 13)) + self.assertIsNone(G_TIME.tzinfo) + self.assertIsNone(h.t.tzinfo) + + def test_subclass_property_override(self): + class Odd(time): + @property + def hour(self): + return -1 + + o = Odd(5, 6) + for _ in range(N): + got = (o.hour, o.minute) + self.assertEqual(got, (-1, 6)) + + +class Slotted: + __slots__ = ("x", "y", "__weakref__") + + +class SlottedChild(Slotted): + __slots__ = ("z",) + + +class Guarded: + __slots__ = ("_v",) + + @property + def v(self): + return self._v + + @v.setter + def v(self, value): + self._v = value * 2 + + +class Target: + pass + + +class SetattrOnSlots(unittest.TestCase): + def test_stores_by_name(self): + s = Slotted() + names = ("x", "y") + for i in range(N): + for name in names: + setattr(s, name, i) + setattr(s, "x", [i]) + self.assertEqual((s.x, s.y), ([N - 1], N - 1)) + + def test_inherited_and_own_slots(self): + c = SlottedChild() + for i in range(N): + setattr(c, "x", i) + setattr(c, "z", i + 1) + self.assertEqual((c.x, c.z), (N - 1, N)) + with self.assertRaises(AttributeError): + setattr(c, "missing", 1) + with self.assertRaises(AttributeError): + c.y + + def test_property_setter_still_runs(self): + g = Guarded() + for i in range(N): + setattr(g, "v", i) + setattr(g, "_v", g._v + 1) + self.assertEqual(g.v, 2 * (N - 1) + 1) + + def test_old_value_is_released(self): + s = Slotted() + refs = [] + for _ in range(50): + t = Target() + refs.append(weakref.ref(t)) + setattr(s, "x", t) + del t + self.assertEqual(sum(r() is not None for r in refs), 1) + setattr(s, "x", None) + self.assertEqual(sum(r() is not None for r in refs), 0) + + def test_setattr_hook_is_asked(self): + class Hooked: + __slots__ = ("a", "log") + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) + if name != "log": + object.__setattr__(self, "log", name) + + h = Hooked() + for i in range(N): + setattr(h, "a", i) + self.assertEqual((h.a, h.log), (N - 1, "a")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_decimal_context_copies.py b/tests/regrtest/test_decimal_context_copies.py new file mode 100644 index 000000000..45b0a826a --- /dev/null +++ b/tests/regrtest/test_decimal_context_copies.py @@ -0,0 +1,86 @@ +"""`decimal.Context.copy()` and `localcontext()` make independent contexts. + +A copy has the source's precision, rounding, exponent limits, capitals, +clamp, flags and traps; changing the copy's values, flags or traps leaves +the source alone and the other way round; the copy's flag and trap +mappings are valid signal dicts of their own; a subclass's copy is a plain +`Context`; and arithmetic under `localcontext()` sees the local settings +and restores the outer ones. +""" + +import copy +import decimal +import unittest +from decimal import Context, Decimal, Inexact, Rounded, DivisionByZero + + +class ContextCopyTests(unittest.TestCase): + def test_values(self): + c = Context(prec=12, rounding=decimal.ROUND_DOWN, Emin=-99, Emax=99, + capitals=0, clamp=1, traps=[DivisionByZero], flags=[Inexact]) + for d in (c.copy(), copy.copy(c), c.__copy__()): + self.assertIs(type(d), Context) + self.assertEqual((d.prec, d.rounding, d.Emin, d.Emax, d.capitals, d.clamp), + (12, decimal.ROUND_DOWN, -99, 99, 0, 1)) + self.assertTrue(d.traps[DivisionByZero]) + self.assertFalse(d.traps[Inexact]) + self.assertTrue(d.flags[Inexact]) + self.assertFalse(d.flags[Rounded]) + self.assertEqual(repr(d), repr(c)) + self.assertIsNot(d.flags, c.flags) + self.assertIsNot(d.traps, c.traps) + self.assertEqual(len(d.flags), len(c.flags)) + self.assertEqual(dict(d.traps), dict(c.traps)) + + def test_independent(self): + c = Context(prec=10) + d = c.copy() + d.prec = 5 + d.traps[Inexact] = True + d.flags[Rounded] = True + self.assertEqual(c.prec, 10) + self.assertFalse(c.traps[Inexact]) + self.assertFalse(c.flags[Rounded]) + c.clear_flags() + d.clear_traps() + self.assertTrue(d.flags[Rounded]) + self.assertFalse(d.traps[DivisionByZero]) + self.assertTrue(c.traps[DivisionByZero]) + with self.assertRaises(ValueError): + d.prec = 0 + with self.assertRaises(KeyError): + d.traps["nope"] = 1 + + def test_subclass(self): + class MyContext(Context): + pass + + c = MyContext(prec=7) + d = c.copy() + self.assertIs(type(d), Context) + self.assertEqual(d.prec, 7) + + def test_localcontext(self): + decimal.setcontext(Context(prec=28)) + outer = decimal.getcontext() + for _ in range(200): + with decimal.localcontext() as ctx: + ctx.prec = 5 + self.assertEqual(str(Decimal(1) / Decimal(3)), "0.33333") + self.assertIs(decimal.getcontext(), ctx) + self.assertIs(decimal.getcontext(), outer) + self.assertEqual(str(Decimal(1) / Decimal(3)), "0.3333333333333333333333333333") + with decimal.localcontext(prec=3, rounding=decimal.ROUND_UP) as ctx: + self.assertEqual(str(Decimal("1.001") + 0), "1.01") + with decimal.localcontext() as ctx: + ctx.traps[DivisionByZero] = True + with self.assertRaises(DivisionByZero): + Decimal(1) / 0 + ctx.traps[DivisionByZero] = False + self.assertEqual(str(Decimal(1) / 0), "Infinity") + self.assertTrue(ctx.flags[DivisionByZero]) + self.assertFalse(outer.flags[DivisionByZero]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_decimal_context_memo.py b/tests/regrtest/test_decimal_context_memo.py new file mode 100644 index 000000000..493e68c66 --- /dev/null +++ b/tests/regrtest/test_decimal_context_memo.py @@ -0,0 +1,81 @@ +"""The current decimal context across context switches. + +Arithmetic finds the current context through a memo that every change of +the thread's current context, and every write to a context's mapping, +invalidates: `localcontext`, `setcontext`, `contextvars.Context.run`, +`copy_context`, asyncio tasks and threads all see their own context. +Run it past the compile threshold. +""" + +import asyncio +import contextvars +import decimal +import threading + +D = decimal.Decimal + + +def mul(n, a, b): + r = None + for _ in range(n): + r = a * b + return r + + +x, y = D("1.23456789"), D("9.87654321") +base = mul(2000, x, y) +assert base == D("12.19326311126352690") +with decimal.localcontext() as c: + c.prec = 3 + assert mul(2000, x, y) == D("12.2") + with decimal.localcontext(prec=5): + assert mul(10, x, y) == D("12.193") + assert mul(10, x, y) == D("12.2") +assert mul(2000, x, y) == base + +ctx = decimal.Context(prec=4) +old = decimal.getcontext() +decimal.setcontext(ctx) +assert mul(10, x, y) == D("12.19") +decimal.setcontext(old) +assert mul(10, x, y) == base + + +def in_copy(): + decimal.setcontext(decimal.Context(prec=2)) + return mul(100, x, y) + + +assert contextvars.copy_context().run(in_copy) == D("12") +assert mul(10, x, y) == base + +out = {} + + +def worker(prec, key): + decimal.setcontext(decimal.Context(prec=prec)) + out[key] = mul(2000, x, y) + + +ts = [threading.Thread(target=worker, args=(p, p)) for p in (2, 6, 9)] +for t in ts: + t.start() +for t in ts: + t.join() +assert out == {2: D("12"), 6: D("12.1933"), 9: D("12.1932631")}, out +assert mul(10, x, y) == base + + +async def task(prec): + decimal.setcontext(decimal.Context(prec=prec)) + await asyncio.sleep(0) + return mul(500, x, y) + + +async def main(): + return await asyncio.gather(task(3), task(7)) + + +assert asyncio.run(main()) == [D("12.2"), D("12.19326")] +assert mul(10, x, y) == base +print("ok") diff --git a/tests/regrtest/test_decimal_context_natives.py b/tests/regrtest/test_decimal_context_natives.py new file mode 100644 index 000000000..f2352184c --- /dev/null +++ b/tests/regrtest/test_decimal_context_natives.py @@ -0,0 +1,639 @@ +"""The `decimal` context operations that run natively. + +`Context.__init__`, `Context.__setattr__`, `Context.copy`, `clear_flags` +and `clear_traps`, `setcontext`, the signal mappings' item reads and +writes, and `Decimal.sqrt` and `Decimal.fma` each have a native half for +the ordinary case and keep the Python method for everything else (a value +to convert, an error to raise, a subclass). These tests pin both halves: +the values stored, every error and its type, the sharing and independence +of the flag and trap mappings, and that a change to a context takes effect +in the next operation, in hot loops too. +""" + +import copy +import decimal +import hashlib +import pickle +import threading +import unittest +from decimal import ( + BasicContext, + Clamped, + Context, + Decimal, + DefaultContext, + DivisionByZero, + ExtendedContext, + Inexact, + InvalidOperation, + Overflow, + Rounded, + Subnormal, + Underflow, + getcontext, + localcontext, + setcontext, +) + +N = 3000 +ONE, THREE = Decimal(1), Decimal(3) + + +class KeepContext(unittest.TestCase): + def setUp(self): + self.saved = getcontext() + setcontext(Context()) + + def tearDown(self): + setcontext(self.saved) + + +class Construction(KeepContext): + def test_defaults_come_from_the_default_context(self): + c = Context() + d = DefaultContext + self.assertEqual( + (c.prec, c.rounding, c.Emin, c.Emax, c.capitals, c.clamp), + (d.prec, d.rounding, d.Emin, d.Emax, d.capitals, d.clamp), + ) + self.assertEqual(dict(c.traps), dict(d.traps)) + self.assertIsNot(c.traps, d.traps) + self.assertFalse(any(c.flags.values())) + old = d.prec + try: + d.prec = 11 + self.assertEqual(Context().prec, 11) + self.assertEqual(Context(prec=7).prec, 7) + finally: + d.prec = old + self.assertEqual(Context().prec, old) + + def test_arguments(self): + c = Context(9, decimal.ROUND_DOWN, -50, 60, 0, 1) + self.assertEqual( + (c.prec, c.rounding, c.Emin, c.Emax, c.capitals, c.clamp), + (9, decimal.ROUND_DOWN, -50, 60, 0, 1), + ) + c = Context(Emax=77, prec=3, clamp=1) + self.assertEqual((c.prec, c.Emax, c.clamp), (3, 77, 1)) + self.assertEqual(c.rounding, DefaultContext.rounding) + self.assertEqual(Context(prec=None, rounding=None).prec, DefaultContext.prec) + + def test_signal_lists(self): + c = Context(flags=[Inexact, Rounded], traps=[Overflow]) + self.assertEqual([s for s, v in c.flags.items() if v], [Inexact, Rounded]) + self.assertEqual([s for s, v in c.traps.items() if v], [Overflow]) + self.assertEqual(len(c.flags), 9) + self.assertEqual(list(c.flags), list(c.traps)) + empty = Context(flags=[], traps=[]) + self.assertFalse(any(empty.flags.values()) or any(empty.traps.values())) + with self.assertRaises(KeyError): + Context(traps=[Overflow, ArithmeticError]) + with self.assertRaises(TypeError): + Context(traps=(Overflow,)) + + def test_signal_mappings(self): + base = Context() + given = dict.fromkeys(base.flags, 0) + given[Inexact] = 1 + c = Context(flags=given) + self.assertTrue(c.flags[Inexact]) + given[Rounded] = 1 + self.assertFalse(c.flags[Rounded]) + again = Context(flags=c.flags, traps=c.traps) + self.assertEqual(dict(again.flags), dict(c.flags)) + self.assertEqual(dict(again.traps), dict(c.traps)) + with self.assertRaises(KeyError): + Context(flags={Inexact: 1}) + with self.assertRaises(KeyError): + Context(flags=dict(given, extra=1)) + + def test_flag_values_are_bools(self): + c = Context() + self.assertIs(c.flags[Inexact], False) + self.assertIs(c.traps[Overflow], True) + self.assertIs(c.traps[Inexact], False) + trapping = Context(traps=[Inexact]) + self.assertIs(trapping.traps[Inexact], True) + self.assertIs(getcontext().flags[Rounded], False) + + def test_bad_values(self): + for kw, exc in ( + (dict(prec=0), ValueError), + (dict(prec=-3), ValueError), + (dict(prec="9"), TypeError), + (dict(prec=1.5), TypeError), + (dict(prec=10**30), OverflowError), + (dict(Emin=1), ValueError), + (dict(Emax=-1), ValueError), + (dict(capitals=2), ValueError), + (dict(clamp=-1), ValueError), + (dict(rounding="ROUND_SIDEWAYS"), TypeError), + (dict(rounding=3), TypeError), + (dict(flags=3), TypeError), + ): + with self.assertRaises(exc, msg=kw): + Context(**kw) + with self.assertRaises(TypeError): + Context(1, 2, 3, 4, 5, 6, 7, 8, 9) + with self.assertRaises(TypeError): + Context(precision=3) + + def test_bool_counts_as_an_int(self): + c = Context(prec=True, capitals=False) + self.assertEqual((c.prec, c.capitals), (1, 0)) + self.assertEqual(str(c.divide(ONE, THREE)), "0.3") + + def test_subclass_and_reinitialization(self): + class Wide(Context): + def __init__(self, extra, **kw): + super().__init__(**kw) + self.extra_seen = extra + + def __setattr__(self, name, value): + if name == "extra_seen": + object.__setattr__(self, name, value) + else: + super().__setattr__(name, value) + + w = Wide(5, prec=12) + self.assertEqual((w.prec, w.extra_seen), (12, 5)) + self.assertEqual(str(w.divide(ONE, THREE)), "0.333333333333") + self.assertIs(type(w.copy()), Context) + c = Context(prec=5) + c.__init__(prec=6) + self.assertEqual(c.prec, 6) + self.assertEqual(str(c.divide(ONE, THREE)), "0.333333") + + def test_hot_construction(self): + total = 0 + for i in range(N): + c = Context(prec=i % 30 + 1) + total += c.prec + len(c.flags) + (c.Emax == DefaultContext.Emax) + self.assertEqual(total, sum(i % 30 + 1 + 9 + 1 for i in range(N))) + + def test_pickle_and_reduce(self): + c = Context(prec=7, rounding=decimal.ROUND_UP, traps=[Inexact], flags=[Rounded]) + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + d = pickle.loads(pickle.dumps(c, proto)) + self.assertEqual((d.prec, d.rounding), (7, decimal.ROUND_UP)) + self.assertEqual(dict(d.traps), dict(c.traps)) + self.assertEqual(dict(d.flags), dict(c.flags)) + + +class Stores(KeepContext): + def test_valid_stores_take_effect_at_once(self): + c = getcontext() + seen = [] + for p in (1, 5, 28, 40, 3): + c.prec = p + seen.append(str(ONE / THREE)) + self.assertEqual(seen, ["0." + "3" * p for p in (1, 5, 28, 40, 3)]) + c.prec = 2 + c.rounding = decimal.ROUND_UP + self.assertEqual(str(ONE / THREE), "0.34") + c.rounding = decimal.ROUND_DOWN + self.assertEqual(str(Decimal(2) / THREE), "0.66") + c.capitals = 0 + self.assertEqual(str(Decimal("1E+30") * 10), "1.0e+31") + c.Emax, c.Emin, c.clamp = 50, -50, 1 + self.assertEqual((c.Emax, c.Emin, c.clamp), (50, -50, 1)) + + def test_every_spelling_of_a_store(self): + c = Context() + c.prec = 5 + setattr(c, "prec", c.prec + 1) + Context.__setattr__(c, "prec", c.prec + 1) + c.__setattr__("prec", c.prec + 1) + name = "".join(["pr", "ec"]) + setattr(c, name, c.prec + 1) + self.assertEqual(c.prec, 9) + self.assertEqual(str(c.divide(ONE, THREE)), "0.333333333") + total = 0 + for i in range(N): + setattr(c, "prec", i % 9 + 1) + total += len(str(c.divide(ONE, THREE))) + self.assertEqual(total, sum(i % 9 + 3 for i in range(N))) + + def test_errors(self): + c = Context() + for name, value, exc in ( + ("prec", 0, ValueError), + ("prec", "3", TypeError), + ("prec", 2**70, OverflowError), + ("Emin", 5, ValueError), + ("Emax", -5, ValueError), + ("capitals", 7, ValueError), + ("clamp", None, TypeError), + ("rounding", "up", TypeError), + ("rounding", None, TypeError), + ("flags", [], TypeError), + ("traps", {}, KeyError), + ("precision", 3, AttributeError), + ("x", 1, AttributeError), + ): + with self.assertRaises(exc, msg=(name, value)): + setattr(c, name, value) + with self.assertRaises(AttributeError): + del c.prec + with self.assertRaises(AttributeError): + c.nothing = 1 + self.assertEqual(c.prec, DefaultContext.prec) + hits = 0 + for i in range(600): + try: + c.prec = i % 3 + except ValueError: + hits += 1 + self.assertEqual((hits, c.prec), (200, 2)) + + def test_stores_after_the_dictionary_was_seen(self): + def look(ctx): + # (Where a context has a `__dict__`, reading it changes how + # its attributes are laid out.) + try: + return vars(ctx) + except TypeError: + return None + + c = Context(prec=4) + look(c) + self.assertIn("prec=4", repr(c)) + c.prec = 6 + setattr(c, "Emax", 99) + self.assertEqual((c.prec, c.Emax), (6, 99)) + self.assertIn("prec=6", repr(c)) + self.assertEqual(str(c.divide(ONE, THREE)), "0.333333") + d = c.copy() + self.assertEqual((d.prec, d.Emax), (6, 99)) + d.flags[Inexact] = True + d.clear_flags() + self.assertFalse(any(d.flags.values())) + e = Context() + look(e) + e.__init__(prec=3) + self.assertEqual(str(e.divide(ONE, THREE)), "0.333") + with localcontext(e) as inner: + look(inner) + inner.prec = 5 + self.assertEqual(str(ONE / THREE), "0.33333") + + def test_signal_mapping_stores(self): + c = Context() + other = Context(flags=[Inexact]) + c.flags = other.flags + self.assertEqual(dict(c.flags), dict(other.flags)) + self.assertTrue(c.flags[Inexact]) + plain = dict.fromkeys(other.flags, False) + plain[Overflow] = True + c.traps = plain + self.assertIsNot(c.traps, plain) + self.assertEqual(type(c.traps), type(other.flags)) + self.assertTrue(c.traps[Overflow]) + with self.assertRaises(Overflow): + c.multiply(Decimal("9E999999"), 10) + with self.assertRaises(KeyError): + c.flags = {Inexact: False} + with self.assertRaises(TypeError): + c.flags = None + + +class Copies(KeepContext): + def test_copy_is_independent(self): + c = Context(prec=9, rounding=decimal.ROUND_FLOOR, Emin=-9, Emax=9, capitals=0, clamp=1) + c.flags[Inexact] = True + c.traps[Clamped] = True + for d in (c.copy(), c.__copy__(), copy.copy(c)): + self.assertIs(type(d), Context) + self.assertEqual( + (d.prec, d.rounding, d.Emin, d.Emax, d.capitals, d.clamp), + (9, decimal.ROUND_FLOOR, -9, 9, 0, 1), + ) + self.assertEqual(dict(d.flags), dict(c.flags)) + self.assertEqual(dict(d.traps), dict(c.traps)) + self.assertIsNot(d.flags, c.flags) + d.flags[Rounded] = True + d.traps[Clamped] = False + d.prec = 3 + self.assertFalse(c.flags[Rounded]) + self.assertTrue(c.traps[Clamped]) + self.assertEqual(c.prec, 9) + + def test_copies_in_a_loop(self): + c = Context(prec=6) + total = 0 + for i in range(N): + d = c.copy() + d.prec = i % 5 + 1 + total += d.prec + c.prec + len(str(d.divide(ONE, THREE))) + self.assertEqual(total, sum(2 * (i % 5 + 1) + 6 + 2 for i in range(N))) + self.assertEqual(c.prec, 6) + + def test_a_mapping_outlives_its_context(self): + flags = Context().flags + with self.assertRaises(ValueError): + flags[Inexact] + with self.assertRaises(ValueError): + flags[Inexact] = True + with self.assertRaises(ValueError): + len(flags) + flags = Context().copy().flags + with self.assertRaises(ValueError): + flags[Inexact] + + def test_mapping_items(self): + c = Context() + f = c.flags + self.assertIs(f[Inexact], False) + f[Inexact] = 1 + self.assertIs(f[Inexact], True) + f[Inexact] = 0 + self.assertIs(f[Inexact], False) + f[Rounded] = "yes" + self.assertIs(f[Rounded], True) + with self.assertRaises(KeyError): + f[ValueError] + with self.assertRaises(KeyError): + f["Inexact"] + with self.assertRaises(KeyError): + f[ValueError] = True + with self.assertRaises(ValueError): + del f[Inexact] + raised = 0 + for i in range(N): + c.clear_flags() + c.divide(ONE, THREE if i % 2 else ONE) + raised += f[Inexact] + c.flags[Rounded] + f[Clamped] = i % 3 == 0 + raised += f[Clamped] + self.assertEqual(raised, 2 * (N // 2) + (N + 2) // 3) + + def test_clearing(self): + c = Context(flags=[Inexact, Rounded, Subnormal], traps=[Overflow, Underflow]) + flags, traps = c.flags, c.traps + c.clear_flags() + self.assertFalse(any(flags.values())) + self.assertIs(flags[Inexact], False) + self.assertTrue(traps[Overflow]) + c.clear_traps() + self.assertFalse(any(traps.values())) + self.assertIs(c.flags, flags) + c.multiply(Decimal("9E999999"), 10) + self.assertTrue(flags[Overflow]) + for _ in range(500): + c.divide(ONE, THREE) + c.clear_flags() + self.assertFalse(any(flags.values())) + + def test_limits(self): + c = Context(prec=5, Emin=-20, Emax=30) + self.assertEqual((c.Etiny(), c.Etop()), (-24, 26)) + c.prec = 9 + self.assertEqual((c.Etiny(), c.Etop()), (-28, 22)) + self.assertIs(type(c.Etiny()), int) + + +class Current(KeepContext): + def test_setcontext(self): + c = Context(prec=6) + setcontext(c) + self.assertIs(getcontext(), c) + self.assertEqual(str(ONE / THREE), "0.333333") + for template in (DefaultContext, BasicContext, ExtendedContext): + template.flags[Rounded] = True + try: + setcontext(template) + got = getcontext() + self.assertIsNot(got, template) + self.assertEqual(got.prec, template.prec) + self.assertFalse(any(got.flags.values())) + finally: + template.clear_flags() + for bad in (None, 3, "ctx", Decimal(1)): + with self.assertRaises(TypeError): + setcontext(bad) + with self.assertRaises(TypeError): + setcontext() + + def test_setcontext_in_a_loop(self): + a, b = Context(prec=3), Context(prec=7) + total = 0 + for i in range(N): + setcontext(a if i % 2 else b) + total += len(str(ONE / THREE)) + (getcontext() is (a if i % 2 else b)) + self.assertEqual(total, (N // 2) * (5 + 9) + N) + + def test_localcontext(self): + outer = getcontext() + outer.prec = 10 + with localcontext() as c: + self.assertIsNot(c, outer) + self.assertIs(getcontext(), c) + c.prec += 2 + self.assertEqual(str(ONE / THREE), "0." + "3" * 12) + with localcontext(prec=4, rounding=decimal.ROUND_UP) as inner: + self.assertEqual((inner.prec, inner.rounding), (4, decimal.ROUND_UP)) + self.assertEqual(str(ONE / THREE), "0.3334") + self.assertIs(getcontext(), c) + self.assertIs(getcontext(), outer) + self.assertEqual(str(ONE / THREE), "0." + "3" * 10) + given = Context(prec=5) + with localcontext(given) as c: + self.assertIsNot(c, given) + self.assertEqual(c.prec, 5) + with self.assertRaises(TypeError): + localcontext(precision=3) + with self.assertRaises(TypeError): + localcontext(3) + with self.assertRaises(ValueError): + localcontext(prec=0) + try: + with localcontext() as c: + c.prec = 2 + raise KeyError("inside") + except KeyError: + pass + self.assertIs(getcontext(), outer) + + def test_localcontext_in_a_loop(self): + getcontext().prec = 8 + total = 0 + for i in range(N): + with localcontext() as c: + c.prec += i % 4 + total += len(str(ONE / THREE)) + total += len(str(ONE / THREE)) + with localcontext(prec=i % 3 + 1): + total += len(str(ONE / THREE)) + self.assertEqual(total, sum(10 + i % 4 + 10 + i % 3 + 3 for i in range(N))) + self.assertEqual(getcontext().prec, 8) + + def test_threads_have_their_own(self): + getcontext().prec = 9 + seen = {} + + def work(p): + getcontext().prec = p + for _ in range(200): + with localcontext() as c: + c.prec += 1 + seen[p] = str(ONE / THREE) + + threads = [threading.Thread(target=work, args=(p,)) for p in (3, 5, 12)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertEqual(seen, {p: "0." + "3" * p for p in (3, 5, 12)}) + self.assertEqual(getcontext().prec, 9) + + +class RootsAndFma(KeepContext): + def test_special_cases(self): + getcontext().prec = 30 + self.assertEqual(repr(Decimal(2).sqrt()), "Decimal('1.41421356237309504880168872421')") + self.assertEqual(repr(Decimal("0.25").sqrt()), "Decimal('0.5')") + self.assertEqual(repr(Decimal("-0").sqrt()), "Decimal('-0')") + self.assertEqual(repr(Decimal("0E-7").sqrt()), "Decimal('0.0000')") + self.assertEqual(repr(Decimal("0E+7").sqrt()), "Decimal('0E+3')") + self.assertEqual(repr(Decimal("1E-7").sqrt()), "Decimal('0.000316227766016837933199889354443')") + self.assertEqual(repr(Decimal(16).sqrt()), "Decimal('4')") + self.assertEqual(repr(Decimal("NaN").sqrt()), "Decimal('NaN')") + self.assertEqual(repr(Decimal("Infinity").sqrt()), "Decimal('Infinity')") + with self.assertRaises(InvalidOperation): + Decimal(-1).sqrt() + self.assertEqual(repr(Decimal(10).fma(3, Decimal("0.5"))), "Decimal('30.5')") + self.assertEqual(repr(Decimal("Infinity").fma(2, 3)), "Decimal('Infinity')") + with self.assertRaises(TypeError): + Decimal(1).fma(1.5, 2) + with self.assertRaises(InvalidOperation): + Decimal("Infinity").fma(0, 1) + + class Sub(Decimal): + pass + + self.assertIs(type(Sub(16).sqrt()), Decimal) + self.assertEqual(Sub(2).fma(Sub(3), 4), 10) + c = Context(prec=3) + self.assertEqual(str(Decimal(2).sqrt(c)), "1.41") + self.assertEqual(str(Decimal(2).sqrt(context=c)), "1.41") + self.assertEqual(str(c.sqrt(2)), "1.41") + self.assertEqual(str(c.fma(2, 3, Decimal("0.004"))), "6.00") + self.assertTrue(c.flags[Inexact] and c.flags[Rounded]) + + def test_against_reference_results(self): + sigs = [Inexact, Rounded, Subnormal, Underflow, Clamped, Overflow, InvalidOperation] + state = [12345] + + def rnd(): + state[0] = (state[0] * 6364136223846793005 + 1442695040888963407) & (2**64 - 1) + return state[0] >> 11 + + def value(): + kind = rnd() % 10 + digits = 1 + rnd() % (6 if kind < 4 else 30 if kind < 8 else 70) + coef = rnd() % (10**digits) + if kind == 9: + coef = (rnd() % 2000) ** 2 + exp = int(rnd() % 61) - 30 + if rnd() % 16 == 0: + exp = int(rnd() % 4001) - 2000 + sign = rnd() % 7 == 0 + return Decimal((int(sign), tuple(int(ch) for ch in str(coef)), exp)) + + rounds = [ + decimal.ROUND_HALF_EVEN, + decimal.ROUND_DOWN, + decimal.ROUND_UP, + decimal.ROUND_CEILING, + decimal.ROUND_FLOOR, + decimal.ROUND_HALF_UP, + decimal.ROUND_HALF_DOWN, + decimal.ROUND_05UP, + ] + out = [] + for _ in range(1500): + prec = [1, 2, 5, 9, 16, 28, 28, 28, 40, 77][rnd() % 10] + c = Context( + prec=prec, + rounding=rounds[rnd() % 8], + Emin=-[999999, 50, 10][rnd() % 3], + Emax=[999999, 50, 10][rnd() % 3], + traps=[], + ) + x, y, z = value(), value(), value() + for name, f in ( + ("sqrt", lambda: x.sqrt(c)), + ("csqrt", lambda: c.sqrt(x)), + ("fma", lambda: x.fma(y, z, c)), + ("cfma", lambda: c.fma(x, y, z)), + ("fmai", lambda: x.fma(3, -7, context=c)), + ): + c.clear_flags() + r = repr(f()) + flags = "".join("1" if c.flags[s] else "0" for s in sigs) + out.append("%s %s %s %s %s -> %s %s" % (name, prec, x, y, z, r, flags)) + out.append("%d %d" % (c.Etiny(), c.Etop())) + digest = hashlib.sha256("\n".join(out).encode()).hexdigest() + self.assertEqual(len(out), 9000) + self.assertEqual(digest, "5c4223afe855a532fbd575882a6d41a81c2b4d2b592cc3f96f573fd4dfa838fe") + + +class PlainSetattr(unittest.TestCase): + def test_setattr_through_hooks_properties_and_slots(self): + class Hooked: + def __setattr__(self, name, value): + object.__setattr__(self, name, (name, value)) + + class Prop: + def __init__(self): + self._v = 0 + + @property + def v(self): + return self._v + + @v.setter + def v(self, value): + self._v = value * 2 + + class Slotted: + __slots__ = ("a", "b") + + h, p, s = Hooked(), Prop(), Slotted() + total = 0 + for i in range(N): + setattr(h, "x", i) + setattr(p, "v", i) + setattr(s, "a", i) + setattr(p, "w", i) + total += h.x[1] + p.v + s.a + p.w + self.assertEqual(total, sum(5 * i for i in range(N))) + self.assertEqual(vars(h), {"x": ("x", N - 1)}) + self.assertEqual(vars(p), {"_v": 2 * (N - 1), "w": N - 1}) + with self.assertRaises(AttributeError): + setattr(s, "c", 1) + delattr(p, "w") + self.assertFalse(hasattr(p, "w")) + with self.assertRaises(AttributeError): + delattr(p, "w") + with self.assertRaises(TypeError): + setattr(p, 3, 1) + + def test_names_with_lone_surrogates(self): + class Bag: + pass + + b = Bag() + name = "x\udc80" + setattr(b, name, 5) + self.assertEqual(getattr(b, name), 5) + self.assertTrue(hasattr(b, name)) + b.plain = 1 + self.assertEqual(b.plain, 1) + delattr(b, name) + self.assertFalse(hasattr(b, name)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_decimal_method_natives.py b/tests/regrtest/test_decimal_method_natives.py new file mode 100644 index 000000000..9679f5e18 --- /dev/null +++ b/tests/regrtest/test_decimal_method_natives.py @@ -0,0 +1,392 @@ +"""The `Decimal` and `Context` methods that run natively past the +arithmetic operators. + +`remainder_near`, `scaleb`, `shift`, `rotate`, the logical operations, +`next_plus`, `next_minus`, `next_toward`, `logb`, `number_class`, +`compare_total`, `compare_total_mag`, `max_mag`, `min_mag`, `radix`, +`exp`, `ln` and `log10` each have a native half for finite operands of +the exact class, as does the constructor for a `(sign, digits, exponent)` +tuple; the Python methods keep the special values, the errors and the +subclasses. `abs`, `round`, `divmod` and the unary operators reach a +natively served value's method through a per-class cache. These tests +pin a table of results, two digests over a few thousand generated +operands (taken from CPython's C implementation), the error cases, and +the hot-loop forms. +""" + +import datetime +import decimal +import hashlib +import inspect +import unittest +from decimal import Context, Decimal + +D = Decimal +N = 3000 + +TABLE = [ + ("D('10').remainder_near(D('6'), c)", "Decimal('-2')"), + ("D('2.1').remainder_near(D('3'), c)", "Decimal('-0.9')"), + ("c.remainder_near(D('-10'), 6)", "Decimal('2')"), + ("D('7.50').scaleb(3, c)", "Decimal('7.50E+3')"), + ("c.scaleb(D('7.50'), -2)", "Decimal('0.0750')"), + ("D('34').shift(8, c)", "Decimal('400000000')"), + ("D('12').shift(-1, c)", "Decimal('1')"), + ("c.shift(D('123456789'), 2)", "Decimal('345678900')"), + ("D('34').rotate(8, c)", "Decimal('400000003')"), + ("D('123456789').rotate(-2, c)", "Decimal('891234567')"), + ("c.rotate(D('12'), 9)", "Decimal('12')"), + ("D('1010').logical_and(D('1100'), c)", "Decimal('1000')"), + ("D('1010').logical_or(D('1100'), c)", "Decimal('1110')"), + ("D('1010').logical_xor(D('1100'), c)", "Decimal('110')"), + ("D('101').logical_invert(c)", "Decimal('111111010')"), + ("c.logical_invert(D('0'))", "Decimal('111111111')"), + ("D('1').next_plus(c)", "Decimal('1.00000001')"), + ("D('1').next_minus(c)", "Decimal('0.999999999')"), + ("D('-1E-1007').next_plus(c)", "Decimal('-9.99999999E-1008')"), + ("c.next_minus(D('1.00000003'))", "Decimal('1.00000002')"), + ("D('2').next_toward(D('1'), c)", "Decimal('1.99999999')"), + ("D('2').next_toward(D('3'), c)", "Decimal('2.00000001')"), + ("D('2').next_toward(D('-2.00'), c)", "Decimal('1.99999999')"), + ("c.next_toward(D('0'), D('1'))", "Decimal('1E-1000007')"), + ("D('250').logb(c)", "Decimal('2')"), + ("D('0.03').logb(c)", "Decimal('-2')"), + ("c.logb(D('2.50'))", "Decimal('0')"), + ("D('2.50').number_class(c)", "'+Normal'"), + ("D('-0').number_class(c)", "'-Zero'"), + ("D('1E-999999').number_class(c)", "'+Normal'"), + ("c.number_class(D('-1E-1000005'))", "'-Subnormal'"), + ("D('12.30').compare_total(D('12.3'))", "Decimal('-1')"), + ("D('12.3').compare_total(D('12.300'))", "Decimal('1')"), + ("D('-127').compare_total(D('12'))", "Decimal('-1')"), + ("D('-12.30').compare_total_mag(D('12.3'))", "Decimal('-1')"), + ("c.compare_total(D('12.30'), D('12.30'))", "Decimal('0')"), + ("D('1').max_mag(D('-2'), c)", "Decimal('-2')"), + ("D('-7').max_mag(D('7'), c)", "Decimal('7')"), + ("D('1').min_mag(D('-2'), c)", "Decimal('1')"), + ("c.min_mag(D('-3'), D('3'))", "Decimal('-3')"), + ("D('5').radix()", "Decimal('10')"), + ('c.radix()', "Decimal('10')"), + ("D('1').exp(c)", "Decimal('2.71828183')"), + ("D('-1').exp(c)", "Decimal('0.367879441')"), + ("D('0.693147181').exp(c)", "Decimal('2.00000000')"), + ("c.exp(D('1E-12'))", "Decimal('1.00000000')"), + ("D('2').ln(c)", "Decimal('0.693147181')"), + ("D('10').ln(c)", "Decimal('2.30258509')"), + ("D('1.000').ln(c)", "Decimal('0')"), + ("c.ln(D('0.5'))", "Decimal('-0.693147181')"), + ("D('2').log10(c)", "Decimal('0.301029996')"), + ("D('1000').log10(c)", "Decimal('3')"), + ("D('0.001').log10(c)", "Decimal('-3')"), + ("c.log10(D('70'))", "Decimal('1.84509804')"), + ('D((0, (3, 1, 4), -2))', "Decimal('3.14')"), + ('D((1, [0, 0, 7], 3))', "Decimal('-7E+3')"), + ('D((0, (), 5))', "Decimal('0E+5')"), + ('D((0, (1, True), 0))', "Decimal('11')"), + ("abs(D('-3.5'))", "Decimal('3.5')"), + ("round(D('2.675'), 2)", "Decimal('2.68')"), + ("round(D('2.5'))", '2'), + ('divmod(D(7), D(2))', "(Decimal('3'), Decimal('1'))"), + ("divmod(D('7.5'), 2)", "(Decimal('3'), Decimal('1.5'))"), + ("-D('0')", "Decimal('0')"), + ("+D('-0')", "Decimal('0')"), +] + +SIGNALS = [ + decimal.Inexact, + decimal.Rounded, + decimal.Subnormal, + decimal.Underflow, + decimal.Clamped, + decimal.Overflow, + decimal.InvalidOperation, + decimal.DivisionByZero, +] +ROUNDINGS = [ + decimal.ROUND_HALF_EVEN, + decimal.ROUND_DOWN, + decimal.ROUND_UP, + decimal.ROUND_CEILING, + decimal.ROUND_FLOOR, + decimal.ROUND_HALF_UP, + decimal.ROUND_HALF_DOWN, + decimal.ROUND_05UP, +] +BINARY = [ + "remainder_near", + "scaleb", + "rotate", + "shift", + "logical_and", + "logical_or", + "logical_xor", + "next_toward", + "compare_total", + "compare_total_mag", + "max_mag", + "min_mag", +] +UNARY = ["logical_invert", "next_plus", "next_minus", "logb", "number_class"] + + +class Lcg: + def __init__(self, seed): + self.state = seed + + def __call__(self): + self.state = (self.state * 6364136223846793005 + 1442695040888963407) & (2**64 - 1) + return self.state >> 11 + + +def flags(c): + return "".join("1" if c.flags[s] else "0" for s in SIGNALS) + + +def attempt(f): + try: + return repr(f()) + except Exception as e: + return type(e).__name__ + + +class Table(unittest.TestCase): + def test_table(self): + c = Context(prec=9, traps=[]) + for source, expected in TABLE: + with self.subTest(source): + self.assertEqual(repr(eval(source, {"D": D, "c": c})), expected) + + def test_results_are_exact_decimals(self): + class Sub(Decimal): + pass + + s = Sub("101") + for r in ( + s.next_plus(), + s.max_mag(Sub(-5)), + s.logical_and(Sub("110")), + s.exp(), + s.ln(), + s.log10(), + s.scaleb(1), + abs(Sub(-2)), + -Sub(2), + round(Sub("1.25"), 1), + ): + self.assertIs(type(r), Decimal) + self.assertEqual(divmod(D(7), Sub(2)), (3, 1)) + self.assertEqual(s.compare_total(Sub("101.0")), 1) + + def test_errors_and_specials(self): + c = Context(prec=9, traps=[decimal.InvalidOperation, decimal.DivisionByZero]) + for f in ( + lambda: D(1).remainder_near(D(0), c), + lambda: D(1).scaleb(D("1.5"), c), + lambda: D(1).shift(10, c), + lambda: D(1).rotate(-10, c), + lambda: D(2).logical_and(D(1), c), + lambda: D("-1").logical_invert(c), + lambda: D(-1).ln(c), + lambda: D(-1).log10(c), + lambda: D("sNaN").next_plus(c), + ): + with self.assertRaises(decimal.InvalidOperation): + f() + with self.assertRaises(decimal.DivisionByZero): + D(0).logb(c) + for f in ( + lambda: D(1).remainder_near(1.5), + lambda: D(1).scaleb("1"), + lambda: D(1).max_mag(None), + lambda: D(1).compare_total(2.0), + lambda: divmod(D(1), 1.5), + lambda: round(D(1), "x"), + ): + with self.assertRaises(TypeError): + f() + quiet = Context(prec=9, traps=[]) + self.assertEqual(repr(D("NaN").next_plus(quiet)), "Decimal('NaN')") + self.assertEqual(repr(D("Infinity").next_minus(quiet)), "Decimal('9.99999999E+999999')") + self.assertEqual(repr(D("-Infinity").exp(quiet)), "Decimal('0')") + self.assertEqual(repr(D(0).ln(quiet)), "Decimal('-Infinity')") + self.assertEqual(repr(D("Infinity").log10(quiet)), "Decimal('Infinity')") + self.assertEqual(repr(D(0).exp(quiet)), "Decimal('1')") + self.assertEqual(D("Infinity").number_class(quiet), "+Infinity") + self.assertEqual(repr(D("NaN").max_mag(D(1), quiet)), "Decimal('1')") + self.assertEqual(repr(D("Infinity").compare_total(D("NaN"))), "Decimal('-1')") + + def test_tuple_construction_errors(self): + for bad, exc in ( + ((2, (1,), 0), ValueError), + ((0, (10,), 0), ValueError), + ((0, (1,), 1.5), ValueError), + ((0, (1,)), ValueError), + ((0, (1,), 10**30), OverflowError), + ((0, (-1,), 0), ValueError), + (("0", (1,), 0), ValueError), + ): + with self.assertRaises(exc, msg=bad): + D(bad) + self.assertEqual(repr(D((0, (1, 2), "F"))), "Decimal('Infinity')") + self.assertEqual(repr(D((1, (), "n"))), "Decimal('-NaN')") + self.assertEqual(repr(D((0, (0, 0, 7), 2))), "Decimal('7E+2')") + self.assertEqual(D(list((0, (1, 5), -1))), D("1.5")) + total = 0 + for i in range(N): + total += D((i % 2, (i % 10, 5), -1)) + self.assertEqual(total, sum((-1) ** (i % 2) * D("%d.5" % (i % 10)) for i in range(N))) + + def test_signatures(self): + self.assertEqual(str(inspect.signature(Decimal.exp)), "(self, /, context=None)") + self.assertEqual( + str(inspect.signature(Decimal.remainder_near)), "(self, /, other, context=None)" + ) + kinds = [p.kind for p in inspect.signature(Context.next_toward).parameters.values()] + self.assertEqual(kinds, [inspect.Parameter.POSITIONAL_ONLY] * 3) + self.assertEqual( + list(inspect.signature(Context).parameters), + ["prec", "rounding", "Emin", "Emax", "capitals", "clamp", "flags", "traps"], + ) + + +class Digests(unittest.TestCase): + def test_methods_against_reference_results(self): + rnd = Lcg(987654321) + + def value(): + kind = rnd() % 12 + if kind == 0: + return D(int(rnd() % 41) - 20) + if kind == 1: + n = 1 + rnd() % 12 + return D("".join("01"[rnd() % 2] for _ in range(n))) + digits = 1 + rnd() % (6 if kind < 6 else 30 if kind < 10 else 60) + coef = rnd() % (10**digits) + exp = int(rnd() % 41) - 20 + if rnd() % 12 == 0: + exp = int(rnd() % 2001) - 1000 + sign = rnd() % 5 == 0 + return D((int(sign), tuple(int(ch) for ch in str(coef)), exp)) + + out = [] + for _ in range(600): + prec = [1, 2, 5, 9, 16, 28, 28, 28, 40, 60][rnd() % 10] + c = Context( + prec=prec, + rounding=ROUNDINGS[rnd() % 8], + Emin=-[999999, 50, 10][rnd() % 3], + Emax=[999999, 50, 10][rnd() % 3], + clamp=rnd() % 4 == 0, + traps=[], + ) + x, y = value(), value() + small = int(rnd() % (2 * prec + 3)) - prec - 1 + for name in BINARY: + for other in (y, small) if name in ("scaleb", "rotate", "shift") else (y,): + for form in (0, 1): + c.clear_flags() + if form == 0: + r = attempt(lambda: getattr(x, name)(other, context=c)) + else: + r = attempt(lambda: getattr(c, name)(x, other)) + out.append("%s%d %s %s %s -> %s %s" % (name, form, prec, x, other, r, flags(c))) + for name in UNARY: + for form in (0, 1): + c.clear_flags() + if form == 0: + r = attempt(lambda: getattr(x, name)(context=c)) + else: + r = attempt(lambda: getattr(c, name)(x)) + out.append("%s%d %s %s -> %s %s" % (name, form, prec, x, r, flags(c))) + t = (int(rnd() % 2), tuple(int(rnd() % 10) for _ in range(rnd() % 8)), int(rnd() % 21) - 10) + out.append( + repr(D(t)) + repr(D(list(t))) + repr(D((t[0], list(t[1]), t[2]))) + repr(x.radix()) + repr(c.radix()) + ) + digest = hashlib.sha256("\n".join(out).encode()).hexdigest() + self.assertEqual(len(out), 24600) + self.assertEqual(digest, "16e55c61910c7005476f6130660939bb4d59bcb07e158e902932af6d81e020db") + + def test_transcendentals_against_reference_results(self): + rnd = Lcg(424242) + + def value(): + kind = rnd() % 14 + if kind == 0: + return D(int(rnd() % 30)) + if kind == 1: + return D(10) ** (int(rnd() % 21) - 10) + if kind == 2: + return D(1) + D(int(rnd() % 1000) - 500).scaleb(-int(rnd() % 30) - 3) + digits = 1 + rnd() % (5 if kind < 8 else 25 if kind < 12 else 50) + coef = rnd() % (10**digits) + exp = int(rnd() % 31) - 20 + if rnd() % 10 == 0: + exp = int(rnd() % 801) - 400 + if rnd() % 25 == 0: + exp = int(rnd() % 2000001) - 1000000 + sign = rnd() % 4 == 0 + return D((int(sign), tuple(int(ch) for ch in str(coef)), exp)) + + out = [] + for _ in range(300): + prec = [1, 2, 3, 7, 9, 16, 28, 28, 28, 34, 50, 90][rnd() % 12] + if rnd() % 200 == 0: + prec = 250 + c = Context( + prec=prec, + rounding=decimal.ROUND_HALF_EVEN if rnd() % 3 else decimal.ROUND_DOWN, + Emin=-[999999, 60, 12][rnd() % 3], + Emax=[999999, 60, 12][rnd() % 3], + clamp=rnd() % 5 == 0, + traps=[], + ) + x = value() + for name in ("exp", "ln", "log10"): + for form in (0, 1): + c.clear_flags() + if form == 0: + r = attempt(lambda: getattr(x, name)(c)) + else: + r = attempt(lambda: getattr(c, name)(x)) + out.append("%s%d %s %s -> %s %s" % (name, form, prec, x, r, flags(c))) + digest = hashlib.sha256("\n".join(out).encode()).hexdigest() + self.assertEqual(len(out), 1800) + self.assertEqual(digest, "a651f52744aab58a4487ab24f0b2762ca376f3cb7f98b71cc76c391ba076fa0d") + + +class HotLoops(unittest.TestCase): + def test_numeric_builtins(self): + x, y = D("3.14159"), D("2.5") + gap = datetime.timedelta(hours=-5) + total = D(0) + days = 0 + for i in range(N): + total += abs(-x) + round(x, i % 4) + round(y) + divmod(x, y)[1] - +y + days += abs(gap).seconds + (-gap).seconds + divmod(gap, datetime.timedelta(hours=2))[0] + expected = sum( + (abs(-x) + round(x, i % 4) + 2 + D("0.64159") - y for i in range(N)), D(0) + ) + self.assertEqual(total, expected) + self.assertEqual(days, N * (18000 + 18000 - 3)) + + def test_methods_in_loops(self): + c = Context(prec=12, traps=[]) + x = D("1.5") + acc = D(0) + for i in range(N): + x = x.next_plus(c) if i % 2 else x.next_minus(c) + acc += x.scaleb(1, c).remainder_near(D(7), c) + x.logb(c) + x.max_mag(-x, c) + acc += D(i % 9 + 1).ln(c).exp(c).log10(c) + self.assertEqual(x, D("1.5")) + reference = Context(prec=12, traps=[]) + want = D(0) + z = D("1.5") + for i in range(N): + z = reference.next_plus(z) if i % 2 else reference.next_minus(z) + want += reference.remainder_near(reference.scaleb(z, 1), 7) + reference.logb(z) + reference.max_mag(z, -z) + want += reference.log10(reference.exp(reference.ln(i % 9 + 1))) + self.assertEqual(acc, want) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_decimal_slot_reads.py b/tests/regrtest/test_decimal_slot_reads.py new file mode 100644 index 000000000..a4a4269dc --- /dev/null +++ b/tests/regrtest/test_decimal_slot_reads.py @@ -0,0 +1,46 @@ +"""Reads of `Decimal`'s slot members (`_sign`, `_int`, `_exp`, +`_is_special`) at one site over values built by Python code and values +the natives built, whose storage takes another form: the members are set +in both, so no read may raise as if one were unset. (CPython's C +`decimal` has no such fields; only the signal test runs there.)""" + +import decimal +import unittest +from decimal import Decimal + + +def fields(d): + return (d._sign, d._int, d._exp, d._is_special) + + +class DecimalSlotReads(unittest.TestCase): + @unittest.skipUnless(hasattr(Decimal(1), "_sign"), + "a decimal without Python-level fields (CPython's C one)") + def test_mixed_sources(self): + ctx = decimal.Context(prec=9, Emin=-20, Emax=20, traps=[]) + with decimal.localcontext(ctx): + a = Decimal("7E+50") + built = [Decimal("1.5"), Decimal(-3), Decimal("NaN"), a] + native = [-Decimal("1.5"), Decimal("2") ** 3, -a, a * a, + Decimal("1") / 3] + want = { + str(d): (d.is_signed(), d.is_nan() or d.is_infinite()) + for d in built + native + } + for _ in range(400): + for d in built + native: + sign, _, _, special = fields(d) + self.assertEqual((bool(sign), special), want[str(d)]) + + def test_overflow_signals(self): + ctx = decimal.Context(prec=9, Emin=-20, Emax=20, traps=[]) + with decimal.localcontext(ctx): + for _ in range(300): + a = Decimal("7E+50") + self.assertEqual(str(-a), "-Infinity") + self.assertEqual(str(a ** 2), "Infinity") + self.assertEqual(str((-a) ** 5), "-Infinity") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_deepcopy_plain_trees.py b/tests/regrtest/test_deepcopy_plain_trees.py new file mode 100644 index 000000000..77a9b5b3e --- /dev/null +++ b/tests/regrtest/test_deepcopy_plain_trees.py @@ -0,0 +1,110 @@ +"""`copy.deepcopy` of trees of plain dicts, lists and tuples. + +A tree of exact dicts, lists and tuples over `None`, bools, ints, floats, +strings and bytes is copied natively, as `copy`'s own table copies it: +equal values, new containers, shared parts still shared, cycles kept, and +a tuple whose items all copy to themselves returned itself. Anything else +in the tree, a memo, a very deep tree, or a trace hook takes the Python +function. +""" + +import copy +import sys +import unittest + + +class DeepcopyPlainTests(unittest.TestCase): + def test_values_and_identity(self): + src = {"a": [1, 2.5, "x", None, True, b"b"], "t": (1, "s"), "n": {"k": [(), [3]]}, 7: 2**80} + for _ in range(100): + out = copy.deepcopy(src) + self.assertEqual(out, src) + self.assertIsNot(out, src) + self.assertIsNot(out["a"], src["a"]) + self.assertIs(out["t"], src["t"]) + self.assertIsNot(out["n"]["k"], src["n"]["k"]) + self.assertIs(out["n"]["k"][0], ()) + self.assertIs(out["a"][2], src["a"][2]) + self.assertEqual(list(out), list(src)) + nested = ([1], [2]) + out = copy.deepcopy(nested) + self.assertIsNot(out, nested) + self.assertEqual(out, nested) + self.assertIsNot(out[0], nested[0]) + + def test_sharing_and_cycles(self): + shared = [1, 2] + src = [shared, shared, {"s": shared}] + out = copy.deepcopy(src) + self.assertIs(out[0], out[1]) + self.assertIs(out[2]["s"], out[0]) + self.assertIsNot(out[0], shared) + loop = [1] + loop.append(loop) + out = copy.deepcopy(loop) + self.assertIs(out[1], out) + d = {} + d["self"] = d + out = copy.deepcopy(d) + self.assertIs(out["self"], out) + t = ([],) + t[0].append(t) + out = copy.deepcopy(t) + self.assertIs(out[0][0], out) + + def test_other_shapes(self): + class C: + def __init__(self): + self.v = [1] + + c = C() + out = copy.deepcopy([c, {1: c}]) + self.assertIsNot(out[0], c) + self.assertIs(out[1][1], out[0]) + self.assertEqual(out[0].v, [1]) + + class L(list): + pass + + lst = L([1, [2]]) + out = copy.deepcopy({"l": lst}) + self.assertIs(type(out["l"]), L) + self.assertIsNot(out["l"][1], lst[1]) + memo = {} + x = [1, [2]] + out = copy.deepcopy(x, memo) + self.assertIn(id(x), memo) + self.assertEqual(copy.deepcopy({1: {2, 3}}), {1: {2, 3}}) + self.assertEqual(copy.deepcopy([1j, 2]), [1j, 2]) + deep = [] + cur = deep + for _ in range(300): + nxt = [] + cur.append(nxt) + cur = nxt + out = copy.deepcopy(deep) + depth = 0 + while out: + out = out[0] + depth += 1 + self.assertEqual(depth, 300) + + def test_trace_sees_copy_frames(self): + seen = [] + + def tracer(frame, event, arg): + if event == "call" and frame.f_code.co_filename.endswith("copy.py"): + seen.append(frame.f_code.co_name) + return None + + sys.settrace(tracer) + try: + copy.deepcopy({"a": [1, 2]}) + finally: + sys.settrace(None) + self.assertIn("deepcopy", seen) + self.assertIn("_deepcopy_dict", seen) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_deeply_nested_closures_compile.py b/tests/regrtest/test_deeply_nested_closures_compile.py new file mode 100644 index 000000000..654e6a373 --- /dev/null +++ b/tests/regrtest/test_deeply_nested_closures_compile.py @@ -0,0 +1,128 @@ +"""Functions nested many levels deep. + +Each nested function reads names from the scopes around it; compiling +the nest works out, once per function, which of its names are free and +which enclosing locals become cells. The cost of compiling grows with +the nest's size and depth, not with a power of its depth, and every +level still sees the right variable. +""" + +import time +import unittest + + +def nested_source(depth): + lines = ["def f0():", " v0 = 0"] + for i in range(depth): + pad = " " * (i + 1) + lines.append(f"{pad}def f{i + 1}():") + lines.append(f"{pad} v{i + 1} = v{i} + 1") + lines.append(" " * (depth + 1) + f"return v{depth}") + for i in range(depth, 0, -1): + lines.append(" " * i + f"return f{i}()") + return "\n".join(lines) + "\n" + + +class NestedClosureTests(unittest.TestCase): + def test_every_level_reads_the_level_above(self): + for depth in (1, 2, 5, 20, 60): + with self.subTest(depth=depth): + ns = {} + exec(compile(nested_source(depth), "", "exec"), ns) + self.assertEqual(ns["f0"](), depth) + + def test_cells_and_free_variables(self): + ns = {} + exec(compile(nested_source(3), "", "exec"), ns) + code = ns["f0"].__code__ + self.assertEqual(code.co_cellvars, ("v0",)) + inner = [c for c in code.co_consts if hasattr(c, "co_freevars")][0] + self.assertEqual(inner.co_freevars, ("v0",)) + self.assertEqual(inner.co_cellvars, ("v1",)) + + def test_names_bound_on_the_way_are_not_reached_through(self): + def outer(): + x = "outer" + + def middle(): + x = "middle" + + def inner(): + def innermost(): + return x + + return innermost() + + return inner() + + return middle(), x + + self.assertEqual(outer(), ("middle", "outer")) + + def with_params(x): + def f(x): + def g(): + return x + + return g() + + return f("param"), x + + self.assertEqual(with_params("arg"), ("param", "arg")) + + def test_nonlocal_and_global_deep_down(self): + src = """ +counter = 100 +def a(): + n = 0 + def b(): + def c(): + nonlocal n + n += 1 + def d(): + global counter + counter += 1 + return n + return d() + return c() + return b(), b(), n +""" + ns = {} + exec(src, ns) + self.assertEqual(ns["a"](), (1, 2, 2)) + self.assertEqual(ns["counter"], 102) + + def test_lambdas_and_comprehensions_in_the_nest(self): + def make(k): + base = k + + def level1(): + return [lambda i=i: base + i for i in range(3)] + + def level2(): + return {j: (lambda: base * j)() for j in range(3)} + + return [f() for f in level1()], level2() + + self.assertEqual(make(10), ([10, 11, 12], {0: 0, 1: 10, 2: 20})) + + def test_compile_cost_grows_slowly_with_depth(self): + def best(src): + t = float("inf") + for _ in range(7): + start = time.perf_counter() + compile(src, "", "exec") + t = min(t, time.perf_counter() - start) + return t + + shallow = best(nested_source(20)) + deep = best(nested_source(80)) + # (Four times as deep: about sixteen times the work at worst. + # Recomputing each nested function's free names at every level + # above it made it about 40 times, and the cubic cost 64; the + # slack absorbs a loaded runner's stalls on millisecond compiles.) + self.assertLess(deep, shallow * 30 + 0.05) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_defaultdict_fast_paths.py b/tests/regrtest/test_defaultdict_fast_paths.py new file mode 100644 index 000000000..ba78b78b9 --- /dev/null +++ b/tests/regrtest/test_defaultdict_fast_paths.py @@ -0,0 +1,68 @@ +"""`defaultdict` construction and misses in place. + +`defaultdict()` and `defaultdict(factory)` of the exact class build the +instance directly; a miss whose factory is a common builtin type stores +and returns the new value as `__missing__` does. Other factories, a +`None` factory, subclasses with their own `__missing__`, and bad +factories keep the Python path and its errors. +""" + +import copy +import pickle +import unittest +from collections import defaultdict + +N = 3000 + + +class OwnMissing(defaultdict): + def __missing__(self, key): + return "mine" + + +class DefaultdictFastPathTests(unittest.TestCase): + def test_construction(self): + for _ in range(N): + a = defaultdict() + b = defaultdict(list) + c = defaultdict(int, {"x": 1}) + self.assertIsNone(a.default_factory) + self.assertIs(b.default_factory, list) + self.assertEqual(c, {"x": 1}) + self.assertEqual(repr(b), "defaultdict(, {})") + with self.assertRaises(TypeError): + defaultdict(1) + + def test_misses(self): + for _ in range(N): + d = defaultdict(list) + d["x"].append(1) + d["x"].append(2) + e = defaultdict(int) + e["a"] += 1 + e["a"] += 1 + f = defaultdict(lambda: "z") + f["q"] + self.assertEqual((d, e, f), ({"x": [1, 2]}, {"a": 2}, {"q": "z"})) + self.assertEqual(list(d), ["x"]) + + def test_none_factory_and_subclass(self): + g = defaultdict(None) + for _ in range(100): + with self.assertRaises(KeyError): + g["k"] + m = OwnMissing(list) + for _ in range(N): + r = m["a"] + self.assertEqual((r, dict(m)), ("mine", {})) + + def test_round_trips(self): + b = defaultdict(list) + b["k"].append(1) + self.assertEqual(pickle.loads(pickle.dumps(b)), b) + self.assertEqual(copy.deepcopy(b), b) + self.assertIs(type(copy.copy(b)), defaultdict) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_defaultdict_missing_verdict.py b/tests/regrtest/test_defaultdict_missing_verdict.py new file mode 100644 index 000000000..b70f49ab3 --- /dev/null +++ b/tests/regrtest/test_defaultdict_missing_verdict.py @@ -0,0 +1,66 @@ +"""defaultdict misses filled in compiled loops while the class keeps the +native __missing__ (a verdict now remembered per class version): counts, +lists and sets as factories, a factory replaced partway, no factory, a +Python factory, a subclass that overrides __missing__, one that gains an +override after the loop warmed up, and get() not inserting, each +matching CPython.""" + +import collections +import unittest + + +def count(n, d, words): + for i in range(n): + for w in words: + d[w] += 1 + return d + + +class DefaultDictMissingTests(unittest.TestCase): + def test_factories(self): + words = "a b a c b a".split() + for n in (1, 300): + d = count(n, collections.defaultdict(int), words) + self.assertEqual(dict(d), {"a": 3 * n, "b": 2 * n, "c": n}) + g = collections.defaultdict(list) + for i in range(n): + g[i % 3].append(i) + self.assertEqual(sorted(g), [0, 1, 2][: min(n, 3)]) + s = collections.defaultdict(set) + for i in range(n): + s["k"].add(i % 2) + self.assertEqual(s["k"], {0, 1} if n > 1 else {0}) + + def test_factory_changes(self): + d = collections.defaultdict(int) + count(300, d, ["x"]) + d.default_factory = lambda: 100 + count(300, d, ["y"]) + self.assertEqual(d["y"], 400) + d.default_factory = None + with self.assertRaises(KeyError): + count(300, d, ["z"]) + self.assertEqual(d.get("w"), None) + self.assertNotIn("w", d) + + def test_subclass_override(self): + class Loud(collections.defaultdict): + def __missing__(self, key): + self[key] = 10 + return 10 + + d = count(300, Loud(int), ["q"]) + self.assertEqual(d["q"], 310) + + class Later(collections.defaultdict): + pass + + d = count(300, Later(int), ["r"]) + self.assertEqual(d["r"], 300) + Later.__missing__ = lambda self, key: self.__setitem__(key, 50) or 50 + d2 = count(300, Later(int), ["r"]) + self.assertEqual(d2["r"], 350) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_del_list_slice.py b/tests/regrtest/test_del_list_slice.py new file mode 100644 index 000000000..b0ea2555b --- /dev/null +++ b/tests/regrtest/test_del_list_slice.py @@ -0,0 +1,58 @@ +"""`del xs[a:b]` of a list. + +A unit step's run is removed by its bounds alone (negative, past either +end, empty, or reversed); an extended slice, a list subclass and items +whose release runs code take the full path, and finalizers run after +the list has changed, last item first, as in CPython. Run it past the compile threshold. +""" + + +class Noisy: + log = [] + + def __init__(self, k): + self.k = k + + def __del__(self): + Noisy.log.append(self.k) + + +class L(list): + pass + + +def run(n): + for i in range(n): + xs = list(range(10)) + del xs[-3:] + assert xs == list(range(7)) + del xs[2:4] + assert xs == [0, 1, 4, 5, 6] + del xs[10:20] + del xs[3:1] + del xs[-20:1] + assert xs == [1, 4, 5, 6] + del xs[:] + assert xs == [] + ys = list(range(8)) + del ys[::2] + assert ys == [1, 3, 5, 7] + del ys[1:3:1] + assert ys == [1, 7] + zs = L(range(5)) + del zs[1:3] + assert zs == [0, 3, 4] and type(zs) is L + ws = ["a", "b", (1, 2), None, 2.5] + del ws[1:4] + assert ws == ["a", 2.5] + holder = [Noisy(1), Noisy(2), Noisy(3)] + del holder[0:2] + assert Noisy.log == [2, 1] and len(holder) == 1 + Noisy.log.clear() + spaced = [Noisy(4), Noisy(5), Noisy(6), Noisy(7)] + del spaced[::2] + assert Noisy.log == [4, 6] and len(spaced) == 2 + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_deque_construction.py b/tests/regrtest/test_deque_construction.py new file mode 100644 index 000000000..9f3e97b2a --- /dev/null +++ b/tests/regrtest/test_deque_construction.py @@ -0,0 +1,47 @@ +"""`deque()` and `deque(xs)` of a list or tuple build in place. + +The exact class's plain constructions lay the instance out as its +`__init__` does; a `maxlen`, any other iterable, and subclasses keep the +Python constructor, and the result behaves as a deque throughout. +""" + +import copy +import pickle +import unittest +from collections import deque + +N = 3000 + + +class D(deque): + pass + + +class DequeConstructionTests(unittest.TestCase): + def test_shapes(self): + L = [1, 2, 3] + for _ in range(N): + a = deque() + b = deque(L) + c = deque((4, 5)) + d = deque("xy") + e = deque(L, 2) + a.append(1) + b.appendleft(0) + self.assertEqual((list(a), list(b), list(c), list(d), list(e)), ([1], [0, 1, 2, 3], [4, 5], ["x", "y"], [2, 3])) + self.assertIsNone(b.maxlen) + self.assertEqual(e.maxlen, 2) + L.append(4) + self.assertEqual(list(b), [0, 1, 2, 3]) + self.assertEqual(list(reversed(b)), [3, 2, 1, 0]) + self.assertIs(type(D([1])), D) + + def test_round_trips(self): + b = deque([1, 2]) + self.assertEqual(copy.copy(b), b) + self.assertEqual(pickle.loads(pickle.dumps(b)), b) + self.assertEqual(repr(deque()), "deque([])") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_deque_iter_odict_eq_native_methods.py b/tests/regrtest/test_deque_iter_odict_eq_native_methods.py new file mode 100644 index 000000000..f9fe10b6a --- /dev/null +++ b/tests/regrtest/test_deque_iter_odict_eq_native_methods.py @@ -0,0 +1,71 @@ +"""Deque iteration through its iterators' leaf halves, OrderedDict +equality over plain keys compared natively, and a native method of a +Python-level class (deque.extend) called in place from compiled loops: +items in order and reversed, a deque mutated during iteration +(RuntimeError), equality sensitive to order and length, keys with a +Python __eq__ (the full walk), bounded deques trimming as they extend, +and extend from a generator or the deque itself, each matching CPython.""" + +import collections +import unittest + + +class Key: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, Key) and self.v == other.v + + +class DequeOdictTests(unittest.TestCase): + def test_deque_iteration(self): + d = collections.deque(range(20)) + d.rotate(3) + for i in range(300): + a = list(d) + r = list(reversed(d)) + s = sum(x for x in d) + self.assertEqual(a, [17, 18, 19] + list(range(17))) + self.assertEqual(r, a[::-1]) + self.assertEqual(s, 190) + with self.assertRaises(RuntimeError): + for x in d: + d.append(1) + + def test_odict_eq(self): + a = collections.OrderedDict(a=1, b=2, c=3) + b = collections.OrderedDict(a=1, b=2, c=3) + c = collections.OrderedDict(b=2, a=1, c=3) + e = collections.OrderedDict([(1, "x"), ("1", "y")]) + f = collections.OrderedDict([(1, "x"), ("1", "y")]) + for i in range(300): + r = (a == b, a == c, a != c, a == dict(c), e == f, a == e) + self.assertEqual(r, (True, False, True, True, True, False)) + k1 = collections.OrderedDict([(Key(1), 1), (Key(2), 2)]) + k2 = collections.OrderedDict([(Key(1), 1), (Key(2), 2)]) + k3 = collections.OrderedDict([(Key(2), 2), (Key(1), 1)]) + self.assertTrue(k1 == k2) + self.assertFalse(k1 == k3) + + def test_extend_in_place(self): + d = collections.deque(maxlen=5) + for i in range(300): + d.extend((i, i + 1, i + 2)) + self.assertEqual(list(d), [299, 300, 299, 300, 301]) + e = collections.deque() + for i in range(300): + e.extend(x for x in range(2)) + e.extendleft([9]) + self.assertEqual(len(e), 900) + self.assertEqual(list(e)[:3], [9, 9, 9]) + f = collections.deque([1, 2]) + f.extend(f) + self.assertEqual(list(f), [1, 2, 1, 2]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_deque_keyword_construction.py b/tests/regrtest/test_deque_keyword_construction.py new file mode 100644 index 000000000..40f5c9d2e --- /dev/null +++ b/tests/regrtest/test_deque_keyword_construction.py @@ -0,0 +1,75 @@ +"""`deque(xs, maxlen=n)` and other keyword constructions. + +The exact class builds natively when its keywords name the next positional +parameters in order; every other spelling, bad value or changed class must +behave as `__init__` has it. +""" + +import unittest +from collections import deque + + +class KeywordConstructionTests(unittest.TestCase): + def test_maxlen_keyword(self): + src = list(range(20)) + for i in range(300): + d = deque(src, maxlen=5) + d.appendleft(i) + self.assertEqual(list(d), [i, 15, 16, 17, 18]) + self.assertEqual(d.maxlen, 5) + self.assertEqual(list(deque((1, 2, 3), maxlen=None)), [1, 2, 3]) + self.assertEqual(deque([1, 2, 3], maxlen=None).maxlen, None) + self.assertEqual(list(deque([1, 2, 3], maxlen=0)), []) + self.assertEqual(list(deque(iterable=[1, 2], maxlen=1)), [2]) + self.assertEqual(list(deque(iterable="ab")), ["a", "b"]) + self.assertEqual(deque(maxlen=3).maxlen, 3) + self.assertEqual(list(deque(iter([1, 2, 3]), maxlen=2)), [2, 3]) + self.assertEqual(list(deque(range(5), maxlen=2)), [3, 4]) + + def test_consume_idiom(self): + it = iter(range(10)) + deque(it, maxlen=0) + self.assertEqual(list(it), []) + + def test_independent_copy(self): + src = [1, 2, 3] + d = deque(src, maxlen=2) + src.append(4) + d.append(5) + self.assertEqual(src, [1, 2, 3, 4]) + self.assertEqual(list(d), [3, 5]) + + def test_errors(self): + with self.assertRaises(ValueError): + deque([1], maxlen=-1) + with self.assertRaises(TypeError): + deque([1], maxlen=1.5) + with self.assertRaises(TypeError): + deque([1], maxlen="2") + with self.assertRaises(TypeError): + deque([1], size=2) + with self.assertRaises(TypeError): + deque([1], 2, maxlen=2) + with self.assertRaises(TypeError): + deque(maxlen=2, iterable=[1], extra=3) + + def test_subclass_and_changed_init(self): + class D(deque): + def __init__(self, iterable=(), maxlen=None): + super().__init__(iterable, maxlen) + self.tag = maxlen + + d = D([1, 2, 3], maxlen=2) + self.assertIs(type(d), D) + self.assertEqual((list(d), d.tag), ([2, 3], 2)) + for _ in range(100): + self.assertEqual(list(D("abc", maxlen=1)), ["c"]) + self.assertEqual(list(deque("abc", maxlen=1)), ["c"]) + + def test_keywords_out_of_order(self): + # (They bind as `__init__` binds them.) + self.assertEqual(list(deque(maxlen=2, iterable=[1, 2, 3])), [2, 3]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_deque_len_loops.py b/tests/regrtest/test_deque_len_loops.py new file mode 100644 index 000000000..e20a58226 --- /dev/null +++ b/tests/regrtest/test_deque_len_loops.py @@ -0,0 +1,70 @@ +"""`len(dq)` in a hot loop reads a deque's length by its direct +operation; deques with a `maxlen`, subclasses with and without their own +`__len__`, a class that borrows `deque.__len__` for another receiver, and +a deque's `__len__` replaced on a subclass later match the general +`len()`.""" + +import collections +import unittest + + +class Plain(collections.deque): + pass + + +class Counted(collections.deque): + def __len__(self): + return 7 + + +class Borrow: + __len__ = collections.deque.__len__ + + +class DequeLenLoops(unittest.TestCase): + def test_lengths(self): + dq = collections.deque() + bounded = collections.deque(maxlen=5) + sub = Plain() + seen = [] + for i in range(20000): + dq.append(i) + bounded.append(i) + sub.appendleft(i) + if len(dq) > 10: + dq.popleft() + if len(sub) > 3: + sub.pop() + if i < 12: + seen.append((len(dq), len(bounded), len(sub))) + self.assertEqual(seen[0], (1, 1, 1)) + self.assertEqual(seen[11], (10, 5, 3)) + self.assertEqual((len(dq), len(bounded), len(sub)), (10, 5, 3)) + + def test_overrides(self): + c = Counted([1, 2]) + n = 0 + for i in range(5000): + n += len(c) + self.assertEqual(n, 35000) + b = Borrow() + for i in range(500): + with self.assertRaises(TypeError): + len(b) + + def test_replaced_later(self): + class D(collections.deque): + pass + + d = D([1, 2, 3]) + out = [] + for i in range(3000): + out.append(len(d)) + D.__len__ = lambda self: 99 + for i in range(3000): + out.append(len(d)) + self.assertEqual((out.count(3), out.count(99)), (3000, 3000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_deque_maxlen_extend.py b/tests/regrtest/test_deque_maxlen_extend.py new file mode 100644 index 000000000..3ac2c77b3 --- /dev/null +++ b/tests/regrtest/test_deque_maxlen_extend.py @@ -0,0 +1,74 @@ +"""`deque(items, maxlen=n)` and `d.extend(items)` of a bounded deque from a +list or tuple longer than the bound, in hot loops. + +The deque must keep the last `n` items in order; items already held must +be released oldest first, before the call returns; a zero bound keeps +nothing; extending must invalidate live iterators; `extendleft` must +still trim from the right. +""" + +import collections +import unittest + +released = [] + + +class Tracked: + def __init__(self, tag): + self.tag = tag + + def __del__(self): + released.append(self.tag) + + +class DequeMaxlenExtend(unittest.TestCase): + def test_construct(self): + src = list(range(20)) + for i in range(3000): + n = i % 7 + d = collections.deque(src, maxlen=n) + self.assertEqual(list(d), src[len(src) - n:] if n else []) + self.assertEqual(d.maxlen, n) + t = collections.deque(tuple(src[:3]), maxlen=5) + self.assertEqual(list(t), [0, 1, 2]) + + def test_extend_existing(self): + for i in range(2000): + d = collections.deque([-3, -2, -1], maxlen=4) + d.extend([0, 1]) + self.assertEqual(list(d), [-2, -1, 0, 1]) + d.extend(tuple(range(10))) + self.assertEqual(list(d), [6, 7, 8, 9]) + d.popleft() + d.extend([10]) + self.assertEqual(list(d), [7, 8, 9, 10]) + d.extendleft([1, 2, 3]) + self.assertEqual(list(d), [3, 2, 1, 7]) + self.assertEqual(len(d), 4) + self.assertEqual(d[0], 3) + self.assertEqual(d[-1], 7) + + def test_release_order(self): + released.clear() + d = collections.deque([Tracked(i) for i in range(3)], maxlen=3) + d.extend([Tracked(10), Tracked(11)]) + self.assertEqual(released, [0, 1]) + d.extend((Tracked(20), Tracked(21), Tracked(22), Tracked(23))) + self.assertEqual(released, [0, 1, 2, 10, 11, 20]) + self.assertEqual([t.tag for t in d], [21, 22, 23]) + + def test_zero_and_iterators(self): + d = collections.deque([1, 2], maxlen=0) + d.extend([3, 4, 5]) + self.assertEqual(list(d), []) + d = collections.deque(range(5), maxlen=3) + it = iter(d) + next(it) + d.extend([7, 8, 9, 10]) + with self.assertRaises(RuntimeError): + next(it) + self.assertEqual(list(d), [8, 9, 10]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_deque_native_iteration.py b/tests/regrtest/test_deque_native_iteration.py new file mode 100644 index 000000000..6c409ce44 --- /dev/null +++ b/tests/regrtest/test_deque_native_iteration.py @@ -0,0 +1,286 @@ +"""A deque's `for` loops, `list()`/`sorted()`/`sum()`, `in`, `copy()` +and construction from a range, a str or with a positional `maxlen`: +the native lanes match the Python methods, for subclasses that override +them, for items whose `__eq__` runs code, and when the deque changes +under a loop.""" + +import collections +import unittest +from collections import deque + +N = 300 + + +class Loud(deque): + def __iter__(self): + return iter(["loud"]) + + +class Counted(deque): + def __len__(self): + Counted.calls += 1 + return super().__len__() + + +Counted.calls = 0 + + +class Picky(deque): + def __contains__(self, x): + return x == "picky" + + +class Quiet(deque): + pass + + +class Eq: + def __init__(self, v): + self.v = v + self.asked = 0 + + def __eq__(self, other): + self.asked += 1 + return self.v == other + + +def loop(it): + out = [] + for x in it: + out.append(x) + return out + + +class ForLoopTests(unittest.TestCase): + def test_plain_loops(self): + d = deque(range(12)) + for _ in range(N): + self.assertEqual(loop(d), list(range(12))) + t = 0 + for x in d: + t += x + self.assertEqual(t, 66) + self.assertEqual(loop(deque()), []) + + def test_after_popleft_and_rotate(self): + for _ in range(N): + d = deque(range(10)) + d.popleft() + d.popleft() + d.appendleft("L") + d.rotate(2) + self.assertEqual(loop(d), [8, 9, "L", 2, 3, 4, 5, 6, 7]) + self.assertEqual(list(d), loop(d)) + + def test_mutation_under_a_loop_raises(self): + for _ in range(50): + d = deque(range(5)) + seen = [] + with self.assertRaises(RuntimeError): + for x in d: + seen.append(x) + if x == 2: + d.append(99) + self.assertEqual(seen, [0, 1, 2]) + d = deque(range(5)) + with self.assertRaises(RuntimeError): + for x in d: + d.popleft() + + def test_item_assignment_under_a_loop_is_seen(self): + for _ in range(50): + d = deque([1, 2, 3]) + seen = [] + for x in d: + seen.append(x) + d[2] = "new" + self.assertEqual(seen, [1, 2, "new"]) + + def test_break_and_the_iterator_object(self): + d = deque(range(6)) + for _ in range(N): + for x in d: + if x == 3: + break + self.assertEqual(x, 3) + it = iter(d) + self.assertEqual(type(it).__name__, "_deque_iterator") + self.assertEqual(next(it), 0) + self.assertEqual(it.__length_hint__(), 5) + self.assertEqual(list(it), [1, 2, 3, 4, 5]) + self.assertEqual(list(it), []) + + def test_subclasses(self): + for _ in range(N): + self.assertEqual(loop(Loud([1, 2])), ["loud"]) + self.assertEqual(list(Loud([1, 2])), ["loud"]) + self.assertEqual(loop(Quiet([1, 2])), [1, 2]) + self.assertEqual(list(Quiet("ab")), ["a", "b"]) + before = Counted.calls + self.assertEqual(list(Counted([1, 2, 3])), [1, 2, 3]) + self.assertEqual(sorted(Counted([3, 1, 2])), [1, 2, 3]) + self.assertGreaterEqual(Counted.calls, before) + + def test_nested_and_shared(self): + d = deque(range(4)) + for _ in range(N): + pairs = [] + for a in d: + for b in d: + if a < b: + pairs.append((a, b)) + self.assertEqual(len(pairs), 6) + self.assertEqual([x for x in d if x % 2], [1, 3]) + self.assertEqual(sum(x for x in d), 6) + + +class CollectTests(unittest.TestCase): + def test_collectors(self): + d = deque([3, 1, 2]) + d.appendleft(9) + d.popleft() + for _ in range(N): + self.assertEqual(list(d), [3, 1, 2]) + self.assertEqual(tuple(d), (3, 1, 2)) + self.assertEqual(sorted(d), [1, 2, 3]) + self.assertEqual(set(d), {1, 2, 3}) + self.assertEqual(sum(d), 6) + self.assertEqual(max(d), 3) + self.assertEqual("-".join(map(str, d)), "3-1-2") + self.assertEqual(dict(deque([("a", 1), ("b", 2)])), {"a": 1, "b": 2}) + a, b, c = d + self.assertEqual((a, b, c), (3, 1, 2)) + self.assertEqual([*d, *d], [3, 1, 2, 3, 1, 2]) + + def test_copy_is_a_snapshot(self): + d = deque([[1], [2]]) + got = list(d) + d.append([3]) + self.assertEqual(got, [[1], [2]]) + self.assertIs(got[0], d[0]) + + +class ContainsTests(unittest.TestCase): + def test_plain_items(self): + d = deque(["a", 1, 2.5, None, b"x", True]) + d.appendleft("gone") + d.popleft() + for _ in range(N): + self.assertIn("a", d) + self.assertIn(1, d) + self.assertIn(1.0, d) + self.assertIn(None, d) + self.assertNotIn("gone", d) + self.assertNotIn(7, d) + self.assertNotIn("b", deque()) + self.assertTrue(d.__contains__(2.5)) + self.assertTrue(deque.__contains__(d, b"x")) + + def test_items_with_eq(self): + for _ in range(50): + e = Eq(5) + d = deque([1, e, 3]) + self.assertIn(5, d) + self.assertGreater(e.asked, 0) + self.assertNotIn(6, d) + self.assertIn(e, d) + nan = float("nan") + self.assertIn(nan, deque([nan])) + self.assertNotIn(float("nan"), deque([nan])) + + def test_eq_that_mutates_raises(self): + d = deque(range(3)) + + class Evil: + def __eq__(self, other): + d.clear() + return False + + with self.assertRaises(RuntimeError): + Evil() in d + + def test_subclass_override(self): + for _ in range(N): + self.assertIn("picky", Picky()) + self.assertNotIn(1, Picky([1])) + self.assertIn(1, Quiet([1])) + + +class ConstructionTests(unittest.TestCase): + def test_sources(self): + for _ in range(N): + self.assertEqual(list(deque(range(5))), [0, 1, 2, 3, 4]) + self.assertEqual(list(deque(range(10, 0, -3))), [10, 7, 4, 1]) + self.assertEqual(list(deque(range(0))), []) + self.assertEqual(list(deque("héllo")), ["h", "é", "l", "l", "o"]) + self.assertEqual(list(deque(x * 2 for x in range(3))), [0, 2, 4]) + self.assertEqual(list(deque({"a": 1, "b": 2})), ["a", "b"]) + self.assertEqual(list(deque(deque([1, 2]))), [1, 2]) + + def test_positional_maxlen(self): + for _ in range(N): + d = deque([1, 2, 3, 4], 2) + self.assertEqual((list(d), d.maxlen), ([3, 4], 2)) + d.append(5) + self.assertEqual(list(d), [4, 5]) + self.assertEqual(list(deque((1, 2, 3), 0)), []) + self.assertEqual(deque([1, 2], None).maxlen, None) + self.assertEqual(list(deque([1, 2], 9)), [1, 2]) + self.assertEqual(list(deque(range(6), 3)), [3, 4, 5]) + self.assertEqual(list(deque("abcd", 2)), ["c", "d"]) + with self.assertRaises(ValueError): + deque([1], -1) + with self.assertRaises(TypeError): + deque([1], "2") + with self.assertRaises(TypeError): + deque(5) + + def test_copy_keeps_maxlen_and_class(self): + for _ in range(N): + d = deque([1, 2, 3], maxlen=3) + c = d.copy() + self.assertEqual((list(c), c.maxlen), ([1, 2, 3], 3)) + c.append(4) + self.assertEqual((list(c), list(d)), ([2, 3, 4], [1, 2, 3])) + q = Quiet([1, 2]).copy() + self.assertIs(type(q), Quiet) + self.assertEqual(list(q), [1, 2]) + + def test_extend_from_other_iterables(self): + for _ in range(N): + d = deque([0]) + d.extend(range(1, 4)) + d.extend(x for x in "ab") + d.extendleft(iter([-1, -2])) + self.assertEqual(list(d), [-2, -1, 0, 1, 2, 3, "a", "b"]) + m = deque(maxlen=3) + m.extend(range(10)) + self.assertEqual(list(m), [7, 8, 9]) + m.extendleft(range(2)) + self.assertEqual(list(m), [1, 0, 7]) + + def test_extend_error_midway_keeps_earlier_items(self): + def gen(): + yield 1 + yield 2 + raise KeyError("stop here") + + d = deque() + with self.assertRaises(KeyError): + d.extend(gen()) + self.assertEqual(list(d), [1, 2]) + with self.assertRaises(TypeError): + d.extend(5) + self.assertEqual(list(d), [1, 2]) + + def test_extend_with_own_iterator_raises(self): + d = deque([1, 2, 3]) + with self.assertRaises(RuntimeError): + d.extend(iter(d)) + d = deque([1, 2]) + d.extend(d) + self.assertEqual(list(d), [1, 2, 1, 2]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_deque_rotate_and_extend_in_blocks.py b/tests/regrtest/test_deque_rotate_and_extend_in_blocks.py new file mode 100644 index 000000000..3bf0521e3 --- /dev/null +++ b/tests/regrtest/test_deque_rotate_and_extend_in_blocks.py @@ -0,0 +1,275 @@ +"""`deque.rotate`, `extend`, `extendleft` and the searches over long deques. + +A rotation moves its items as one block, with room made at the front +for the next few rotations at once; `extend` and `extendleft` of a list +or tuple take its items in at once, trimming to `maxlen` as item-by-item +appends would. Every result matches a list model, through any mix of +rotations, extensions and pops, with and without `maxlen`. +""" + +import collections +import random +import time +import unittest + + +def rotated(items, k): + if not items: + return items + k %= len(items) + return items[-k:] + items[:-k] if k else list(items) + + +class RotateTests(unittest.TestCase): + def test_rotations_match_a_list(self): + for n in (0, 1, 2, 7, 100, 1001): + for k in (0, 1, -1, 2, -3, n // 3, -(n // 3), n // 2, n - 1, n, n + 5, -(2 * n) - 1, 10**9): + with self.subTest(n=n, k=k): + d = collections.deque(range(n)) + d.rotate(k) + self.assertEqual(list(d), rotated(list(range(n)), k)) + d.rotate(-k) + self.assertEqual(list(d), list(range(n))) + + def test_repeated_rotations(self): + d = collections.deque(range(4000)) + model = list(range(4000)) + for step in (1333, -1333, 1, -1, 1999, -2001, 4000, 7): + for _ in range(13): + d.rotate(step) + model = rotated(model, step) + self.assertEqual(list(d), model) + self.assertEqual(d[0], model[0]) + self.assertEqual(d[-1], model[-1]) + self.assertEqual(len(d), 4000) + + def test_rotation_keeps_items_alive_and_unique(self): + items = [object() for _ in range(300)] + d = collections.deque(items) + for _ in range(50): + d.rotate(97) + self.assertEqual(sorted(map(id, d)), sorted(map(id, items))) + d.rotate(-(97 * 50) % 300) + self.assertTrue(all(a is b for a, b in zip(d, items))) + + def test_rotation_with_maxlen_and_after_pops(self): + d = collections.deque(range(10), maxlen=10) + d.rotate(3) + self.assertEqual(list(d), [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]) + d.append(10) + self.assertEqual(list(d), [8, 9, 0, 1, 2, 3, 4, 5, 6, 10]) + d.appendleft(-1) + self.assertEqual(list(d), [-1, 8, 9, 0, 1, 2, 3, 4, 5, 6]) + for _ in range(4): + d.popleft() + d.rotate(-2) + self.assertEqual(list(d), [3, 4, 5, 6, 1, 2]) + + def test_rotation_during_iteration_is_an_error(self): + d = collections.deque(range(10)) + it = iter(d) + next(it) + d.rotate(2) + with self.assertRaises(RuntimeError): + next(it) + + +class ExtendTests(unittest.TestCase): + def test_extend_and_extendleft_match_a_list(self): + for src in ([], [1], [1, 2, 3], (4, 5), tuple(range(50)), list(range(1000))): + with self.subTest(n=len(src)): + d = collections.deque([0]) + d.extend(src) + self.assertEqual(list(d), [0] + list(src)) + d = collections.deque([0]) + d.extendleft(src) + self.assertEqual(list(d), list(reversed(src)) + [0]) + + def test_maxlen_trims_as_appends_would(self): + for maxlen in (0, 1, 3, 10): + for src in ([1, 2, 3], tuple(range(25)), []): + with self.subTest(maxlen=maxlen, n=len(src)): + d = collections.deque(range(5), maxlen=maxlen) + d.extend(src) + want = collections.deque(range(5), maxlen=maxlen) + for x in src: + want.append(x) + self.assertEqual(list(d), list(want)) + d = collections.deque(range(5), maxlen=maxlen) + d.extendleft(src) + want = collections.deque(range(5), maxlen=maxlen) + for x in src: + want.appendleft(x) + self.assertEqual(list(d), list(want)) + + def test_other_iterables(self): + d = collections.deque() + d.extend(x * 2 for x in range(3)) + d.extendleft(iter("ab")) + d.extend(range(3)) + d.extend({7: 0}) + self.assertEqual(list(d), ["b", "a", 0, 2, 4, 0, 1, 2, 7]) + d.extend(d) + self.assertEqual(len(d), 18) + d.extendleft(d) + self.assertEqual(len(d), 36) + + def failing(): + yield 1 + yield 2 + raise ValueError("stop") + + d = collections.deque() + with self.assertRaises(ValueError): + d.extend(failing()) + self.assertEqual(list(d), [1, 2]) + with self.assertRaises(TypeError): + d.extend(5) + with self.assertRaises(TypeError): + d.extendleft(None) + + def test_subclasses_and_identity(self): + class D(collections.deque): + pass + + d = D([1]) + d.extend((2, 3)) + d.extendleft([0]) + self.assertEqual(list(d), [0, 1, 2, 3]) + self.assertIs(type(d), D) + items = [object(), object()] + e = collections.deque() + e.extend(items) + self.assertIs(e[0], items[0]) + items.append(object()) + self.assertEqual(len(e), 2) + + def test_extension_during_iteration_is_an_error(self): + d = collections.deque(range(3)) + it = iter(d) + next(it) + d.extend([9]) + with self.assertRaises(RuntimeError): + next(it) + + +class RandomTests(unittest.TestCase): + def test_random_mixes(self): + r = random.Random(7) + for maxlen in (None, 20): + d = collections.deque(range(30), maxlen=maxlen) + model = list(range(30))[-maxlen:] if maxlen else list(range(30)) + for step in range(4000): + op = r.randrange(7) + if op == 0: + k = r.randrange(-80, 80) + d.rotate(k) + model = rotated(model, k) + elif op == 1: + items = [r.randrange(100) for _ in range(r.randrange(6))] + d.extend(items) + model = model + items + elif op == 2: + items = tuple(r.randrange(100) for _ in range(r.randrange(6))) + d.extendleft(items) + model = list(reversed(items)) + model + if maxlen: + model = model[:maxlen] + elif op == 3 and model: + self.assertEqual(d.popleft(), model.pop(0)) + elif op == 4 and model: + self.assertEqual(d.pop(), model.pop()) + elif op == 5: + x = r.randrange(100) + d.appendleft(x) + model.insert(0, x) + if maxlen: + model = model[:maxlen] + else: + x = r.randrange(100) + d.append(x) + model.append(x) + if maxlen: + model = model[-maxlen:] + self.assertEqual(list(d), model, step) + + +class SearchTests(unittest.TestCase): + def test_plain_values(self): + d = collections.deque([1, 2.0, "a", b"b", None, True, 2]) + self.assertIn(2, d) + self.assertIn(1.0, d) + self.assertIn("a", d) + self.assertNotIn("b", d) + self.assertIn(b"b", d) + self.assertIn(None, d) + self.assertEqual(d.count(2), 2) + self.assertEqual(d.count(1), 2) + self.assertEqual(d.index(2), 1) + self.assertEqual(d.index(2, 2), 6) + self.assertEqual(d.index("a", -5, -3), 2) + with self.assertRaises(ValueError) as cm: + d.index(99) + self.assertEqual(str(cm.exception), "deque.index(x): x not in deque") + with self.assertRaises(ValueError): + d.index(2, 2, 6) + nan = float("nan") + n = collections.deque([nan]) + self.assertIn(nan, n) + self.assertNotIn(float("nan"), n) + self.assertEqual(n.count(nan), 1) + + def test_python_equality_still_runs(self): + calls = [] + + class Eq: + def __eq__(self, other): + calls.append(other) + return other == 5 + + d = collections.deque([1, Eq(), 3]) + self.assertIn(5, d) + self.assertEqual(d.count(5), 1) + self.assertEqual(d.index(5), 1) + self.assertTrue(calls) + self.assertIn(Eq(), collections.deque([5])) + + class Mutating: + def __eq__(self, other): + d.append(0) + return False + + d = collections.deque([Mutating(), 1]) + with self.assertRaises(RuntimeError): + 2 in d + + def test_after_rotations_and_pops(self): + d = collections.deque(range(1000)) + d.rotate(300) + for _ in range(10): + d.popleft() + self.assertEqual(d.index(0), 290) + self.assertNotIn(700, d) + self.assertEqual(d.count(999), 1) + + +class CostTests(unittest.TestCase): + def test_a_rotation_costs_what_it_moves(self): + def best(n): + d = collections.deque(range(n)) + k = n // 3 + t = float("inf") + for _ in range(3): + start = time.perf_counter() + for _ in range(30): + d.rotate(k) + t = min(t, time.perf_counter() - start) + return t + + small = best(3_000) + large = best(300_000) + self.assertLess(large, small * 300 + 0.05) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_descriptor_set_direct.py b/tests/regrtest/test_descriptor_set_direct.py new file mode 100644 index 000000000..40b9f3204 --- /dev/null +++ b/tests/regrtest/test_descriptor_set_direct.py @@ -0,0 +1,171 @@ +"""Compiled attribute stores through a data descriptor's Python `__set__` +call it directly; the values stored, validation raises (caught in the +frame or past it), stores from `self.x = v`, descriptors shadowing the +instance dict, non-data descriptors, and a descriptor replaced later +match the general store.""" + +import unittest +import weakref + + +class Typed: + def __set_name__(self, owner, name): + self.name = "_" + name + + def __get__(self, obj, cls): + if obj is None: + return self + return getattr(obj, self.name) + + def __set__(self, obj, v): + if not isinstance(v, int): + raise TypeError(f"{self.name[1:]} must be int") + setattr(obj, self.name, v) + + +class Counted: + def __init__(self): + self.sets = 0 + + def __get__(self, obj, cls): + return obj.__dict__.get("c") + + def __set__(self, obj, v): + self.sets += 1 + obj.__dict__["c"] = v + return "ignored" + + +class NonData: + def __get__(self, obj, cls): + return "from descriptor" + + +class P: + x = Typed() + c = Counted() + nd = NonData() + + def __init__(self, x): + self.x = x + + def bump(self): + for i in range(20): + self.x = self.x + 1 + + +class Tracked: + deleted = 0 + + def __del__(self): + Tracked.deleted += 1 + + +class Holder: + def __set__(self, obj, v): + obj.__dict__["h"] = v + + def __get__(self, obj, cls): + return obj.__dict__["h"] + + +class Q: + h = Holder() + + +class DescriptorSetDirect(unittest.TestCase): + def test_typed(self): + p = P(0) + for i in range(3000): + p.x = i + self.assertEqual(p.x, 2999) + self.assertEqual(p._x, 2999) + self.assertNotIn("x", p.__dict__) + + def test_counted_and_dict_shadow(self): + p = P(0) + for i in range(2000): + p.c = i + self.assertEqual(P.__dict__["c"].sets, 2000) + self.assertEqual(p.__dict__["c"], 1999) + p.__dict__["x"] = "shadow" + p.x = 5 + self.assertEqual(p._x, 5) + self.assertEqual(p.x, 5) + + def test_validation_raises(self): + p = P(0) + n = 0 + for i in range(1000): + try: + p.x = "bad" + except TypeError as e: + n += 1 + self.assertEqual(str(e), "x must be int") + self.assertEqual(n, 1000) + + def store(o, v): + o.x = v + return "after" + + for i in range(1000): + with self.assertRaises(TypeError): + store(p, "no") + self.assertEqual(store(p, i), "after") + self.assertEqual(p.x, 999) + + def test_self_stores(self): + for i in range(200): + p = P(i) + p.bump() + self.assertEqual(p.x, i + 20) + + def test_non_data_descriptor(self): + p = P(0) + for i in range(1000): + p.nd = i + self.assertEqual(p.nd, 999) + self.assertEqual(p.__dict__["nd"], 999) + + def test_lifetimes(self): + q = Q() + for i in range(500): + q.h = Tracked() + before = Tracked.deleted + t = Tracked() + r = weakref.ref(t) + q.h = t + del t + self.assertIsNotNone(r()) + q.h = None + self.assertIsNone(r()) + self.assertEqual(Tracked.deleted, before + 2) + + def test_replaced(self): + class D: + def __set__(self, obj, v): + obj.__dict__["d"] = v + 1 + + def __get__(self, obj, cls): + return obj.__dict__["d"] + + class C: + d = D() + + c = C() + for i in range(1000): + c.d = i + self.assertEqual(c.d, 1000) + D.__set__ = lambda self, obj, v: obj.__dict__.__setitem__("d", -v) + for i in range(1000): + c.d = i + self.assertEqual(c.d, -999) + C.d = 5 + for i in range(1000): + c.d = i + self.assertEqual(c.__dict__["d"], 999) + self.assertEqual(c.d, 999) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_copy_tracking.py b/tests/regrtest/test_dict_copy_tracking.py new file mode 100644 index 000000000..5643c477b --- /dev/null +++ b/tests/regrtest/test_dict_copy_tracking.py @@ -0,0 +1,30 @@ +"""`dict.copy()` of a dict whose values can and can't close a cycle. + +The copy is deferred for the collector without a scan of its values; a +copy that then joins a cycle is still collected, and `gc.is_tracked` +answers as CPython's does. +""" + +import gc +import weakref + + +class Node: + pass + + +plain = {"k%d" % i: i for i in range(20)} +for _ in range(3000): + c = plain.copy() + assert c == plain and c is not plain + assert gc.is_tracked(c) == gc.is_tracked(plain.copy()) + +n = Node() +holder = {"n": n} +c = holder.copy() +assert gc.is_tracked(c) +c["self"] = c +r = weakref.ref(n) +del n, holder, c +gc.collect() +assert r() is None diff --git a/tests/regrtest/test_dict_copy_with_keywords.py b/tests/regrtest/test_dict_copy_with_keywords.py new file mode 100644 index 000000000..4250b0a17 --- /dev/null +++ b/tests/regrtest/test_dict_copy_with_keywords.py @@ -0,0 +1,88 @@ +"""`dict(d, k=v)` of an exact dict, which copies its table once and puts +each keyword in by name, keeps CPython's results: new and replaced keys, +key order, non-string keys beside the names, keys whose `__eq__` runs, +subclasses and other first arguments, and a fresh, independent result.""" + +import unittest + +N = 3000 + + +class Key: + """Hashes like the string `name` and equals it, counting comparisons.""" + + calls = 0 + + def __init__(self, name): + self.name = name + + def __hash__(self): + return hash(self.name) + + def __eq__(self, other): + Key.calls += 1 + return other == self.name + + +class D(dict): + def keys(self): + return ["a"] + + +class DictCopyWithKeywordsTests(unittest.TestCase): + def test_new_and_replaced(self): + src = {"a": 1, "b": 2} + for _ in range(N): + r = dict(src, c=3) + self.assertEqual(r, {"a": 1, "b": 2, "c": 3}) + self.assertEqual(list(r), ["a", "b", "c"]) + r = dict(src, a=9) + self.assertEqual(r, {"a": 9, "b": 2}) + self.assertEqual(list(r), ["a", "b"]) + r = dict(src, b=5, z=0, a=7) + self.assertEqual(list(r.items()), [("a", 7), ("b", 5), ("z", 0)]) + self.assertEqual(dict({}, x=1), {"x": 1}) + self.assertEqual(src, {"a": 1, "b": 2}) + + def test_fresh_result(self): + src = {"a": [1]} + for _ in range(N): + r = dict(src, b=2) + self.assertIsNot(r, src) + self.assertIs(type(r), dict) + r["a"] = 0 + del r["b"] + self.assertEqual(src, {"a": [1]}) + self.assertIs(dict(src, b=2)["a"], src["a"]) + + def test_other_keys(self): + src = {1: "one", (2, 3): "t", None: 0, "s": "str"} + for _ in range(N): + r = dict(src, s="S", n=1) + self.assertEqual(r, {1: "one", (2, 3): "t", None: 0, "s": "S", "n": 1}) + Key.calls = 0 + k = Key("a") + src = {k: 1} + for _ in range(N // 10): + r = dict(src, a=2) + self.assertEqual(len(r), 1) + self.assertIs(next(iter(r)), k) + self.assertEqual(r[k], 2) + self.assertGreater(Key.calls, 0) + + def test_other_first_arguments(self): + for _ in range(N // 10): + # (A dict subclass that keeps dict's iteration is merged from + # its table, its own keys() unread, as CPython merges it.) + self.assertEqual(dict(D(a=1, b=2), c=3), {"a": 1, "b": 2, "c": 3}) + self.assertEqual(dict([("a", 1)], b=2), {"a": 1, "b": 2}) + self.assertEqual(dict(zip("ab", (1, 2)), a=0), {"a": 0, "b": 2}) + self.assertEqual(dict(a=1, b=2), {"a": 1, "b": 2}) + with self.assertRaises(TypeError): + dict({}, {}, a=1) + with self.assertRaises(TypeError): + dict(1, a=1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_display_instance_keys.py b/tests/regrtest/test_dict_display_instance_keys.py new file mode 100644 index 000000000..f7e8cc649 --- /dev/null +++ b/tests/regrtest/test_dict_display_instance_keys.py @@ -0,0 +1,128 @@ +"""Dict displays whose keys are instances, in hot loops. + +The frame JIT builds `{k: v}` itself when each instance key's `__hash__` +is a pure leaf and no two keys' hashes agree. Equal keys, keys whose +hashes collide, a key equal to a `str` key, a hash of `-1`, a raising or +unhashable key, and a `__hash__` that isn't a leaf must all build what +the general path builds. +""" + +import dataclasses +import unittest + + +@dataclasses.dataclass(frozen=True) +class FZ: + a: int + b: int = 0 + + +class Same: + def __init__(self, a): + self.a = a + + def __hash__(self): + return 7 + + def __eq__(self, o): + return isinstance(o, Same) and self.a == o.a + + +class LikeStr: + def __hash__(self): + return hash("x") + + def __eq__(self, o): + return o == "x" + + +class MinusOne: + def __hash__(self): + return -1 + + +class Raises: + def __hash__(self): + raise ValueError("no hash") + + +class Unhashable: + __hash__ = None + + +class Counting: + calls = 0 + + def __init__(self, a): + self.a = a + + def __hash__(self): + Counting.calls += 1 + return self.a + + def __eq__(self, o): + return isinstance(o, Counting) and self.a == o.a + + +class DictDisplayInstanceKeys(unittest.TestCase): + def test_frozen_dataclass_keys(self): + for i in range(3000): + d = {FZ(i % 7): i, FZ(-1): "x"} + self.assertEqual(d[FZ(i % 7)], i) + self.assertEqual(len(d), 2) + self.assertEqual(list({FZ(1): 1, FZ(2): 2}), [FZ(1), FZ(2)]) + + def test_equal_keys(self): + for i in range(2000): + first = FZ(i) + d = {first: "a", FZ(i): "b"} + self.assertEqual(len(d), 1) + self.assertIs(next(iter(d)), first) + self.assertEqual(d[first], "b") + + def test_colliding_hashes(self): + for i in range(2000): + d = {Same(1): 1, Same(2): 2, Same(1): 3} + self.assertEqual(len(d), 2) + self.assertEqual(d[Same(1)], 3) + self.assertEqual(d[Same(2)], 2) + + def test_key_equal_to_a_str_key(self): + for _ in range(2000): + d = {"x": 1, LikeStr(): 2} + self.assertEqual(d, {"x": 2}) + self.assertIs(type(next(iter(d))), str) + + def test_minus_one(self): + k = MinusOne() + for _ in range(2000): + d = {k: 1} + self.assertEqual(hash(k), -2) + self.assertEqual(d[k], 1) + + def test_raising_and_unhashable(self): + for _ in range(500): + with self.assertRaises(ValueError): + {Raises(): 1} + with self.assertRaises(TypeError): + {Unhashable(): 1} + with self.assertRaises(TypeError): + {FZ(1): 1, Unhashable(): 2} + + def test_hash_called_once_per_key(self): + Counting.calls = 0 + for i in range(3000): + {Counting(i): 1, Counting(i + 1): 2} + self.assertEqual(Counting.calls, 6000) + + def test_mixed_with_scalars(self): + for i in range(2000): + d = {1: "int", "s": "str", FZ(i): "fz"} + self.assertEqual(d[1], "int") + self.assertEqual(d["s"], "str") + self.assertEqual(d[FZ(i)], "fz") + self.assertEqual(list(d), [1, "s", FZ(i)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_from_kwargs.py b/tests/regrtest/test_dict_from_kwargs.py new file mode 100644 index 000000000..0de0ff6b4 --- /dev/null +++ b/tests/regrtest/test_dict_from_kwargs.py @@ -0,0 +1,65 @@ +"""`dict(**mapping)` returns the mapping the call built. + +The keyword mapping a `CALL_FUNCTION_EX` builds for `dict(**d)` is held by +nothing else, so it becomes the new dict in place of a copy. The result +never aliases the caller's mapping, keeps its order, and non-string keys +still raise. +""" + +import unittest + +N = 3000 + + +class S(str): + pass + + +class DictFromKwargsTests(unittest.TestCase): + def test_copy_is_independent(self): + D = {"a": 1, "b": 2} + for _ in range(N): + r = dict(**D) + self.assertEqual(r, D) + self.assertIsNot(r, D) + r["c"] = 3 + self.assertNotIn("c", D) + + def test_merges_and_order(self): + D = {"b": 2, "a": 1} + E = {"c": 3} + for _ in range(N): + r = dict(z=0, **D) + q = dict(**D, **E) + self.assertEqual(list(r.items()), [("z", 0), ("b", 2), ("a", 1)]) + self.assertEqual(list(q), ["b", "a", "c"]) + + def test_non_string_keys_raise(self): + for _ in range(100): + with self.assertRaises(TypeError): + dict(**{1: 2}) + + def test_string_subclass_keys(self): + k = S("k") + for _ in range(N): + r = dict(**{k: 1}) + self.assertEqual(r, {"k": 1}) + + def test_subclass_and_positional(self): + class D2(dict): + pass + + for _ in range(N): + a = D2(**{"x": 1}) + b = dict(*([("y", 2)],), **{"x": 1}) + self.assertIs(type(a), D2) + self.assertEqual(b, {"y": 2, "x": 1}) + + def test_empty(self): + for _ in range(N): + r = dict(**{}) + self.assertEqual(r, {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_from_lazy_pairs.py b/tests/regrtest/test_dict_from_lazy_pairs.py new file mode 100644 index 000000000..df98706dc --- /dev/null +++ b/tests/regrtest/test_dict_from_lazy_pairs.py @@ -0,0 +1,60 @@ +"""dict() of generators, iterators and zips of pairs from compiled loops: +insertion order, duplicate keys (last value wins, first position kept), +list and string pairs, a pair of the wrong length, an unhashable key, +keys whose __eq__ and __hash__ are Python code, and a generator that +raises partway, each matching CPython.""" + +import unittest + + +class K: + def __init__(self, k): + self.k = k + + def __eq__(self, o): + return isinstance(o, K) and self.k == o.k + + def __hash__(self): + return hash(self.k) + + def __repr__(self): + return "K(%r)" % self.k + + +def build(n, make): + out = None + for i in range(n): + out = dict(make()) + return out + + +class DictFromPairsTests(unittest.TestCase): + def test_shapes(self): + pairs = [("b", 1), ("a", 2), ("b", 3), (4, None)] + for n in (1, 300): + got = build(n, lambda: ((k, v) for k, v in pairs)) + self.assertEqual(list(got.items()), [("b", 3), ("a", 2), (4, None)]) + self.assertEqual(build(n, lambda: iter([["x", 1], "yz"])), {"x": 1, "y": "z"}) + self.assertEqual(build(n, lambda: zip("ab", [1, 2])), {"a": 1, "b": 2}) + self.assertEqual(build(n, lambda: (p for p in [])), {}) + ks = build(n, lambda: ((K(i % 2), i) for i in range(4))) + self.assertEqual(ks, {K(0): 2, K(1): 3}) + + def test_errors(self): + with self.assertRaises(ValueError): + build(300, lambda: (p for p in [("a", 1, 2)])) + with self.assertRaises(TypeError): + build(300, lambda: (p for p in [([], 1)])) + with self.assertRaises(TypeError): + build(300, lambda: (p for p in [1])) + + def gen(): + yield ("a", 1) + raise RuntimeError("partway") + + with self.assertRaises(RuntimeError): + build(300, gen) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_int_key_miss.py b/tests/regrtest/test_dict_int_key_miss.py new file mode 100644 index 000000000..3f27ce554 --- /dev/null +++ b/tests/regrtest/test_dict_int_key_miss.py @@ -0,0 +1,82 @@ +"""Compiled `d[i]` of an exact dict missing an int key raises its +`KeyError` in compiled code and the frame's own handler catches it; the +exception (its args the key itself), keys of other kinds, a handler that +doesn't match, a miss caught past the frame, dict subclasses with +`__missing__`, and lists, tuples and strings indexed out of range match the +general subscript.""" + +import unittest + + +class Missing(dict): + def __missing__(self, k): + return -k + + +class DictIntKeyMiss(unittest.TestCase): + def test_caught_here(self): + d = {i: i for i in range(0, 100, 2)} + hits = misses = 0 + for i in range(3000): + try: + hits += d[i % 100] >= 0 + except KeyError as e: + self.assertEqual(e.args, (i % 100,)) + misses += 1 + self.assertEqual((hits, misses), (1500, 1500)) + + def test_other_keys_and_unmatched(self): + d = {} + n = 0 + for i in range(1000): + for k in (i, -i, 2**70 + i, "s%d" % i, (i,), 1.5): + try: + d[k] + except KeyError as e: + self.assertEqual(e.args[0], k) + n += 1 + self.assertEqual(n, 6000) + + def inner(i): + try: + return d[i] + except IndexError: + return "index" + + for i in range(500): + with self.assertRaises(KeyError): + inner(i) + + def test_past_the_frame(self): + d = {} + + def get(i): + return d[i] + + n = 0 + for i in range(1000): + try: + get(i) + except LookupError: + n += 1 + self.assertEqual(n, 1000) + + def test_missing_and_sequences(self): + m = Missing(a=1) + xs, t, s = [1, 2], (1, 2), "ab" + out = [] + for i in range(1000): + out.append(m[i]) + for seq in (xs, t, s): + try: + seq[i + 2] + except IndexError as e: + out.append(str(e)) + self.assertEqual(out[:4], [0, "list index out of range", + "tuple index out of range", + "string index out of range"]) + self.assertEqual(len(out), 4000) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_literal_keys.py b/tests/regrtest/test_dict_literal_keys.py new file mode 100644 index 000000000..bc34872c2 --- /dev/null +++ b/tests/regrtest/test_dict_literal_keys.py @@ -0,0 +1,24 @@ +"""Dict literals in compiled code. + +Distinct `str` and `int` keys go in without probing for an equal one; a +repeated key, `True` against `1`, and `None` keys take the probe, the last +value winning and the first key kept; a literal that closes a cycle is +still collected. Run it past the compile threshold. +""" + +import gc +def f(n): + for i in range(n): + d = {"a": i, "b": [i], 1: "x", "a": 5} + assert d == {"a": 5, "b": [i], 1: "x"} and list(d) == ["a", "b", 1] + e = {1: "a", True: "b", 2: "c", 2: "d"} + assert e == {1: "b", 2: "d"} and type(next(iter(e))) is int + g = {None: 1, "k": 2, None: 3} + assert g == {None: 3, "k": 2} +f(5000) +l = [] +d = {"x": l} +l.append(d) +del d, l +gc.collect() +print("ok") diff --git a/tests/regrtest/test_dict_merge_then_pairs.py b/tests/regrtest/test_dict_merge_then_pairs.py new file mode 100644 index 000000000..4f5232b52 --- /dev/null +++ b/tests/regrtest/test_dict_merge_then_pairs.py @@ -0,0 +1,110 @@ +"""A dict display that merges a mapping and then lists pairs +(`{**d, "k": v}`) keeps CPython's result when compiled code adds the pairs +straight into the merged dict: order, a listed key replacing a merged one, +keys of every kind, and values released when replaced.""" + +import gc +import unittest + +N = 3000 + + +def repeat(f): + """`f()` run often enough for compiled code to take the display; every + result must equal the first, in the same order.""" + first = f() + for _ in range(N): + r = f() + if r != first or list(r.items()) != list(first.items()): + raise AssertionError((first, r)) + return first + + +class Released: + count = 0 + + def __del__(self): + Released.count += 1 + + +class Key(str): + pass + + +class MergeThenPairsTests(unittest.TestCase): + def test_order_and_replacement(self): + d = {"a": 1, "b": 2, "c": 3} + r = repeat(lambda: {**d, "d": 4}) + self.assertEqual(list(r.items()), [("a", 1), ("b", 2), ("c", 3), ("d", 4)]) + r = repeat(lambda: {**d, "b": 20, "e": 5}) + self.assertEqual(list(r.items()), [("a", 1), ("b", 20), ("c", 3), ("e", 5)]) + # (A key listed twice: the last value, at the first place.) + r = repeat(lambda: {**d, "x": 1, "y": 2, "x": 3}) + self.assertEqual(list(r.items()), [("a", 1), ("b", 2), ("c", 3), ("x", 3), ("y", 2)]) + self.assertEqual(d, {"a": 1, "b": 2, "c": 3}) + + def test_fresh_dict_each_time(self): + d = {"a": 1} + seen = [{**d, "b": i} for i in range(N)] + self.assertEqual([s["b"] for s in seen], list(range(N))) + self.assertTrue(all(s is not d for s in seen)) + self.assertEqual(d, {"a": 1}) + + def test_many_pairs(self): + d = {"a": 0} + r = repeat(lambda: {**d, "k1": 1, "k2": 2, "k3": 3, "k4": 4, "k5": 5, + "k6": 6, "k7": 7, "k8": 8, "k9": 9}) + self.assertEqual(list(r), ["a"] + [f"k{i}" for i in range(1, 10)]) + + def test_int_and_mixed_keys(self): + d = {1: "one", 2: "two"} + self.assertEqual(repeat(lambda: {**d, 2: "TWO", 3: "three"}), + {1: "one", 2: "TWO", 3: "three"}) + self.assertEqual(repeat(lambda: {**d, "s": 0}), {1: "one", 2: "two", "s": 0}) + # (Equal keys of other types: the merged key stays, the value is + # replaced.) + r = repeat(lambda: {**d, True: "t", 2.0: "f"}) + self.assertEqual(list(r.items()), [(1, "t"), (2, "f")]) + self.assertIs(type(list(r)[0]), int) + r = repeat(lambda: {**{True: "t"}, 1: "one"}) + self.assertEqual(list(r.items()), [(True, "one")]) + big = 2**80 + self.assertEqual(repeat(lambda: {**{big: 1}, big: 2}), {big: 2}) + self.assertEqual(repeat(lambda: {**{(1, 2): 1}, "a": 2}), {(1, 2): 1, "a": 2}) + r = repeat(lambda: {**{Key("a"): 1}, "a": 2}) + self.assertIs(type(list(r)[0]), Key) + self.assertEqual(r, {"a": 2}) + + def test_other_mappings(self): + class M: + def keys(self): + return ["a", "b"] + + def __getitem__(self, k): + return k * 2 + + self.assertEqual(repeat(lambda: {**M(), "b": 0, "c": 1}), {"a": "aa", "b": 0, "c": 1}) + self.assertEqual(repeat(lambda: {**{}, "a": 1}), {"a": 1}) + + def test_replaced_values_released(self): + gc.collect() + d = {"a": 1} + before = Released.count + for _ in range(N): + # (The merged value is replaced, the listed one replaced in + # turn: two released per display, then the display itself.) + r = {**{"a": Released()}, "a": Released(), "a": 1} + self.assertEqual(r, {"a": 1}) + self.assertEqual(Released.count - before, 2 * N) + self.assertEqual(d, {"a": 1}) + + def test_errors(self): + for _ in range(N // 10): + with self.assertRaises(TypeError): + {**{"a": 1}, []: 2} + with self.assertRaises(TypeError): + {**[1], "a": 2} + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_merges_of_any_size.py b/tests/regrtest/test_dict_merges_of_any_size.py new file mode 100644 index 000000000..cbc233f1a --- /dev/null +++ b/tests/regrtest/test_dict_merges_of_any_size.py @@ -0,0 +1,409 @@ +"""Merging one dict into another, whatever their sizes. + +`d.update(other)`, `d |= other`, `d | other`, `{**d, **other}`, +`dict(d)` and `d.copy()` give the same dict whether the two are small or +large, whether the keys are strings, ints, tuples or objects with their +own `__eq__`, and whether `other` is a dict or an iterable of pairs. An +existing key keeps its place and its key object and takes the new value; +new keys follow in the source's order. +""" + +import unittest + + +class Key: + """A key whose hash and equality are Python code.""" + + calls = 0 + + def __init__(self, name): + self.name = name + + def __hash__(self): + return hash(self.name) + + def __eq__(self, other): + Key.calls += 1 + return isinstance(other, Key) and self.name == other.name + + def __repr__(self): + return f"Key({self.name!r})" + + +def model_merge(dst_items, src_items): + """The merged items, by the language's rules, on lists of pairs.""" + out = [] + for k, v in list(dst_items) + list(src_items): + for i, (ok, _) in enumerate(out): + if ok == k: + out[i] = (ok, v) + break + else: + out.append((k, v)) + return out + + +def sources(): + yield "strs", [(f"k{i}", i) for i in range(40)], [(f"k{i}", -i) for i in range(20, 70)] + yield "ints", [(i, i) for i in range(40)], [(i, -i) for i in range(20, 70)] + yield "mixed numbers", [(1, "a"), (2.0, "b"), (True, "c")], [(1.0, "x"), (2, "y"), (3, "z")] + yield "tuples", [((i, str(i)), i) for i in range(30)], [((i, str(i)), -i) for i in range(15, 45)] + yield "objects", [(Key(i), i) for i in range(30)], [(Key(i), -i) for i in range(15, 45)] + yield "strs then objects", ( + [(f"k{i}", i) for i in range(30)] + [(Key(i), i) for i in range(5)] + ), [(f"k{i}", -i) for i in range(20, 40)] + [(Key(3), "new"), ("tail", 1), (Key(9), 2)] + yield "into empty", [], [(f"k{i}", i) for i in range(50)] + yield "from empty", [(f"k{i}", i) for i in range(50)], [] + yield "one each", [("a", 1)], [("a", 2)] + yield "large", [(f"k{i}", i) for i in range(3000)], [(f"k{i}", -i) for i in range(1500, 4500)] + + +MERGERS = { + "update": lambda d, s: (d.update(s), d)[1], + "ior": lambda d, s: d.__ior__(s), + "or": lambda d, s: d | s, + "unpack": lambda d, s: {**d, **s}, + "update pairs": lambda d, s: (d.update(list(s.items())), d)[1], + "update zip": lambda d, s: (d.update(zip(s.keys(), s.values())), d)[1], + "update lists": lambda d, s: (d.update([k, v] for k, v in s.items()), d)[1], +} + + +class MergeTests(unittest.TestCase): + def test_merges_match_the_model(self): + for label, dst_items, src_items in sources(): + want = model_merge(dst_items, src_items) + for name, merge in MERGERS.items(): + with self.subTest(label=label, merge=name): + d = dict(dst_items) + s = dict(src_items) + out = merge(d, s) + self.assertEqual(list(out.items()), want) + self.assertEqual(len(out), len(want)) + # The source is as it was. + self.assertEqual(list(s.items()), list(dict(src_items).items())) + for k, v in want: + self.assertEqual(out[k], v) + + def test_an_existing_key_object_is_kept(self): + a, b = 1, 1.0 + d = {a: "int"} + d.update({b: "float"}) + self.assertEqual(list(d.items()), [(1, "float")]) + self.assertIs(type(next(iter(d))), int) + first = Key("x") + d = {first: 0} + d |= {Key("x"): 1} + self.assertIs(next(iter(d)), first) + self.assertEqual(d[first], 1) + + def test_in_place_merges_keep_the_dict(self): + d = {"a": 1} + alias = d + d |= {"b": 2} + self.assertIs(d, alias) + self.assertEqual(alias, {"a": 1, "b": 2}) + self.assertIsNone(d.update({"c": 3})) + self.assertEqual(alias, {"a": 1, "b": 2, "c": 3}) + merged = d | {"d": 4} + self.assertIsNot(merged, d) + self.assertNotIn("d", d) + + def test_a_dict_merged_into_itself(self): + d = {f"k{i}": i for i in range(100)} + before = list(d.items()) + d.update(d) + self.assertEqual(list(d.items()), before) + d |= d + self.assertEqual(list(d.items()), before) + self.assertEqual(d | d, d) + # (Not a change: an iteration in progress goes on.) + seen = 0 + for _ in d: + d.update(d) + d |= d + seen += 1 + self.assertEqual(seen, 100) + + def test_new_keys_stop_an_iteration_and_new_values_do_not(self): + d = {f"k{i}": i for i in range(50)} + same_keys = {f"k{i}": -i for i in range(50)} + seen = 0 + for _ in d: + d.update(same_keys) + d |= same_keys + seen += 1 + self.assertEqual(seen, 50) + self.assertEqual(d, same_keys) + with self.assertRaises(RuntimeError): + for _ in d: + d.update({"new": 1}) + d = {"a": 1} + with self.assertRaises(RuntimeError): + for _ in d: + d |= {"b": 1} + + def test_copies_are_independent(self): + for n in (0, 1, 5, 9, 200): + with self.subTest(n=n): + d = {f"k{i}": [i] for i in range(n)} + for copy in (dict(d), d.copy(), {**d}, d | {}): + self.assertEqual(copy, d) + self.assertIsNot(copy, d) + self.assertEqual(list(copy), list(d)) + self.assertTrue(all(copy[k] is d[k] for k in d)) + copy["extra"] = 1 + self.assertNotIn("extra", d) + if n: + del copy["k0"] + self.assertIn("k0", d) + + def test_a_copy_of_a_dict_with_removed_keys(self): + d = {i: str(i) for i in range(300)} + for i in range(0, 300, 3): + del d[i] + copy = d.copy() + self.assertEqual(list(copy.items()), list(d.items())) + self.assertEqual(len(copy), 200) + copy[0] = "back" + self.assertEqual(list(copy)[-1], 0) + self.assertNotIn(0, d) + target = {} + target.update(d) + self.assertEqual(list(target.items()), list(d.items())) + + def test_values_replaced_and_dropped(self): + import weakref + + class Value: + pass + + old = Value() + ref = weakref.ref(old) + d = {f"k{i}": i for i in range(100)} + d["k50"] = old + del old + self.assertIsNotNone(ref()) + d.update({"k50": 1, "k200": 2}) + self.assertIsNone(ref()) + self.assertEqual(d["k50"], 1) + + def test_keyword_updates(self): + d = {"a": 1} + d.update(a=2, b=3) + self.assertEqual(d, {"a": 2, "b": 3}) + d.update({"c": 4}, a=5) + self.assertEqual(list(d.items()), [("a", 5), ("b", 3), ("c", 4)]) + d.update([("z", 0)], y=1) + self.assertEqual(list(d)[-2:], ["z", "y"]) + base = {f"k{i}": i for i in range(50)} + built = dict(base, k1="one", extra=True) + self.assertEqual(len(built), 51) + self.assertEqual(built["k1"], "one") + self.assertEqual(list(built)[:50], list(base)) + self.assertEqual(base["k1"], 1) + + +class PairSourceTests(unittest.TestCase): + def test_pairs_of_any_sequence_kind(self): + d = {} + d.update([("a", 1), ["b", 2], "c3", iter(("d", 4)), {"e": 0, 5: 0}, range(6, 8)]) + self.assertEqual(d, {"a": 1, "b": 2, "c": "3", "d": 4, "e": 5, 6: 7}) + + def test_a_pair_of_the_wrong_length(self): + for bad, n in ((("a",), 1), (("a", 1, 2), 3), ([], 0), ([1, 2, 3, 4], 4), ("abc", 3)): + with self.subTest(bad=bad): + d = {"keep": 1} + with self.assertRaises(ValueError) as cm: + d.update([("ok", 1), bad]) + self.assertEqual( + str(cm.exception), + f"dictionary update sequence element #1 has length {n}; 2 is required", + ) + # The pairs before the bad one went in. + self.assertEqual(d, {"keep": 1, "ok": 1}) + + def test_an_item_that_is_not_a_sequence(self): + d = {} + with self.assertRaises(TypeError): + d.update([("a", 1), 5]) + self.assertEqual(d, {"a": 1}) + + def test_an_unhashable_key_in_a_pair(self): + d = {} + with self.assertRaises(TypeError): + d.update([("a", 1), ([], 2), ("b", 3)]) + self.assertEqual(d, {"a": 1}) + + def test_a_list_pair_changed_by_a_key(self): + # A pair is read before its key is hashed. + pair = [None, "value"] + + class Sly: + def __hash__(self): + pair.append("extra") + return 1 + + pair[0] = Sly() + d = {} + d.update([pair]) + self.assertEqual(list(d.values()), ["value"]) + + def test_the_constructor_reads_the_same_pairs(self): + for label, dst_items, src_items in sources(): + pairs = list(dst_items) + list(src_items) + want = model_merge(pairs, []) + for name, build in ( + ("list of tuples", lambda: dict(pairs)), + ("tuple of lists", lambda: dict(tuple([k, v] for k, v in pairs))), + ("generator", lambda: dict((k, v) for k, v in pairs)), + ("zip", lambda: dict(zip([k for k, _ in pairs], [v for _, v in pairs]))), + ("items view", lambda: dict(dict(pairs).items())), + ("update list", lambda: (lambda d: (d.update(pairs), d)[1])({})), + ("update items view", lambda: (lambda d: (d.update(dict(pairs).items()), d)[1])({})), + ("mixed pairs", lambda: dict([p if i % 3 else list(p) for i, p in enumerate(pairs)])), + ): + with self.subTest(label=label, build=name): + self.assertEqual(list(build().items()), want) + + def test_constructor_errors(self): + with self.assertRaises(ValueError) as cm: + dict([("a", 1), ("b", 2, 3)]) + self.assertEqual( + str(cm.exception), + "dictionary update sequence element #1 has length 3; 2 is required", + ) + with self.assertRaises(TypeError): + dict([("a", 1), ([], 2)]) + with self.assertRaises(TypeError): + dict([("a", 1), 7]) + self.assertEqual(dict(["ab", ("c", "d"), ["e", "f"]]), {"a": "b", "c": "d", "e": "f"}) + + def test_an_items_view_of_the_dict_itself(self): + d = {f"k{i}": i for i in range(30)} + before = list(d.items()) + d.update(d.items()) + self.assertEqual(list(d.items()), before) + copy = dict(d.items()) + self.assertEqual(copy, d) + self.assertIsNot(copy, d) + copy["new"] = 1 + self.assertNotIn("new", d) + with self.assertRaises((TypeError, ValueError)): + dict({"ab": 1, "cde": 2}.keys()) + self.assertEqual(dict({"ab": 1, "cd": 2}.keys()), {"a": "b", "c": "d"}) + + def test_many_pairs(self): + keys = [f"k{i}" for i in range(5000)] + d = {} + d.update(zip(keys, range(5000))) + self.assertEqual(len(d), 5000) + self.assertEqual(list(d)[:3], ["k0", "k1", "k2"]) + self.assertEqual(d["k4999"], 4999) + d.update((k, -v) for k, v in list(d.items())) + self.assertEqual(d["k4999"], -4999) + self.assertEqual(list(d)[:3], ["k0", "k1", "k2"]) + d.update(enumerate(keys)) + self.assertEqual(len(d), 10000) + self.assertEqual(d[17], "k17") + + +class PythonKeyTests(unittest.TestCase): + def test_a_key_that_changes_the_source_stops_the_merge(self): + class Mutator: + def __init__(self, target): + self.target = target + + def __hash__(self): + return 7 + + def __eq__(self, other): + self.target.clear() + return False + + src = {} + src["a"] = 1 + src[Mutator(src)] = 2 + dst = {"z": 0} + + class Seven: + def __hash__(self): + return 7 + + def __eq__(self, other): + return NotImplemented + + dst[Seven()] = 1 + with self.assertRaises(RuntimeError): + dst.update(src) + + def test_python_keys_compare_as_often_as_needed(self): + d = {Key(i): i for i in range(20)} + s = {Key(i): -i for i in range(10, 30)} + Key.calls = 0 + d.update(s) + self.assertEqual(len(d), 30) + self.assertGreaterEqual(Key.calls, 10) + self.assertEqual([k.name for k in d], list(range(30))) + self.assertEqual([d[Key(i)] for i in (0, 10, 29)], [0, -10, -29]) + + +class SplatTests(unittest.TestCase): + def test_displays(self): + for label, dst_items, src_items in sources(): + src = dict(src_items) + with self.subTest(label=label): + self.assertEqual(list({**src}.items()), list(src.items())) + self.assertIsNot({**src}, src) + both = {**dict(dst_items), **src} + self.assertEqual(list(both.items()), model_merge(dst_items, src_items)) + self.assertEqual(list({"first": 0, **src}.items())[0], ("first", 0)) + self.assertEqual({**src, **src}, src) + big = {str(i): i for i in range(5000)} + copy = {**big} + copy["new"] = 1 + self.assertNotIn("new", big) + self.assertEqual(list(copy)[:3], ["0", "1", "2"]) + self.assertEqual({**{1: "x"}, 1.0: "y"}, {1: "y"}) + + def test_keyword_splats(self): + def f(**kw): + return kw + + kw = {f"k{i}": i for i in range(300)} + got = f(**kw) + self.assertEqual(got, kw) + self.assertIsNot(got, kw) + got["extra"] = 1 + self.assertNotIn("extra", kw) + self.assertEqual(f(a=1, **{"b": 2}), {"a": 1, "b": 2}) + with self.assertRaises(TypeError): + f(**{"x": 1}, x=2) + with self.assertRaises(TypeError): + f(**{"a": 1}, **{"a": 2}) + with self.assertRaises(TypeError): + f(**{1: 2}) + with self.assertRaises(TypeError): + f(**[1, 2]) + + def test_mappings_that_are_not_dicts(self): + import collections + import os + + self.assertEqual({**collections.OrderedDict(a=1)}, {"a": 1}) + self.assertIs(type({**os.environ}), dict) + + class Mapping: + def keys(self): + return ["a", "b"] + + def __getitem__(self, k): + return k.upper() + + self.assertEqual({**Mapping()}, {"a": "A", "b": "B"}) + with self.assertRaises(TypeError): + {**1} + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_one_argument_calls.py b/tests/regrtest/test_dict_one_argument_calls.py new file mode 100644 index 000000000..9ef597a00 --- /dev/null +++ b/tests/regrtest/test_dict_one_argument_calls.py @@ -0,0 +1,60 @@ +"""`dict(x)` with one positional argument, in compiled code. + +A compiled `dict(x)` builds a mapping's copy, a lazy iterable's pairs +(`zip` over a generator, a generator of pairs) and an eager container's +pairs as before, with the same errors. +""" + +import collections +import unittest + +N = 3000 + + +class Mapping: + def keys(self): + return ["a"] + + def __getitem__(self, k): + return 1 + + +def pairs(): + yield ("x", 1) + yield ["y", 2] + + +def gen(n): + for i in range(n): + yield i + + +class DictOneArgumentTests(unittest.TestCase): + def test_shapes(self): + for _ in range(N): + r = ( + dict([(1, 2)]), + dict({"a": 1}), + dict(Mapping()), + dict(pairs()), + dict(zip("abc", gen(3))), + dict(collections.OrderedDict(z=1)), + dict(iter([(3, 4)])), + ) + self.assertEqual(r, ({1: 2}, {"a": 1}, {"a": 1}, {"x": 1, "y": 2}, + {"a": 0, "b": 1, "c": 2}, {"z": 1}, {3: 4})) + + def test_errors(self): + for _ in range(N // 10): + with self.assertRaises(ValueError): + dict([(1, 2, 3)]) + with self.assertRaises(TypeError): + dict(5) + with self.assertRaises(TypeError): + dict([([], 1)]) + with self.assertRaises(ValueError): + dict(x for x in ["abc"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_popitem_and_set_iand.py b/tests/regrtest/test_dict_popitem_and_set_iand.py new file mode 100644 index 000000000..dbea3d44d --- /dev/null +++ b/tests/regrtest/test_dict_popitem_and_set_iand.py @@ -0,0 +1,112 @@ +"""dict.popitem from compiled loops (a leaf half that pops the last entry +in place), set &= set (the replaced table released whole) and set |= set +(in place in compiled code), with set and str/int key lookups: popped +pairs in LIFO order, KeyError on an empty dict, a dict subclass, an +OrderedDict, a dict changed while iterated over, and intersections that +keep the left operand's elements, each matching CPython.""" + +import collections +import unittest + + +def pops(n): + out = [] + for i in range(n): + d = {"a": 1, "b": 2, i: i} + out.append(d.popitem()) + out.append(d.popitem()) + return out + + +class Key: + def __init__(self, v, tag): + self.v = v + self.tag = tag + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, Key) and self.v == other.v + + +class PopitemTests(unittest.TestCase): + def test_lifo(self): + for n in (1, 300): + r = pops(n) + self.assertEqual(r[-2:], [(n - 1, n - 1), ("b", 2)]) + self.assertEqual(len(r), 2 * n) + + def test_empty_and_args(self): + d = {} + for i in range(300): + d[i] = i + self.assertEqual(d.popitem(), (i, i)) + with self.assertRaises(KeyError): + d.popitem() + with self.assertRaises(TypeError): + {1: 2}.popitem(1) + + def test_subclasses(self): + class D(dict): + pass + + d = D(a=1, b=2) + self.assertEqual(d.popitem(), ("b", 2)) + o = collections.OrderedDict(a=1, b=2, c=3) + self.assertEqual(o.popitem(last=False), ("a", 1)) + self.assertEqual(o.popitem(), ("c", 3)) + + def test_changed_while_iterated(self): + d = {i: i for i in range(10)} + with self.assertRaises(RuntimeError): + for k in d: + d.popitem() + + def test_set_iand(self): + a = {Key(1, "a"), Key(2, "a"), Key(3, "a")} + b = {Key(2, "b"), Key(3, "b"), Key(4, "b")} + for i in range(300): + s = set(a) + s &= b + self.assertEqual(sorted(k.v for k in s), [2, 3]) + ints = set(range(10)) + for i in range(300): + t = set(ints) + t &= set(range(5, 15)) + t &= frozenset({5, 6, 99}) + self.assertEqual(t, {5, 6}) + t &= set() + self.assertEqual(t, set()) + + def test_set_ior(self): + s = set(range(5)) + alias = s + for i in range(300): + s |= {i % 7, 100} + s |= frozenset({i % 3}) + self.assertIs(s, alias) + self.assertEqual(s, set(range(7)) | {100}) + k = {Key(1, "a")} + for i in range(300): + k |= {Key(1, "b"), Key(i % 4, "c")} + self.assertEqual(sorted(x.v for x in k), [0, 1, 2, 3]) + self.assertEqual([x.tag for x in k if x.v == 1], ["a"]) + s |= s + self.assertEqual(len(s), 8) + f = frozenset({1}) + g = f + f |= {2} + self.assertIsNot(f, g) + self.assertEqual(f, {1, 2}) + + def test_key_equality(self): + a = "".join(["ab", "c"]) + d = {"abc": 1, 5: 2, 2**40: 3} + for i in range(300): + r = (d[a], d[5], d[2**40], a in {"abc"}, 5.0 in {5}, True in {1}) + self.assertEqual(r, (1, 2, 3, True, True, True)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_removals_at_any_position.py b/tests/regrtest/test_dict_removals_at_any_position.py new file mode 100644 index 000000000..f0177a842 --- /dev/null +++ b/tests/regrtest/test_dict_removals_at_any_position.py @@ -0,0 +1,483 @@ +"""Removing a key costs the same wherever it sits in a dict. + +A dict keeps its keys in insertion order and answers "the i-th key" for +its iterators, views and caches. Removing a key from the front or the +middle of a large dict leaves a marker in the dict's entry list instead of +moving every later entry down, and the dict closes the gaps in one pass +later; none of that may show: order, positions, views, iteration, copies +and the errors for a dict changed during iteration all stay as they are in +a dict that never lost a key. + +Every check runs against a model (a list of pairs) through the removal +idioms programs use: `del d[k]`, `d.pop(k)`, pop and re-insert (an LRU +touch), `popitem`, and `OrderedDict`'s `popitem(last=False)` and +`move_to_end`. A last group checks that the cost per removal stays flat as +the dict grows. +""" + +import collections +import copy +import pickle +import time +import unittest +import weakref + +SIZES = (3, 9, 17, 40, 200, 3000) + + +class Rng: + """A fixed sequence, the same on every implementation.""" + + def __init__(self, seed): + self.state = seed + + def below(self, n): + self.state = (self.state * 6364136223846793005 + 1442695040888963407) % (1 << 64) + return (self.state >> 33) % n + + +def same(test, d, model): + """`d` shows exactly `model`'s pairs, in order, through every reader.""" + keys = [k for k, _ in model] + values = [v for _, v in model] + test.assertEqual(len(d), len(model)) + test.assertEqual(list(d), keys) + test.assertEqual(list(d.keys()), keys) + test.assertEqual(list(d.values()), values) + test.assertEqual(list(d.items()), model) + test.assertEqual(list(reversed(d)), keys[::-1]) + test.assertEqual(list(reversed(d.items())), model[::-1]) + test.assertEqual([k for k in d], keys) + test.assertEqual([d[k] for k in keys], values) + test.assertEqual(dict(d), dict(model)) + test.assertEqual(list(d.copy().items()), model) + test.assertEqual(list({**d}.items()), model) + test.assertEqual(sorted(d, key=repr), sorted(keys, key=repr)) + test.assertEqual(repr(d) if type(d) is dict else None, repr(dict(model)) if type(d) is dict else None) + if model: + test.assertEqual(next(iter(d)), keys[0]) + test.assertEqual(next(reversed(d)), keys[-1]) + test.assertEqual(next(iter(d.items())), model[0]) + for k in keys[:: max(1, len(keys) // 25)]: + test.assertIn(k, d) + test.assertNotIn("never a key", d) + + +class RemovalOrderTests(unittest.TestCase): + def test_del_from_the_front(self): + for n in SIZES: + d = {i: str(i) for i in range(n)} + model = [(i, str(i)) for i in range(n)] + for i in range(n): + del d[i] + del model[0] + if i % max(1, n // 20) == 0: + same(self, d, model) + self.assertEqual(d, {}) + d["again"] = 1 + self.assertEqual(list(d.items()), [("again", 1)]) + + def test_del_from_the_middle_outwards(self): + for n in SIZES: + d = {("k", i): i for i in range(n)} + model = [(("k", i), i) for i in range(n)] + order = sorted(range(n), key=lambda i: abs(i - n // 2)) + for step, i in enumerate(order): + del d[("k", i)] + model.remove((("k", i), i)) + if step % max(1, n // 20) == 0: + same(self, d, model) + self.assertEqual(len(d), 0) + + def test_random_removals_and_additions(self): + for n in SIZES: + rng = Rng(n) + d = {} + model = [] + fresh = 0 + for step in range(6 * n + 50): + roll = rng.below(10) + if roll < 4 or not model: + fresh += 1 + key = "key%d" % fresh if fresh % 3 else fresh + d[key] = step + model.append((key, step)) + elif roll < 6: + at = rng.below(len(model)) + key, _ = model.pop(at) + del d[key] + elif roll < 8: + at = rng.below(len(model)) + key, value = model.pop(at) + self.assertEqual(d.pop(key), value) + elif roll == 8: + at = rng.below(len(model)) + key, value = model[at] + d[key] = value + 1 + model[at] = (key, value + 1) + else: + self.assertEqual(d.popitem(), model.pop()) + if step % 37 == 0: + same(self, d, model) + same(self, d, model) + + def test_pop_and_reinsert_moves_a_key_to_the_end(self): + for n in SIZES: + rng = Rng(7 * n) + d = {i: i * i for i in range(n)} + model = [(i, i * i) for i in range(n)] + for step in range(4 * n + 20): + at = rng.below(n) + key, value = model.pop(at) + got = d.pop(key) + self.assertEqual(got, value) + d[key] = got + model.append((key, value)) + if step % 53 == 0: + same(self, d, model) + same(self, d, model) + + def test_oldest_key_out_for_each_new_one(self): + for n in SIZES: + d = {i: None for i in range(n)} + for i in range(n, 12 * n + 40): + d[i] = None + oldest = next(iter(d)) + self.assertEqual(oldest, i - n) + del d[oldest] + self.assertEqual(len(d), n) + self.assertEqual(list(d), list(range(11 * n + 40, 12 * n + 40))) + + def test_missing_keys_still_raise(self): + d = {i: i for i in range(100)} + for i in range(0, 100, 2): + del d[i] + for i in range(0, 100, 2): + with self.assertRaises(KeyError): + del d[i] + with self.assertRaises(KeyError): + d.pop(i) + self.assertEqual(d.pop(i, "gone"), "gone") + self.assertIsNone(d.get(i)) + self.assertEqual(list(d), list(range(1, 100, 2))) + + def test_keys_that_compare_through_python(self): + class Key: + def __init__(self, n): + self.n = n + + def __hash__(self): + return self.n % 5 + + def __eq__(self, other): + return isinstance(other, Key) and self.n == other.n + + keys = [Key(i) for i in range(120)] + d = {k: k.n for k in keys} + model = [(k, k.n) for k in keys] + for i in range(0, 120, 3): + del d[Key(i)] + model = [(k, v) for k, v in model if v != i] + self.assertEqual([v for v in d.values()], [v for _, v in model]) + for k, v in model: + self.assertEqual(d[Key(v)], v) + self.assertNotIn(Key(3), d) + + def test_values_are_released_when_removed(self): + class Token: + pass + + d = {} + refs = [] + for i in range(300): + t = Token() + d[i] = t + refs.append(weakref.ref(t)) + del t + for i in range(0, 300, 2): + del d[i] + self.assertTrue(all(refs[i]() is None for i in range(0, 300, 2))) + self.assertTrue(all(refs[i]() is not None for i in range(1, 300, 2))) + d.clear() + self.assertTrue(all(r() is None for r in refs)) + + +class ReadersAfterRemovalTests(unittest.TestCase): + def holed(self, n=400): + d = {i: -i for i in range(n)} + for i in range(0, n, 3): + del d[i] + model = [(i, -i) for i in range(n) if i % 3] + return d, model + + def test_views_and_copies(self): + d, model = self.holed() + same(self, d, model) + self.assertEqual(d.keys() & {1, 2, 3, 4}, {1, 2, 4}) + self.assertEqual(d.keys() - set(range(100, 1000)), {i for i in range(100) if i % 3}) + self.assertEqual(list(copy.copy(d).items()), model) + self.assertEqual(list(copy.deepcopy(d).items()), model) + self.assertEqual(list(pickle.loads(pickle.dumps(d)).items()), model) + self.assertEqual(list(dict.fromkeys(d)), [k for k, _ in model]) + self.assertEqual(sum(d.values()), sum(v for _, v in model)) + self.assertEqual(max(d), model[-1][0]) + self.assertEqual(d == dict(model), True) + self.assertEqual({k: v for k, v in d.items()}, dict(model)) + + def test_update_and_merge(self): + d, model = self.holed() + other = {i: "new" for i in range(390, 420)} + d.update(other) + want = dict(model) + want.update(other) + self.assertEqual(list(d.items()), list(want.items())) + merged = d | {"last": 1} + self.assertEqual(list(merged)[-1], "last") + self.assertEqual(len(merged), len(want) + 1) + + def test_setdefault_and_in_place_values(self): + d, model = self.holed() + for k, v in model[::7]: + d[k] += 1000 + self.assertEqual(d.setdefault(k, None), v + 1000) + self.assertEqual(d.setdefault("fresh", 5), 5) + self.assertEqual(list(d)[-1], "fresh") + self.assertEqual(len(d), len(model) + 1) + + def test_iteration_notices_changes(self): + d, _ = self.holed() + with self.assertRaises(RuntimeError): + for k in d: + del d[k] + d, _ = self.holed() + with self.assertRaises(RuntimeError): + for k in d: + d[("new", k)] = 1 + d, model = self.holed() + seen = [] + for k in d: + d[k] = "replaced" + seen.append(k) + self.assertEqual(seen, [k for k, _ in model]) + + def test_iterators_resume_across_positions(self): + d, model = self.holed(1000) + it = iter(d.items()) + got = [next(it) for _ in range(100)] + got += list(it) + self.assertEqual(got, model) + back = reversed(d) + tail = [next(back) for _ in range(50)] + self.assertEqual(tail, [k for k, _ in model][::-1][:50]) + self.assertEqual(len(list(back)), len(model) - 50) + + def test_sorting_in_place_users(self): + d, model = self.holed() + self.assertEqual(sorted(d.items(), reverse=True), sorted(model, reverse=True)) + self.assertEqual(list(dict(sorted(d.items(), key=lambda kv: -kv[0]))), [k for k, _ in model][::-1]) + + def test_kwargs_and_namespaces(self): + def collect(**kw): + return kw + + d = {"name%d" % i: i for i in range(60)} + for i in range(0, 60, 2): + del d["name%d" % i] + self.assertEqual(collect(**d), {"name%d" % i: i for i in range(1, 60, 2)}) + ns = {"x%d" % i: i for i in range(80)} + for i in range(0, 40): + ns.pop("x%d" % i) + self.assertEqual(eval("x40 + x79", ns), 119) + with self.assertRaises(NameError): + eval("x5", ns) + + def test_instance_namespaces(self): + class Box: + pass + + b = Box() + for i in range(60): + setattr(b, "f%d" % i, i) + for i in range(0, 60, 2): + if i % 4: + delattr(b, "f%d" % i) + else: + del b.__dict__["f%d" % i] + self.assertEqual([getattr(b, "f%d" % i) for i in range(1, 60, 2)], list(range(1, 60, 2))) + self.assertFalse(hasattr(b, "f2")) + self.assertFalse(hasattr(b, "f4")) + b.f2 = "back" + self.assertEqual(list(vars(b))[-1], "f2") + self.assertEqual(len(vars(b)), 31) + + +class OrderedDictTests(unittest.TestCase): + def check(self, od, model): + self.assertEqual(list(od.items()), model) + self.assertEqual(list(reversed(od)), [k for k, _ in model][::-1]) + self.assertEqual(len(od), len(model)) + if model: + self.assertEqual(next(iter(od)), model[0][0]) + + def test_lru_eviction(self): + for n in SIZES: + od = collections.OrderedDict((i, i) for i in range(n)) + model = [(i, i) for i in range(n)] + for i in range(n, 6 * n + 30): + od[i] = i + model.append((i, i)) + self.assertEqual(od.popitem(last=False), model.pop(0)) + if i % 41 == 0: + self.check(od, model) + self.check(od, model) + + def test_move_to_end_both_ways(self): + for n in SIZES: + rng = Rng(n + 1) + od = collections.OrderedDict((i, str(i)) for i in range(n)) + model = [(i, str(i)) for i in range(n)] + for step in range(5 * n + 30): + at = rng.below(n) + item = model.pop(at) + if rng.below(5) == 0: + od.move_to_end(item[0], last=False) + model.insert(0, item) + else: + od.move_to_end(item[0]) + model.append(item) + if step % 29 == 0: + self.check(od, model) + self.check(od, model) + with self.assertRaises(KeyError): + od.move_to_end("absent") + + def test_mixed_operations(self): + for n in SIZES: + rng = Rng(3 * n + 2) + od = collections.OrderedDict() + model = [] + fresh = 0 + for step in range(8 * n + 60): + roll = rng.below(12) + if roll < 5 or not model: + fresh += 1 + od[fresh] = step + model.append((fresh, step)) + elif roll < 7: + self.assertEqual(od.popitem(last=False), model.pop(0)) + elif roll == 7: + self.assertEqual(od.popitem(), model.pop()) + elif roll < 10: + at = rng.below(len(model)) + key, value = model.pop(at) + if roll == 8: + self.assertEqual(od.pop(key), value) + else: + del od[key] + else: + at = rng.below(len(model)) + item = model.pop(at) + od.move_to_end(item[0]) + model.append(item) + if step % 31 == 0: + self.check(od, model) + self.check(od, model) + self.assertEqual(od, collections.OrderedDict(model)) + + def test_iteration_notices_changes(self): + od = collections.OrderedDict((i, i) for i in range(100)) + for i in range(0, 60): + del od[i] + with self.assertRaises(RuntimeError): + for k in od: + od.move_to_end(k) + with self.assertRaises(RuntimeError): + for k in od: + del od[k] + + +class WeakDictionaryTests(unittest.TestCase): + def test_sliding_window(self): + class Node: + def __init__(self, n): + self.n = n + + d = weakref.WeakValueDictionary() + keep = collections.deque() + for i in range(2000): + node = Node(i) + d[i] = node + keep.append(node) + if len(keep) > 150: + keep.popleft() + del node + self.assertEqual(sorted(d.keys()), list(range(1850, 2000))) + self.assertEqual([d[i].n for i in range(1850, 2000)], list(range(1850, 2000))) + keep.clear() + self.assertEqual(len(d), 0) + + +class CostTests(unittest.TestCase): + """The cost of a removal doesn't grow with the dict.""" + + def per_op(self, body, n, ops): + best = None + for _ in range(3): + state = body(n, 0) + t0 = time.perf_counter() + body(n, ops, state) + dt = (time.perf_counter() - t0) / ops + best = dt if best is None else min(best, dt) + return best + + def flat(self, body): + # (Each removal used to move every later entry: a dict 64 times + # the size cost about 64 times as much. Allow 8, far past noise.) + body(2000, 30_000, body(2000, 0)) + small = self.per_op(body, 2000, 30_000) + large = self.per_op(body, 128_000, 30_000) + self.assertLess(large, 8 * small + 2e-6, (small, large)) + + def test_fifo_dict(self): + def body(n, ops, d=None): + if d is None: + return {i: i for i in range(n)} + for i in range(n, n + ops): + d[i] = i + del d[i - n] + + self.flat(body) + + def test_pop_and_reinsert(self): + def body(n, ops, d=None): + if d is None: + return {i: i for i in range(n)} + for i in range(ops): + k = (i * 7919) % n + v = d.pop(k) + d[k] = v + + self.flat(body) + + def test_ordered_dict_lru(self): + def body(n, ops, od=None): + if od is None: + return collections.OrderedDict((i, i) for i in range(n)) + for i in range(n, n + ops): + od[i] = i + od.popitem(last=False) + + self.flat(body) + + def test_ordered_dict_move_to_end(self): + def body(n, ops, od=None): + if od is None: + return collections.OrderedDict((i, i) for i in range(n)) + for i in range(ops): + od.move_to_end((i * 7919) % n) + + self.flat(body) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_subclass_iter_end.py b/tests/regrtest/test_dict_subclass_iter_end.py new file mode 100644 index 000000000..f622175b2 --- /dev/null +++ b/tests/regrtest/test_dict_subclass_iter_end.py @@ -0,0 +1,45 @@ +"""The end of a loop over a `dict` subclass's keys, values or items. + +`heapq.nlargest` loops over `iter(counter.items())` kept in a local. +Compiled code ends such a loop in place when the instance lives on; an +iterator that stays exhausted after its dict grows, and a temporary +instance whose `__del__` runs when the loop lets it go, keep CPython's +behavior. Run it past the compile threshold. +""" + +import collections + +log = [] + + +class D(dict): + def __del__(self): + log.append("del") + + +def drain(d): + it = iter(d.items()) + n = 0 + for kv in it: + n += 1 + d["late"] = 1 + assert next(it, None) is None + return n + + +def temporary(): + n = 0 + for k in D(a=1, b=2): + n += 1 + log.append("after") + return n + + +c = collections.Counter("aabbc") +for _ in range(3000): + assert drain(collections.Counter("aab")) == 2 + before = len(c) + assert drain(c) == before + del log[:] + assert temporary() == 2 + assert log == ["del", "after"], log diff --git a/tests/regrtest/test_dict_subclass_merge_rule.py b/tests/regrtest/test_dict_subclass_merge_rule.py new file mode 100644 index 000000000..8d37f0af2 --- /dev/null +++ b/tests/regrtest/test_dict_subclass_merge_rule.py @@ -0,0 +1,83 @@ +"""A dict subclass's instance merged into a dict (`dict(x)`, `dict(x, k=v)`, +`{**x}`, `f(**x)`, `d.update(x)`, `Sub(x)`) is read from its table when its +class keeps dict's `__iter__`, whatever its own `keys` and `__getitem__`, as +CPython's `dict_merge` reads it; with its own `__iter__` it's read through +`keys()` and `__getitem__`.""" + +import unittest + +N = 300 + + +class OwnKeys(dict): + def keys(self): + return ["a"] + + +class OwnKeysAndIter(dict): + def keys(self): + return ["a"] + + def __iter__(self): + return iter(["a"]) + + +class OwnGetitem(dict): + def __getitem__(self, key): + return 99 + + +class Reversed(dict): + def keys(self): + return reversed(list(dict.keys(self))) + + __iter__ = keys + + +def kw(**k): + return k + + +class DictSubclassMergeTests(unittest.TestCase): + def merges(self, x): + d = {} + d.update(x) + return [dict(x), dict(x, z=0), {**x}, kw(**x), d, OwnKeys(x)] + + def test_table_read(self): + for cls in (OwnKeys, OwnGetitem): + x = cls(a=1, b=2) + for _ in range(N): + got = self.merges(x) + self.assertEqual(got[:5], [{"a": 1, "b": 2}, {"a": 1, "b": 2, "z": 0}, + {"a": 1, "b": 2}, {"a": 1, "b": 2}, {"a": 1, "b": 2}]) + self.assertEqual(dict.items(got[5]), {"a": 1, "b": 2}.items()) + self.assertEqual([type(g) for g in got[:5]], [dict] * 5) + + def test_own_iter_reads_keys(self): + x = OwnKeysAndIter(a=1, b=2) + for _ in range(N): + got = self.merges(x) + self.assertEqual(got[:5], [{"a": 1}, {"a": 1, "z": 0}, {"a": 1}, {"a": 1}, {"a": 1}]) + x = Reversed([("a", 1), ("b", 2), ("c", 3)]) + for _ in range(N): + self.assertEqual(list(dict(x).items()), [("c", 3), ("b", 2), ("a", 1)]) + self.assertEqual(list({**x}), ["c", "b", "a"]) + + def test_plain_subclass(self): + class Plain(dict): + pass + x = Plain(a=1, b=2) + for _ in range(N): + self.assertEqual(self.merges(x)[:5], [{"a": 1, "b": 2}, {"a": 1, "b": 2, "z": 0}, + {"a": 1, "b": 2}, {"a": 1, "b": 2}, + {"a": 1, "b": 2}]) + + def test_duplicate_keyword(self): + x = OwnKeys(a=1) + with self.assertRaises(TypeError): + kw(a=0, **x) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_subclass_missing_compiled.py b/tests/regrtest/test_dict_subclass_missing_compiled.py new file mode 100644 index 000000000..451c814fb --- /dev/null +++ b/tests/regrtest/test_dict_subclass_missing_compiled.py @@ -0,0 +1,144 @@ +"""A dict subclass's __missing__ called from compiled loops: Counter +increments of new and old keys (d[k] += 1), a user class whose +__missing__ stores or raises, a subclass that overrides __getitem__ (no +__missing__ call), keys whose hash runs Python, and a class whose +__missing__ changes partway, each matching CPython's results, with +(k, v) in d.items(), v in d.values() and k in d.keys() answered as CPython +answers them.""" + +import collections +import unittest + +WORDS = "the quick brown fox jumps over the lazy dog".split() + + +class Default(dict): + def __missing__(self, key): + return -1 + + +class Storing(dict): + def __missing__(self, key): + self[key] = v = len(key) + return v + + +class Raising(dict): + def __missing__(self, key): + raise LookupError(key) + + +class Own(dict): + def __getitem__(self, key): + return "own" + + def __missing__(self, key): + return "missing" + + +class H: + def __init__(self, k): + self.k = k + + def __hash__(self): + return hash(self.k) + + def __eq__(self, other): + return isinstance(other, H) and self.k == other.k + + +def counts(n): + c = None + for i in range(n): + c = collections.Counter() + for w in WORDS: + c[w] += 1 + return c + + +def reads(n, d, keys): + out = None + for i in range(n): + out = [d[k] for k in keys] + return out + + +class MissingTests(unittest.TestCase): + def test_counter(self): + for n in (1, 400): + c = counts(n) + self.assertEqual(c["the"], 2) + self.assertEqual(sum(c.values()), 9) + self.assertEqual(c["absent"], 0) + self.assertNotIn("absent", c) + + def test_default(self): + for n in (1, 400): + self.assertEqual(reads(n, Default(a=1), ["a", "b", 3]), [1, -1, -1]) + d = Storing() + self.assertEqual(reads(n, d, ["ab", "abc"]), [2, 3]) + self.assertEqual(d, {"ab": 2, "abc": 3}) + self.assertEqual(reads(n, Own(a=1), ["a", "b"]), ["own", "own"]) + self.assertEqual(reads(n, Default({H(1): 5}), [H(1), H(2)]), [5, -1]) + + def test_raising(self): + def run(n): + caught = 0 + d = Raising(a=1) + for i in range(n): + try: + d["b"] + except LookupError as e: + caught += e.args == ("b",) + return caught + + self.assertEqual(run(400), 400) + with self.assertRaises(KeyError): + reads(300, dict(a=1), ["a", "b"]) + + def test_changed_missing(self): + class C(dict): + def __missing__(self, key): + return 1 + + d = C() + self.assertEqual(reads(400, d, ["x"]), [1]) + C.__missing__ = lambda self, key: 2 + self.assertEqual(reads(300, d, ["x"]), [2]) + del C.__missing__ + with self.assertRaises(KeyError): + reads(300, d, ["x"]) + + def test_view_membership(self): + d = {"a": 1, "b": [2], 3: "c"} + + def run(n): + out = None + for i in range(n): + out = ( + ("a", 1) in d.items(), + ("a", 2) in d.items(), + ("b", [2]) in d.items(), + ("z", 1) in d.items(), + "a" in d.items(), + ("a",) in d.items(), + ("a", 1, 2) in d.items(), + (3, "c") in d.items(), + 1 in d.values(), + [2] in d.values(), + "z" in d.values(), + "a" in d.keys(), + 4 in d.keys(), + ) + return out + + want = (True, False, True, False, False, False, False, True, True, True, False, True, False) + for n in (1, 400): + self.assertEqual(run(n), want) + with self.assertRaises(TypeError): + ([], 1) in d.items() + self.assertTrue((H(1), 5) in {H(1): 5}.items()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_subclass_native_lanes.py b/tests/regrtest/test_dict_subclass_native_lanes.py new file mode 100644 index 000000000..ec89dfba7 --- /dev/null +++ b/tests/regrtest/test_dict_subclass_native_lanes.py @@ -0,0 +1,295 @@ +"""Dict subclasses (`defaultdict`, `Counter`, `OrderedDict`, plain +subclasses): `for` loops, `list()` and `sorted()`, `==`, `copy()`, +construction from another mapping, `dict(od)` and `key=d.get` take +native lanes that match the general paths, keep each class's order and +factory, see changes made under a loop, and leave overridden `__iter__` +and `__eq__` in charge.""" + +import collections +import unittest +from collections import Counter, OrderedDict, defaultdict + +N = 300 + + +class Plain(dict): + pass + + +class Doubled(dict): + def __iter__(self): + for k in dict.__iter__(self): + yield k + yield k + + +class NeverEqual(dict): + def __eq__(self, other): + return False + + __hash__ = None + + +class Val: + def __init__(self, v): + self.v = v + self.asked = 0 + + def __eq__(self, other): + self.asked += 1 + return isinstance(other, Val) and self.v == other.v + + __hash__ = None + + +def loop(it): + out = [] + for x in it: + out.append(x) + return out + + +class IterationTests(unittest.TestCase): + def test_for_loops(self): + base = {("k", i): i for i in range(8)} + dd = defaultdict(int, base) + ct = Counter("abracadabra") + pl = Plain(base) + for _ in range(N): + self.assertEqual(loop(dd), list(base)) + self.assertEqual(loop(pl), list(base)) + self.assertEqual(loop(ct), ["a", "b", "r", "c", "d"]) + self.assertEqual([k for k in dd if k[1] % 2], [("k", 1), ("k", 3), ("k", 5), ("k", 7)]) + self.assertEqual(sum(1 for _ in ct), 5) + self.assertEqual(loop(defaultdict(list)), []) + + def test_collectors(self): + ct = Counter("mississippi") + dd = defaultdict(list, {3: "c", 1: "a", 2: "b"}) + for _ in range(N): + self.assertEqual(list(ct), ["m", "i", "s", "p"]) + self.assertEqual(sorted(dd), [1, 2, 3]) + self.assertEqual(tuple(dd), (3, 1, 2)) + self.assertEqual(set(Plain(a=1, b=2)), {"a", "b"}) + self.assertEqual(max(ct, key=ct.get), "i") + self.assertEqual(min(dd, key=dd.get), 1) + self.assertEqual(sorted(ct, key=ct.get), ["m", "p", "i", "s"]) + self.assertEqual(",".join(ct), "m,i,s,p") + a, b, c = dd + self.assertEqual((a, b, c), (3, 1, 2)) + + def test_override_of_iter_is_used(self): + d = Doubled(a=1, b=2) + for _ in range(N): + self.assertEqual(loop(d), ["a", "a", "b", "b"]) + self.assertEqual(list(d), ["a", "a", "b", "b"]) + self.assertEqual(sorted(d), ["a", "a", "b", "b"]) + + def test_size_change_under_a_loop_raises(self): + for _ in range(50): + dd = defaultdict(int, {i: i for i in range(5)}) + with self.assertRaises(RuntimeError): + for k in dd: + dd[k + 100] = 1 + ct = Counter("abc") + with self.assertRaises(RuntimeError): + for k in ct: + del ct[k] + + def test_value_change_under_a_loop_is_fine(self): + dd = defaultdict(int, {i: i for i in range(5)}) + for k in dd: + dd[k] += 10 + self.assertEqual(list(dd.values()), [10, 11, 12, 13, 14]) + + def test_missing_key_read_under_a_loop_raises(self): + dd = defaultdict(int, {1: 1, 2: 2}) + with self.assertRaises(RuntimeError): + for k in dd: + dd[k * 10] + + +class EqualityTests(unittest.TestCase): + def test_plain_values(self): + base = {("k", i): i * 1.5 for i in range(10)} + sbase = {"s%d" % i: "v%d" % i for i in range(10)} + for _ in range(N): + self.assertEqual(defaultdict(int, base), base) + self.assertEqual(base, Plain(base)) + self.assertEqual(Counter("aab"), {"a": 2, "b": 1}) + self.assertEqual(defaultdict(str, sbase), OrderedDict(sbase)) + self.assertNotEqual(defaultdict(int, base), {**base, ("k", 3): 0.0}) + self.assertNotEqual(Plain(sbase), {**sbase, "extra": 1}) + self.assertNotEqual(Plain(sbase), {k + "x": v for k, v in sbase.items()}) + self.assertTrue({1: None, 2: True, 3: b"x"} == {3: b"x", 2: True, 1: None}) + self.assertFalse({1: None} == {1: False}) + self.assertFalse({1: b"x"} == {1: b"y"}) + + def test_mixed_numbers_and_nans(self): + nan = float("nan") + for _ in range(N): + self.assertEqual({1: 1, 2: 2.0}, {1: 1.0, 2: 2}) + self.assertEqual({True: "a"}, {1: "a"}) + self.assertEqual({"x": nan}, {"x": nan}) + self.assertNotEqual({"x": float("nan")}, {"x": float("nan")}) + self.assertEqual({(1, "a"): (1, 2)}, {(1, "a"): (1, 2)}) + self.assertNotEqual({"a": [1]}, {"a": [2]}) + self.assertEqual({"a": {"b": [1, {"c": 2}]}}, {"a": {"b": [1, {"c": 2}]}}) + + def test_values_with_eq(self): + for _ in range(50): + a, b = Val(1), Val(1) + self.assertEqual({"k": a, "n": 1}, {"n": 1, "k": b}) + self.assertGreater(a.asked + b.asked, 0) + self.assertNotEqual({"k": Val(1)}, {"k": Val(2)}) + same = Val(3) + self.assertEqual({"k": same}, {"k": same}) + self.assertEqual(same.asked, 0) + + def test_ordered_dict_order_and_overrides(self): + for _ in range(N): + a = OrderedDict([(1, "a"), (2, "b")]) + b = OrderedDict([(2, "b"), (1, "a")]) + self.assertNotEqual(a, b) + self.assertEqual(a, dict(b)) + self.assertEqual(dict(a), b) + self.assertEqual(a, OrderedDict(a)) + self.assertFalse(NeverEqual(a=1) == NeverEqual(a=1)) + self.assertFalse(NeverEqual(a=1) == {"a": 1}) + self.assertFalse({"a": 1} == NeverEqual(a=1)) + + +class CopyTests(unittest.TestCase): + def test_defaultdict(self): + for _ in range(N): + dd = defaultdict(list, {("k", 1): [1], "s": [2]}) + c = dd.copy() + self.assertIs(type(c), defaultdict) + self.assertIs(c.default_factory, list) + self.assertEqual(c, dd) + self.assertIs(c[("k", 1)], dd[("k", 1)]) + c["new"].append(1) + self.assertNotIn("new", dd) + d2 = defaultdict(int, dd) + self.assertEqual(dict(d2), dict(dd)) + self.assertIs(d2.default_factory, int) + d3 = defaultdict(None, Counter("aab")) + self.assertEqual(dict(d3), {"a": 2, "b": 1}) + with self.assertRaises(KeyError): + d3["zz"] + self.assertEqual(defaultdict(int, {}).copy(), {}) + + def test_counter(self): + for _ in range(N): + ct = Counter("abracadabra") + c = ct.copy() + self.assertIs(type(c), Counter) + self.assertEqual(c.most_common(2), [("a", 5), ("b", 2)]) + c["a"] += 1 + self.assertEqual(ct["a"], 5) + c2 = Counter(ct) + c2.update(ct) + self.assertEqual(c2["a"], 10) + d = {} + d.update(ct) + self.assertEqual(list(d), ["a", "b", "r", "c", "d"]) + self.assertEqual({**ct}, dict(ct)) + merged = {"z": 0} + merged.update(defaultdict(int, a=1)) + self.assertEqual(merged, {"z": 0, "a": 1}) + + def test_ordered_dict(self): + for _ in range(N): + od = OrderedDict([(("k", i), i) for i in range(6)]) + od.move_to_end(("k", 1)) + od.move_to_end(("k", 4), last=False) + want = [("k", 4), ("k", 0), ("k", 2), ("k", 3), ("k", 5), ("k", 1)] + c = od.copy() + self.assertIs(type(c), OrderedDict) + self.assertEqual(list(c), want) + self.assertEqual(list(dict(od)), want) + self.assertEqual(list(OrderedDict(od).items()), [(k, k[1]) for k in want]) + c[("k", 9)] = 9 + c.move_to_end(("k", 0)) + self.assertEqual(list(od), want) + d = {} + d.update(od) + self.assertEqual(list(d), want) + self.assertEqual(OrderedDict().copy(), OrderedDict()) + self.assertEqual(dict(OrderedDict()), {}) + + def test_ordered_dict_stores_with_tuple_and_temporary_keys(self): + for _ in range(N): + od = OrderedDict() + for j in range(8): + od[(j % 4, "k")] = j + od["s" + str(j % 3)] = j + self.assertEqual( + list(od.items()), + [((0, "k"), 4), ("s0", 6), ((1, "k"), 5), ("s1", 7), ((2, "k"), 6), ("s2", 5), ((3, "k"), 7)], + ) + od[(0, "k")] += 10 + self.assertEqual(od[(0, "k")], 14) + self.assertEqual(od.popitem(), ((3, "k"), 7)) + self.assertEqual(od.popitem(last=False), ((0, "k"), 14)) + with self.assertRaises(TypeError): + od[[1, 2]] = 3 + with self.assertRaises(TypeError): + od[([1], 2)] = 3 + self.assertEqual(len(od), 5) + + def test_ordered_dict_copy_after_deletes_and_moves(self): + for _ in range(N): + od = OrderedDict((i, str(i)) for i in range(8)) + del od[3] + od[3] = "again" + c = od.copy() + self.assertEqual(list(c), [0, 1, 2, 4, 5, 6, 7, 3]) + self.assertEqual(c, od) + c2 = OrderedDict(od) + self.assertEqual(list(c2.items()), list(od.items())) + od.move_to_end(0) + c3 = od.copy() + self.assertEqual(list(c3), [1, 2, 4, 5, 6, 7, 3, 0]) + c3[99] = "new" + c3.move_to_end(1) + self.assertEqual(list(od), [1, 2, 4, 5, 6, 7, 3, 0]) + self.assertEqual(list(reversed(c3))[:2], [1, 99]) + self.assertEqual(c3.popitem(), (1, "1")) + self.assertNotIn(99, od) + + def test_ordered_dict_subclass_copy(self): + class Sub(OrderedDict): + pass + + s = Sub(a=1, b=2) + s.move_to_end("a") + c = s.copy() + self.assertIs(type(c), Sub) + self.assertEqual(list(c.items()), [("b", 2), ("a", 1)]) + self.assertEqual(list(dict(s)), ["b", "a"]) + + def test_keys_with_python_hash(self): + class K: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, K) and self.v == other.v + + for _ in range(50): + od = OrderedDict([(K(1), "a"), (K(2), "b")]) + c = od.copy() + self.assertEqual([k.v for k in c], [1, 2]) + self.assertEqual(c[K(2)], "b") + self.assertEqual([k.v for k in dict(od)], [1, 2]) + dd = defaultdict(int, {K(1): 1}) + self.assertEqual(dd.copy()[K(1)], 1) + self.assertEqual({K(1): 1}, defaultdict(int, {K(1): 1})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_subclass_table_copy_and_context_lanes.py b/tests/regrtest/test_dict_subclass_table_copy_and_context_lanes.py new file mode 100644 index 000000000..62d2621be --- /dev/null +++ b/tests/regrtest/test_dict_subclass_table_copy_and_context_lanes.py @@ -0,0 +1,246 @@ +"""A dict subclass built from a dict copies the dict's table whole; +`decimal.getcontext`, `dict.fromkeys`, `hmac.compare_digest`, +`zlib.decompressobj` and `json`'s scanner constructor run in place from +compiled code; and a decimal context's flag mapping copies without a +call a key. Each behaves as the general path does.""" + +import decimal +import hmac +import json +import unittest +import zlib +from collections import OrderedDict + +N = 300 + + +class Plain(dict): + pass + + +class Noisy(dict): + """A subclass whose own `__setitem__` the constructor never calls.""" + + stored = 0 + + def __setitem__(self, key, value): + Noisy.stored += 1 + dict.__setitem__(self, key, value) + + +class Odd: + def __init__(self, v): + self.v = v + + def __hash__(self): + return 1 + + def __eq__(self, other): + return isinstance(other, Odd) and self.v == other.v + + +class DictSubclassInit(unittest.TestCase): + def test_copy_of_a_dict(self): + src = {"a": 1, 2: [3], (4, 5): None, 6.5: "x"} + for _ in range(N): + d = Plain(src) + self.assertEqual(d, src) + self.assertIs(type(d), Plain) + self.assertEqual(list(d), list(src)) + self.assertIs(d[2], src[2]) + d["new"] = 1 + del d["a"] + self.assertEqual(src, {"a": 1, 2: [3], (4, 5): None, 6.5: "x"}) + src["later"] = 2 + self.assertNotIn("later", d) + + def test_keywords_and_empty(self): + for _ in range(N): + got = (Plain({"a": 1}, b=2), Plain(a=1), Plain(), Plain({}), Plain({}, a=3), Plain({"a": 1}, a=9)) + self.assertEqual(got, ({"a": 1, "b": 2}, {"a": 1}, {}, {}, {"a": 3}, {"a": 9})) + self.assertEqual(list(got[0]), ["a", "b"]) + + def test_init_again_merges(self): + d = Plain({"a": 1, "b": 2}) + for i in range(N): + d.__init__({"b": i, "c": 3}) + self.assertEqual(d, {"a": 1, "b": N - 1, "c": 3}) + self.assertEqual(list(d), ["a", "b", "c"]) + d.__init__(d) + self.assertEqual(d, {"a": 1, "b": N - 1, "c": 3}) + e = Plain() + e.__init__(e) + self.assertEqual(e, {}) + + def test_setitem_override_is_not_called(self): + Noisy.stored = 0 + for _ in range(N): + d = Noisy({"a": 1, "b": 2}) + self.assertEqual((Noisy.stored, dict(d)), (0, {"a": 1, "b": 2})) + d["c"] = 3 + self.assertEqual(Noisy.stored, 1) + + def test_colliding_keys(self): + src = {Odd(i): i for i in range(6)} + for _ in range(20): + d = Plain(src) + self.assertEqual(len(d), 6) + self.assertEqual(d[Odd(4)], 4) + self.assertNotIn(Odd(9), d) + + def test_other_sources(self): + od = OrderedDict([("x", 1), ("y", 2)]) + for _ in range(N): + got = (Plain(od), Plain([("a", 1), ("b", 2)]), Plain(Plain({"k": 1})), + Plain(zip("ab", (1, 2))), Plain({"a": 1}.items())) + self.assertEqual(got, ({"x": 1, "y": 2}, {"a": 1, "b": 2}, {"k": 1}, {"a": 1, "b": 2}, {"a": 1})) + for bad in (5, [1], [(1, 2, 3)]): + with self.assertRaises((TypeError, ValueError)): + Plain(bad) + with self.assertRaises(TypeError): + Plain({}, {}) + + def test_unhashable_and_values_alive(self): + import weakref + + class Node: + pass + + n = Node() + r = weakref.ref(n) + d = Plain({"n": n}) + del n + self.assertIsNotNone(r()) + del d + import gc + + gc.collect() + self.assertIsNone(r()) + + +class InPlaceNatives(unittest.TestCase): + def test_getcontext(self): + first = decimal.getcontext() + for _ in range(N): + ctx = decimal.getcontext() + self.assertIs(ctx, first) + with decimal.localcontext() as inner: + for _ in range(N): + got = decimal.getcontext() + self.assertIs(got, inner) + self.assertIsNot(inner, first) + self.assertIs(decimal.getcontext(), first) + with self.assertRaises(TypeError): + decimal.getcontext(1) + + def test_fromkeys(self): + class Sub(dict): + pass + + calls = [] + + def gen(): + calls.append(1) + yield "a" + yield "b" + + for _ in range(N): + got = (dict.fromkeys("ab"), dict.fromkeys(["x", "y"], 0), Sub.fromkeys(("k",), []), dict.fromkeys(gen(), 1), + OrderedDict.fromkeys("ba", 2), dict.fromkeys({"q": 1}), dict.fromkeys(range(3), "v")) + self.assertEqual(got, ({"a": None, "b": None}, {"x": 0, "y": 0}, {"k": []}, {"a": 1, "b": 1}, + OrderedDict([("b", 2), ("a", 2)]), {"q": None}, {0: "v", 1: "v", 2: "v"})) + self.assertIs(type(got[2]), Sub) + self.assertIs(type(got[4]), OrderedDict) + self.assertEqual(len(calls), N) + shared = dict.fromkeys("ab", []) + self.assertIs(shared["a"], shared["b"]) + for _ in range(5): + with self.assertRaises(TypeError): + dict.fromkeys(5) + with self.assertRaises(TypeError): + dict.fromkeys([[]]) + with self.assertRaises(TypeError): + dict.fromkeys() + + def test_compare_digest(self): + for _ in range(N): + got = (hmac.compare_digest(b"abc", b"abc"), hmac.compare_digest(b"abc", b"abd"), + hmac.compare_digest("abc", "abc"), hmac.compare_digest(b"a", b"ab")) + self.assertEqual(got, (True, False, True, False)) + for _ in range(5): + with self.assertRaises(TypeError): + hmac.compare_digest(b"a", "a") + with self.assertRaises(TypeError): + hmac.compare_digest("é", "é") + + def test_json_hooks(self): + seen = [] + + def hook(d): + seen.append(sorted(d)) + return tuple(sorted(d.items())) + + for _ in range(N): + got = json.loads('{"a": [1, {"b": null}], "c": 2.5}', object_hook=hook) + pairs = json.loads('{"x": 1, "y": 2}', object_pairs_hook=list) + floats = json.loads("[1.5, 2]", parse_float=str, parse_int=float) + self.assertEqual(got, (("a", [1, (("b", None),)]), ("c", 2.5))) + self.assertEqual(pairs, [("x", 1), ("y", 2)]) + self.assertEqual(floats, ["1.5", 2.0]) + self.assertEqual(seen[-2:], [["b"], ["a", "c"]]) + for _ in range(5): + with self.assertRaises(json.JSONDecodeError): + json.loads("{", object_hook=hook) + + def test_decompressobj(self): + blob = zlib.compress(b"hello world " * 50) + for _ in range(60): + d = zlib.decompressobj() + out = d.decompress(blob[:20]) + d.decompress(blob[20:]) + d.flush() + self.assertEqual(out, b"hello world " * 50) + self.assertTrue(d.eof) + for _ in range(5): + with self.assertRaises(zlib.error): + zlib.decompressobj().decompress(b"not zlib data") + + +class ContextMappings(unittest.TestCase): + def test_flag_mapping_copy(self): + ctx = decimal.Context() + ctx.flags[decimal.Inexact] = True + for _ in range(N): + flags = ctx.flags.copy() + traps = ctx.traps.copy() + self.assertIs(type(flags), dict) + self.assertEqual(flags, dict(ctx.flags)) + self.assertTrue(flags[decimal.Inexact]) + self.assertEqual(set(traps), set(ctx.traps)) + flags[decimal.Inexact] = False + self.assertTrue(ctx.flags[decimal.Inexact]) + + def test_context_copies_are_independent(self): + base = decimal.Context(prec=7, traps=[decimal.DivisionByZero]) + for i in range(60): + c = base.copy() + c.prec = 3 + i % 5 + c.flags[decimal.Rounded] = True + c.traps[decimal.Overflow] = True + d = decimal.Context(prec=9, flags=[decimal.Clamped]) + self.assertEqual((base.prec, base.flags[decimal.Rounded], base.traps[decimal.Overflow]), (7, False, False)) + self.assertTrue(base.traps[decimal.DivisionByZero]) + self.assertEqual((c.prec, c.traps[decimal.DivisionByZero], c.traps[decimal.Overflow]), (3 + 59 % 5, True, True)) + self.assertEqual((d.prec, d.flags[decimal.Clamped], d.flags[decimal.Inexact]), (9, True, False)) + + def test_local_contexts(self): + outer = decimal.getcontext().prec + for i in range(60): + with decimal.localcontext() as ctx: + ctx.prec = 5 + got = decimal.Decimal(1) / decimal.Decimal(3) + with decimal.localcontext(prec=3, rounding=decimal.ROUND_UP): + up = decimal.Decimal("1.2341") + 0 + self.assertEqual((str(got), str(up), decimal.getcontext().prec), ("0.33333", "1.24", outer)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_subclass_temp_keys.py b/tests/regrtest/test_dict_subclass_temp_keys.py new file mode 100644 index 000000000..6c39d5920 --- /dev/null +++ b/tests/regrtest/test_dict_subclass_temp_keys.py @@ -0,0 +1,200 @@ +"""Subscripts of dict subclasses (`defaultdict`, `OrderedDict`, +`Counter`, plain subclasses) by keys the subscript holds alone +(`d[w + "x"]`, `d[(a, b)]`) and by tuple keys: reads, misses, stores +and augmented assignments match the general paths, overridden methods +still run, and the keys' reference counts come out even.""" + +import collections +import sys +import unittest +from collections import Counter, OrderedDict, defaultdict + +N = 400 + + +class Shout(dict): + def __getitem__(self, key): + return "shout:" + str(dict.__getitem__(self, key)) + + +class Logged(dict): + def __init__(self, *a): + super().__init__(*a) + self.sets = [] + + def __setitem__(self, key, value): + self.sets.append(key) + dict.__setitem__(self, key, value) + + +class Filled(dict): + def __missing__(self, key): + return ("missing", key) + + +class Plain(dict): + pass + + +class HashKey: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, HashKey) and self.v == other.v + + +class TempKeyTests(unittest.TestCase): + def test_defaultdict_reads_and_misses(self): + words = ["alpha", "beta", "gamma", "alpha", "beta", "alpha"] + for _ in range(N): + g = defaultdict(list) + for w in words: + g[w + "!"].append(w) + self.assertEqual({k: len(v) for k, v in g.items()}, {"alpha!": 3, "beta!": 2, "gamma!": 1}) + t = defaultdict(list) + for i, w in enumerate(words): + t[(len(w), w[0])].append(i) + self.assertEqual(t[(5, "a")], [0, 3, 5]) + self.assertEqual(list(t), [(5, "a"), (4, "b"), (5, "g")]) + c = defaultdict(int) + for w in words: + c[w.upper()] += 1 + c[(w, 1)] += 2 + self.assertEqual(c["ALPHA"], 3) + self.assertEqual(c[("beta", 1)], 4) + + def test_defaultdict_factories(self): + for _ in range(N // 4): + d = defaultdict(lambda: "made") + self.assertEqual(d[("k", 1)], "made") + self.assertEqual(d["k" + str(1)], "made") + self.assertEqual(len(d), 2) + none = defaultdict() + with self.assertRaises(KeyError): + none[("k", 2)] + with self.assertRaises(KeyError): + none["k" + str(2)] + self.assertEqual(len(none), 0) + s = defaultdict(set) + s[(1, 2)].add(3) + s[(1, 2)].add(4) + self.assertEqual(s, {(1, 2): {3, 4}}) + nested = defaultdict(dict) + nested["a" + "b"][(1,)] = 2 + self.assertEqual(nested, {"ab": {(1,): 2}}) + + def test_ordered_dict_and_counter(self): + for _ in range(N): + od = OrderedDict() + for i in range(6): + od[(i % 3, "k")] = i + od["s" + str(i % 2)] = i + self.assertEqual(list(od), [(0, "k"), "s0", (1, "k"), "s1", (2, "k")]) + self.assertEqual(od[(2, "k")], 5) + self.assertEqual(od["s" + "1"], 5) + with self.assertRaises(KeyError): + od[(9, "k")] + c = Counter() + for ch in "abracadabra": + c[ch + ch] += 1 + c[(ch,)] += 1 + self.assertEqual(c["aa"], 5) + self.assertEqual(c[("b",)], 2) + self.assertEqual(c[("zz",)], 0) + self.assertNotIn(("zz",), c) + + def test_plain_subclass(self): + for _ in range(N): + p = Plain() + for i in range(5): + p[(i, i)] = i + p["k" + str(i)] = -i + self.assertEqual(p[(3, 3)], 3) + self.assertEqual(p["k" + str(4)], -4) + p[(3, 3)] += 10 + self.assertEqual(p[(3, 3)], 13) + with self.assertRaises(KeyError): + p[(7, 7)] + with self.assertRaises(KeyError): + p["k" + "9"] + self.assertEqual(len(p), 10) + + def test_overrides_still_run(self): + for _ in range(N): + s = Shout({(1, 2): "v", "ab": "w"}) + self.assertEqual(s[(1, 2)], "shout:v") + self.assertEqual(s["a" + "b"], "shout:w") + lg = Logged() + lg[(1, 2)] = 3 + lg["a" + "b"] = 4 + self.assertEqual(lg.sets, [(1, 2), "ab"]) + self.assertEqual(dict(lg), {(1, 2): 3, "ab": 4}) + f = Filled({(1,): "x"}) + self.assertEqual(f[(1,)], "x") + self.assertEqual(f[(2,)], ("missing", (2,))) + self.assertEqual(f["a" + "b"], ("missing", "ab")) + self.assertEqual(len(f), 1) + + def test_keys_with_python_hash(self): + for _ in range(N // 4): + d = defaultdict(list) + d[HashKey(1)].append("a") + d[HashKey(1)].append("b") + d[(HashKey(2), 0)].append("c") + self.assertEqual(d[HashKey(1)], ["a", "b"]) + self.assertEqual(d[(HashKey(2), 0)], ["c"]) + self.assertEqual(len(d), 2) + + def test_unhashable_keys_raise(self): + d = defaultdict(list) + for _ in range(20): + with self.assertRaises(TypeError): + d[[1, 2]] + with self.assertRaises(TypeError): + d[([1], 2)] = 1 + with self.assertRaises(TypeError): + d[{1: 2}].append(1) + self.assertEqual(len(d), 0) + + def test_reference_counts(self): + class Part: + pass + + key_part = Part() + value = object() + d = defaultdict(lambda: value) + od = OrderedDict() + before = (sys.getrefcount(key_part), sys.getrefcount(value)) + for _ in range(N): + d[(key_part, 1)] + d[(key_part, 2)] = value + od[(key_part, 3)] = value + od[(key_part, 3)] + d[(key_part, 1)] is value + mid = (sys.getrefcount(key_part), sys.getrefcount(value)) + # One tuple per distinct key holds the part; each entry the value. + self.assertEqual(mid[0] - before[0], 3) + self.assertEqual(mid[1] - before[1], 3) + d.clear() + od.clear() + self.assertEqual((sys.getrefcount(key_part), sys.getrefcount(value)), before) + + def test_store_displaces_values(self): + for _ in range(N): + d = defaultdict(list) + first = ["first"] + d[("k", 0)] = first + d[("k", 0)] = ["second"] + self.assertEqual(d[("k", 0)], ["second"]) + self.assertEqual(first, ["first"]) + d["x" + "y"] = first + d["x" + "y"] = None + self.assertIsNone(d["xy"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_subscr_leaf_key.py b/tests/regrtest/test_dict_subscr_leaf_key.py new file mode 100644 index 000000000..14ff91c7d --- /dev/null +++ b/tests/regrtest/test_dict_subscr_leaf_key.py @@ -0,0 +1,102 @@ +"""Compiled `d[k]` of an instance whose class's Python `__hash__` (and a +stored key's `__eq__`) evaluate frameless reads the value in place; the +values, equal but distinct keys, a missing key's `KeyError` (its args the +key itself), hash collisions, stored keys of other kinds, temporaries as +keys, `__eq__` with effects, and an `__eq__` that raises match the +general subscript.""" + +import unittest + + +class P: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x = x + self.y = y + + def __hash__(self): + return hash((self.x, self.y)) + + def __eq__(self, o): + return isinstance(o, P) and self.x == o.x and self.y == o.y + + +class Collide: + def __init__(self, v): + self.v = v + + def __hash__(self): + return 3 + + def __eq__(self, o): + return isinstance(o, Collide) and self.v == o.v + + +class Counted: + eqs = 0 + + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, o): + Counted.eqs += 1 + return isinstance(o, Counted) and self.v == o.v + + +class Boom: + def __hash__(self): + return 9 + + def __eq__(self, o): + raise ValueError("eq") + + +class DictSubscrLeafKey(unittest.TestCase): + def test_values(self): + keys = [P(i, i * 2) for i in range(30)] + d = {k: i for i, k in enumerate(keys)} + for _ in range(200): + for i, k in enumerate(keys): + self.assertEqual(d[k], i) + self.assertEqual(d[P(i, i * 2)], i) + + def test_missing(self): + d = {P(1, 1): "a"} + for _ in range(300): + k = P(2, 2) + with self.assertRaises(KeyError) as cm: + d[k] + self.assertIs(cm.exception.args[0], k) + + def test_collisions_and_mixed(self): + d = {Collide(i): i for i in range(5)} + d[3] = "int" + d[hash((7, 7))] = "h" + d[P(7, 7)] = "p" + for _ in range(300): + self.assertEqual(d[Collide(4)], 4) + self.assertEqual(d[3], "int") + self.assertEqual(d[P(7, 7)], "p") + with self.assertRaises(KeyError): + d[Collide(8)] + + def test_eq_with_effects_and_raises(self): + d = {Counted(i): i for i in range(4)} + Counted.eqs = 0 + for _ in range(300): + self.assertEqual(d[Counted(2)], 2) + self.assertEqual(Counted.eqs, 300) + b = Boom() + e = {b: 1} + for _ in range(300): + self.assertEqual(e[b], 1) + with self.assertRaises(ValueError): + e[Boom()] + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_update_leaf.py b/tests/regrtest/test_dict_update_leaf.py new file mode 100644 index 000000000..f691b2de7 --- /dev/null +++ b/tests/regrtest/test_dict_update_leaf.py @@ -0,0 +1,62 @@ +"""`d.update(other)` and `d.copy()` of plain dicts in compiled code. + +A merge from another plain dict whose keys run no code takes the +source's entries in place: an existing key keeps its key object and takes +the new value, new keys append in order, and a live iterator over the +destination notices a new key. Keys with a Python `__eq__`, `d.update(d)`, +keywords, and other mappings behave as in CPython. Run it past the +compile threshold. +""" + +import types + + +class K: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, K) and self.v == other.v + + +def merge(d, src): + d.update(src) + return d + + +N = 3000 +base = {"a": 1, "b": 2} +one = 1.0 +for i in range(N): + assert merge({}, base) == base + out = merge({"b": 0, "z": 9}, base) + assert list(out) == ["b", "z", "a"] and out == {"b": 2, "z": 9, "a": 1} + d = {one: "x"} + merge(d, {1: "y"}) + assert d == {1.0: "y"} and type(next(iter(d))) is float + kd = merge({K(1): 1}, {K(1): 2, K(2): 3}) + assert len(kd) == 2 and kd[K(1)] == 2 + same = {"s": 1} + assert merge(same, same) == {"s": 1} + c = base.copy() + c["a"] = i + assert base == {"a": 1, "b": 2} and list(c) == ["a", "b"] and c["a"] == i +d = {"a": 1} +d.update({"b": 2}, c=3) +assert d == {"a": 1, "b": 2, "c": 3} +d.update(types.MappingProxyType({"e": 5})) +assert d["e"] == 5 +it = iter(d) +next(it) +try: + for _ in range(N): + merge(d, {"new": 0}) + next(it) +except RuntimeError: + pass +else: + raise AssertionError("a new key during iteration") +print("ok") diff --git a/tests/regrtest/test_dict_values_loops.py b/tests/regrtest/test_dict_values_loops.py new file mode 100644 index 000000000..d3c1faf43 --- /dev/null +++ b/tests/regrtest/test_dict_values_loops.py @@ -0,0 +1,99 @@ +"""`for v in d.values()` in compiled loops. + +Values of every kind come back in insertion order, ints and heap objects +alike; a dict that changes size during the loop, or loses and regains its +only key, raises `RuntimeError` as CPython does; a value replaced in place mid-loop is +seen; `OrderedDict`, dict subclasses and reversed views keep their own +behavior. Loops run past the compile threshold. +""" + +import collections +import unittest + + +class ValuesLoopTests(unittest.TestCase): + def test_values(self): + d = {("k%d" % i): i for i in range(50)} + objs = {i: [i] for i in range(20)} + for _ in range(300): + total = 0 + for v in d.values(): + total += v + self.assertEqual(total, sum(range(50))) + got = [] + for v in objs.values(): + got.append(v[0]) + self.assertEqual(got, list(range(20))) + + def test_mixed_values(self): + d = {"a": 1, "b": "two", "c": None, "d": 2**70, "e": 1.5} + for _ in range(300): + out = [] + for v in d.values(): + out.append(v) + self.assertEqual(out, [1, "two", None, 2**70, 1.5]) + + def test_size_change(self): + for _ in range(100): + d = {i: i for i in range(10)} + with self.assertRaises(RuntimeError): + for v in d.values(): + if v == 3: + d[100] = 0 + d = {i: i for i in range(10)} + with self.assertRaises(RuntimeError): + for v in d.values(): + if v == 3: + del d[0] + + def test_keys_changed_same_size(self): + # (CPython's own case, test_dict's test_mutating_iteration_delete.) + for _ in range(100): + d = {0: 0} + with self.assertRaises(RuntimeError): + for v in d.values(): + del d[0] + d[0] = 0 + + def test_value_replaced(self): + for _ in range(100): + d = {i: i for i in range(5)} + seen = [] + for v in d.values(): + seen.append(v) + if v == 1: + d[3] = "new" + self.assertEqual(seen, [0, 1, 2, "new", 4]) + + def test_other_mappings(self): + od = collections.OrderedDict((i, -i) for i in range(10)) + od.move_to_end(0) + + class Sub(dict): + pass + + s = Sub(a=1, b=2) + for _ in range(200): + self.assertEqual([v for v in od.values()], [-i for i in range(1, 10)] + [0]) + out = [] + for v in s.values(): + out.append(v) + self.assertEqual(out, [1, 2]) + out = [] + for v in reversed({1: "x", 2: "y"}.values()): + out.append(v) + self.assertEqual(out, ["y", "x"]) + + def test_empty_and_exhausted(self): + it = iter({}.values()) + self.assertEqual(list(it), []) + d = {1: 2} + it = iter(d.values()) + for _ in it: + pass + d[5] = 6 + self.assertEqual(list(it), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dict_zip_pairs.py b/tests/regrtest/test_dict_zip_pairs.py new file mode 100644 index 000000000..efea5a82e --- /dev/null +++ b/tests/regrtest/test_dict_zip_pairs.py @@ -0,0 +1,66 @@ +"""`dict(zip(ks, vs))` over sources that run Python code. + +The pairs come straight from the two sources in the order the zip steps +them; an item the first source gave is dropped when the second has none; +errors from either source or from an unhashable key propagate; strict +zips, other arities and iterables keep the general path. +""" + +log = [] + + +def gen(xs, tag): + for x in xs: + log.append((tag, x)) + yield x + + +def boom(n): + yield from range(n) + raise RuntimeError("boom") + + +def run(n): + for _ in range(n): + log.clear() + assert dict(zip("abc", gen(range(3), "v"))) == {"a": 0, "b": 1, "c": 2} + log.clear() + d = dict(zip(gen("abcd", "k"), gen(range(2), "v"))) + assert d == {"a": 0, "b": 1} + assert log == [("k", "a"), ("v", 0), ("k", "b"), ("v", 1), ("k", "c")], log + log.clear() + assert dict(zip(gen("ab", "k"), gen(range(5), "v"))) == {"a": 0, "b": 1} + assert log == [("k", "a"), ("v", 0), ("k", "b"), ("v", 1)], log + assert dict(zip("aa", range(2))) == {"a": 1} + k = iter("xyz") + assert dict(zip(k, gen(range(1), "v"))) == {"x": 0} and list(k) == ["z"] + try: + dict(zip("abcd", boom(2))) + except RuntimeError: + pass + else: + raise AssertionError("source error") + try: + dict(zip(gen([[1]], "k"), "a")) + except TypeError: + pass + else: + raise AssertionError("unhashable key") + try: + dict(zip("ab", gen(range(3), "v"), strict=True)) + except ValueError: + pass + else: + raise AssertionError("strict") + assert dict(zip(gen(range(2), "k"), "ab", strict=True)) == {0: "a", 1: "b"} + try: + dict(zip(gen([(1, 2)], "p"))) + except ValueError: + pass + else: + raise AssertionError("one-item tuples") + assert dict(x for x in [(1, 2)]) == {1: 2} + + +run(400) +print("ok") diff --git a/tests/regrtest/test_dict_zip_text_sources.py b/tests/regrtest/test_dict_zip_text_sources.py new file mode 100644 index 000000000..df75b614b --- /dev/null +++ b/tests/regrtest/test_dict_zip_text_sources.py @@ -0,0 +1,58 @@ +"""`dict(zip(text, values))` and `dict(zip(keys, text))` with a string +source keep CPython's pairs and leave the shared iterators where CPython's +zip leaves them: the longer source one item past the shorter's end, +non-ASCII characters, repeated keys, empty and unequal sources.""" + +import unittest + +N = 3000 + + +class DictZipTextTests(unittest.TestCase): + def test_pairs(self): + L = list(range(10)) + for _ in range(N): + self.assertEqual(dict(zip("abc", L)), {"a": 0, "b": 1, "c": 2}) + self.assertEqual(dict(zip(L, "abc")), {0: "a", 1: "b", 2: "c"}) + self.assertEqual(dict(zip("abc", "xyz")), {"a": "x", "b": "y", "c": "z"}) + self.assertEqual(dict(zip("h\xe9€\U0001f600", (1, 2, 3, 4))), + {"h": 1, "\xe9": 2, "€": 3, "\U0001f600": 4}) + self.assertEqual(dict(zip("abab", L)), {"a": 2, "b": 3}) + self.assertEqual(dict(zip("", L)), {}) + self.assertEqual(dict(zip("abc", [])), {}) + self.assertEqual(list(dict(zip("cba", L))), ["c", "b", "a"]) + + def test_iterators_left_in_place(self): + for _ in range(N): + # (The first source longer: its next item is taken and dropped + # when the second has none.) + k, v = iter("h\xe9€xyz"), iter([1, 2]) + self.assertEqual(dict(zip(k, v)), {"h": 1, "\xe9": 2}) + self.assertEqual(list(k), ["x", "y", "z"]) + self.assertEqual(list(v), []) + # (The first source shorter: the second is left after the + # pairs.) + k, v = iter("ab"), iter("€xyz") + self.assertEqual(dict(zip(k, v)), {"a": "€", "b": "x"}) + self.assertEqual(list(k), []) + self.assertEqual(list(v), ["y", "z"]) + k = iter("abcdef") + next(k) + self.assertEqual(dict(zip(k, (1, 2, 3))), {"b": 1, "c": 2, "d": 3}) + self.assertEqual(list(k), ["f"]) + k, v = iter("abc"), iter("xyz") + self.assertEqual(dict(zip(k, v)), {"a": "x", "b": "y", "c": "z"}) + self.assertEqual((list(k), list(v)), ([], [])) + + def test_long_text(self): + text = "".join(chr(0x61 + i % 26) for i in range(5000)) + values = list(range(4000)) + for _ in range(N // 100): + d = dict(zip(text, values)) + self.assertEqual(len(d), 26) + self.assertEqual(d["a"], 3978) + self.assertEqual(dict(zip(values[:3], text)), {0: "a", 1: "b", 2: "c"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dictcomp_map_add.py b/tests/regrtest/test_dictcomp_map_add.py new file mode 100644 index 000000000..e4345b142 --- /dev/null +++ b/tests/regrtest/test_dictcomp_map_add.py @@ -0,0 +1,59 @@ +"""Dict comprehensions in compiled code (`MAP_ADD`). + +A key the native probe settles is stored in place; a duplicate key keeps +the first key object and takes the last value; unhashable keys raise; +keys with a Python `__eq__` or `__hash__`, `True` against `1`, and a +replaced value's finalizer behave as in CPython. Run it past the compile +threshold. +""" + + +class K: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, K) and self.v == other.v + + +class D: + log = [] + + def __init__(self, n): + self.n = n + + def __del__(self): + D.log.append(self.n) + + +def run(n): + xs = (1, 2, 3, 2, 1) + for i in range(n): + d = {x: x * 10 + i % 3 for x in xs} + assert d == {1: 10 + i % 3, 2: 20 + i % 3, 3: 30 + i % 3} + assert list(d) == [1, 2, 3] + e = {k: v for k, v in [(1, "a"), (True, "b"), (1.0, "c")]} + assert e == {1: "c"} and type(next(iter(e))) is int + s = {str(x): None for x in xs} + assert list(s) == ["1", "2", "3"] + kd = {K(x): x for x in xs} + assert len(kd) == 3 and kd[K(2)] == 2 + try: + {[x]: x for x in xs} + except TypeError: + pass + else: + raise AssertionError("unhashable key") + D.log.clear() + dd = {k: D(k) for k in (5, 5)} + assert D.log == [5], D.log + assert dd[5].n == 5 + del dd + D.log.clear() + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_dir_entry_fast_methods.py b/tests/regrtest/test_dir_entry_fast_methods.py new file mode 100644 index 000000000..cf7c2f062 --- /dev/null +++ b/tests/regrtest/test_dir_entry_fast_methods.py @@ -0,0 +1,176 @@ +"""`os.DirEntry` kind and inode methods in hot loops. + +`is_dir()`, `is_file()`, `is_symlink()` and `inode()` answer from what the +directory read stored, in place, once compiled code calls them; a kind the +read didn't know, a link to follow, or a keyword call takes the full +method. Each loop runs long enough for its function to compile and checks +every answer against `os.stat`/`os.lstat`. +""" + +import os +import shutil +import stat +import tempfile +import unittest + +ROUNDS = 3000 + + +def kinds(entries): + out = [] + for _ in range(ROUNDS): + out = [] + for e in entries: + out.append((e.name, e.is_dir(), e.is_file(), e.is_symlink())) + return sorted(out) + + +def kinds_nofollow(entries): + out = [] + for _ in range(ROUNDS): + out = [] + for e in entries: + out.append( + ( + e.name, + e.is_dir(follow_symlinks=False), + e.is_file(follow_symlinks=False), + ) + ) + return sorted(out) + + +def inodes(entries): + out = [] + for _ in range(ROUNDS): + out = [(e.name, e.inode()) for e in entries] + return sorted(out) + + +def expected(top, name, follow=True): + path = os.path.join(top, name) + try: + st = os.stat(path) if follow else os.lstat(path) + except OSError: + return False, False + return stat.S_ISDIR(st.st_mode), stat.S_ISREG(st.st_mode) + + +class DirEntryFastMethodTests(unittest.TestCase): + def setUp(self): + self.top = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.top) + for name in ("a.txt", "b.txt"): + with open(os.path.join(self.top, name), "w") as f: + f.write(name) + os.mkdir(os.path.join(self.top, "sub")) + self.links = False + if hasattr(os, "symlink"): + try: + os.symlink(os.path.join(self.top, "a.txt"), os.path.join(self.top, "to_file")) + os.symlink(os.path.join(self.top, "sub"), os.path.join(self.top, "to_dir")) + os.symlink(os.path.join(self.top, "gone"), os.path.join(self.top, "dangling")) + self.links = True + except OSError: + pass + + def entries(self): + with os.scandir(self.top) as it: + return list(it) + + def test_kinds_follow(self): + got = kinds(self.entries()) + want = [] + for name in os.listdir(self.top): + d, f = expected(self.top, name) + link = os.path.islink(os.path.join(self.top, name)) + want.append((name, d, f, link)) + self.assertEqual(got, sorted(want)) + + def test_kinds_no_follow(self): + got = kinds_nofollow(self.entries()) + want = sorted((name,) + expected(self.top, name, follow=False) for name in os.listdir(self.top)) + self.assertEqual(got, want) + + def test_links(self): + if not self.links: + self.skipTest("no symlinks") + by_name = {e.name: e for e in self.entries()} + for _ in range(ROUNDS): + self.assertTrue(by_name["to_dir"].is_dir()) + self.assertFalse(by_name["to_dir"].is_dir(follow_symlinks=False)) + self.assertTrue(by_name["to_file"].is_file()) + self.assertTrue(by_name["to_file"].is_symlink()) + self.assertFalse(by_name["dangling"].is_file()) + self.assertFalse(by_name["dangling"].is_dir()) + self.assertTrue(by_name["dangling"].is_symlink()) + self.assertFalse(by_name["sub"].is_symlink()) + + def test_inodes(self): + got = inodes(self.entries()) + want = sorted((name, os.lstat(os.path.join(self.top, name)).st_ino) for name in os.listdir(self.top)) + self.assertEqual(got, want) + + def test_entries_outlive_their_files(self): + entries = self.entries() + before = kinds(entries) + for name in os.listdir(self.top): + path = os.path.join(self.top, name) + if os.path.isdir(path) and not os.path.islink(path): + shutil.rmtree(path) + else: + os.unlink(path) + # (Kinds the directory read stored stay, and so does a followed + # link's, which the entry's cached `stat()` result answers.) + self.assertEqual(kinds(entries), before) + if self.links: + by_name = {e.name: e for e in entries} + self.assertTrue(by_name["to_dir"].stat().st_mode & stat.S_IFDIR) + + def test_followed_kind_is_the_cached_stat(self): + if not self.links: + self.skipTest("no symlinks") + by_name = {e.name: e for e in self.entries()} + link = by_name["to_file"] + # The target replaced by a directory after the entry's first + # followed look: the entry keeps answering from that look. + self.assertTrue(link.is_file()) + os.unlink(os.path.join(self.top, "a.txt")) + os.mkdir(os.path.join(self.top, "a.txt")) + for _ in range(ROUNDS): + self.assertTrue(link.is_file()) + self.assertFalse(link.is_dir()) + self.assertTrue(stat.S_ISREG(link.stat().st_mode)) + # A fresh entry looks again. + fresh = {e.name: e for e in self.entries()}["to_file"] + self.assertTrue(fresh.is_dir()) + + def test_fd_listing(self): + if os.scandir not in getattr(os, "supports_fd", set()): + self.skipTest("no scandir(fd)") + fd = os.open(self.top, os.O_RDONLY) + try: + with os.scandir(fd) as it: + entries = list(it) + got = kinds(entries) + finally: + os.close(fd) + want = [] + for name in os.listdir(self.top): + d, f = expected(self.top, name) + want.append((name, d, f, os.path.islink(os.path.join(self.top, name)))) + self.assertEqual(got, sorted(want)) + + def test_unbound_calls(self): + entries = self.entries() + is_dir, is_symlink = os.DirEntry.is_dir, os.DirEntry.is_symlink + for _ in range(ROUNDS): + for e in entries: + self.assertEqual(is_dir(e), e.is_dir()) + self.assertEqual(is_symlink(e), e.is_symlink()) + with self.assertRaises(TypeError): + is_dir(object()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_dir_names.py b/tests/regrtest/test_dir_names.py new file mode 100644 index 000000000..42fac2427 --- /dev/null +++ b/tests/regrtest/test_dir_names.py @@ -0,0 +1,40 @@ +"""`dir()` of classes, instances, functions, modules and aliases. + +`inspect.getmembers` starts from `dir(cls)`. The names come back sorted +and without duplicates, an instance's own attributes among its class's, +a function's attributes among its type's, and a PEP 604 union without +its private bookkeeping. Run it past the compile threshold. +""" + +import sys + + +class A: + x = 1 + + def m(self): + pass + + +class B(A): + y = 2 + + +def f(): + pass + + +f.tag = 1 +a = B() +a.z = 3 + +for _ in range(2000): + for o in (A, B, a, f, a.m, sys, 1, "s", [1], list[int], int | str): + d = dir(o) + assert d == sorted(set(d)), o + assert {"x", "y", "m", "__init__", "__class__"} <= set(dir(B)) + assert {"x", "y", "z", "m"} <= set(dir(a)) + assert "tag" in dir(f) and "__code__" in dir(f) + u = dir(int | str) + assert "__origin__" in u and "__is_pep604_union__" not in u + assert "__origin__" in dir(list[int]) and "append" in dir(list[int]) diff --git a/tests/regrtest/test_dunder_import_lane.py b/tests/regrtest/test_dunder_import_lane.py new file mode 100644 index 000000000..96cf7a595 --- /dev/null +++ b/tests/regrtest/test_dunder_import_lane.py @@ -0,0 +1,233 @@ +"""Direct ``__import__`` calls, module specs and module dunder reads. + +Compiled code answers ``__import__(name, ...)`` of an already imported +module from the import cache, natively loaded modules' specs carry +``_initializing = False`` as CPython's ``_load_unlocked`` leaves them, and +``getattr(module, "__dunder__", default)`` reads a dunder the module's +dictionary holds in place. Each case runs hot enough to compile and must +agree with the full import and attribute paths. +""" + +import builtins +import importlib +import json +import os +import os.path +import subprocess +import sys +import types +import unittest + +N = 3000 + + +class DirectImportTests(unittest.TestCase): + def test_plain_and_dotted(self): + def run(): + out = [] + for _ in range(N): + out.append(__import__("os")) + out.append(__import__("os.path")) + return out + + out = run() + self.assertTrue(all(m is os for m in out)) + + def test_fromlist_forms(self): + def run(fromlist): + last = None + for _ in range(N): + last = __import__("os.path", None, None, fromlist) + return last + + self.assertIs(run(["sep"]), os.path) + self.assertIs(run(("sep", "join")), os.path) + self.assertIs(run([]), os) + self.assertIs(run(()), os) + self.assertIs(run(None), os) + + def test_fromlist_loads_submodule(self): + # A from-list name the package's dict doesn't hold may be a + # submodule: the full import loads it. + name = "json.tool" + sys.modules.pop(name, None) + if hasattr(json, "tool"): + del json.tool + + def run(): + last = None + for _ in range(N): + last = __import__("json", None, None, ["tool"]) + return last + + self.assertIs(run(), json) + self.assertIn(name, sys.modules) + self.assertIs(json.tool, sys.modules[name]) + + def test_sys_modules_entry_changes(self): + name = "_dunder_import_lane_fake" + first = types.ModuleType(name) + second = object() + found = [] + try: + for i in range(N): + sys.modules[name] = first if i % 2 == 0 else second + found.append(__import__(name)) + finally: + sys.modules.pop(name, None) + self.assertTrue(all(m is first for m in found[0::2])) + self.assertTrue(all(m is second for m in found[1::2])) + + def test_none_entry_raises(self): + name = "_dunder_import_lane_blocked" + sys.modules[name] = None + try: + raised = 0 + for _ in range(N): + try: + __import__(name) + except ModuleNotFoundError: + raised += 1 + self.assertEqual(raised, N) + finally: + sys.modules.pop(name, None) + + def test_errors(self): + def run(*args, **kwargs): + caught = [] + for _ in range(N): + try: + __import__(*args, **kwargs) + except Exception as e: + caught.append(type(e)) + return set(caught) + + self.assertEqual(run(42), {TypeError}) + self.assertEqual(run(""), {ValueError}) + self.assertEqual(run("os", None, None, None, -1), {ValueError}) + self.assertEqual(run("os", None, None, None, 1), {TypeError}) + self.assertEqual(run("os", [], None, None, 1), {TypeError}) + self.assertEqual(run("os", level=1), {KeyError}) + + def test_original_builtin_skips_replacement(self): + original = builtins.__import__ + calls = [] + + def hook(*args, **kwargs): + calls.append(args[0]) + return original(*args, **kwargs) + + builtins.__import__ = hook + try: + found = [original("os") for _ in range(N)] + import json as again + finally: + builtins.__import__ = original + self.assertTrue(all(m is os for m in found)) + self.assertIs(again, json) + self.assertEqual(calls, ["json"]) + + def test_audit_event_only_on_load(self): + # CPython raises the `import` audit event in `import_find_and_load`: + # for a module it loads, not for one `sys.modules` already holds. + code = ( + "import sys\n" + "seen = []\n" + "sys.addaudithook(lambda e, a: seen.append(a[0]) if e == 'import' else None)\n" + "def run():\n" + " for _ in range(3000):\n" + " __import__('os')\n" + " import os\n" + " from os import path\n" + "run()\n" + "import colorsys\n" + "import colorsys\n" + "sys.modules['_audit_blocked'] = None\n" + "try:\n" + " import _audit_blocked\n" + "except ImportError:\n" + " pass\n" + "print(seen.count('os'), seen.count('colorsys'), seen.count('_audit_blocked'))\n" + ) + out = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, check=True + ) + self.assertEqual(out.stdout.split(), ["0", "1", "1"]) + + +class SpecInitializingTests(unittest.TestCase): + def test_loaded_modules_are_not_initializing(self): + for module in (os, json, importlib, unittest): + spec = module.__spec__ + self.assertIs(spec._initializing, False, module.__name__) + + def test_import_module_in_a_loop(self): + def run(): + last = None + for _ in range(N): + last = importlib.import_module("os") + importlib.import_module("os.path") + return last + + self.assertIs(run(), os) + + def test_import_module_after_removal(self): + name = "_dunder_import_lane_mod" + mod = types.ModuleType(name) + mod.__spec__ = importlib.machinery.ModuleSpec(name, None) + sys.modules[name] = mod + try: + found = [importlib.import_module(name) for _ in range(N)] + finally: + sys.modules.pop(name, None) + self.assertTrue(all(m is mod for m in found)) + with self.assertRaises(ModuleNotFoundError): + importlib.import_module(name) + + +class ModuleDunderGetattrTests(unittest.TestCase): + def test_spec_and_loader(self): + def read(m): + return getattr(m, "__spec__", None), getattr(m, "__loader__", None) + + for _ in range(N): + spec, loader = read(os) + self.assertIs(spec, os.__spec__) + self.assertIs(loader, os.__loader__) + + def test_stored_dunder_then_removed(self): + m = types.ModuleType("_dunder_import_lane_attrs") + m.__custom__ = 3 + + def read(): + return getattr(m, "__custom__", None) + + self.assertEqual([read() for _ in range(N)], [3] * N) + del m.__custom__ + self.assertEqual([read() for _ in range(N)], [None] * N) + + def test_module_getattr_hook_for_dunders(self): + m = types.ModuleType("_dunder_import_lane_hook") + m.__getattr__ = lambda name: "hooked " + name + + def read(): + return getattr(m, "__other__", None), getattr(m, "plain", None) + + for _ in range(N): + got = read() + self.assertEqual(got, ("hooked __other__", "hooked plain")) + + def test_module_dict_and_class(self): + m = types.ModuleType("_dunder_import_lane_dict") + + def read(): + return getattr(m, "__dict__", None), getattr(m, "__class__", None) + + for _ in range(N): + d, c = read() + self.assertIs(d, vars(m)) + self.assertIs(c, types.ModuleType) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_effect_leaf_read_after_store.py b/tests/regrtest/test_effect_leaf_read_after_store.py new file mode 100644 index 000000000..3e09e124e --- /dev/null +++ b/tests/regrtest/test_effect_leaf_read_after_store.py @@ -0,0 +1,83 @@ +"""Methods that store an attribute and read it back (an iterator's +`__next__`, a counter's `bump`) read the buffered value; the values seen, +two instances of one class, a read of another attribute, `__slots__` +classes, a store followed by a raise, and a class whose attribute is +replaced later match the general method call.""" + +import unittest + + +class It: + def __init__(self, n): + self.i = 0 + self.n = n + + def __iter__(self): + return self + + def __next__(self): + self.i += 1 + if self.i > self.n: + raise StopIteration + return self.i + + +class Counter: + __slots__ = ("a", "b") + + def __init__(self): + self.a = 0 + self.b = 100 + + def bump(self, other): + self.a = self.a + 1 + other.a = other.a + 2 + return (self.a, other.a, self.b) + + +class Boom: + def __init__(self): + self.x = 0 + + def step(self): + self.x = self.x + 1 + if self.x % 3 == 0: + raise ValueError(self.x) + return self.x + + +class EffectLeafReadAfterStore(unittest.TestCase): + def test_iterator(self): + total = 0 + for k in range(300): + for v in It(20): + total += v + self.assertEqual(total, 300 * 210) + + def test_two_instances(self): + p, q = Counter(), Counter() + out = [] + for i in range(2000): + out.append(p.bump(q)) + self.assertEqual(out[0], (1, 2, 100)) + self.assertEqual(out[-1], (2000, 4000, 100)) + self.assertEqual((p.a, q.a), (2000, 4000)) + s = Counter() + for i in range(500): + r = s.bump(s) + self.assertEqual(r, (1500, 1500, 100)) + + def test_raise_after_store(self): + b = Boom() + seen = [] + for i in range(3000): + try: + seen.append(b.step()) + except ValueError as e: + seen.append(-e.args[0]) + self.assertEqual(seen[:6], [1, 2, -3, 4, 5, -6]) + self.assertEqual(b.x, 3000) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enum_class_collect.py b/tests/regrtest/test_enum_class_collect.py new file mode 100644 index 000000000..1167af53e --- /dev/null +++ b/tests/regrtest/test_enum_class_collect.py @@ -0,0 +1,70 @@ +"""list(), tuple(), set() and sorted() of an enum class from compiled +loops: members in definition order without aliases, a Flag class's +canonical members, an empty enum, a metaclass that overrides __iter__, +and a member added after creation through the internal tables, each +matching CPython.""" + +import enum +import unittest + + +class Color(enum.Enum): + RED = 1 + GREEN = 2 + CRIMSON = 1 + BLUE = 3 + + +class Perm(enum.Flag): + R = 4 + W = 2 + X = 1 + RW = 6 + + +class Empty(enum.Enum): + pass + + +class RevMeta(enum.EnumType): + def __iter__(cls): + return reversed(cls._member_names_) + + +class Rev(enum.Enum, metaclass=RevMeta): + A = 1 + B = 2 + + +def collect(n, cls): + out = None + for i in range(n): + out = (list(cls), tuple(cls), len(set(cls))) + return out + + +class EnumCollectTests(unittest.TestCase): + def test_members(self): + for n in (1, 300): + self.assertEqual(collect(n, Color)[0], [Color.RED, Color.GREEN, Color.BLUE]) + self.assertEqual(collect(n, Color)[1], (Color.RED, Color.GREEN, Color.BLUE)) + self.assertEqual(collect(n, Perm)[0], [Perm.R, Perm.W, Perm.X]) + self.assertEqual(collect(n, Empty), ([], (), 0)) + self.assertEqual(collect(n, Rev)[0], ["B", "A"]) + self.assertEqual(sorted(Color, key=lambda m: m.value), [Color.RED, Color.GREEN, Color.BLUE]) + + def test_extended(self): + class E(enum.Enum): + A = 1 + + self.assertEqual(collect(300, E)[0], [E.A]) + member = object.__new__(E) + member._name_ = "B" + member._value_ = 2 + E._member_map_["B"] = member + E._member_names_.append("B") + self.assertEqual(collect(300, E)[0], [E.A, member]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enum_class_loops.py b/tests/regrtest/test_enum_class_loops.py new file mode 100644 index 000000000..f4d29117a --- /dev/null +++ b/tests/regrtest/test_enum_class_loops.py @@ -0,0 +1,97 @@ +"""for loops over enum classes and len() of them from compiled code: the +members in order without aliases, a member added to the tables while a +loop runs (seen, as the generator would see it), an empty enum, a +metaclass overriding __iter__ or __len__, a Flag class, and map over a +dict's __getitem__ with a missing key's KeyError, each matching +CPython.""" + +import enum +import unittest + + +class Color(enum.Enum): + RED = 1 + GREEN = 2 + CRIMSON = 1 + BLUE = 3 + + +class Perm(enum.Flag): + R = 4 + W = 2 + X = 1 + + +class Empty(enum.Enum): + pass + + +class OddMeta(enum.EnumType): + def __iter__(cls): + return iter(["x", "y"]) + + def __len__(cls): + return 7 + + +class Odd(enum.Enum, metaclass=OddMeta): + A = 1 + + +def loop(n, cls): + out = None + for i in range(n): + got = [] + for m in cls: + got.append(m) + out = (got, len(cls)) + return out + + +class EnumLoopTests(unittest.TestCase): + def test_loops(self): + for n in (1, 300): + self.assertEqual(loop(n, Color), ([Color.RED, Color.GREEN, Color.BLUE], 3)) + self.assertEqual(loop(n, Perm), ([Perm.R, Perm.W, Perm.X], 3)) + self.assertEqual(loop(n, Empty), ([], 0)) + self.assertEqual(loop(n, Odd), (["x", "y"], 7)) + + def test_added_during_loop(self): + def run(n): + out = None + for i in range(n): + + class E(enum.Enum): + A = 1 + + got = [] + for m in E: + got.append(m.name if hasattr(m, "name") else m) + if len(got) == 1: + extra = object.__new__(E) + extra._name_ = "B" + extra._value_ = 2 + E._member_map_["B"] = extra + E._member_names_.append("B") + out = got + return out + + self.assertEqual(run(300), ["A", "B"]) + + def test_map_getitem(self): + d = {"a": 1, "b": 2} + + def run(n, keys): + out = None + for i in range(n): + out = list(map(d.__getitem__, keys)) + return out + + for n in (1, 300): + self.assertEqual(run(n, ["b", "a"]), [2, 1]) + with self.assertRaises(KeyError): + run(300, ["a", "z"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enum_hash_and_fields_compiled.py b/tests/regrtest/test_enum_hash_and_fields_compiled.py new file mode 100644 index 000000000..ffa38a960 --- /dev/null +++ b/tests/regrtest/test_enum_hash_and_fields_compiled.py @@ -0,0 +1,116 @@ +"""Enum members as dict and set keys, and their .name and .value, read +from compiled loops: hashes equal to hash(member._name_), lookups and +set building, values of any type, a class that overrides __hash__, name +or value, a member whose _name_ was replaced, a class whose __hash__ +changes after the loop warmed up, and a profiler that still sees +enum's methods, each matching CPython.""" + +import enum +import sys +import unittest + + +class Color(enum.Enum): + RED = 1 + GREEN = (2, "g") + BLUE = "b" + + +class OwnHash(enum.Enum): + A = 1 + + def __hash__(self): + return 7 + + +class OwnValue(enum.Enum): + A = 1 + + @enum.property + def value(self): + return "overridden" + + +class Late(enum.Enum): + A = 1 + B = 2 + + +def lookups(n, d, key): + out = None + for i in range(n): + out = (d[key], key in d, hash(key)) + return out + + +def sets(n, a, b): + out = None + for i in range(n): + out = {a, b} + return out + + +def fields(n, m): + out = None + for i in range(n): + out = (m.name, m.value) + return out + + +class EnumHashAndFieldTests(unittest.TestCase): + def test_hash_and_lookups(self): + d = {Color.RED: "r", Color.GREEN: "g"} + for n in (1, 400): + self.assertEqual(lookups(n, d, Color.GREEN), ("g", True, hash("GREEN"))) + self.assertEqual(sets(n, Color.RED, Color.BLUE), {Color.BLUE, Color.RED}) + self.assertEqual(len(sets(n, Color.RED, Color.RED)), 1) + self.assertEqual(lookups(n, {OwnHash.A: 1}, OwnHash.A), (1, True, 7)) + with self.assertRaises(KeyError): + lookups(300, d, Color.BLUE) + + def test_fields(self): + for n in (1, 400): + self.assertEqual(fields(n, Color.RED), ("RED", 1)) + self.assertEqual(fields(n, Color.GREEN), ("GREEN", (2, "g"))) + self.assertEqual(fields(n, Color.BLUE), ("BLUE", "b")) + self.assertEqual(fields(n, OwnValue.A), ("A", "overridden")) + + def test_class_changes(self): + d = {Late.A: 1, Late.B: 2} + self.assertEqual(lookups(400, d, Late.B)[2], hash("B")) + Late.__hash__ = lambda self: 5 + try: + self.assertEqual(lookups(400, {Late.B: 2}, Late.B), (2, True, 5)) + finally: + del Late.__hash__ + self.assertEqual(lookups(400, d, Late.B), (2, True, hash("B"))) + + def test_temporaries_released(self): + def loop(n): + total = 0 + for i in range(n): + total += len(Color.GREEN.value) + return total + + self.assertEqual(loop(300), 600) + + def test_profiler_sees_methods(self): + fields(400, Color.RED) + seen = [] + + def prof(frame, event, arg): + if event == "call": + seen.append(frame.f_code.co_name) + + sys.setprofile(prof) + try: + fields(1, Color.RED) + hash(Color.RED) + finally: + sys.setprofile(None) + self.assertIn("__get__", seen) + self.assertIn("__hash__", seen) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enum_membership_compiled.py b/tests/regrtest/test_enum_membership_compiled.py new file mode 100644 index 000000000..e933e6f63 --- /dev/null +++ b/tests/regrtest/test_enum_membership_compiled.py @@ -0,0 +1,106 @@ +"""x in SomeEnum and SomeEnum[name] from compiled loops: members, their values, aliases' +values, values of other types, an unhashable value, a member of another +enum, IntEnum and StrEnum values, a Flag class (its _missing_ answers), +and a metaclass overriding __contains__, each matching CPython.""" + +import enum +import unittest + + +class Color(enum.Enum): + RED = 1 + GREEN = 2 + CRIMSON = 1 + LIST = [1, 2] + + +class Shape(enum.Enum): + SQ = 1 + + +class Num(enum.IntEnum): + ONE = 1 + + +class Txt(enum.StrEnum): + A = "a" + + +class Perm(enum.Flag): + R = 4 + W = 2 + + +class OddMeta(enum.EnumType): + def __contains__(cls, v): + return v == "odd" + + +class Odd(enum.Enum, metaclass=OddMeta): + X = 1 + + +def test(n, x, cls): + out = None + for i in range(n): + out = x in cls + return out + + +class EnumMembershipTests(unittest.TestCase): + def test_answers(self): + cases = [ + (Color.RED, Color, True), + (Color.CRIMSON, Color, True), + (1, Color, True), + (2, Color, True), + (3, Color, False), + ("RED", Color, False), + ([1, 2], Color, True), + ([3], Color, False), + (Shape.SQ, Color, False), + (1, Num, True), + (Num.ONE, Num, True), + (2.0, Num, False), + ("a", Txt, True), + ("b", Txt, False), + (6, Perm, True), + (Perm.R, Perm, True), + (8, Perm, False), + ("odd", Odd, True), + (1, Odd, False), + ] + for n in (1, 300): + for x, cls, want in cases: + self.assertIs(test(n, x, cls), want, (x, cls)) + + +class EnumItemTests(unittest.TestCase): + def test_items(self): + def get(n, cls, name): + out = None + for i in range(n): + out = cls[name] + return out + + for n in (1, 300): + self.assertIs(get(n, Color, "RED"), Color.RED) + self.assertIs(get(n, Color, "CRIMSON"), Color.RED) + self.assertIs(get(n, Perm, "W"), Perm.W) + with self.assertRaises(KeyError): + get(300, Color, "BLUE") + with self.assertRaises(KeyError): + get(300, Color, 1) + + class M(enum.EnumType): + def __getitem__(cls, name): + return "meta" + + class E(enum.Enum, metaclass=M): + A = 1 + + self.assertEqual(get(300, E, "A"), "meta") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enum_value_call.py b/tests/regrtest/test_enum_value_call.py new file mode 100644 index 000000000..92805d0d5 --- /dev/null +++ b/tests/regrtest/test_enum_value_call.py @@ -0,0 +1,97 @@ +"""`SomeEnum(value)` answered from the class's member maps. + +With `enum`'s own `EnumType.__call__` and `Enum.__new__`, a member of the +class comes back as it is and a value that hashes natively is looked up +in `_value2member_map_`; misses, unhashable values, `_missing_` hooks, +other enums' members and overridden `__call__`s keep the Python path. +""" + +import enum +import unittest + +N = 3000 + + +class Color(enum.Enum): + RED = 1 + GREEN = 2 + ALIAS = 1 + + +class Shade(enum.Enum): + LIGHT = 1 + + +class Perm(enum.IntFlag): + R = 4 + W = 2 + + +class Lenient(enum.Enum): + A = "a" + + @classmethod + def _missing_(cls, value): + if isinstance(value, str) and value.lower() == "a": + return cls.A + return None + + +class Planet(enum.Enum): + EARTH = (5.97, 6.37) + + def __init__(self, mass, radius): + self.mass = mass + + +class Odd(enum.Enum): + L = [1, 2] + + +class Meta(enum.EnumType): + def __call__(cls, *args, **kw): + return "overridden" + + +class Custom(enum.Enum, metaclass=Meta): + X = 1 + + +class EnumValueCallTests(unittest.TestCase): + def test_values_and_members(self): + for _ in range(N): + a = Color(1) + b = Color(Color.GREEN) + c = Color(True) + f = Perm(4) + self.assertIs(a, Color.RED) + self.assertIs(b, Color.GREEN) + self.assertIs(c, Color.RED) + self.assertIs(f, Perm.R) + self.assertIs(Color(Color.ALIAS), Color.RED) + + def test_misses_and_hooks(self): + for _ in range(100): + with self.assertRaises(ValueError): + Color(3) + with self.assertRaises(ValueError): + Color(Shade.LIGHT) + self.assertIs(Lenient("A"), Lenient.A) + self.assertEqual(Perm(6), Perm.R | Perm.W) + self.assertIs(Planet((5.97, 6.37)), Planet.EARTH) + self.assertIs(Odd([1, 2]), Odd.L) + self.assertEqual(Custom(1), "overridden") + + def test_members_added_later(self): + class Grow(enum.Enum): + A = 1 + + for _ in range(N): + r = Grow(1) + self.assertIs(r, Grow.A) + with self.assertRaises(ValueError): + Grow(2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enumerate_adapter_pairs.py b/tests/regrtest/test_enumerate_adapter_pairs.py new file mode 100644 index 000000000..9096486d9 --- /dev/null +++ b/tests/regrtest/test_enumerate_adapter_pairs.py @@ -0,0 +1,66 @@ +"""`for i, (x, y) in enumerate(adapter)` steps the index and the adapter's +item without building the outer pair; the results, the counter, and the +adapters' end match the general step.""" + +import itertools +import unittest + + +class EnumerateAdapterPairs(unittest.TestCase): + def test_enumerate_zip_unpacked(self): + a = list(range(50)) + b = [str(x) for x in range(100, 150)] + out = [] + for _ in range(200): + out = [] + for i, (x, y) in enumerate(zip(a, b)): + out.append((i, x, y)) + self.assertEqual(out, [(i, i, str(100 + i)) for i in range(50)]) + + def test_start_and_shorter_source(self): + for _ in range(200): + got = [(i, x, y) for i, (x, y) in enumerate(zip("abc", [1, 2]), 10)] + self.assertEqual(got, [(10, "a", 1), (11, "b", 2)]) + + def test_counter_survives_break(self): + e = enumerate(zip(range(10), range(10, 20))) + for _ in range(3): + for i, (x, y) in e: + if i % 3 == 2: + break + self.assertEqual(next(e), (9, (9, 19))) + self.assertRaises(StopIteration, next, e) + + def test_items_kept_by_consumer(self): + kept = [] + for _ in range(100): + kept = [] + for i, pair in enumerate(zip([1, 2, 3], "xyz")): + kept.append(pair) + self.assertEqual(kept, [(1, "x"), (2, "y"), (3, "z")]) + self.assertEqual(len({id(p) for p in kept}), 3) + + def test_other_adapters(self): + for _ in range(100): + got = [(i, v) for i, v in enumerate(map(abs, [-1, -2, 3]))] + tw = [(i, v) for i, v in enumerate(itertools.takewhile(lambda v: v < 3, [1, 2, 3, 1]))] + fl = [(i, v) for i, v in enumerate(filter(None, [0, 5, 0, 6]))] + self.assertEqual(got, [(0, 1), (1, 2), (2, 3)]) + self.assertEqual(tw, [(0, 1), (1, 2)]) + self.assertEqual(fl, [(0, 5), (1, 6)]) + + def test_nested_unpack_of_three(self): + for _ in range(100): + got = [(i, a + b + c) for i, (a, b, c) in enumerate(zip([1, 2], [3, 4], [5, 6]))] + self.assertEqual(got, [(0, 9), (1, 12)]) + + def test_strict_zip_end(self): + def run(): + for i, (x, y) in enumerate(zip([1, 2, 3], [4, 5], strict=True)): + pass + for _ in range(50): + self.assertRaises(ValueError, run) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enumerate_collect.py b/tests/regrtest/test_enumerate_collect.py new file mode 100644 index 000000000..304dee7ae --- /dev/null +++ b/tests/regrtest/test_enumerate_collect.py @@ -0,0 +1,39 @@ +"""`list(enumerate(xs))` and `tuple(enumerate(xs))` over lists and tuples. + +The pairs come from the rest of the source at once: a `start`, an +enumerate already partly consumed, a source iterator shared with other +code, an empty source, a count past the machine word, a list subclass, +and the exhausted iterators afterwards behave as in CPython. +""" + +import sys + + +class L(list): + pass + + +def run(n): + for _ in range(n): + xs = [5, 6, 7] + assert list(enumerate(xs)) == [(0, 5), (1, 6), (2, 7)] + assert tuple(enumerate(("a", "b"), 3)) == ((3, "a"), (4, "b")) + e = enumerate(xs, 10) + assert next(e) == (10, 5) + assert list(e) == [(11, 6), (12, 7)] + assert list(e) == [] and next(e, None) is None + src = iter(xs) + e2 = enumerate(src) + assert next(e2) == (0, 5) + assert list(e2) == [(1, 6), (2, 7)] and next(src, None) is None + assert list(enumerate([])) == [] and list(enumerate(())) == [] + assert list(enumerate(L([1, 2]))) == [(0, 1), (1, 2)] + grow = [1] + assert list(enumerate(grow)) == [(0, 1)] + grow.append(2) + + +run(3000) +big = list(enumerate([1, 2], sys.maxsize)) +assert big == [(sys.maxsize, 1), (sys.maxsize + 1, 2)] +print("ok") diff --git a/tests/regrtest/test_enumerate_end_in_place.py b/tests/regrtest/test_enumerate_end_in_place.py new file mode 100644 index 000000000..e15af1578 --- /dev/null +++ b/tests/regrtest/test_enumerate_end_in_place.py @@ -0,0 +1,52 @@ +"""`for i, x in enumerate(seq)` ends in place in compiled code. + +At the end of a list or tuple, the enumerate iterator leaves the stack +without the general step: its list cursor detaches as CPython's does (an +append after the end can't resume it), and an end whose release could +finalize items keeps the general path, so finalizers still run in order. +""" + +import unittest + +N = 3000 + + +class Fin: + deaths = 0 + + def __del__(self): + Fin.deaths += 1 + + +class EnumerateEndTests(unittest.TestCase): + def test_generator_expressions(self): + xs = [1, 2, 3] + t = (4, 5) + for _ in range(N): + a = sum(i * v for i, v in enumerate(xs)) + b = [i + v for i, v in enumerate(t)] + self.assertEqual(a, 8) + self.assertEqual(b, [4, 6]) + + def test_exhausted_iterator_stays_exhausted(self): + for _ in range(N): + xs = [1] + e = enumerate(xs) + out = [v for _, v in e] + xs.append(2) + rest = list(e) + self.assertEqual((out, rest), ([1], [])) + + def test_finalizing_items(self): + Fin.deaths = 0 + for _ in range(200): + for _i, _f in enumerate([Fin(), Fin()]): + pass + for _i, _f in enumerate((Fin(),)): + pass + del _f + self.assertEqual(Fin.deaths, 600) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enumerate_generator_drain.py b/tests/regrtest/test_enumerate_generator_drain.py new file mode 100644 index 000000000..e0db8ea38 --- /dev/null +++ b/tests/regrtest/test_enumerate_generator_drain.py @@ -0,0 +1,83 @@ +"""list(enumerate(gen)) drains the generator as list(gen) does, then +numbers its items: start values, a partly consumed generator, an +exhausted one, a generator that raises partway (the enumerate's count +moving past the items taken), StopIteration inside the body (PEP 479), +a generator that reads its own enumerate, and tuple()/sorted() of the +same, each matching CPython.""" + +import unittest + + +def gen(n, fail_at=None): + for i in range(n): + if i == fail_at: + raise KeyError(i) + yield i * 10 + + +def drain(n, start): + out = None + for i in range(n): + out = list(enumerate((x for x in "abc"), start)) + return out + + +class EnumerateGenTests(unittest.TestCase): + def test_values(self): + for n in (1, 300): + self.assertEqual(drain(n, 0), [(0, "a"), (1, "b"), (2, "c")]) + self.assertEqual(drain(n, -2), [(-2, "a"), (-1, "b"), (0, "c")]) + self.assertEqual(list(enumerate(gen(0))), []) + self.assertEqual(tuple(enumerate(gen(2), 5)), ((5, 0), (6, 10))) + self.assertEqual(sorted(enumerate(gen(3)), reverse=True)[0], (2, 20)) + big = 2**62 + self.assertEqual(list(enumerate(gen(2), big)), [(big, 0), (big + 1, 10)]) + + def test_partly_consumed(self): + g = gen(5) + next(g) + e = enumerate(g) + next(e) + self.assertEqual(list(e), [(1, 20), (2, 30), (3, 40)]) + self.assertEqual(list(e), []) + self.assertEqual(list(enumerate(g)), []) + + def test_raise_partway(self): + e = enumerate(gen(5, fail_at=3)) + with self.assertRaises(KeyError): + list(e) + with self.assertRaises(StopIteration): + next(e) + e = enumerate(gen(5, fail_at=3), 7) + try: + list(e) + except KeyError: + pass + self.assertEqual(e.__reduce__()[1][1], 10) + e = enumerate(gen(4), 2) + list(e) + self.assertEqual(e.__reduce__()[1][1], 6) + + def test_stop_iteration_in_body(self): + def bad(): + yield 1 + raise StopIteration + with self.assertRaises(RuntimeError): + list(enumerate(bad())) + + def test_self_reference(self): + holder = [] + + def g(): + yield 1 + try: + next(holder[0]) + except ValueError as exc: + yield str(exc) + e = enumerate(g()) + holder.append(e) + self.assertEqual(list(e), [(0, 1), (1, "generator already executing")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enumerate_loop_ends.py b/tests/regrtest/test_enumerate_loop_ends.py new file mode 100644 index 000000000..7a6148768 --- /dev/null +++ b/tests/regrtest/test_enumerate_loop_ends.py @@ -0,0 +1,81 @@ +"""`for i, x in enumerate(seq)` ending in compiled code. + +A loop over `enumerate` of a temporary list or tuple ends without leaving +compiled code when the iterator's release frees only plain values. The +loop must end as the full path ends it: items with finalizers (released +at the next safe point, in order), a shared `enumerate` (a generator +expression's), a list appended to after the end, and a `break`. +""" + +import gc +import unittest + + +class Fin: + log = [] + + def __init__(self, k): + self.k = k + + def __del__(self): + Fin.log.append(self.k) + + +def count(a, b): + n = 0 + for i, x in enumerate([a, b]): + n += i + return n + + +def count_tuple(a, b): + n = 0 + for i, x in enumerate((a, b, a)): + n += i + return n + + +def with_fin(k): + n = 0 + for i, x in enumerate([Fin(k), Fin(k + 1)]): + n += 1 + return n + + +class EnumerateEndTests(unittest.TestCase): + def test_plain_ends(self): + for _ in range(2000): + self.assertEqual(count("x", "y"), 1) + self.assertEqual(count_tuple(1, 2.5), 3) + + def test_finalizers_run(self): + Fin.log.clear() + for k in range(0, 400, 2): + self.assertEqual(with_fin(k), 2) + gc.collect() + self.assertEqual(sorted(Fin.log), list(range(400))) + + def test_shared_and_appended(self): + xs = [1, 2] + for _ in range(500): + e = enumerate(xs) + got = [p for p in e] + self.assertEqual(got, [(0, 1), (1, 2)]) + self.assertEqual(list(e), []) + ys = [1] + it = enumerate(ys) + for _ in it: + pass + ys.append(2) + self.assertEqual(list(it), []) + + def test_break(self): + for _ in range(500): + for i, x in enumerate([7, 8, 9]): + if x == 8: + break + self.assertEqual(i, 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_enumerate_seq_pairs.py b/tests/regrtest/test_enumerate_seq_pairs.py new file mode 100644 index 000000000..9859047fd --- /dev/null +++ b/tests/regrtest/test_enumerate_seq_pairs.py @@ -0,0 +1,77 @@ +"""`for i, x in enumerate(seq)` over lists and tuples in compiled code. + +The pair is read in place from the source; a list that grows or shrinks +mid-loop, a source iterator also advanced by hand, a `start`, items that +leave the loop's numeric lane, and a counter past the machine word behave +as in CPython. Run it past the compile thresholds, with object and numeric +loop bodies. +""" + +import sys + + +def pairs(xs): + out = [] + for i, x in enumerate(xs): + out.append((i, x)) + return out + + +def weighted(n, xs): + s = 0 + for _ in range(n): + for i, x in enumerate(xs): + s += i * x + return s + + +def growing(n): + xs = [1, 2] + seen = [] + for i, x in enumerate(xs): + seen.append(i) + if len(xs) < n: + xs.append(x) + return seen + + +def shrinking(): + xs = list(range(6)) + seen = [] + for i, x in enumerate(xs): + seen.append((i, x)) + if xs: + xs.pop() + return seen + + +def shared(xs): + it = iter(xs) + out = [] + for i, x in enumerate(it): + out.append((i, x, next(it, None))) + return out + + +N = 3000 +for _ in range(N): + assert pairs([5, 6, 7]) == [(0, 5), (1, 6), (2, 7)] + assert pairs(("a", "b")) == [(0, "a"), (1, "b")] + assert pairs([]) == [] + assert growing(5) == [0, 1, 2, 3, 4] + assert shrinking() == [(0, 0), (1, 1), (2, 2)] + assert shared([1, 2, 3, 4, 5]) == [(0, 1, 2), (1, 3, 4), (2, 5, None)] +assert weighted(N, list(range(10))) == 285 * N +assert weighted(N, tuple(range(10))) == 285 * N +assert weighted(N, [float(v) for v in range(10)]) == 285.0 * N +assert weighted(1, [1, 2.5, 3]) == 2.5 + 6 +assert list(enumerate([7, 8], start=10)) == [(10, 7), (11, 8)] +big = list(enumerate([1, 2], start=sys.maxsize)) +assert big == [(sys.maxsize, 1), (sys.maxsize + 1, 2)] +try: + weighted(1, [1, "x"]) +except TypeError: + pass +else: + raise AssertionError("int * str in the sum") +print("ok") diff --git a/tests/regrtest/test_enumerate_zip_fresh_pair.py b/tests/regrtest/test_enumerate_zip_fresh_pair.py new file mode 100644 index 000000000..c287ebda0 --- /dev/null +++ b/tests/regrtest/test_enumerate_zip_fresh_pair.py @@ -0,0 +1,174 @@ +"""`enumerate(zip(xs, ys))` loops, whose zip pair is built fresh each step. + +The loop's step gives the index and a new pair from the two sources' +cursors, which the unpacking after it takes apart in place. Each case +runs hot with heap items (strings built at run time, lists, instances) +and must agree with CPython: the items, kept pairs, strict and uneven +ends, a zip stepped by hand between loop steps, and reference counts +after the loop. +""" + +import sys +import unittest + +N = 400 + + +class Item: + def __init__(self, k): + self.k = k + + +def make(n): + words = ["w%d" % i for i in range(n)] + lists = [[i] for i in range(n)] + return words, lists + + +class EnumerateZipFreshPairTests(unittest.TestCase): + def test_unpacked_items(self): + words, lists = make(6) + + def run(): + out = None + for _ in range(N): + out = [] + for i, (w, l) in enumerate(zip(words, tuple(lists))): + out.append((i, w, l[0])) + return out + + self.assertEqual(run(), [(i, "w%d" % i, i) for i in range(6)]) + + def test_kept_pairs_are_distinct(self): + words, lists = make(5) + + def run(): + kept = None + for _ in range(N): + kept = [] + for i, pair in enumerate(zip(words, lists), 10): + kept.append((i, pair)) + return kept + + kept = run() + self.assertEqual([i for i, _ in kept], list(range(10, 15))) + self.assertEqual([p for _, p in kept], list(zip(words, lists))) + self.assertEqual(len({id(p) for _, p in kept}), 5) + + def test_pair_held_while_stepping(self): + words, lists = make(4) + + def run(): + seen = None + for _ in range(N): + seen = [] + prev = None + for i, (w, l) in enumerate(zip(words, lists)): + if prev is not None: + seen.append(prev) + prev = (w, l) + seen.append(prev) + return seen + + self.assertEqual(run(), list(zip(words, lists))) + + def test_uneven_end(self): + words, lists = make(7) + + def run(): + out = None + for _ in range(N): + out = [(i, w) for i, (w, _) in enumerate(zip(words, lists[:3]))] + return out + + self.assertEqual(run(), [(0, "w0"), (1, "w1"), (2, "w2")]) + + def test_strict_end(self): + words, lists = make(5) + + def run(ys): + n = 0 + for _ in range(N): + for i, (w, l) in enumerate(zip(words, ys, strict=True)): + n += i + return n + + self.assertEqual(run(lists), N * 10) + with self.assertRaises(ValueError): + run(lists[:4]) + + def test_same_iterator_twice(self): + def run(): + out = None + for _ in range(N): + it = iter(["a", "b", "c", "d", "e"]) + out = [(i, x, y) for i, (x, y) in enumerate(zip(it, it))] + return out + + self.assertEqual(run(), [(0, "a", "b"), (1, "c", "d")]) + + def test_zip_stepped_by_hand(self): + words, lists = make(9) + + def run(): + out = None + for _ in range(N): + z = zip(words, lists) + out = [] + for i, (w, l) in enumerate(z): + out.append((i, w)) + next(z, None) + return out + + self.assertEqual(run(), [(0, "w0"), (1, "w2"), (2, "w4"), (3, "w6"), (4, "w8")]) + + def test_list_grows_during_loop(self): + def run(): + out = None + for _ in range(N): + xs = ["x0", "x1"] + ys = ["y%d" % i for i in range(6)] + out = [] + for i, (x, y) in enumerate(zip(xs, ys)): + if len(xs) < 4: + xs.append("x%d" % len(xs)) + out.append(x + y) + return out + + self.assertEqual(run(), ["x0y0", "x1y1", "x2y2", "x3y3"]) + + def test_instances_and_refcounts(self): + objs = [Item(i) for i in range(5)] + names = ["n%d" % i for i in range(5)] + before = [sys.getrefcount(o) for o in objs] + + def run(): + total = 0 + for _ in range(N): + for i, (o, s) in enumerate(zip(objs, names)): + total += o.k + len(s) + i + return total + + self.assertEqual(run(), N * (10 + 10 + 10)) + self.assertEqual([sys.getrefcount(o) for o in objs], before) + + def test_enumerate_kept_and_resumed(self): + words, lists = make(6) + + def run(): + out = None + for _ in range(N): + e = enumerate(zip(words, lists)) + out = [] + for i, (w, l) in e: + out.append(w) + if i == 2: + break + out.extend(w for _, (w, _) in e) + return out + + self.assertEqual(run(), words) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_exception_default_slot_reads.py b/tests/regrtest/test_exception_default_slot_reads.py new file mode 100644 index 000000000..446e6a2f0 --- /dev/null +++ b/tests/regrtest/test_exception_default_slot_reads.py @@ -0,0 +1,109 @@ +"""Reads of an exception's `args`, `__traceback__` and chaining links. + +A never-raised exception's `__traceback__`, `__cause__` and `__context__` +read as `None` and `__suppress_context__` as `False`, in compiled code and +in the interpreter alike; once set they read their values. A subclass's +own property or `__getattribute__`, and an unset `__slots__` member of an +exception subclass, behave as before. +""" + +import unittest + +N = 3000 + + +class E(Exception): + pass + + +class Slotted(Exception): + __slots__ = ("extra",) + + +class OwnTraceback(Exception): + @property + def __traceback__(self): + return "own" + + +class Hooked(Exception): + def __getattribute__(self, name): + if name == "__cause__": + return "hooked" + return super().__getattribute__(name) + + +def read_links(e): + return (e.__traceback__, e.__cause__, e.__context__, e.__suppress_context__, e.args) + + +class ExceptionSlotReadTests(unittest.TestCase): + def test_defaults(self): + e = E(1) + for _ in range(N): + r = read_links(e) + self.assertEqual(r, (None, None, None, False, (1,))) + + def test_set_values(self): + cause = ValueError("c") + try: + try: + raise KeyError("k") + except KeyError: + raise E(2) from cause + except E as caught: + e = caught + for _ in range(N): + r = read_links(e) + tb, c, ctx, sup, args = r + self.assertIsNotNone(tb) + self.assertIs(tb, e.__traceback__) + self.assertIs(c, cause) + self.assertIsInstance(ctx, KeyError) + self.assertTrue(sup) + self.assertEqual(args, (2,)) + + def test_changing_receivers(self): + raised = [] + for k in range(4): + try: + raise E(k) + except E as e: + raised.append(e) + fresh = [E(k) for k in range(4)] + out = [] + for i in range(N): + e = (raised if i % 2 else fresh)[i % 4] + out.append(e.__traceback__ is None) + self.assertEqual(out[:4], [True, False, True, False]) + + def test_assigned_links(self): + e = E() + for i in range(N): + if i == N // 2: + e.__cause__ = KeyError() + e.__traceback__ = None + r = e.__cause__ + self.assertIsInstance(r, KeyError) + self.assertTrue(e.__suppress_context__) + with self.assertRaises(TypeError): + del e.__traceback__ + + def test_overrides(self): + o, h = OwnTraceback(), Hooked() + for _ in range(N): + r = (o.__traceback__, h.__cause__, h.__context__) + self.assertEqual(r, ("own", "hooked", None)) + + def test_unset_slots_member(self): + s = Slotted() + for _ in range(500): + with self.assertRaises(AttributeError): + s.extra + self.assertIsNone(s.__traceback__) + s.extra = 5 + self.assertEqual(s.extra, 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_exception_slot_reads.py b/tests/regrtest/test_exception_slot_reads.py new file mode 100644 index 000000000..e4adfa50a --- /dev/null +++ b/tests/regrtest/test_exception_slot_reads.py @@ -0,0 +1,37 @@ +"""`e.args` and an exception's other pseudo-slots read from compiled code. + +An exception's `args` lives in its slot storage, read through the class's +slot descriptor. Compiled code reads it there once a site finds the class +resolving the name to that descriptor: a subclass that replaces `args` +with a property, or an instance whose `args` is reassigned, must still +read what Python would. Run it past the compile threshold. +""" + + +class E(Exception): + pass + + +class Prop(Exception): + @property + def args(self): + return ("prop",) + + +def read(e): + return e.args + + +e = E(1, 2) +for _ in range(3000): + assert read(e) == (1, 2) + assert read(ValueError("v")) == ("v",) + assert read(Prop(5)) == ("prop",) + +e.args = ("new",) +for _ in range(100): + assert read(e) == ("new",) + +E.args = property(lambda self: "shadowed") +for _ in range(100): + assert read(e) == "shadowed", read(e) diff --git a/tests/regrtest/test_exception_str_and_slot_reads.py b/tests/regrtest/test_exception_str_and_slot_reads.py new file mode 100644 index 000000000..ebf1207da --- /dev/null +++ b/tests/regrtest/test_exception_str_and_slot_reads.py @@ -0,0 +1,163 @@ +"""`str(e)`, `f"{e}"` and pseudo-slot reads of exceptions in compiled loops. + +`BaseException.__str__` is called with the instance (no bound method), in +place for `str(e)` when the argument runs no code of its own; an exception +site's `e.args`, `e.__context__` and kin read the instance's laid-out +slots directly once the site knows the class. Each must agree with the +full paths: every argument shape, `KeyError`'s repr, a subclass with its +own `__str__` (added after the reads warmed up, too), a nested exception +argument, an argument whose `__str__` raises, unset and set chaining +slots, a class that shadows `args` with a property, and `__slots__` on an +exception subclass. +""" + +import unittest + + +class E(Exception): + pass + + +class Loud: + def __str__(self): + return "loud" + + +class Bad: + def __str__(self): + raise RuntimeError("no str") + + +class WithArgsProp(Exception): + @property + def args(self): + return ("prop",) + + +class Slotted(Exception): + __slots__ = ("extra",) + + +def str_many(e, n=200): + out = None + for _ in range(n): + out = str(e) + return out + + +def fmt_many(e, n=200): + out = None + for _ in range(n): + out = f"{e}" + return out + + +class ExceptionStrTests(unittest.TestCase): + def test_shapes(self): + cases = [ + E(), E("x"), E(1), E(1, 2), E(None), E(1.5), E((1, 2)), + E("\udcac"), KeyError("k"), KeyError(3), KeyError(), ValueError("v"), + E(E("inner")), E(Loud()), KeyError(Loud()), OSError(2, "no"), + E([1, "a"]), E(b"b"), + ] + wants = [ + "", "x", "1", "(1, 2)", "None", "1.5", "(1, 2)", "\udcac", "'k'", "3", + "", "v", "inner", "loud", None, "[Errno 2] no", "[1, 'a']", "b'b'", + ] + for e, want in zip(cases, wants): + with self.subTest(e=ascii(e)): + if want is None: + # (`KeyError`'s repr of an instance argument.) + want = repr(e.args[0]) + self.assertEqual(str_many(e), want) + self.assertEqual(fmt_many(e), want) + + def test_argument_str_raises(self): + e = E(Bad()) + for _ in range(100): + with self.assertRaises(RuntimeError): + str(e) + with self.assertRaises(RuntimeError): + f"{e}" + + def test_arguments_with_python_repr(self): + calls = [] + + class R: + def __repr__(self): + calls.append(1) + return "R!" + + e1, e2 = E([R()]), E(R(), 2) + for _ in range(100): + self.assertEqual(str(e1), "[R!]") + self.assertEqual(f"{e1}", "[R!]") + self.assertEqual(str(e2), "(R!, 2)") + self.assertEqual(f"{e2}", "(R!, 2)") + self.assertEqual(len(calls), 400) + + def test_override_after_warm_up(self): + class F(Exception): + pass + + e = F("a") + self.assertEqual(str_many(e), "a") + F.__str__ = lambda self: "over" + self.assertEqual(str_many(e), "over") + self.assertEqual(fmt_many(e), "over") + del F.__str__ + self.assertEqual(str_many(e), "a") + + def test_str_returns_non_string(self): + class G(Exception): + pass + + G.__str__ = Exception.__repr__ + self.assertEqual(str_many(G(1)), "G(1)") + + +class ExceptionSlotReadTests(unittest.TestCase): + def test_args_and_chaining(self): + e = E(1, 2) + for _ in range(300): + self.assertEqual(e.args, (1, 2)) + self.assertIsNone(e.__context__) + self.assertIsNone(e.__cause__) + self.assertIs(e.__suppress_context__, False) + self.assertIsNone(e.__traceback__) + try: + try: + raise KeyError("a") + except KeyError as inner: + raise E("b") from inner + except E as caught: + outer = caught + for _ in range(300): + self.assertIsInstance(outer.__cause__, KeyError) + self.assertIs(outer.__context__, outer.__cause__) + self.assertIs(outer.__suppress_context__, True) + self.assertIsNotNone(outer.__traceback__) + self.assertEqual(outer.args, ("b",)) + outer.args = ("c", 3) + outer.__context__ = None + for _ in range(300): + self.assertEqual(outer.args, ("c", 3)) + self.assertIsNone(outer.__context__) + + def test_mixed_classes_at_one_site(self): + items = [E(1), KeyError(2), WithArgsProp(3), OSError(2, "x"), Slotted(5)] + for _ in range(200): + got = [x.args for x in items] + self.assertEqual(got, [(1,), (2,), ("prop",), (2, "x"), (5,)]) + + def test_slotted_subclass(self): + s = Slotted("m") + s.extra = 7 + for _ in range(300): + self.assertEqual(s.args, ("m",)) + self.assertEqual(s.extra, 7) + self.assertIsNone(s.__context__) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_extend_update_live_items.py b/tests/regrtest/test_extend_update_live_items.py new file mode 100644 index 000000000..129d83afe --- /dev/null +++ b/tests/regrtest/test_extend_update_live_items.py @@ -0,0 +1,134 @@ +"""list.extend() and set.update() over a generator or an iterator class +add each item as it comes, as CPython does: a generator that reads the +receiver sees it grow, the items before an error stay added, and the +same from compiled loops; lists, tuples and other sets still extend at +once (a list extended by itself doubles).""" + +import unittest + + +class Count: + def __init__(self, n): + self.i = 0 + self.n = n + + def __iter__(self): + return self + + def __next__(self): + if self.i >= self.n: + raise StopIteration + self.i += 1 + return self.i + + +def boom(xs): + yield 1 + yield 2 + raise ValueError(len(xs)) + + +def grow(n): + out = None + for i in range(n): + xs = [] + xs.extend(len(xs) for _ in range(3)) + s = set() + s.update(len(s) for _ in range(3)) + out = (xs, s) + return out + + +class LiveExtendTests(unittest.TestCase): + def test_sees_growth(self): + for n in (1, 400): + self.assertEqual(grow(n), ([0, 1, 2], {0, 1, 2})) + + def test_error_keeps_items(self): + xs = [0] + with self.assertRaises(ValueError) as cm: + xs.extend(boom(xs)) + self.assertEqual(xs, [0, 1, 2]) + self.assertEqual(cm.exception.args, (3,)) + s = {0} + with self.assertRaises(ValueError): + s.update(boom(s)) + self.assertEqual(s, {0, 1, 2}) + + def test_iterator_class(self): + xs = [] + xs.extend(Count(3)) + self.assertEqual(xs, [1, 2, 3]) + s = set() + s.update(Count(2)) + self.assertEqual(s, {1, 2}) + + def test_mixed_items(self): + class H: + def __init__(self, k): + self.k = k + + def __hash__(self): + return hash(self.k) + + def __eq__(self, other): + return self.k == (other.k if isinstance(other, H) else other) + + def run(n): + out = None + for i in range(n): + s = {1} + s.update(x for x in (1, "a", (2, "b"), H(1), H("z"), "a", 2.5)) + xs = [0] + xs.extend(y for y in [1, 2]) + xs.extend(self._delegate([3, 4])) + out = (s, xs) + return out + + for n in (1, 300): + s, xs = run(n) + self.assertEqual(len(s), 5) + self.assertIn((2, "b"), s) + self.assertIn("z", s) + self.assertEqual(xs, [0, 1, 2, 3, 4, 5]) + + @staticmethod + def _delegate(items): + yield from items + yield 5 + + def test_length_hint(self): + class BadLen: + def __iter__(self): + return iter(range(3)) + + def __len__(self): + raise RuntimeError("hello") + + class TypeLen(BadLen): + def __len__(self): + raise TypeError + + with self.assertRaises(RuntimeError): + [].extend(BadLen()) + xs = [] + xs.extend(TypeLen()) + self.assertEqual(xs, [0, 1, 2]) + s = set() + s.update(BadLen()) + self.assertEqual(s, {0, 1, 2}) + + def test_plain_sources(self): + xs = [1, 2] + xs.extend(xs) + self.assertEqual(xs, [1, 2, 1, 2]) + xs.extend((3,)) + s = {1} + s.update({2}, [3], (4,)) + self.assertEqual((xs[-1], s), (3, {1, 2, 3, 4})) + with self.assertRaises(TypeError): + s.update(x for x in [[1]]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_file_read_write_direct.py b/tests/regrtest/test_file_read_write_direct.py new file mode 100644 index 000000000..f13dbc8e3 --- /dev/null +++ b/tests/regrtest/test_file_read_write_direct.py @@ -0,0 +1,117 @@ +"""Binary file reads and writes served without extra copies. + +A read of less than half a buffer is served from the stream's read-ahead +(one `read(2)` of a buffer's worth fills it, as CPython's +`BufferedReader` does), a read to the end of a regular file reads into a +`bytes` of the size `fstat` reports, and a write of at least a buffer's +worth with nothing staged goes straight to the descriptor. `tell`, +`seek`, `readline`, `peek`, `read1`, `readinto`, a file that grows +meanwhile, `r+b` streams, a text stream's `.buffer`, pipes and +unbuffered streams see the same bytes and positions as before. The +expected output is CPython's. +""" + +import contextlib +import io +import os +import shutil +import tempfile +import threading + + +def reads(): + d = tempfile.mkdtemp() + p = os.path.join(d, "f") + data = bytes(range(256)) * 1000 + b"line1\nline2\n" * 5000 + with open(p, "wb") as f: + f.write(data) + out = [] + with open(p, "rb") as f: + out.append(f.read(10)); out.append(f.tell()); out.append(f.readline()); out.append(f.read(3)); out.append(f.tell()) + f.seek(5); out.append(f.read(4)); out.append(f.tell()) + out.append(os.lseek(f.fileno(), 0, os.SEEK_CUR) >= f.tell()) + out.append(f.read1(5)); out.append(f.peek(2)[:2]); out.append(f.read(70000)[-3:]); out.append(f.tell()) + b = bytearray(7); out.append(f.readinto(b)); out.append(bytes(b)); out.append(f.tell()) + rest = f.read(); out.append(len(rest)); out.append(f.read(5)); out.append(f.tell()) + with open(p, "r+b") as f: + out.append(f.read(4)); f.write(b"ZZ"); f.seek(0); out.append(f.read(8)); out.append(f.tell()) + with open(p, "rb") as f: + n = 0 + while chunk := f.read(8192): + n += len(chunk) + out.append(n == len(data)) + f.seek(0); out.append(sum(len(c) for c in iter(lambda: f.read(1000), b""))) + with open(p, "rb", buffering=0) as f: + out.append(type(f).__name__); out.append(f.read(5)); out.append(f.tell()) + r, w = os.pipe() + os.write(w, b"abcdefgh"); os.close(w) + with open(r, "rb") as f: + out.append(f.read(3)); out.append(f.read(100)); out.append(f.read(3)) + print(out) + # read-all edge cases + with open(p, "rb") as f: + f.seek(len(data) - 5); print(f.read(), f.read(), f.tell()) + f.seek(len(data) + 10); print(f.read(), f.tell()) + f.seek(0); f.readline(); print(len(f.read()), f.tell()) + with open(p, "ab") as g: + pass + with open(p, "rb") as f, open(p, "ab") as g: + f.read(7); g.write(b"TAIL"); g.flush(); print(f.read()[-6:], f.tell()) + open(p, "wb").close() + with open(p, "rb") as f: + print(f.read(), f.read(3)) + with open(p, "rb", buffering=0) as f: + print(f.read(), f.readall()) + print(open("/dev/null", "rb").read()) + shutil.rmtree(d) + + +def writes(): + d = tempfile.mkdtemp(); p = os.path.join(d, "w") + big = bytes(range(256)) * 600 + out = [] + with open(p, "wb") as f: + f.write(b"head"); f.write(big); out.append(f.tell()); f.write(big); f.write(b"x" * 10) + out.append(os.path.getsize(p)) + with open(p, "wb") as f: + f.write(big); out.append(os.path.getsize(p)); f.write(b"tail"); out.append(os.path.getsize(p)); out.append(f.tell()) + out.append(os.path.getsize(p)) + with open(p, "r+b") as f: + f.read(3); f.write(big); out.append(f.tell()); f.seek(0); out.append(len(f.read())) + with open(p, "w", encoding="latin-1") as t: + t.write("abc"); t.buffer.write(big); t.write("def") + with open(p, "rb") as f: + x = f.read(); out.append((len(x), x[:3], x[-3:])) + with open(p, "ab") as f: + f.write(big); out.append(f.tell()) + r, w = os.pipe() + got = [] + def drain(): + n = 0 + while chunk := os.read(r, 1 << 20): + n += len(chunk) + got.append(n) + th = threading.Thread(target=drain) + with open(w, "wb") as f: + th.start(); f.write(big[:150000]) + th.join() + out.append(got[0]) + print(out) + shutil.rmtree(d) + + +def output(case): + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + case() + return buf.getvalue() + + +EXPECTED_READS = "[b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t', 10, b'\\n', b'\\x0b\\x0c\\r', 14, b'\\x05\\x06\\x07\\x08', 9, True, b'\\t\\n\\x0b\\x0c\\r', b'\\x0e\\x0f', b'{|}', 70014, 7, b'~\\x7f\\x80\\x81\\x82\\x83\\x84', 70021, 245979, b'', 316000, b'\\x00\\x01\\x02\\x03', b'\\x00\\x01\\x02\\x03ZZ\\x06\\x07', 8, True, 316000, 'FileIO', b'\\x00\\x01\\x02\\x03Z', 5, b'abc', b'defgh', b'']\nb'ine2\\n' b'' 316000\nb'' 316010\n315989 316000\nb'2\\nTAIL' 316004\nb'' b''\nb'' b''\nb''\n" +EXPECTED_WRITES = "[153604, 307214, 153600, 153600, 153604, 153604, 153603, 153604, (153606, b'\\x00\\x01\\x02', b'def'), 307206, 150000]\n" + +got = output(reads) +assert got == EXPECTED_READS, got +got = output(writes) +assert got == EXPECTED_WRITES, got +print("ok") diff --git a/tests/regrtest/test_filter_collected_at_once.py b/tests/regrtest/test_filter_collected_at_once.py new file mode 100644 index 000000000..9ac373be8 --- /dev/null +++ b/tests/regrtest/test_filter_collected_at_once.py @@ -0,0 +1,96 @@ +"""`list(filter(None, xs))` and `filter(bool, xs)` collected in one call. + +Lists and tuples of ints, floats, strings, `None` and bools give the +truthy items in order, from the start or after some were taken; the +filter and its source iterator are exhausted afterwards; an item with its +own `__bool__` anywhere among the rest is tested through it, in order; +and a source iterator shared with other code ends up where stepping it +item by item leaves it. +""" + +import gc +import unittest +import weakref + + +class Truth: + calls = [] + + def __init__(self, v): + self.v = v + + def __bool__(self): + Truth.calls.append(self.v) + return bool(self.v) + + +class FilterCollectTests(unittest.TestCase): + def test_plain(self): + xs = [0, 1, 2, 0, -3, 0.0, 1.5, "", "a", None, True, False] * 50 + want = [x for x in xs if x] + self.assertEqual(list(filter(None, xs)), want) + self.assertEqual(list(filter(bool, xs)), want) + self.assertEqual(list(filter(None, tuple(xs))), want) + self.assertEqual(sorted(filter(None, xs), key=str), sorted(want, key=str)) + self.assertEqual(list(filter(None, [])), []) + self.assertEqual(list(filter(None, [0, 0, None, ""])), []) + + def test_after_some_taken(self): + xs = list(range(10)) + f = filter(None, xs) + self.assertEqual(next(f), 1) + self.assertEqual(next(f), 2) + self.assertEqual(list(f), list(range(3, 10))) + self.assertEqual(list(f), []) + with self.assertRaises(StopIteration): + next(f) + + def test_shared_source(self): + xs = [0, 1, 2, 3] + it = iter(xs) + f = filter(None, it) + self.assertEqual(list(f), [1, 2, 3]) + self.assertEqual(list(it), []) + xs.append(4) + # An exhausted list iterator stays exhausted. + self.assertEqual(list(it), []) + self.assertEqual(list(f), []) + + def test_bool_items(self): + Truth.calls = [] + xs = [1, Truth(0), 2, Truth(5), 0] + self.assertEqual([x if isinstance(x, int) else x.v for x in filter(None, xs)], + [1, 2, 5]) + self.assertEqual(Truth.calls, [0, 5]) + + def test_bool_error(self): + class Bad: + def __bool__(self): + raise ValueError("no") + + xs = [1, 2, Bad(), 3] + f = filter(None, xs) + with self.assertRaises(ValueError): + list(f) + self.assertEqual(list(f), [3]) + + def test_list_released(self): + class Box(list): + pass + + xs = Box([0, 1, 2]) + r = weakref.ref(xs) + f = filter(None, iter(xs)) + del xs + self.assertEqual(list(f), [1, 2]) + gc.collect() + self.assertIsNone(r()) + + def test_many(self): + xs = list(range(-500, 500)) * 3 + for _ in range(300): + self.assertEqual(len(list(filter(None, xs))), 2997) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_filter_generator_step.py b/tests/regrtest/test_filter_generator_step.py new file mode 100644 index 000000000..78543bbda --- /dev/null +++ b/tests/regrtest/test_filter_generator_step.py @@ -0,0 +1,130 @@ +"""A loop over `filter(None, gen)` steps the generator directly; the +items kept, an item whose `__bool__` runs code (kept, dropped or +raising), the generator's state afterwards and the adapter's own match +the general filter.""" + +import unittest + + +def gen(xs): + for x in xs: + yield x + + +class Flag: + def __init__(self, v): + self.v = v + + def __bool__(self): + # Not a frameless leaf: it calls a Python function. + return bool(_identity(self.v)) + + +def _identity(x): + return x + + +class Plain: + pass + + +class Boom: + def __bool__(self): + raise ValueError("boom") + + +ITEMS = [0, 1, "", "a", None, 2.5, 0.0, [], [0], (), (1,), {}, {1: 2}, False, True] +EXPECT = [x for x in ITEMS if x] + + +class FilterGeneratorStep(unittest.TestCase): + def test_scalars_and_containers(self): + for _ in range(500): + out = [] + for x in filter(None, gen(ITEMS)): + out.append(x) + self.assertEqual(out, EXPECT) + out = [] + for x in filter(bool, gen(ITEMS)): + out.append(x) + self.assertEqual(out, EXPECT) + + def test_python_bool_items(self): + for _ in range(300): + items = [Flag(0), 1, Flag(1), 0, Flag(2), Plain(), 3] + out = [] + for x in filter(None, gen(items)): + out.append(x) + self.assertEqual(out, [items[1], items[2], items[4], items[5], 6 // 2]) + + def test_raising_bool(self): + for _ in range(200): + g = gen([1, 0, Boom(), 5]) + out = [] + with self.assertRaises(ValueError): + for x in filter(None, g): + out.append(x) + self.assertEqual(out, [1]) + # The generator went on past the raising item, as CPython's. + self.assertEqual(list(g), [5]) + + def test_break_and_resume(self): + for _ in range(300): + g = gen(range(10)) + f = filter(None, g) + out = [] + for x in f: + out.append(x) + if x == 4: + break + self.assertEqual(out, [1, 2, 3, 4]) + self.assertEqual(next(g), 5) + self.assertEqual(list(f), [6, 7, 8, 9]) + self.assertEqual(list(f), []) + + def test_resume_after_put_back(self): + for _ in range(200): + g = gen([0, Flag(1), 0, 2, Flag(0), 3]) + f = filter(None, g) + out = [] + for x in f: + out.append(x if not isinstance(x, Flag) else "flag") + if x == 2: + break + self.assertEqual(out, ["flag", 2]) + self.assertEqual(list(f), [3]) + + def test_generator_return_and_empty(self): + def g2(): + yield 0 + yield 7 + return 99 + + for _ in range(300): + self.assertEqual([x for x in filter(None, g2())], [7]) + self.assertEqual([x for x in filter(None, gen([]))], []) + self.assertEqual([x for x in filter(None, gen([0, None, ""]))], []) + + def test_generator_raises(self): + def bad(): + yield 1 + yield 0 + raise KeyError("k") + + for _ in range(200): + out = [] + with self.assertRaises(KeyError): + for x in filter(None, bad()): + out.append(x) + self.assertEqual(out, [1]) + + def test_sum_of_kept(self): + for _ in range(300): + t = 0 + for x in filter(None, (i % 3 for i in range(30))): + t += x + self.assertEqual(t, 30) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_filter_truth_fast.py b/tests/regrtest/test_filter_truth_fast.py new file mode 100644 index 000000000..8140c96cd --- /dev/null +++ b/tests/regrtest/test_filter_truth_fast.py @@ -0,0 +1,36 @@ +"""`filter(None, it)` and `filter(bool, it)` over plain sequence iterators. + +Items whose truth is plain data are stepped in place; an instance with a +`__bool__` between them is tested through it, in order; a list that +grows while it's filtered yields the new items; an exhausted filter +stays exhausted. Items are heap objects too. Run it past the compile +threshold. +""" + + +class B: + calls = 0 + + def __init__(self, v): + self.v = v + + def __bool__(self): + B.calls += 1 + return self.v + + +t, f = B(True), B(False) +for i in range(3000): + B.calls = 0 + assert list(filter(None, (0, 1, "", "a", t, 0.0, f, None, 2.5, False))) == [1, "a", t, 2.5] + assert B.calls == 2 + assert list(filter(bool, [0, "x", 0, ()])) == ["x"] + xs = [0, 1] + it = filter(None, xs) + assert next(it) == 1 + xs.append(5) + assert next(it) == 5 + assert next(it, "end") == "end" + xs.append(7) + assert next(it, "end") == "end" + assert list(filter(None, "a\x00b")) == ["a", "\x00", "b"] diff --git a/tests/regrtest/test_finalizer_calls_and_class_flag_stores.py b/tests/regrtest/test_finalizer_calls_and_class_flag_stores.py new file mode 100644 index 000000000..f0ea21de6 --- /dev/null +++ b/tests/regrtest/test_finalizer_calls_and_class_flag_stores.py @@ -0,0 +1,320 @@ +"""Finalizers call `__del__` directly, and a class keeps its attribute +version when a store changes nothing. + +A dying instance's Python `__del__` is called with the instance (no bound +method, the function remembered per class version), and storing on a class +the very object its dictionary already holds under the name no longer +invalidates what call sites remembered about the class. These tests pin the +behaviour around both: which `__del__` runs and how its errors are +reported, and that every store that does change something is seen at once. +""" + +import gc +import math +import sys +import unittest + +N = 3000 + + +def collect(): + gc.collect() + + +class Finalizers(unittest.TestCase): + def test_del_runs_once_with_the_instance(self): + seen = [] + + class Tracked: + def __init__(self, tag): + self.tag = tag + + def __del__(self): + seen.append((type(self).__name__, self.tag)) + + for i in range(5): + Tracked(i) + collect() + self.assertEqual(seen, [("Tracked", i) for i in range(5)]) + + def test_hot_finalizers(self): + count = [0] + + class Tracked: + def __del__(self): + count[0] += 1 + + for _ in range(N): + Tracked() + collect() + self.assertEqual(count[0], N) + + def test_inherited_and_overridden(self): + log = [] + + class Base: + def __del__(self): + log.append("base") + + class Same(Base): + pass + + class Own(Base): + def __del__(self): + log.append("own") + Base.__del__(self) + + Same() + Own() + collect() + self.assertEqual(log, ["base", "own", "base"]) + + def test_del_replaced_on_the_class(self): + log = [] + + class Tracked: + def __del__(self): + log.append("first") + + for _ in range(50): + Tracked() + collect() + Tracked.__del__ = lambda self: log.append("second") + for _ in range(50): + Tracked() + collect() + del Tracked.__del__ + for _ in range(50): + Tracked() + collect() + self.assertEqual(log, ["first"] * 50 + ["second"] * 50) + + def test_del_that_is_not_a_plain_function(self): + log = [] + + class Recorder: + def __call__(self, *args): + log.append(len(args)) + + class WithCallable: + __del__ = Recorder() + + class WithStatic: + @staticmethod + def __del__(): + log.append("static") + + WithCallable() + collect() + self.assertEqual(log, [0]) + WithStatic() + collect() + self.assertEqual(log, [0, "static"]) + + def test_error_goes_to_the_unraisable_hook(self): + caught = [] + old = sys.unraisablehook + sys.unraisablehook = caught.append + try: + + class Bad: + def __del__(self): + raise KeyError("in del") + + Bad() + collect() + finally: + sys.unraisablehook = old + self.assertEqual(len(caught), 1) + self.assertIsInstance(caught[0].exc_value, KeyError) + self.assertIn("Bad.__del__", repr(caught[0].object) + str(caught[0].err_msg)) + caught.clear() + + def test_resurrection(self): + saved = [] + + class Phoenix: + def __del__(self): + saved.append(self) + + Phoenix() + collect() + self.assertEqual(len(saved), 1) + saved.clear() + collect() + self.assertEqual(saved, []) + + def test_del_that_makes_more_garbage(self): + log = [] + + class Inner: + def __del__(self): + log.append("inner") + + class Outer: + def __del__(self): + log.append("outer") + Inner() + + for _ in range(20): + Outer() + collect() + self.assertEqual((log.count("outer"), log.count("inner")), (20, 20)) + + +class ClassFlagStores(unittest.TestCase): + def test_flag_set_per_instance(self): + class Registry: + dirty = False + made = 0 + + def __init__(self): + Registry.dirty = True + Registry.made += 1 + + def read(self): + return self.dirty, self.made + + for _ in range(N): + r = Registry() + self.assertEqual(r.read(), (True, N)) + Registry.dirty = False + self.assertEqual(r.read(), (False, N)) + Registry.dirty = True + self.assertEqual((r.dirty, Registry.dirty), (True, True)) + + def test_a_change_after_many_same_stores_is_seen(self): + class Config: + mode = "a" + + def get(self): + return self.mode + + c = Config() + got = [] + for i in range(N): + Config.mode = "a" + if i == N - 10: + Config.mode = "b" + got.append(c.get()) + Config.mode = "a" + got.append(c.get()) + self.assertEqual(got.count("b"), 1) + self.assertEqual(got[-1], "a") + + def test_equal_but_distinct_objects_are_stored(self): + class Holder: + items = [1] + + first = Holder.items + second = [1] + Holder.items = second + self.assertIs(Holder.items, second) + self.assertIsNot(Holder.items, first) + Holder.zero = 0.0 + Holder.zero = -0.0 + self.assertEqual(math.copysign(1.0, Holder.zero), -1.0) + nan = float("nan") + Holder.nan = nan + Holder.nan = nan + self.assertIs(Holder.nan, nan) + + def test_same_function_and_descriptor_stored_again(self): + class Shape: + def area(self): + return 1 + + size = property(lambda self: 2) + + s = Shape() + area, size = Shape.__dict__["area"], Shape.__dict__["size"] + for _ in range(N): + Shape.area = area + Shape.size = size + got = (s.area(), s.size) + self.assertEqual(got, (1, 2)) + Shape.area = lambda self: 3 + Shape.size = property(lambda self: 4) + self.assertEqual((s.area(), s.size), (3, 4)) + + def test_store_shadowing_an_instance_attribute(self): + class Thing: + pass + + t = Thing() + t.value = "instance" + for _ in range(100): + Thing.value = "class" + self.assertEqual(t.value, "instance") + prop = property(lambda self: "property") + Thing.value = prop + self.assertEqual(t.value, "property") + Thing.value = prop + self.assertEqual(t.value, "property") + del Thing.value + self.assertEqual(t.value, "instance") + + def test_metaclass_setattr_sees_every_store(self): + stores = [] + + class Meta(type): + def __setattr__(cls, name, value): + stores.append((name, value)) + super().__setattr__(name, value) + + class Watched(metaclass=Meta): + flag = True + + for _ in range(5): + Watched.flag = True + self.assertEqual(stores, [("flag", True)] * 5) + + def test_subclasses_see_base_changes(self): + class Base: + level = 1 + + class Child(Base): + def get(self): + return self.level + + c = Child() + for _ in range(N): + Base.level = 1 + got = c.get() + self.assertEqual(got, 1) + Base.level = 2 + self.assertEqual(c.get(), 2) + Child.level = 2 + Base.level = 3 + self.assertEqual(c.get(), 2) + + def test_special_methods_stored_again(self): + class Num: + def __init__(self, v): + self.v = v + + def __eq__(self, other): + return self.v == other.v + + def __hash__(self): + return hash(self.v) + + def __len__(self): + return self.v + + eq, hash_, len_ = Num.__dict__["__eq__"], Num.__dict__["__hash__"], Num.__dict__["__len__"] + for _ in range(200): + Num.__eq__ = eq + Num.__hash__ = hash_ + Num.__len__ = len_ + got = (Num(3) == Num(3), len({Num(1), Num(1)}), len(Num(4))) + self.assertEqual(got, (True, 1, 4)) + Num.__len__ = lambda self: 9 + self.assertEqual(len(Num(4)), 9) + Num.__hash__ = None + with self.assertRaises(TypeError): + hash(Num(1)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_float_e_g_rounding.py b/tests/regrtest/test_float_e_g_rounding.py new file mode 100644 index 000000000..4502fa5a9 --- /dev/null +++ b/tests/regrtest/test_float_e_g_rounding.py @@ -0,0 +1,88 @@ +"""`e` and `g` formatting of floats rounds the exact binary value. + +At every precision from 0 to 20 digits, for floats across the whole +exponent range (zeros, subnormals, values whose shortest form is short and +values whose digits run long), `format(x, '.Ne')` and `'.Ng'` give the +digits `decimal` gives when it rounds the float's exact value half to +even. Inputs are built with `ldexp` from seeded random fractions, and from +decimal literals, so nothing depends on a platform's `pow`. +""" + +import decimal +import math +import random +import unittest + + +def exact_e(x, after): + """`x` in scientific form with `after` digits past the point.""" + if x == 0: + # (A decimal zero keeps an exponent of its own: written out here.) + return ("-" if math.copysign(1, x) < 0 else "") + ("0." + "0" * after if after else "0"), 0 + d = decimal.Decimal(x) + with decimal.localcontext() as ctx: + ctx.prec = 1000 + ctx.rounding = decimal.ROUND_HALF_EVEN + text = format(d, ".%de" % after) + mant, exp = text.split("e") + return mant, int(exp) + + +def split(text): + mant, exp = text.split("e") + return mant, int(exp) + + +VALUES = [0.0, 1.5, 0.1, 0.2, 0.3, 123.456, 2.5, 0.5, 1e22, 1e23, 9.995, 1.0000000000000002, + 0.9999999999999999, 5e-324, 2.2250738585072014e-308, 2.225073858507201e-308, + 1.7976931348623157e308, 1234567890123456.0, 0.000123, 100.0, 1e-7, 3.0, 7.0e15] + + +class RoundingTests(unittest.TestCase): + def values(self): + rnd = random.Random(20261122) + out = list(VALUES) + for _ in range(400): + out.append(math.ldexp(rnd.random(), rnd.randint(-1070, 1020))) + for _ in range(200): + # Short decimals: their shortest form has few digits. + out.append(float("%d.%de%d" % (rnd.randint(1, 999), rnd.randint(0, 99), rnd.randint(-300, 300)))) + return out + + def test_e(self): + for x in self.values(): + for after in range(0, 21): + got = split(format(x, ".%de" % after)) + self.assertEqual(got, exact_e(x, after), (x, after)) + self.assertEqual(split(format(-x, ".%de" % after)), + ("-" + got[0], got[1]) if x else (format(-x, ".%de" % after).split("e")[0], got[1])) + + def test_g(self): + for x in self.values(): + for prec in range(1, 21): + got = format(x, ".%dg" % prec) + mant, exp = exact_e(x, prec - 1) + if -4 <= exp < prec: + want = format(decimal.Decimal(mant + "e%d" % exp), "f") + if "." in want: + want = want.rstrip("0").rstrip(".") + self.assertEqual(got, want, (x, prec)) + else: + m = mant.rstrip("0").rstrip(".") if "." in mant else mant + self.assertEqual(split(got), (m, exp), (x, prec)) + + def test_alternate_and_no_type(self): + self.assertEqual(format(1.5, "#.6g"), "1.50000") + self.assertEqual(format(1.5, ".6"), "1.5") + self.assertEqual(format(100.0, ".4"), "100.0") + self.assertEqual(format(1e16, ".3"), "1e+16") + self.assertEqual(format(0.0, ".3e"), "0.000e+00") + self.assertEqual(format(-0.0, "g"), "-0") + self.assertEqual("%.3g" % 1234.5, "1.23e+03") + self.assertEqual("%g" % 1.5, "1.5") + self.assertEqual(f"{2.5:.0e}", "2e+00") + self.assertEqual(f"{3.5:.0e}", "4e+00") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_float_exp_and_general_table.py b/tests/regrtest/test_float_exp_and_general_table.py new file mode 100644 index 000000000..1f6b5b6ca --- /dev/null +++ b/tests/regrtest/test_float_exp_and_general_table.py @@ -0,0 +1,718 @@ +"""`format(x, spec)` of floats in the `e`, `g` and type-omitted styles. + +The digits come from one exact formatting (or the shortest one, padded, +for a value whose binary expansion is short); the sign, grouping, padding +and alignment are laid around them. Each row is CPython 3.14's result, +over round values, long mantissas, extremes and the zeros. +""" + +import unittest + +ROWS = [ + (0.5, 'g', '0.5'), + (0.5, '.3g', '0.5'), + (0.5, '.10g', '0.5'), + (0.5, '.1g', '0.5'), + (0.5, '.0g', '0.5'), + (0.5, 'e', '5.000000e-01'), + (0.5, '.2e', '5.00e-01'), + (0.5, '.0e', '5e-01'), + (0.5, '.12e', '5.000000000000e-01'), + (0.5, 'G', '0.5'), + (0.5, 'E', '5.000000E-01'), + (0.5, '', '0.5'), + (0.5, '.4', '0.5'), + (0.5, '+g', '+0.5'), + (0.5, ' g', ' 0.5'), + (0.5, '10.3g', ' 0.5'), + (0.5, ',g', '0.5'), + (0.5, '_.3e', '5.000e-01'), + (0.5, '.17g', '0.5'), + (0.5, '#g', '0.500000'), + (0.5, '#.3g', '0.500'), + (0.5, '-^12.4g', '----0.5-----'), + (0.5, '015.3e', '0000005.000e-01'), + (100.0, 'g', '100'), + (100.0, '.3g', '100'), + (100.0, '.10g', '100'), + (100.0, '.1g', '1e+02'), + (100.0, '.0g', '1e+02'), + (100.0, 'e', '1.000000e+02'), + (100.0, '.2e', '1.00e+02'), + (100.0, '.0e', '1e+02'), + (100.0, '.12e', '1.000000000000e+02'), + (100.0, 'G', '100'), + (100.0, 'E', '1.000000E+02'), + (100.0, '', '100.0'), + (100.0, '.4', '100.0'), + (100.0, '+g', '+100'), + (100.0, ' g', ' 100'), + (100.0, '10.3g', ' 100'), + (100.0, ',g', '100'), + (100.0, '_.3e', '1.000e+02'), + (100.0, '.17g', '100'), + (100.0, '#g', '100.000'), + (100.0, '#.3g', '100.'), + (100.0, '-^12.4g', '----100-----'), + (100.0, '015.3e', '0000001.000e+02'), + (1234.5678, 'g', '1234.57'), + (1234.5678, '.3g', '1.23e+03'), + (1234.5678, '.10g', '1234.5678'), + (1234.5678, '.1g', '1e+03'), + (1234.5678, '.0g', '1e+03'), + (1234.5678, 'e', '1.234568e+03'), + (1234.5678, '.2e', '1.23e+03'), + (1234.5678, '.0e', '1e+03'), + (1234.5678, '.12e', '1.234567800000e+03'), + (1234.5678, 'G', '1234.57'), + (1234.5678, 'E', '1.234568E+03'), + (1234.5678, '', '1234.5678'), + (1234.5678, '.4', '1.235e+03'), + (1234.5678, '+g', '+1234.57'), + (1234.5678, ' g', ' 1234.57'), + (1234.5678, '10.3g', ' 1.23e+03'), + (1234.5678, ',g', '1,234.57'), + (1234.5678, '_.3e', '1.235e+03'), + (1234.5678, '.17g', '1234.5678'), + (1234.5678, '#g', '1234.57'), + (1234.5678, '#.3g', '1.23e+03'), + (1234.5678, '-^12.4g', '----1235----'), + (1234.5678, '015.3e', '0000001.235e+03'), + (0.1, 'g', '0.1'), + (0.1, '.3g', '0.1'), + (0.1, '.10g', '0.1'), + (0.1, '.1g', '0.1'), + (0.1, '.0g', '0.1'), + (0.1, 'e', '1.000000e-01'), + (0.1, '.2e', '1.00e-01'), + (0.1, '.0e', '1e-01'), + (0.1, '.12e', '1.000000000000e-01'), + (0.1, 'G', '0.1'), + (0.1, 'E', '1.000000E-01'), + (0.1, '', '0.1'), + (0.1, '.4', '0.1'), + (0.1, '+g', '+0.1'), + (0.1, ' g', ' 0.1'), + (0.1, '10.3g', ' 0.1'), + (0.1, ',g', '0.1'), + (0.1, '_.3e', '1.000e-01'), + (0.1, '.17g', '0.10000000000000001'), + (0.1, '#g', '0.100000'), + (0.1, '#.3g', '0.100'), + (0.1, '-^12.4g', '----0.1-----'), + (0.1, '015.3e', '0000001.000e-01'), + (1e+22, 'g', '1e+22'), + (1e+22, '.3g', '1e+22'), + (1e+22, '.10g', '1e+22'), + (1e+22, '.1g', '1e+22'), + (1e+22, '.0g', '1e+22'), + (1e+22, 'e', '1.000000e+22'), + (1e+22, '.2e', '1.00e+22'), + (1e+22, '.0e', '1e+22'), + (1e+22, '.12e', '1.000000000000e+22'), + (1e+22, 'G', '1E+22'), + (1e+22, 'E', '1.000000E+22'), + (1e+22, '', '1e+22'), + (1e+22, '.4', '1e+22'), + (1e+22, '+g', '+1e+22'), + (1e+22, ' g', ' 1e+22'), + (1e+22, '10.3g', ' 1e+22'), + (1e+22, ',g', '1e+22'), + (1e+22, '_.3e', '1.000e+22'), + (1e+22, '.17g', '1e+22'), + (1e+22, '#g', '1.00000e+22'), + (1e+22, '#.3g', '1.00e+22'), + (1e+22, '-^12.4g', '---1e+22----'), + (1e+22, '015.3e', '0000001.000e+22'), + (1e-05, 'g', '1e-05'), + (1e-05, '.3g', '1e-05'), + (1e-05, '.10g', '1e-05'), + (1e-05, '.1g', '1e-05'), + (1e-05, '.0g', '1e-05'), + (1e-05, 'e', '1.000000e-05'), + (1e-05, '.2e', '1.00e-05'), + (1e-05, '.0e', '1e-05'), + (1e-05, '.12e', '1.000000000000e-05'), + (1e-05, 'G', '1E-05'), + (1e-05, 'E', '1.000000E-05'), + (1e-05, '', '1e-05'), + (1e-05, '.4', '1e-05'), + (1e-05, '+g', '+1e-05'), + (1e-05, ' g', ' 1e-05'), + (1e-05, '10.3g', ' 1e-05'), + (1e-05, ',g', '1e-05'), + (1e-05, '_.3e', '1.000e-05'), + (1e-05, '.17g', '1.0000000000000001e-05'), + (1e-05, '#g', '1.00000e-05'), + (1e-05, '#.3g', '1.00e-05'), + (1e-05, '-^12.4g', '---1e-05----'), + (1e-05, '015.3e', '0000001.000e-05'), + (123456789.0, 'g', '1.23457e+08'), + (123456789.0, '.3g', '1.23e+08'), + (123456789.0, '.10g', '123456789'), + (123456789.0, '.1g', '1e+08'), + (123456789.0, '.0g', '1e+08'), + (123456789.0, 'e', '1.234568e+08'), + (123456789.0, '.2e', '1.23e+08'), + (123456789.0, '.0e', '1e+08'), + (123456789.0, '.12e', '1.234567890000e+08'), + (123456789.0, 'G', '1.23457E+08'), + (123456789.0, 'E', '1.234568E+08'), + (123456789.0, '', '123456789.0'), + (123456789.0, '.4', '1.235e+08'), + (123456789.0, '+g', '+1.23457e+08'), + (123456789.0, ' g', ' 1.23457e+08'), + (123456789.0, '10.3g', ' 1.23e+08'), + (123456789.0, ',g', '1.23457e+08'), + (123456789.0, '_.3e', '1.235e+08'), + (123456789.0, '.17g', '123456789'), + (123456789.0, '#g', '1.23457e+08'), + (123456789.0, '#.3g', '1.23e+08'), + (123456789.0, '-^12.4g', '-1.235e+08--'), + (123456789.0, '015.3e', '0000001.235e+08'), + (2.5, 'g', '2.5'), + (2.5, '.3g', '2.5'), + (2.5, '.10g', '2.5'), + (2.5, '.1g', '2'), + (2.5, '.0g', '2'), + (2.5, 'e', '2.500000e+00'), + (2.5, '.2e', '2.50e+00'), + (2.5, '.0e', '2e+00'), + (2.5, '.12e', '2.500000000000e+00'), + (2.5, 'G', '2.5'), + (2.5, 'E', '2.500000E+00'), + (2.5, '', '2.5'), + (2.5, '.4', '2.5'), + (2.5, '+g', '+2.5'), + (2.5, ' g', ' 2.5'), + (2.5, '10.3g', ' 2.5'), + (2.5, ',g', '2.5'), + (2.5, '_.3e', '2.500e+00'), + (2.5, '.17g', '2.5'), + (2.5, '#g', '2.50000'), + (2.5, '#.3g', '2.50'), + (2.5, '-^12.4g', '----2.5-----'), + (2.5, '015.3e', '0000002.500e+00'), + (0.125, 'g', '0.125'), + (0.125, '.3g', '0.125'), + (0.125, '.10g', '0.125'), + (0.125, '.1g', '0.1'), + (0.125, '.0g', '0.1'), + (0.125, 'e', '1.250000e-01'), + (0.125, '.2e', '1.25e-01'), + (0.125, '.0e', '1e-01'), + (0.125, '.12e', '1.250000000000e-01'), + (0.125, 'G', '0.125'), + (0.125, 'E', '1.250000E-01'), + (0.125, '', '0.125'), + (0.125, '.4', '0.125'), + (0.125, '+g', '+0.125'), + (0.125, ' g', ' 0.125'), + (0.125, '10.3g', ' 0.125'), + (0.125, ',g', '0.125'), + (0.125, '_.3e', '1.250e-01'), + (0.125, '.17g', '0.125'), + (0.125, '#g', '0.125000'), + (0.125, '#.3g', '0.125'), + (0.125, '-^12.4g', '---0.125----'), + (0.125, '015.3e', '0000001.250e-01'), + (0.3333333333333333, 'g', '0.333333'), + (0.3333333333333333, '.3g', '0.333'), + (0.3333333333333333, '.10g', '0.3333333333'), + (0.3333333333333333, '.1g', '0.3'), + (0.3333333333333333, '.0g', '0.3'), + (0.3333333333333333, 'e', '3.333333e-01'), + (0.3333333333333333, '.2e', '3.33e-01'), + (0.3333333333333333, '.0e', '3e-01'), + (0.3333333333333333, '.12e', '3.333333333333e-01'), + (0.3333333333333333, 'G', '0.333333'), + (0.3333333333333333, 'E', '3.333333E-01'), + (0.3333333333333333, '', '0.3333333333333333'), + (0.3333333333333333, '.4', '0.3333'), + (0.3333333333333333, '+g', '+0.333333'), + (0.3333333333333333, ' g', ' 0.333333'), + (0.3333333333333333, '10.3g', ' 0.333'), + (0.3333333333333333, ',g', '0.333333'), + (0.3333333333333333, '_.3e', '3.333e-01'), + (0.3333333333333333, '.17g', '0.33333333333333331'), + (0.3333333333333333, '#g', '0.333333'), + (0.3333333333333333, '#.3g', '0.333'), + (0.3333333333333333, '-^12.4g', '---0.3333---'), + (0.3333333333333333, '015.3e', '0000003.333e-01'), + (0.6666666666666666, 'g', '0.666667'), + (0.6666666666666666, '.3g', '0.667'), + (0.6666666666666666, '.10g', '0.6666666667'), + (0.6666666666666666, '.1g', '0.7'), + (0.6666666666666666, '.0g', '0.7'), + (0.6666666666666666, 'e', '6.666667e-01'), + (0.6666666666666666, '.2e', '6.67e-01'), + (0.6666666666666666, '.0e', '7e-01'), + (0.6666666666666666, '.12e', '6.666666666667e-01'), + (0.6666666666666666, 'G', '0.666667'), + (0.6666666666666666, 'E', '6.666667E-01'), + (0.6666666666666666, '', '0.6666666666666666'), + (0.6666666666666666, '.4', '0.6667'), + (0.6666666666666666, '+g', '+0.666667'), + (0.6666666666666666, ' g', ' 0.666667'), + (0.6666666666666666, '10.3g', ' 0.667'), + (0.6666666666666666, ',g', '0.666667'), + (0.6666666666666666, '_.3e', '6.667e-01'), + (0.6666666666666666, '.17g', '0.66666666666666663'), + (0.6666666666666666, '#g', '0.666667'), + (0.6666666666666666, '#.3g', '0.667'), + (0.6666666666666666, '-^12.4g', '---0.6667---'), + (0.6666666666666666, '015.3e', '0000006.667e-01'), + (9.9999995, 'g', '10'), + (9.9999995, '.3g', '10'), + (9.9999995, '.10g', '9.9999995'), + (9.9999995, '.1g', '1e+01'), + (9.9999995, '.0g', '1e+01'), + (9.9999995, 'e', '9.999999e+00'), + (9.9999995, '.2e', '1.00e+01'), + (9.9999995, '.0e', '1e+01'), + (9.9999995, '.12e', '9.999999500000e+00'), + (9.9999995, 'G', '10'), + (9.9999995, 'E', '9.999999E+00'), + (9.9999995, '', '9.9999995'), + (9.9999995, '.4', '10.0'), + (9.9999995, '+g', '+10'), + (9.9999995, ' g', ' 10'), + (9.9999995, '10.3g', ' 10'), + (9.9999995, ',g', '10'), + (9.9999995, '_.3e', '1.000e+01'), + (9.9999995, '.17g', '9.9999994999999995'), + (9.9999995, '#g', '10.0000'), + (9.9999995, '#.3g', '10.0'), + (9.9999995, '-^12.4g', '-----10-----'), + (9.9999995, '015.3e', '0000001.000e+01'), + (0.000123456, 'g', '0.000123456'), + (0.000123456, '.3g', '0.000123'), + (0.000123456, '.10g', '0.000123456'), + (0.000123456, '.1g', '0.0001'), + (0.000123456, '.0g', '0.0001'), + (0.000123456, 'e', '1.234560e-04'), + (0.000123456, '.2e', '1.23e-04'), + (0.000123456, '.0e', '1e-04'), + (0.000123456, '.12e', '1.234560000000e-04'), + (0.000123456, 'G', '0.000123456'), + (0.000123456, 'E', '1.234560E-04'), + (0.000123456, '', '0.000123456'), + (0.000123456, '.4', '0.0001235'), + (0.000123456, '+g', '+0.000123456'), + (0.000123456, ' g', ' 0.000123456'), + (0.000123456, '10.3g', ' 0.000123'), + (0.000123456, ',g', '0.000123456'), + (0.000123456, '_.3e', '1.235e-04'), + (0.000123456, '.17g', '0.00012345600000000001'), + (0.000123456, '#g', '0.000123456'), + (0.000123456, '#.3g', '0.000123'), + (0.000123456, '-^12.4g', '-0.0001235--'), + (0.000123456, '015.3e', '0000001.235e-04'), + (5e-324, 'g', '4.94066e-324'), + (5e-324, '.3g', '4.94e-324'), + (5e-324, '.10g', '4.940656458e-324'), + (5e-324, '.1g', '5e-324'), + (5e-324, '.0g', '5e-324'), + (5e-324, 'e', '4.940656e-324'), + (5e-324, '.2e', '4.94e-324'), + (5e-324, '.0e', '5e-324'), + (5e-324, '.12e', '4.940656458412e-324'), + (5e-324, 'G', '4.94066E-324'), + (5e-324, 'E', '4.940656E-324'), + (5e-324, '', '5e-324'), + (5e-324, '.4', '4.941e-324'), + (5e-324, '+g', '+4.94066e-324'), + (5e-324, ' g', ' 4.94066e-324'), + (5e-324, '10.3g', ' 4.94e-324'), + (5e-324, ',g', '4.94066e-324'), + (5e-324, '_.3e', '4.941e-324'), + (5e-324, '.17g', '4.9406564584124654e-324'), + (5e-324, '#g', '4.94066e-324'), + (5e-324, '#.3g', '4.94e-324'), + (5e-324, '-^12.4g', '-4.941e-324-'), + (5e-324, '015.3e', '000004.941e-324'), + (1.7976931348623157e+308, 'g', '1.79769e+308'), + (1.7976931348623157e+308, '.3g', '1.8e+308'), + (1.7976931348623157e+308, '.10g', '1.797693135e+308'), + (1.7976931348623157e+308, '.1g', '2e+308'), + (1.7976931348623157e+308, '.0g', '2e+308'), + (1.7976931348623157e+308, 'e', '1.797693e+308'), + (1.7976931348623157e+308, '.2e', '1.80e+308'), + (1.7976931348623157e+308, '.0e', '2e+308'), + (1.7976931348623157e+308, '.12e', '1.797693134862e+308'), + (1.7976931348623157e+308, 'G', '1.79769E+308'), + (1.7976931348623157e+308, 'E', '1.797693E+308'), + (1.7976931348623157e+308, '', '1.7976931348623157e+308'), + (1.7976931348623157e+308, '.4', '1.798e+308'), + (1.7976931348623157e+308, '+g', '+1.79769e+308'), + (1.7976931348623157e+308, ' g', ' 1.79769e+308'), + (1.7976931348623157e+308, '10.3g', ' 1.8e+308'), + (1.7976931348623157e+308, ',g', '1.79769e+308'), + (1.7976931348623157e+308, '_.3e', '1.798e+308'), + (1.7976931348623157e+308, '.17g', '1.7976931348623157e+308'), + (1.7976931348623157e+308, '#g', '1.79769e+308'), + (1.7976931348623157e+308, '#.3g', '1.80e+308'), + (1.7976931348623157e+308, '-^12.4g', '-1.798e+308-'), + (1.7976931348623157e+308, '015.3e', '000001.798e+308'), + (-0.0, 'g', '-0'), + (-0.0, '.3g', '-0'), + (-0.0, '.10g', '-0'), + (-0.0, '.1g', '-0'), + (-0.0, '.0g', '-0'), + (-0.0, 'e', '-0.000000e+00'), + (-0.0, '.2e', '-0.00e+00'), + (-0.0, '.0e', '-0e+00'), + (-0.0, '.12e', '-0.000000000000e+00'), + (-0.0, 'G', '-0'), + (-0.0, 'E', '-0.000000E+00'), + (-0.0, '', '-0.0'), + (-0.0, '.4', '-0.0'), + (-0.0, '+g', '-0'), + (-0.0, ' g', '-0'), + (-0.0, '10.3g', ' -0'), + (-0.0, ',g', '-0'), + (-0.0, '_.3e', '-0.000e+00'), + (-0.0, '.17g', '-0'), + (-0.0, '#g', '-0.00000'), + (-0.0, '#.3g', '-0.00'), + (-0.0, '-^12.4g', '------0-----'), + (-0.0, '015.3e', '-000000.000e+00'), + (-1.5, 'g', '-1.5'), + (-1.5, '.3g', '-1.5'), + (-1.5, '.10g', '-1.5'), + (-1.5, '.1g', '-2'), + (-1.5, '.0g', '-2'), + (-1.5, 'e', '-1.500000e+00'), + (-1.5, '.2e', '-1.50e+00'), + (-1.5, '.0e', '-2e+00'), + (-1.5, '.12e', '-1.500000000000e+00'), + (-1.5, 'G', '-1.5'), + (-1.5, 'E', '-1.500000E+00'), + (-1.5, '', '-1.5'), + (-1.5, '.4', '-1.5'), + (-1.5, '+g', '-1.5'), + (-1.5, ' g', '-1.5'), + (-1.5, '10.3g', ' -1.5'), + (-1.5, ',g', '-1.5'), + (-1.5, '_.3e', '-1.500e+00'), + (-1.5, '.17g', '-1.5'), + (-1.5, '#g', '-1.50000'), + (-1.5, '#.3g', '-1.50'), + (-1.5, '-^12.4g', '-----1.5----'), + (-1.5, '015.3e', '-000001.500e+00'), + (1e+16, 'g', '1e+16'), + (1e+16, '.3g', '1e+16'), + (1e+16, '.10g', '1e+16'), + (1e+16, '.1g', '1e+16'), + (1e+16, '.0g', '1e+16'), + (1e+16, 'e', '1.000000e+16'), + (1e+16, '.2e', '1.00e+16'), + (1e+16, '.0e', '1e+16'), + (1e+16, '.12e', '1.000000000000e+16'), + (1e+16, 'G', '1E+16'), + (1e+16, 'E', '1.000000E+16'), + (1e+16, '', '1e+16'), + (1e+16, '.4', '1e+16'), + (1e+16, '+g', '+1e+16'), + (1e+16, ' g', ' 1e+16'), + (1e+16, '10.3g', ' 1e+16'), + (1e+16, ',g', '1e+16'), + (1e+16, '_.3e', '1.000e+16'), + (1e+16, '.17g', '10000000000000000'), + (1e+16, '#g', '1.00000e+16'), + (1e+16, '#.3g', '1.00e+16'), + (1e+16, '-^12.4g', '---1e+16----'), + (1e+16, '015.3e', '0000001.000e+16'), + (999999.5, 'g', '1e+06'), + (999999.5, '.3g', '1e+06'), + (999999.5, '.10g', '999999.5'), + (999999.5, '.1g', '1e+06'), + (999999.5, '.0g', '1e+06'), + (999999.5, 'e', '9.999995e+05'), + (999999.5, '.2e', '1.00e+06'), + (999999.5, '.0e', '1e+06'), + (999999.5, '.12e', '9.999995000000e+05'), + (999999.5, 'G', '1E+06'), + (999999.5, 'E', '9.999995E+05'), + (999999.5, '', '999999.5'), + (999999.5, '.4', '1e+06'), + (999999.5, '+g', '+1e+06'), + (999999.5, ' g', ' 1e+06'), + (999999.5, '10.3g', ' 1e+06'), + (999999.5, ',g', '1e+06'), + (999999.5, '_.3e', '1.000e+06'), + (999999.5, '.17g', '999999.5'), + (999999.5, '#g', '1.00000e+06'), + (999999.5, '#.3g', '1.00e+06'), + (999999.5, '-^12.4g', '---1e+06----'), + (999999.5, '015.3e', '0000001.000e+06'), + (0.30000000000000004, 'g', '0.3'), + (0.30000000000000004, '.3g', '0.3'), + (0.30000000000000004, '.10g', '0.3'), + (0.30000000000000004, '.1g', '0.3'), + (0.30000000000000004, '.0g', '0.3'), + (0.30000000000000004, 'e', '3.000000e-01'), + (0.30000000000000004, '.2e', '3.00e-01'), + (0.30000000000000004, '.0e', '3e-01'), + (0.30000000000000004, '.12e', '3.000000000000e-01'), + (0.30000000000000004, 'G', '0.3'), + (0.30000000000000004, 'E', '3.000000E-01'), + (0.30000000000000004, '', '0.30000000000000004'), + (0.30000000000000004, '.4', '0.3'), + (0.30000000000000004, '+g', '+0.3'), + (0.30000000000000004, ' g', ' 0.3'), + (0.30000000000000004, '10.3g', ' 0.3'), + (0.30000000000000004, ',g', '0.3'), + (0.30000000000000004, '_.3e', '3.000e-01'), + (0.30000000000000004, '.17g', '0.30000000000000004'), + (0.30000000000000004, '#g', '0.300000'), + (0.30000000000000004, '#.3g', '0.300'), + (0.30000000000000004, '-^12.4g', '----0.3-----'), + (0.30000000000000004, '015.3e', '0000003.000e-01'), + (1234567.0, 'g', '1.23457e+06'), + (1234567.0, '.3g', '1.23e+06'), + (1234567.0, '.10g', '1234567'), + (1234567.0, '.1g', '1e+06'), + (1234567.0, '.0g', '1e+06'), + (1234567.0, 'e', '1.234567e+06'), + (1234567.0, '.2e', '1.23e+06'), + (1234567.0, '.0e', '1e+06'), + (1234567.0, '.12e', '1.234567000000e+06'), + (1234567.0, 'G', '1.23457E+06'), + (1234567.0, 'E', '1.234567E+06'), + (1234567.0, '', '1234567.0'), + (1234567.0, '.4', '1.235e+06'), + (1234567.0, '+g', '+1.23457e+06'), + (1234567.0, ' g', ' 1.23457e+06'), + (1234567.0, '10.3g', ' 1.23e+06'), + (1234567.0, ',g', '1.23457e+06'), + (1234567.0, '_.3e', '1.235e+06'), + (1234567.0, '.17g', '1234567'), + (1234567.0, '#g', '1.23457e+06'), + (1234567.0, '#.3g', '1.23e+06'), + (1234567.0, '-^12.4g', '-1.235e+06--'), + (1234567.0, '015.3e', '0000001.235e+06'), + (0.0, 'g', '0'), + (0.0, '.3g', '0'), + (0.0, '.10g', '0'), + (0.0, '.1g', '0'), + (0.0, '.0g', '0'), + (0.0, 'e', '0.000000e+00'), + (0.0, '.2e', '0.00e+00'), + (0.0, '.0e', '0e+00'), + (0.0, '.12e', '0.000000000000e+00'), + (0.0, 'G', '0'), + (0.0, 'E', '0.000000E+00'), + (0.0, '', '0.0'), + (0.0, '.4', '0.0'), + (0.0, '+g', '+0'), + (0.0, ' g', ' 0'), + (0.0, '10.3g', ' 0'), + (0.0, ',g', '0'), + (0.0, '_.3e', '0.000e+00'), + (0.0, '.17g', '0'), + (0.0, '#g', '0.00000'), + (0.0, '#.3g', '0.00'), + (0.0, '-^12.4g', '-----0------'), + (0.0, '015.3e', '0000000.000e+00'), + (123456789000000.0, 'g', '1.23457e+14'), + (123456789000000.0, '.3g', '1.23e+14'), + (123456789000000.0, '.10g', '1.23456789e+14'), + (123456789000000.0, '.1g', '1e+14'), + (123456789000000.0, '.0g', '1e+14'), + (123456789000000.0, 'e', '1.234568e+14'), + (123456789000000.0, '.2e', '1.23e+14'), + (123456789000000.0, '.0e', '1e+14'), + (123456789000000.0, '.12e', '1.234567890000e+14'), + (123456789000000.0, 'G', '1.23457E+14'), + (123456789000000.0, 'E', '1.234568E+14'), + (123456789000000.0, '', '123456789000000.0'), + (123456789000000.0, '.4', '1.235e+14'), + (123456789000000.0, '+g', '+1.23457e+14'), + (123456789000000.0, ' g', ' 1.23457e+14'), + (123456789000000.0, '10.3g', ' 1.23e+14'), + (123456789000000.0, ',g', '1.23457e+14'), + (123456789000000.0, '_.3e', '1.235e+14'), + (123456789000000.0, '.17g', '123456789000000'), + (123456789000000.0, '#g', '1.23457e+14'), + (123456789000000.0, '#.3g', '1.23e+14'), + (123456789000000.0, '-^12.4g', '-1.235e+14--'), + (123456789000000.0, '015.3e', '0000001.235e+14'), + (3.14159, 'g', '3.14159'), + (3.14159, '.3g', '3.14'), + (3.14159, '.10g', '3.14159'), + (3.14159, '.1g', '3'), + (3.14159, '.0g', '3'), + (3.14159, 'e', '3.141590e+00'), + (3.14159, '.2e', '3.14e+00'), + (3.14159, '.0e', '3e+00'), + (3.14159, '.12e', '3.141590000000e+00'), + (3.14159, 'G', '3.14159'), + (3.14159, 'E', '3.141590E+00'), + (3.14159, '', '3.14159'), + (3.14159, '.4', '3.142'), + (3.14159, '+g', '+3.14159'), + (3.14159, ' g', ' 3.14159'), + (3.14159, '10.3g', ' 3.14'), + (3.14159, ',g', '3.14159'), + (3.14159, '_.3e', '3.142e+00'), + (3.14159, '.17g', '3.1415899999999999'), + (3.14159, '#g', '3.14159'), + (3.14159, '#.3g', '3.14'), + (3.14159, '-^12.4g', '---3.142----'), + (3.14159, '015.3e', '0000003.142e+00'), + (2.675, 'g', '2.675'), + (2.675, '.3g', '2.67'), + (2.675, '.10g', '2.675'), + (2.675, '.1g', '3'), + (2.675, '.0g', '3'), + (2.675, 'e', '2.675000e+00'), + (2.675, '.2e', '2.67e+00'), + (2.675, '.0e', '3e+00'), + (2.675, '.12e', '2.675000000000e+00'), + (2.675, 'G', '2.675'), + (2.675, 'E', '2.675000E+00'), + (2.675, '', '2.675'), + (2.675, '.4', '2.675'), + (2.675, '+g', '+2.675'), + (2.675, ' g', ' 2.675'), + (2.675, '10.3g', ' 2.67'), + (2.675, ',g', '2.675'), + (2.675, '_.3e', '2.675e+00'), + (2.675, '.17g', '2.6749999999999998'), + (2.675, '#g', '2.67500'), + (2.675, '#.3g', '2.67'), + (2.675, '-^12.4g', '---2.675----'), + (2.675, '015.3e', '0000002.675e+00'), + (1.0005, 'g', '1.0005'), + (1.0005, '.3g', '1'), + (1.0005, '.10g', '1.0005'), + (1.0005, '.1g', '1'), + (1.0005, '.0g', '1'), + (1.0005, 'e', '1.000500e+00'), + (1.0005, '.2e', '1.00e+00'), + (1.0005, '.0e', '1e+00'), + (1.0005, '.12e', '1.000500000000e+00'), + (1.0005, 'G', '1.0005'), + (1.0005, 'E', '1.000500E+00'), + (1.0005, '', '1.0005'), + (1.0005, '.4', '1.0'), + (1.0005, '+g', '+1.0005'), + (1.0005, ' g', ' 1.0005'), + (1.0005, '10.3g', ' 1'), + (1.0005, ',g', '1.0005'), + (1.0005, '_.3e', '1.000e+00'), + (1.0005, '.17g', '1.0004999999999999'), + (1.0005, '#g', '1.00050'), + (1.0005, '#.3g', '1.00'), + (1.0005, '-^12.4g', '-----1------'), + (1.0005, '015.3e', '0000001.000e+00'), + (1.234e-05, 'g', '1.234e-05'), + (1.234e-05, '.3g', '1.23e-05'), + (1.234e-05, '.10g', '1.234e-05'), + (1.234e-05, '.1g', '1e-05'), + (1.234e-05, '.0g', '1e-05'), + (1.234e-05, 'e', '1.234000e-05'), + (1.234e-05, '.2e', '1.23e-05'), + (1.234e-05, '.0e', '1e-05'), + (1.234e-05, '.12e', '1.234000000000e-05'), + (1.234e-05, 'G', '1.234E-05'), + (1.234e-05, 'E', '1.234000E-05'), + (1.234e-05, '', '1.234e-05'), + (1.234e-05, '.4', '1.234e-05'), + (1.234e-05, '+g', '+1.234e-05'), + (1.234e-05, ' g', ' 1.234e-05'), + (1.234e-05, '10.3g', ' 1.23e-05'), + (1.234e-05, ',g', '1.234e-05'), + (1.234e-05, '_.3e', '1.234e-05'), + (1.234e-05, '.17g', '1.234e-05'), + (1.234e-05, '#g', '1.23400e-05'), + (1.234e-05, '#.3g', '1.23e-05'), + (1.234e-05, '-^12.4g', '-1.234e-05--'), + (1.234e-05, '015.3e', '0000001.234e-05'), + (7.0, 'g', '7'), + (7.0, '.3g', '7'), + (7.0, '.10g', '7'), + (7.0, '.1g', '7'), + (7.0, '.0g', '7'), + (7.0, 'e', '7.000000e+00'), + (7.0, '.2e', '7.00e+00'), + (7.0, '.0e', '7e+00'), + (7.0, '.12e', '7.000000000000e+00'), + (7.0, 'G', '7'), + (7.0, 'E', '7.000000E+00'), + (7.0, '', '7.0'), + (7.0, '.4', '7.0'), + (7.0, '+g', '+7'), + (7.0, ' g', ' 7'), + (7.0, '10.3g', ' 7'), + (7.0, ',g', '7'), + (7.0, '_.3e', '7.000e+00'), + (7.0, '.17g', '7'), + (7.0, '#g', '7.00000'), + (7.0, '#.3g', '7.00'), + (7.0, '-^12.4g', '-----7------'), + (7.0, '015.3e', '0000007.000e+00'), + (99999.95, 'g', '99999.9'), + (99999.95, '.3g', '1e+05'), + (99999.95, '.10g', '99999.95'), + (99999.95, '.1g', '1e+05'), + (99999.95, '.0g', '1e+05'), + (99999.95, 'e', '9.999995e+04'), + (99999.95, '.2e', '1.00e+05'), + (99999.95, '.0e', '1e+05'), + (99999.95, '.12e', '9.999995000000e+04'), + (99999.95, 'G', '99999.9'), + (99999.95, 'E', '9.999995E+04'), + (99999.95, '', '99999.95'), + (99999.95, '.4', '1e+05'), + (99999.95, '+g', '+99999.9'), + (99999.95, ' g', ' 99999.9'), + (99999.95, '10.3g', ' 1e+05'), + (99999.95, ',g', '99,999.9'), + (99999.95, '_.3e', '1.000e+05'), + (99999.95, '.17g', '99999.949999999997'), + (99999.95, '#g', '99999.9'), + (99999.95, '#.3g', '1.00e+05'), + (99999.95, '-^12.4g', '---1e+05----'), + (99999.95, '015.3e', '0000001.000e+05'), + (1e+100, 'g', '1e+100'), + (1e+100, '.3g', '1e+100'), + (1e+100, '.10g', '1e+100'), + (1e+100, '.1g', '1e+100'), + (1e+100, '.0g', '1e+100'), + (1e+100, 'e', '1.000000e+100'), + (1e+100, '.2e', '1.00e+100'), + (1e+100, '.0e', '1e+100'), + (1e+100, '.12e', '1.000000000000e+100'), + (1e+100, 'G', '1E+100'), + (1e+100, 'E', '1.000000E+100'), + (1e+100, '', '1e+100'), + (1e+100, '.4', '1e+100'), + (1e+100, '+g', '+1e+100'), + (1e+100, ' g', ' 1e+100'), + (1e+100, '10.3g', ' 1e+100'), + (1e+100, ',g', '1e+100'), + (1e+100, '_.3e', '1.000e+100'), + (1e+100, '.17g', '1e+100'), + (1e+100, '#g', '1.00000e+100'), + (1e+100, '#.3g', '1.00e+100'), + (1e+100, '-^12.4g', '---1e+100---'), + (1e+100, '015.3e', '000001.000e+100'), +] + + +class FloatFormatTableTests(unittest.TestCase): + def test_rows(self): + for _ in range(3): + for value, spec, want in ROWS: + self.assertEqual(format(value, spec), want, (value, spec)) + + def test_percent_style(self): + for value, spec, want in ROWS: + if spec in ("g", "e", ".3g", ".2e", "G", "E"): + self.assertEqual(("%" + spec) % value, want, (value, spec)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_float_exponent_format.py b/tests/regrtest/test_float_exponent_format.py new file mode 100644 index 000000000..5c6da56f6 --- /dev/null +++ b/tests/regrtest/test_float_exponent_format.py @@ -0,0 +1,86 @@ +"""Exponent-form float formatting (`format(x, '.Ne')`, `'%.Ne'`, `E`) is +correctly rounded. + +Most values are rounded from their shortest digits; the result must +equal the exact binary value rounded half to even, for values whose +shortest digits are shorter or longer than the precision, ties in those +digits, carries into a new power of ten, and subnormal and extreme +values. +""" + +import random +import struct +import unittest +from fractions import Fraction + + +def reference(x, prec, upper=False): + if x == 0: + mant, exp = "0" + ("." + "0" * prec if prec else ""), 0 + else: + q = Fraction(abs(x)) + exp = len(str(int(q))) - 1 if q >= 1 else -len(str(int(1 / q))) + # (The exponent with 10**exp <= q < 10**(exp + 1).) + while Fraction(10) ** exp > q: + exp -= 1 + while Fraction(10) ** (exp + 1) <= q: + exp += 1 + n = round(q / Fraction(10) ** (exp - prec)) # half to even + if n == 10 ** (prec + 1): + n //= 10 + exp += 1 + d = str(n) + mant = d[0] + ("." + d[1:] if prec else "") + neg = x < 0 or (x == 0 and str(x).startswith("-")) + s = ("-" if neg else "") + mant + "e" + ("-" if exp < 0 else "+") + str(abs(exp)).rjust(2, "0") + return s.upper() if upper else s + + +def values(): + r = random.Random(11) + vals = [0.0, -0.0, 0.5, 1.5, 2.5, 0.125, 0.375, 3.14159, 2.675, 1.005, 9.9995, + 9.5, 99.5, 0.95, 9.999999999999999, 1e22, 1e23, 5e-324, 2.2250738585072014e-308, + 1.7976931348623157e308, 123456789.0, 1234.5678, 0.1, 0.2, 0.30000000000000004, + 1 / 3, 2 / 3, 100.0, 1e-7, 6.02214076e23, 1.25e-5] + vals += [r.uniform(-1e6, 1e6) for _ in range(1500)] + vals += [r.uniform(1, 10) * float("1e%d" % r.randint(-30, 30)) for _ in range(1500)] + # (Short decimals: their shortest digits are fewer than many + # precisions ask for, and some end on a tie.) + vals += [float("%d.%de%d" % (r.randint(0, 99), r.randint(0, 999), r.randint(-10, 10))) + for _ in range(1500)] + for _ in range(1500): + v = struct.unpack("5") + self.assertEqual(str(cm.exception), "__str__ returned non-string (type int)") + + def test_replaced(self): + class K: + def __str__(self): + return "one" + + k = K() + out = [] + for i in range(2000): + out.append(format(k)) + K.__format__ = lambda self, spec: "two" + for i in range(2000): + out.append(format(k)) + self.assertEqual((out.count("one"), out.count("two")), (2000, 2000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_format_dunder_direct.py b/tests/regrtest/test_format_dunder_direct.py new file mode 100644 index 000000000..0bd4f986b --- /dev/null +++ b/tests/regrtest/test_format_dunder_direct.py @@ -0,0 +1,122 @@ +"""Compiled f-string formatting calls a class's Python `__format__` +directly; the text with and without a spec, a `str` subclass result, a +non-string result's TypeError, raises (caught in the frame or past it), +objects without their own `__format__`, and a method replaced later +match the general formatting.""" + +import unittest + + +class K: + def __init__(self, a, b): + self.a = a + self.b = b + self.calls = 0 + + def fmt(self): + return "K(%r, %r)" % (self.a, self.b) + + def __format__(self, spec): + self.calls += 1 + return format(self.fmt(), spec) + + +class S(str): + pass + + +class SubResult: + def __format__(self, spec): + return S("sub" + spec) + + +class Bad: + def __format__(self, spec): + return 42 + + +class Raiser: + def __format__(self, spec): + raise KeyError(spec) + + +class Plain: + def __repr__(self): + return "Plain()" + + +class FormatDunderDirect(unittest.TestCase): + def test_text(self): + k = K(1, "x") + for i in range(3000): + self.assertEqual(f"{k}", "K(1, 'x')") + self.assertEqual(f"<{k:>12}>", "< K(1, 'x')>") + self.assertEqual(f"{k:.3}", "K(1") + self.assertEqual(k.calls, 9000) + + def test_dynamic_spec(self): + k = K(2, 3) + for w in range(500): + width = w % 15 + self.assertEqual(f"{k:{width}}", format(k.fmt(), str(width))) + + def test_subclass_result(self): + o = SubResult() + for i in range(1000): + r = f"{o:z}" + self.assertEqual(r, "subz") + self.assertEqual(f"[{o}]", "[sub]") + + def test_bad_result(self): + b = Bad() + for i in range(500): + with self.assertRaises(TypeError) as cm: + f"{b}" + self.assertEqual(str(cm.exception), "__format__ must return a str, not int") + + def test_raises(self): + r = Raiser() + n = 0 + for i in range(1000): + try: + f"{r:q}" + except KeyError as e: + n += 1 + self.assertEqual(e.args, ("q",)) + self.assertEqual(n, 1000) + + def show(o): + return f"({o})" + + for i in range(1000): + with self.assertRaises(KeyError): + show(r) + self.assertEqual(show(K(i, 0)), "(K(%d, 0))" % i) + + def test_plain_objects(self): + p = Plain() + for i in range(1000): + self.assertEqual(f"{p!r}", "Plain()") + self.assertEqual(f"{p}", "Plain()") + self.assertEqual(f"{i:03}", "%03d" % i) + + def test_replaced(self): + class C: + def __format__(self, spec): + return "a" + + c = C() + out = [] + for i in range(1000): + out.append(f"{c}") + C.__format__ = lambda self, spec: "b" + spec + for i in range(1000): + out.append(f"{c:s}") + del C.__format__ + self.assertTrue(f"{c}".startswith("<")) + self.assertEqual(out.count("a"), 1000) + self.assertEqual(out.count("bs"), 1000) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_format_kwargs_mapping.py b/tests/regrtest/test_format_kwargs_mapping.py new file mode 100644 index 000000000..c34b7e303 --- /dev/null +++ b/tests/regrtest/test_format_kwargs_mapping.py @@ -0,0 +1,50 @@ +"""`template.format(**d)` formats from the mapping the call built. + +An exact string's `format` called with only a `**` mapping of string keys +reads it as `format_map` would; whatever that can't render plainly +(positional fields, missing names, values with their own `__format__`) +keeps the general call and its errors. +""" + +import unittest + +N = 3000 + + +class Money: + def __format__(self, spec): + return "$" + spec + + +class FormatKwargsTests(unittest.TestCase): + def test_plain_values(self): + D = {"a": 1, "b": "x", "c": 2.5} + for _ in range(N): + r = "{a}-{b}-{c:.1f}".format(**D) + self.assertEqual(r, "1-x-2.5") + self.assertEqual(D, {"a": 1, "b": "x", "c": 2.5}) + + def test_errors_match(self): + for _ in range(100): + with self.assertRaises(KeyError): + "{zz}".format(**{"a": 1}) + with self.assertRaises(IndexError): + "{0}".format(**{"a": 1}) + + def test_custom_format_and_attributes(self): + class P: + x = 7 + + for _ in range(N): + r = "{m:5}|{p.x}".format(**{"m": Money(), "p": P()}) + self.assertEqual(r, "$5|7") + + def test_merged_mappings(self): + D = {"a": 1} + for _ in range(N): + r = "{a}{b}".format(**D, b=2) + self.assertEqual(r, "12") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_format_spec_align_bigint.py b/tests/regrtest/test_format_spec_align_bigint.py new file mode 100644 index 000000000..03d651802 --- /dev/null +++ b/tests/regrtest/test_format_spec_align_bigint.py @@ -0,0 +1,29 @@ +"""Format specs: alignment, and big ints with float presentation types. + +Padding and alignment (`>`, `<`, `^`, `=`, fill characters, widths the +value already meets) give CPython's strings, and a big int formatted with +`f`, `e`, `%` or `g` converts as `float(n)` does, raising `OverflowError` +when it can't. Run past the compile threshold. +""" + + +def run(n): + for i in range(n): + assert "{:>8}|{:<6}|{:^7}|{:*^9}".format("ab", 7, "x", -3) == " ab|7 | x |***-3****" + assert format(-42, "=+8") == "- 42" and format(255, "#010x") == "0x000000ff" + assert format("héllo", ">7") == " héllo" and format("toolong", ">3") == "toolong" + assert format(10**20, ".2f") == "100000000000000000000.00" + assert format(-10**20, "e") == "-1.000000e+20" + assert "%.1f" % 10**20 == "100000000000000000000.0" + assert f"{10**18:%}" == "100000000000000000000.000000%" + assert format(10**20, "g") == "1e+20" + + +run(2000) +try: + format(10**400, ".2f") +except OverflowError: + pass +else: + raise AssertionError("a huge int as a float") +print("ok") diff --git a/tests/regrtest/test_format_spec_percent_long.py b/tests/regrtest/test_format_spec_percent_long.py new file mode 100644 index 000000000..10c37ab78 --- /dev/null +++ b/tests/regrtest/test_format_spec_percent_long.py @@ -0,0 +1,43 @@ +"""Format specs in hot loops: the `%` type, non-ASCII fill characters, +and specs longer than a short spec's stack buffer. + +Each must render as CPython renders it (the `%` sign counts toward the +width, zero padding included), and an invalid long spec must raise the +same error. +""" + +import unittest + +CASES = [ + (0.256, ".2%", "25.60%"), + (0.5, "%", "50.000000%"), + (-0.125, "+.1%", "-12.5%"), + (0.1, "010.3%", "00010.000%"), + (1234.5, "é^20,.2f", "é" * 6 + "1,234.50" + "é" * 6), + (7, "→>8", "→" * 7 + "7"), + (3.14159, "0>30.10f", "0000000000000000003.1415900000"), + (255, "#x", "0xff"), + (12345678, "_", "12_345_678"), + (1.5, "*>0000000000000000000000020.3f", "*" * 15 + "1.500"), + (2.5, "é<00000000000000000000012.1%", "250.0%" + "é" * 6), +] + + +class FormatSpecPercentLong(unittest.TestCase): + def test_cases(self): + for _ in range(1000): + for value, spec, want in CASES: + self.assertEqual(format(value, spec), want) + self.assertEqual(("{:" + spec + "}").format(value), want) + + def test_percent_loop(self): + for i in range(3000): + self.assertEqual("{:.1%}".format(i / 1000), "%.1f%%" % (i / 10)) + + def test_invalid_long_spec(self): + with self.assertRaises(ValueError): + format(1.5, " " * 25 + ">5") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_forwarding_wrapper_callbacks.py b/tests/regrtest/test_forwarding_wrapper_callbacks.py new file mode 100644 index 000000000..2bdb06cdc --- /dev/null +++ b/tests/regrtest/test_forwarding_wrapper_callbacks.py @@ -0,0 +1,306 @@ +"""Decorator wrappers that only forward their arguments, as callbacks. + +A wrapper whose whole body is `return fn(*args, **kwargs)` (or `return +fn(*a)`), with `fn` its one free variable, called by `map`, `filter`, +`sorted` or `sum` runs its target directly when the target's call runs no +code, with no frame for the wrapper. What the full call gives must not +change: an error from the target is raised through the wrapper (its frame +in the traceback), the cell's current value is the one called, an empty +cell raises `NameError`, a wrapper that names itself recurses until +`RecursionError`, and trace hooks see both frames. +""" + +import functools +import sys +import traceback +import unittest + +ROUNDS = 3000 + + +def deco(fn): + @functools.wraps(fn) + def wrapper(*args, **kwargs): + return fn(*args, **kwargs) + + return wrapper + + +def deco_pos(fn): + def wrapper(*a): + return fn(*a) + + return wrapper + + +@deco +def inc(a): + return a + 1 + + +@deco +def add(a, b): + return a + b + + +@deco_pos +def neg(a): + return -a + + +@deco +def positive(a): + return a > 0 + + +def warm(fn, *args): + for _ in range(ROUNDS): + fn(*args) + list(map(fn, *([x] for x in args))) + + +class ForwardingWrapperTests(unittest.TestCase): + def setUp(self): + warm(inc, 1) + warm(add, 1, 2) + warm(neg, 1) + warm(positive, 1) + + def test_map_filter_sorted_sum(self): + xs = list(range(-5, 20)) + for _ in range(50): + self.assertEqual(list(map(inc, xs)), [x + 1 for x in xs]) + self.assertEqual(list(map(add, xs, xs)), [2 * x for x in xs]) + self.assertEqual(list(map(neg, xs)), [-x for x in xs]) + self.assertEqual(list(filter(positive, xs)), [x for x in xs if x > 0]) + self.assertEqual(sorted(xs, key=neg), sorted(xs, reverse=True)) + self.assertEqual(sum(map(add, xs, xs)), 2 * sum(xs)) + self.assertEqual(max(xs, key=neg), -5) + out = [] + for v in map(inc, xs): + out.append(v) + self.assertEqual(out, [x + 1 for x in xs]) + + def test_declined_items(self): + class Num: + def __init__(self, v): + self.v = v + + def __add__(self, other): + return Num(self.v + other) + + def __eq__(self, other): + return isinstance(other, Num) and self.v == other.v + + for _ in range(50): + self.assertEqual(list(map(inc, [1, 2.5, 2**80])), [2, 3.5, 2**80 + 1]) + self.assertEqual(list(map(inc, [Num(1)])), [Num(2)]) + + def test_error_names_the_wrapper(self): + for _ in range(20): + try: + list(map(inc, [1, "x"])) + except TypeError as e: + names = [f.name for f in traceback.extract_tb(e.__traceback__)] + else: + self.fail("no TypeError") + self.assertEqual(names[-2:], ["wrapper", "inc"]) + + def test_cell_rebound(self): + def make(): + def first(a): + return a + 1 + + def second(a): + return a * 10 + + target = first + + def wrapper(*args, **kwargs): + return target(*args, **kwargs) + + def switch(): + nonlocal target + target = second + + return wrapper, switch, first + + w, switch, first = make() + warm(first, 1) + for _ in range(ROUNDS): + list(map(w, [1, 2])) + self.assertEqual(list(map(w, [1, 2])), [2, 3]) + switch() + self.assertEqual(list(map(w, [1, 2])), [10, 20]) + + def test_empty_cell(self): + def make(): + def wrapper(*args): + return target(*args) + + if False: + target = None + return wrapper + + w = make() + with self.assertRaises(NameError): + list(map(w, [1])) + + def test_self_reference(self): + def make(): + def w(*a): + return w(*a) + + return w + + w = make() + with self.assertRaises(RecursionError): + list(map(w, [1])) + + def test_targets(self): + wl = deco(len) + wm = deco([10, 20, 30].index) + wt = deco(int) + ws = deco(str.upper) + for _ in range(ROUNDS): + list(map(wl, ["ab"])) + list(map(wt, ["5"])) + self.assertEqual(list(map(wl, ["", "ab", (1, 2, 3)])), [0, 2, 3]) + self.assertEqual(list(map(wm, [20, 30])), [1, 2]) + self.assertEqual(list(map(wt, ["5", 2.5])), [5, 2]) + self.assertEqual(list(map(ws, ["a", "b"])), ["A", "B"]) + with self.assertRaises(ValueError): + list(map(wm, [99])) + with self.assertRaises(ValueError): + list(map(wt, ["x"])) + + def test_code_replaced(self): + w = deco(lambda a: a + 1) + for _ in range(ROUNDS): + list(map(w, [1])) + + self.assertEqual(list(map(w, [1, 2])), [2, 3]) + + def deco2(fn): + def wrapper(*args, **kwargs): + return ("other", fn(*args, **kwargs)) + + return wrapper + + w.__code__ = deco2(None).__code__ + self.assertEqual(list(map(w, [1, 2])), [("other", 2), ("other", 3)]) + w.__code__ = deco(None).__code__ + self.assertEqual(list(map(w, [1, 2])), [2, 3]) + + w2 = deco(abs) + for _ in range(ROUNDS): + list(map(w2, [-1])) + self.assertEqual(list(map(w2, [-3])), [3]) + + def test_direct_calls(self): + # The same wrappers called from Python code. + total = 0 + for i in range(ROUNDS): + total += add(i, 1) + inc(i) + neg(i) + self.assertEqual(total, sum(range(ROUNDS)) + 2 * ROUNDS) + for _ in range(20): + self.assertEqual(add(2.5, 1), 3.5) + self.assertEqual(add("a", "b"), "ab") + try: + add(1, "x") + except TypeError as e: + names = [f.name for f in traceback.extract_tb(e.__traceback__)] + else: + self.fail("no TypeError") + self.assertEqual(names[-2:], ["wrapper", "add"]) + + def test_direct_calls_rebound_and_methods(self): + def make(): + def first(a): + return a + 1 + + def second(a): + return a * 10 + + target = first + + def wrapper(*args): + return target(*args) + + def switch(): + nonlocal target + target = second + + return wrapper, switch + + w, switch = make() + out = [w(i) for i in range(ROUNDS)] + self.assertEqual(out[-1], ROUNDS) + switch() + self.assertEqual([w(i) for i in range(3)], [0, 10, 20]) + + class C: + def __init__(self, v): + self.v = v + + @deco + def get(self, k): + return self.v + k + + c = C(5) + self.assertEqual(sum(c.get(i) for i in range(ROUNDS)), 5 * ROUNDS + sum(range(ROUNDS))) + self.assertEqual(C(1).get(2), 3) + + @deco + def loopy(n): + t = 0 + for i in range(n): + t += i + return t + + self.assertEqual([loopy(4) for _ in range(ROUNDS)][-1], 6) + + @deco + def kw(a, b=2, *, c=3): + return a + b + c + + self.assertEqual([kw(i) for i in range(ROUNDS)][-1], ROUNDS - 1 + 5) + self.assertEqual(kw(1, c=0), 3) + with self.assertRaises(TypeError): + kw() + + def test_trace_hook(self): + calls = [] + + def tracer(frame, event, arg): + if event == "call": + calls.append(frame.f_code.co_name) + return None + + sys.settrace(tracer) + try: + got = list(map(inc, [1, 2])) + finally: + sys.settrace(None) + self.assertEqual(got, [2, 3]) + self.assertEqual(calls, ["wrapper", "inc", "wrapper", "inc"]) + + def test_profile_hook(self): + calls = [] + + def prof(frame, event, arg): + if event == "call": + calls.append(frame.f_code.co_name) + + sys.setprofile(prof) + try: + got = sorted([3, 1, 2], key=neg) + finally: + sys.setprofile(None) + self.assertEqual(got, [3, 2, 1]) + self.assertEqual(calls.count("wrapper"), 3) + self.assertEqual(calls.count("neg"), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_framed_init_constructors.py b/tests/regrtest/test_framed_init_constructors.py new file mode 100644 index 000000000..2fa6d837d --- /dev/null +++ b/tests/regrtest/test_framed_init_constructors.py @@ -0,0 +1,74 @@ +"""Compiled constructions of classes whose `__init__` is neither +store-only nor a leaf skip the frameless attempts; the instances, a +`super().__init__` chain, defaults, an `__init__` replaced later by a +store-only or a leaf one (and back), and a subclass that inherits it +match the general construction.""" + +import unittest + + +class Base: + def __init__(self, x, y=0): + self.x = x + self.y = y + + +class Child(Base): + def __init__(self, x): + super().__init__(x, 1) + self.z = x * 2 + + +class Grand(Child): + pass + + +class Logged: + log = [] + + def __init__(self, x, tag="t"): + Logged.log.append(tag) + self.x = x + + +class FramedInitConstructors(unittest.TestCase): + def test_instances(self): + out = [] + for i in range(3000): + c = Child(i) + g = Grand(i + 1) + out.append((c.x, c.y, c.z, g.x, g.z, type(g).__name__)) + self.assertEqual(out[5], (5, 1, 10, 6, 12, "Grand")) + Logged.log.clear() + for i in range(3000): + self.assertEqual(Logged(i).x, i) + Logged(i, tag="u") + self.assertEqual(Logged.log.count("t"), 3000) + self.assertEqual(Logged.log.count("u"), 3000) + + def test_replaced_init(self): + class K: + def __init__(self, a): + self.a = [a] + self.b = len(self.a) + + def store_only(self, a): + self.a = a + + def leafish(self, a): + self.a = a + 1 + + orig = K.__init__ + out = [] + for phase, init in enumerate((orig, store_only, leafish, orig)): + K.__init__ = init + for i in range(2000): + out.append(K(i).a) + self.assertEqual(out[1], [1]) + self.assertEqual(out[2001], 1) + self.assertEqual(out[4001], 2) + self.assertEqual(out[6001], [1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_fresh_receiver_field_read.py b/tests/regrtest/test_fresh_receiver_field_read.py new file mode 100644 index 000000000..e3a0aacee --- /dev/null +++ b/tests/regrtest/test_fresh_receiver_field_read.py @@ -0,0 +1,128 @@ +"""`C(...).field` of a fresh instance, the read releasing its last reference. + +The frame JIT's field cache answers the read, then the instance goes. The +value must outlive the instance, the instance's finalizer and weak +reference callbacks must run at the read, before the next statement, and +a slotted class or a field shadowed later must read as the general path +reads it. +""" + +import gc +import unittest +import weakref + + +class Plain: + def __init__(self, a): + self.a = a + 1 + self.b = [a] + + +class Logged: + def __init__(self, a, log): + self.a = a + self.log = log + + def __del__(self): + self.log.append("del") + + +class Slotted: + __slots__ = ("a", "b") + + def __init__(self, a): + self.a = a + self.b = [a] + + +class FreshReceiverFieldRead(unittest.TestCase): + def test_value_outlives_instance(self): + t = 0 + kept = [] + for i in range(3000): + t += Plain(i).a + kept.append(Plain(i).b) + self.assertEqual(t, sum(range(1, 3001))) + self.assertEqual(kept[-1], [2999]) + self.assertEqual(len(kept), 3000) + + def test_finalizer_runs_at_the_read(self): + log = [] + for i in range(3000): + log.append(Logged(i, log).a) + self.assertEqual(log[:4], ["del", 0, "del", 1]) + self.assertEqual(log[-2:], ["del", 2999]) + self.assertEqual(len(log), 6000) + + def test_finalizer_runs_at_a_polymorphic_read(self): + class L2(Logged): + pass + + class L3(Logged): + pass + + class L4(Logged): + pass + + kinds = (Logged, L2, L3, L4) + log = [] + for i in range(3000): + log.append(kinds[i % 4](i, log).a) + self.assertEqual(log[0::2], ["del"] * 3000) + self.assertEqual(log[1::2], list(range(3000))) + + def test_weakref_callback_runs_at_the_read(self): + log = [] + + def make(i): + p = Plain(i) + refs.append(weakref.ref(p, lambda r: log.append("gone"))) + return p + + refs = [] + for i in range(2000): + log.append(make(i).a) + refs.clear() + self.assertEqual(log[:4], ["gone", 1, "gone", 2]) + self.assertEqual(len(log), 4000) + + def test_slotted(self): + t = 0 + for i in range(3000): + t += Slotted(i).a + len(Slotted(i).b) + self.assertEqual(t, sum(range(3000)) + 3000) + + def test_shadowed_mid_loop(self): + class K: + def __init__(self, a): + self.a = a + + out = [] + for i in range(3000): + if i == 1500: + K.a = property(lambda self: -1, lambda self, v: None) + out.append(K(i).a) + self.assertEqual(out[1499], 1499) + self.assertEqual(out[1500:], [-1] * 1500) + + def test_cycle_kept_until_collection(self): + class Cyc: + def __init__(self, a): + self.a = a + self.me = self + + gc.collect() + refs = [] + t = 0 + for i in range(2000): + c = Cyc(i) + refs.append(weakref.ref(c)) + del c + t += Cyc(i).a + self.assertEqual(t, sum(range(2000))) + gc.collect() + self.assertTrue(all(r() is None for r in refs)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_frozen_cache_dont_write_bytecode.py b/tests/regrtest/test_frozen_cache_dont_write_bytecode.py index cd0eb0202..4a497b3b4 100644 --- a/tests/regrtest/test_frozen_cache_dont_write_bytecode.py +++ b/tests/regrtest/test_frozen_cache_dont_write_bytecode.py @@ -43,7 +43,8 @@ def run(cache, cwd, code, dont_write): 'print(json.dumps({"v": frozen_cache_user_mod.VALUE}))\n') assert run(cache, directory, code, True) == '{"v": 7}\n' names = cached_names(cache) - assert 'json' in names or 'json.decoder' in names, sorted(names)[:20] + # (Artifacts are named by module and source hash: `json.`.) + assert any(n.split('.')[0] == 'json' for n in names), sorted(names)[:20] # The user module's bytecode stays unwritten under -B. assert not os.path.exists(os.path.join(directory, '__pycache__')) # A second process reads what the first wrote. diff --git a/tests/regrtest/test_frozen_cache_source_keys.py b/tests/regrtest/test_frozen_cache_source_keys.py new file mode 100644 index 000000000..063f824a8 --- /dev/null +++ b/tests/regrtest/test_frozen_cache_source_keys.py @@ -0,0 +1,65 @@ +"""The frozen code cache keys each artifact by its module's source. + +Artifacts are named `.`, so builds whose embedded +sources differ keep one each instead of replacing each other's at every +start. Writing one removes the same module's artifacts for other sources +(and an earlier layout's unhashed one) once they are a day old, and +keeps fresher ones. +""" + +import os +import subprocess +import sys +import tempfile +import time + + +def run(cache): + env = dict(os.environ) + env['WEAVEPY_FROZEN_CACHE'] = cache + env.pop('PYTHONDONTWRITEBYTECODE', None) + result = subprocess.run([sys.executable, '-c', 'import json; print(json.dumps(1))'], + env=env, capture_output=True, text=True, timeout=120) + assert result.returncode == 0, (result.stdout, result.stderr) + return result.stdout + + +def artifact_dir(cache): + for root, _dirs, files in os.walk(cache): + if any(f.split('.')[0] == 'json' for f in files): + return root + return None + + +if sys.implementation.name == 'weavepy': + with tempfile.TemporaryDirectory() as cache: + assert run(cache) == '1\n' + directory = artifact_dir(cache) + assert directory is not None + mine = [f for f in os.listdir(directory) + if f.startswith('json.') and f.count('.') == 1] + assert len(mine) == 1, mine + # Another build's artifacts: an old and a fresh one, and an old + # unhashed one. + old = time.time() - 3 * 24 * 3600 + stale = os.path.join(directory, 'json.' + '0' * 16) + fresh = os.path.join(directory, 'json.' + 'f' * 16) + legacy = os.path.join(directory, 'json') + for path in (stale, fresh, legacy): + with open(path, 'wb') as f: + f.write(b'not an artifact') + os.utime(stale, (old, old)) + os.utime(legacy, (old, old)) + # A start that writes `json` again (its own artifact gone). + os.remove(os.path.join(directory, mine[0])) + assert run(cache) == '1\n' + assert os.path.exists(os.path.join(directory, mine[0])) + assert not os.path.exists(stale) + assert not os.path.exists(legacy) + assert os.path.exists(fresh) + # And a start that finds its own reads it, writing nothing. + before = os.stat(os.path.join(directory, mine[0])).st_mtime_ns + assert run(cache) == '1\n' + assert os.stat(os.path.join(directory, mine[0])).st_mtime_ns == before + +print('frozen cache source keys: ok') diff --git a/tests/regrtest/test_frozenset_tracking.py b/tests/regrtest/test_frozenset_tracking.py new file mode 100644 index 000000000..6e2737844 --- /dev/null +++ b/tests/regrtest/test_frozenset_tracking.py @@ -0,0 +1,40 @@ +"""Collector tracking of frozensets. + +A frozenset of atomic values can't be part of a cycle; `gc.is_tracked` +still answers `True` for every frozenset, as CPython's does. A frozenset +holding an object that can close a cycle is tracked from birth, and the +cycle through it is collected. +""" + +import gc +import weakref + + +class Node: + def __hash__(self): + return id(self) + + +def build(n): + out = [] + for i in range(n): + out.append(frozenset((i, "a", None, 2.5, b"x"))) + return out + + +for fs in build(3000)[:3]: + assert gc.is_tracked(fs) +assert gc.is_tracked(frozenset()) +assert gc.is_tracked(frozenset([(1, 2)])) + +collected = [] +for _ in range(200): + node = Node() + node.ref = frozenset([node]) + weakref.finalize(node, collected.append, 1) + assert gc.is_tracked(node.ref) + del node +gc.collect() +assert len(collected) == 200, len(collected) +assert frozenset((1, 2)) | {3} == {1, 2, 3} +print("ok") diff --git a/tests/regrtest/test_fstring_seq_repr_and_dict_views.py b/tests/regrtest/test_fstring_seq_repr_and_dict_views.py new file mode 100644 index 000000000..aa4d26c7f --- /dev/null +++ b/tests/regrtest/test_fstring_seq_repr_and_dict_views.py @@ -0,0 +1,41 @@ +"""f-string `!r` of scalar lists and tuples, and generator loops over dict views. + +Compiled code renders `{x!r}` of a list or tuple of plain scalars in place, +and steps a generator expression's dict view to its end in place (the +generator's `.0` holds the iterator too). Lists or tuples holding anything +else, a dict changed during iteration, and an exhausted view's iterator +must still behave as CPython's. Run it past the compile threshold. +""" + + +class R: + def __repr__(self): + return "R!" + + +def render(x): + return f"<{x!r}>" + + +d = {"a": 1, "b": 2} +for _ in range(3000): + assert render([]) == "<[]>" + assert render([1, "x", None, 2.5, True]) == "<[1, 'x', None, 2.5, True]>" + assert render((1,)) == "<(1,)>" and render(()) == "<()>" + assert render([R()]) == "<[R!]>" + assert render(("it's",)) == '<("it\'s",)>' + assert tuple(v for v in d.values() if v) == (1, 2) + assert sum(k for k, v in d.items() if k) == 0 if False else True + g = (k for k in d.keys()) + assert list(g) == ["a", "b"] and list(g) == [] + +e = {"k": 1} +g = (v for v in e.values()) +next(g) +e["z"] = 2 +try: + next(g) +except RuntimeError as ex: + assert "changed size" in str(ex), ex +else: + raise AssertionError("no RuntimeError") diff --git a/tests/regrtest/test_function_fields_and_probes.py b/tests/regrtest/test_function_fields_and_probes.py new file mode 100644 index 000000000..f51ae2b07 --- /dev/null +++ b/tests/regrtest/test_function_fields_and_probes.py @@ -0,0 +1,111 @@ +"""Reads of a function's fields and probes for names it lacks. + +`f.__defaults__`, `f.__kwdefaults__`, `f.__code__`, `f.__globals__` and +`f.__builtins__` answer in place as the full read does, an entry a function +stores winning. `getattr(f, name, default)` and `hasattr(f, name)` for a +name the function type doesn't define either (`__signature__`, +`__wrapped__`, as `inspect` asks) answer from a miss remembered on the +type, while each function's own entries still win. A generator's public +names it lacks (`hasattr(gen, "keys")`) are answered likewise. +""" + +import builtins +import functools +import inspect +import unittest + +N = 3000 + + +def f(a, b=1, *args, c, d=2, **kw): + pass + + +def plain(x): + pass + + +class FunctionAttrReadTests(unittest.TestCase): + def test_defaults_and_code(self): + for _ in range(N): + r = (f.__defaults__, f.__kwdefaults__, f.__code__, plain.__defaults__, + plain.__kwdefaults__, f.__globals__, f.__builtins__) + self.assertEqual(r[0], (1,)) + self.assertEqual(r[1], {"d": 2}) + self.assertIs(r[2], f.__code__) + self.assertEqual(r[2].co_name, "f") + self.assertEqual((r[3], r[4]), (None, None)) + self.assertIs(r[5], globals()) + self.assertIs(r[6], builtins.__dict__) + + def test_assigned_defaults(self): + def g(a=1): + return a + + out = [] + for i in range(N): + if i == N // 2: + g.__defaults__ = (5,) + out.append((g.__defaults__, g())) + self.assertEqual(out[0], ((1,), 1)) + self.assertEqual(out[-1], ((5,), 5)) + + def test_missing_names_with_defaults(self): + def g(): + pass + + seen = [] + for i in range(N): + if i == N // 3: + g.__signature__ = "sig" + if i == 2 * N // 3: + del g.__signature__ + seen.append((getattr(g, "__signature__", None), hasattr(g, "__wrapped__"))) + self.assertEqual(seen[0], (None, False)) + self.assertEqual(seen[N // 2], ("sig", False)) + self.assertEqual(seen[-1], (None, False)) + with self.assertRaises(AttributeError): + g.__signature__ + + def test_other_functions_keep_their_entries(self): + def base(): + pass + + @functools.wraps(base) + def wrapper(): + pass + + for _ in range(N): + a = (hasattr(plain, "__wrapped__"), getattr(plain, "__wrapped__", 0)) + b = (hasattr(wrapper, "__wrapped__"), getattr(wrapper, "__wrapped__", 0)) + self.assertEqual(a, (False, 0)) + self.assertEqual(b, (True, base)) + + def test_signatures(self): + for _ in range(N // 10): + s = inspect.signature(f) + t = inspect.signature(plain) + self.assertEqual(str(s), "(a, b=1, *args, c, d=2, **kw)") + self.assertEqual(str(t), "(x)") + + def test_generator_probes(self): + def gen(): + yield 1 + + async def coro(): + pass + + g = gen() + c = coro() + for _ in range(N): + r = (hasattr(g, "keys"), getattr(g, "items", "d"), hasattr(g, "send"), + hasattr(g, "gi_code"), hasattr(g, "gi_nope"), hasattr(c, "keys"), + hasattr(c, "cr_await")) + c.close() + self.assertEqual(r, (False, "d", True, True, False, False, True)) + with self.assertRaises(AttributeError): + g.keys + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_functions_with_many_parameters.py b/tests/regrtest/test_functions_with_many_parameters.py new file mode 100644 index 000000000..bb0b0f514 --- /dev/null +++ b/tests/regrtest/test_functions_with_many_parameters.py @@ -0,0 +1,96 @@ +"""Functions with very many parameters and locals. + +Generated code (a `namedtuple`'s constructor, a dataclass's `__init__`, a +template compiled to one function) can have thousands of parameters and +locals. Parsing and compiling such a function takes time in proportion to +its size, a duplicated parameter is still reported, and the function +works. +""" + +import collections +import time +import unittest + + +def source(n): + names = ["p%d" % i for i in range(n)] + args = ", ".join(names) + return "def f(%s):\n return (%s)\n" % (args, args), names + + +class ManyParameterTests(unittest.TestCase): + def test_a_function_of_two_thousand_parameters(self): + n = 2000 + src, names = source(n) + ns = {} + exec(src, ns) + f = ns["f"] + self.assertEqual(f(*range(n)), tuple(range(n))) + self.assertEqual(f.__code__.co_argcount, n) + self.assertEqual(f.__code__.co_varnames, tuple(names)) + self.assertEqual(f(**{name: i for i, name in enumerate(names)}), tuple(range(n))) + with self.assertRaises(TypeError): + f(*range(n - 1)) + + def test_a_lambda_and_keyword_only_parameters(self): + n = 1500 + names = ["q%d" % i for i in range(n)] + g = eval("lambda %s, *, %s: (%s, %s)" % (", ".join(names), ", ".join("k" + x for x in names), names[0], "k" + names[-1])) + self.assertEqual(g(*range(n), **{"k" + x: -i for i, x in enumerate(names)}), (0, -(n - 1))) + + def test_duplicates_are_reported(self): + n = 3000 + names = ["p%d" % i for i in range(n)] + for dup in (0, n // 2, n - 1): + args = ", ".join(names + [names[dup]]) + with self.assertRaises(SyntaxError) as cm: + compile("def f(%s): pass" % args, "", "exec") + self.assertIn("duplicate argument 'p%d'" % dup, str(cm.exception)) + with self.assertRaises(SyntaxError): + compile("lambda %s, *%s: 0" % (", ".join(names), names[7]), "", "eval") + with self.assertRaises(SyntaxError): + compile("def f(%s, *, %s): pass" % (", ".join(names), names[-1]), "", "exec") + + def test_many_locals(self): + n = 3000 + body = "\n".join(" v%d = %d" % (i, i) for i in range(n)) + total = " + ".join("v%d" % i for i in range(0, n, 97)) + ns = {} + exec("def g():\n%s\n return %s\n" % (body, total), ns) + self.assertEqual(ns["g"](), sum(range(0, n, 97))) + self.assertEqual(len(ns["g"].__code__.co_varnames), n) + + def test_a_wide_namedtuple(self): + n = 3000 + names = ["f%d" % i for i in range(n)] + Wide = collections.namedtuple("Wide", names) + w = Wide(*range(n)) + self.assertEqual(w, tuple(range(n))) + self.assertEqual((w.f0, w.f1499, getattr(w, names[-1])), (0, 1499, n - 1)) + self.assertEqual(w._replace(f7=-7)[7], -7) + self.assertEqual(Wide._make(range(n)), w) + self.assertEqual(len(w._asdict()), n) + + def test_time_follows_size(self): + def cost(n): + src, _ = source(n) + best = None + for _ in range(5): + t0 = time.perf_counter() + compile(src, "", "exec") + dt = time.perf_counter() - t0 + best = dt if best is None else min(best, dt) + return best + + cost(500) + small = cost(2000) + large = cost(16000) + # (Eight times the parameters took sixty times as long when each + # name was looked up by scanning the others. Linear is eight; the + # shared arm64 CI runners have measured up to 36 for the large + # compile alone, so allow 44.) + self.assertLess(large, 44 * small + 0.01, (small, large)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_fused_call_argument_runs.py b/tests/regrtest/test_fused_call_argument_runs.py new file mode 100644 index 000000000..3752d11db --- /dev/null +++ b/tests/regrtest/test_fused_call_argument_runs.py @@ -0,0 +1,78 @@ +"""Calls of small pure functions whose argument runs aren't all plain loads. + +The interpreter evaluates `f(a, b)` of a pure leaf function straight from +its operand loads when every argument is a local, a constant or a small +int. A call whose run ends otherwise (keywords, an attribute, an operator) +takes the ordinary call, with the same results. +""" + +import unittest + + +def add(a, b=10): + return a + b + + +def first(a, b, c, d, e, f, g, h): + return a + + +def neg(): + return -1 + + +class K: + def m(self, x, y=5): + return x * y + + @staticmethod + def s(x, y=2): + return x - y + + +class FusedCallArgumentRuns(unittest.TestCase): + def test_global_function_shapes(self): + out = [] + o = K() + o.v = 7 + for i in range(300): + out.append(( + add(i), + add(i, 2), + add(i, b=3), + add(b=4, a=i), + add(i, o.v), + add(i + 1, 2), + add(i, -i), + first(i, 1, 2, 3, 4, 5, 6, 7), + first(i, 1, 2, 3, 4, 5, 6, o.v), + neg(), + )) + for i, row in enumerate(out): + self.assertEqual( + row, + (i + 10, i + 2, i + 3, i + 4, i + 7, i + 3, 0, i, i, -1), + ) + + def test_method_and_static_shapes(self): + o = K() + got = [] + for i in range(300): + got.append((o.m(i), o.m(i, 2), o.m(i, y=3), o.m(i, len("ab")), + K.s(i), K.s(i, y=1), K.s(i, i * 2))) + for i, row in enumerate(got): + self.assertEqual(row, (i * 5, i * 2, i * 3, i * 2, i - 2, i - 1, -i)) + + def test_unbound_local_argument_raises(self): + def f(): + if False: + x = 1 + return add(x, 1) + + for _ in range(3): + with self.assertRaises(UnboundLocalError): + f() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_generator_lean_resumes.py b/tests/regrtest/test_generator_lean_resumes.py new file mode 100644 index 000000000..bb57a9870 --- /dev/null +++ b/tests/regrtest/test_generator_lean_resumes.py @@ -0,0 +1,386 @@ +"""A generator suspended where its compiled body has resumed before takes +a short path back in: one that asks only what can change between two +resumes. Everything else about a resume stays as the general path has +it: values sent in, exceptions thrown in, a body that stops partway, a +frame someone looked at, re-entry, and the order things are released.""" + +import gc +import sys +import unittest +import weakref + +N = 400 + + +def count(n): + for i in range(n): + yield i + + +def two_points(n): + for i in range(n): + yield i + yield -i + + +def six_points(n): + for i in range(n): + yield i + yield i + 10 + yield i + 20 + yield i + 30 + yield i + 40 + yield i + 50 + + +def echo(): + got = None + while True: + got = yield got + + +def guarded(log): + try: + for i in range(1000): + yield i + finally: + log.append("closed") + + +def catches(n): + for i in range(n): + try: + yield i + except ValueError as e: + yield ("caught", str(e)) + + +def delegating(n): + yield from count(n) + yield "after" + + +def calls_out(n, f): + for i in range(n): + yield f(i) + + +def returns_value(n): + for i in range(n): + yield i + return "done" + + +class GeneratorLeanResumes(unittest.TestCase): + def test_plain_loop(self): + for _ in range(N): + got = [] + for v in count(10): + got.append(v) + self.assertEqual(got, list(range(10))) + + def test_two_resume_points(self): + for _ in range(N): + got = [] + for v in two_points(4): + got.append(v) + self.assertEqual(got, [0, 0, 1, -1, 2, -2, 3, -3]) + + def test_more_resume_points_than_the_table_keeps(self): + for _ in range(N): + got = [] + for v in six_points(3): + got.append(v) + self.assertEqual(got, [i + k for i in range(3) for k in (0, 10, 20, 30, 40, 50)]) + a, b = six_points(2), six_points(2) + mixed = [] + for _ in range(6): + mixed.append((next(a), next(b), next(b))) + self.assertEqual(mixed[0], (0, 0, 10)) + self.assertEqual(mixed[-1], (50, 41, 51)) + self.assertEqual(next(b, "end"), "end") + + def test_next_calls(self): + for _ in range(N): + g = count(3) + got = (next(g), next(g), next(g), next(g, "end"), next(g, "end")) + self.assertEqual(got, (0, 1, 2, "end", "end")) + + def test_stop_iteration_value(self): + for _ in range(N): + g = returns_value(2) + next(g) + next(g) + with self.assertRaises(StopIteration) as cm: + next(g) + self.assertEqual(cm.exception.value, "done") + + def test_send_between_nexts(self): + for _ in range(N): + g = echo() + got = [next(g), g.send(1), next(g), g.send("x"), next(g), next(g)] + self.assertEqual(got, [None, 1, None, "x", None, None]) + + def test_throw_between_nexts(self): + for _ in range(N): + g = catches(5) + got = [next(g), next(g), g.throw(ValueError("boom")), next(g), next(g)] + self.assertEqual(got, [0, 1, ("caught", "boom"), 2, 3]) + + def test_close_runs_finally(self): + for _ in range(N): + log = [] + g = guarded(log) + for v in g: + if v == 5: + break + self.assertEqual(log, []) + g.close() + self.assertEqual(log, ["closed"]) + self.assertEqual(next(g, "end"), "end") + + def test_dropped_generator_runs_finally(self): + for _ in range(50): + log = [] + g = guarded(log) + next(g) + next(g) + del g + gc.collect() + self.assertEqual(log, ["closed"]) + + def test_reentry_inside_the_loop(self): + for _ in range(N): + g = count(10) + got = [] + for v in g: + got.append((v, next(g, None))) + self.assertEqual(got, [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]) + + def test_running_generator_refuses_reentry(self): + def selfish(): + for i in range(3): + try: + next(me) + except ValueError as e: + yield str(e) + + for _ in range(50): + me = selfish() + got = list(me) + self.assertEqual(got, ["generator already executing"] * 3) + + def test_frame_looked_at_midway(self): + for _ in range(N): + g = count(6) + got = [next(g), next(g)] + f = g.gi_frame + self.assertEqual(f.f_locals["i"], 1) + got += [next(g), next(g)] + self.assertEqual(g.gi_frame.f_locals["i"], 3) + got += list(g) + self.assertIsNone(g.gi_frame) + self.assertEqual(got, [0, 1, 2, 3, 4, 5]) + + def test_state_flags(self): + g = count(3) + for _ in range(N): + g = count(3) + self.assertFalse(g.gi_running) + self.assertFalse(g.gi_suspended) + next(g) + next(g) + self.assertTrue(g.gi_suspended) + self.assertFalse(g.gi_running) + list(g) + self.assertFalse(g.gi_suspended) + + def test_yield_from(self): + for _ in range(N): + got = [] + for v in delegating(3): + got.append(v) + self.assertEqual(got, [0, 1, 2, "after"]) + + def test_body_that_calls_python(self): + def twice(x): + return x * 2 + + for _ in range(N): + got = [] + for v in calls_out(5, twice): + got.append(v) + self.assertEqual(got, [0, 2, 4, 6, 8]) + + def test_body_that_raises(self): + def fussy(x): + if x == 3: + raise KeyError(x) + return x + + for _ in range(N): + g = calls_out(5, fussy) + got = [] + with self.assertRaises(KeyError): + for v in g: + got.append(v) + self.assertEqual(next(g, "end"), "end") + self.assertEqual(got, [0, 1, 2]) + + def test_nested_generators(self): + def outer(n): + for i in range(n): + total = 0 + for v in count(i): + total += v + yield total + + for _ in range(N): + got = [] + for v in outer(6): + got.append(v) + self.assertEqual(got, [0, 0, 1, 3, 6, 10]) + + def test_interleaved_generators(self): + for _ in range(N): + a, b = count(5), two_points(3) + got = [] + for x in a: + got.append((x, next(b, None))) + self.assertEqual(got, [(0, 0), (1, 0), (2, 1), (3, -1), (4, 2)]) + + def test_recursive_generator(self): + def walk(node): + yield node[0] + for child in node[1]: + for v in walk(child): + yield v + + tree = (1, [(2, [(4, []), (5, [])]), (3, [(6, [(7, [])])])]) + for _ in range(N): + got = [] + for v in walk(tree): + got.append(v) + self.assertEqual(got, [1, 2, 4, 5, 3, 6, 7]) + + def test_deep_recursion_raises(self): + def deep(n): + if n: + for v in deep(n - 1): + yield v + yield n + + self.assertEqual(sum(deep(50)), sum(range(51))) + with self.assertRaises(RecursionError): + for _ in deep(sys.getrecursionlimit() + 50): + pass + + def test_yielded_values_are_released(self): + class Node: + pass + + def makes(n): + for _ in range(n): + yield Node() + + for _ in range(50): + refs = [] + for v in makes(8): + refs.append(weakref.ref(v)) + del v + gc.collect() + self.assertEqual(sum(r() is not None for r in refs), 0) + + def test_locals_survive_between_resumes(self): + def running_total(xs): + total = 0 + seen = [] + for x in xs: + total += x + seen.append(x) + yield total, len(seen) + + for _ in range(N): + got = [] + for pair in running_total([5, 6, 7]): + got.append(pair) + self.assertEqual(got, [(5, 1), (11, 2), (18, 3)]) + + def test_exception_state_across_yields(self): + def inside_handler(): + try: + raise ValueError("inner") + except ValueError: + yield sys.exception() is not None + yield type(sys.exception()).__name__ + yield sys.exception() + + for _ in range(N): + got = [] + for v in inside_handler(): + got.append(v) + self.assertEqual(got, [True, "ValueError", None]) + + def test_consumer_in_a_handler(self): + def sees(): + for _ in range(3): + yield type(sys.exception()).__name__ + + for _ in range(N): + got = [] + try: + raise KeyError("outer") + except KeyError: + for v in sees(): + got.append(v) + self.assertEqual(got, ["KeyError"] * 3) + + def test_trace_function_sees_resumes(self): + events = [] + + def tracer(frame, event, arg): + if frame.f_code is count.__code__: + events.append(event) + return tracer + + for v in count(3): + pass + for _ in range(N): + for v in count(3): + pass + g = count(2) + next(g) + sys.settrace(tracer) + try: + rest = list(g) + finally: + sys.settrace(None) + self.assertEqual(rest, [1]) + self.assertIn("call", events) + self.assertIn("return", events) + + def test_threads_share_a_generator_in_turn(self): + import threading + + g = count(200) + got = [] + lock = threading.Lock() + + def pull(): + while True: + with lock: + v = next(g, None) + if v is None: + return + got.append(v) + + threads = [threading.Thread(target=pull) for _ in range(4)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertEqual(got, list(range(200))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_generator_native_midstep_stack.py b/tests/regrtest/test_generator_native_midstep_stack.py new file mode 100644 index 000000000..6d6b4fa5d --- /dev/null +++ b/tests/regrtest/test_generator_native_midstep_stack.py @@ -0,0 +1,127 @@ +"""A generator whose native code arrives while a consumer drains it. + +`sum(gen)`, `list(gen)` and the like can run a generator's whole body in +one step. The body gets hot and compiles during that step, and its native +code needs more value-stack room than the step started with: the stack +grows then, and the rest of the step runs natively with the same results +as the interpreted start. Run again with compiles made synchronous, so +the native code lands at the same back edge every time. +""" + +import os +import subprocess +import sys +import unittest + +N = 30000 + + +def naturals(limit): + i = 0 + while i < limit: + yield i + i += 1 + + +def squared(it): + for x in it: + yield x * x + + +def odds_only(it): + for x in it: + if x & 1: + yield x + + +def wide(it): + # A body whose deepest stack is well past the loop's own. + for x in it: + yield (x, x + 1, x + 2, x + 3, x + 4, x + 5, x + 6, x + 7, x + 8, x + 9) + + +def wide_calls(it): + for x in it: + yield max(x, x + 1, x + 2, x + 3, x + 4, x + 5, x + 6, x + 7) + min(x, 1, 2, 3, 4, 5, 6, 7) + + +class Box: + def __init__(self, v): + self.v = v + + def __del__(self): + Box.dropped += 1 + + +Box.dropped = 0 + + +def boxes(n): + i = 0 + while i < n: + yield Box(i) + i += 1 + + +def values(it): + for b in it: + yield b.v + + +class DrainTests(unittest.TestCase): + def test_sum_of_a_pipeline(self): + want = sum(x * x for x in range(N) if (x * x) & 1) + self.assertEqual(sum(odds_only(squared(naturals(N)))), want) + self.assertEqual(sum(x + 1 for x in naturals(N)), N * (N + 1) // 2) + + def test_list_and_tuple(self): + self.assertEqual(list(squared(naturals(N))), [x * x for x in range(N)]) + self.assertEqual(tuple(odds_only(naturals(N))), tuple(range(1, N, 2))) + + def test_wide_bodies(self): + got = list(wide(naturals(N))) + self.assertEqual(len(got), N) + self.assertEqual(got[0], tuple(range(10))) + self.assertEqual(got[-1], tuple(range(N - 1, N + 9))) + self.assertEqual(sum(t[9] for t in got), sum(range(9, N + 9))) + self.assertEqual( + sum(wide_calls(naturals(N))), + sum(x + 7 + min(x, 1) for x in range(N)), + ) + + def test_min_max_any_all(self): + self.assertEqual(max(squared(naturals(N))), (N - 1) ** 2) + self.assertEqual(min(odds_only(naturals(N))), 1) + self.assertTrue(all(x >= 0 for x in squared(naturals(N)))) + self.assertFalse(any(x < 0 for x in squared(naturals(N)))) + + def test_objects_are_released_on_time(self): + Box.dropped = 0 + self.assertEqual(sum(values(boxes(N))), N * (N - 1) // 2) + self.assertEqual(Box.dropped, N) + + def test_early_exit_and_reuse(self): + g = odds_only(squared(naturals(N))) + head = [next(g) for _ in range(5)] + self.assertEqual(head, [1, 9, 25, 49, 81]) + self.assertEqual(sum(g), sum(x * x for x in range(11, N) if x & 1)) + self.assertEqual(sum(g), 0) + + +class SynchronousCompileTests(unittest.TestCase): + @unittest.skipIf(os.environ.get("WEAVEPY_FRAME_JIT_SYNC"), "the synchronous run itself") + def test_synchronous_compiles(self): + env = dict(os.environ, WEAVEPY_FRAME_JIT_SYNC="1") + r = subprocess.run( + [sys.executable, __file__, "DrainTests"], + env=env, + capture_output=True, + text=True, + timeout=240, + ) + self.assertEqual(r.returncode, 0, r.stderr[-2000:]) + self.assertIn("OK", r.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_generator_short_chains.py b/tests/regrtest/test_generator_short_chains.py new file mode 100644 index 000000000..c7cc6011c --- /dev/null +++ b/tests/regrtest/test_generator_short_chains.py @@ -0,0 +1,148 @@ +"""Two- and three-level `yield from` chains of short-lived generators. + +A generator resting in a `yield from` whose delegate is itself in one +resumes through the chain collapse rather than level by level. A tree +walk's levels start, yield a few values and finish while their parents +rest in `yield from`: values must come out in order, each level's return +value must land in its parent's `yield from`, and `send`, `throw` and +`close` must reach the innermost level, run long enough for the walk's +code to compile. +""" + +import unittest + +ROUNDS = 3000 + + +class Node: + def __init__(self, v, kids=()): + self.v = v + self.kids = kids + + def walk(self): + yield self.v + for k in self.kids: + yield from k.walk() + + def walk_counted(self): + yield self.v + n = 1 + for k in self.kids: + n += yield from k.walk_counted() + return n + + +def tree(depth, fan=3, start=0): + if depth == 0: + return Node(start) + return Node(start, [tree(depth - 1, fan, start * fan + i + 1) for i in range(fan)]) + + +def preorder(node, out): + out.append(node.v) + for k in node.kids: + preorder(k, out) + return out + + +def echo_leaf(tag): + got = [] + try: + while True: + v = yield (tag, len(got)) + got.append(v) + except KeyError as e: + return (tag, got, e.args) + finally: + got.append("closed") + + +def middle(tag): + r = yield from echo_leaf(tag) + yield ("middle-got", r) + return r + + +def top(tag): + r = yield from middle(tag) + yield ("top-got", r) + + +class ShortChainTests(unittest.TestCase): + def test_order(self): + for depth in (1, 2, 3): + t = tree(depth) + want = preorder(t, []) + for _ in range(ROUNDS // depth): + self.assertEqual(list(t.walk()), want) + + def test_return_values(self): + t = tree(2) + size = len(preorder(t, [])) + for _ in range(ROUNDS): + g = t.walk_counted() + seen = [] + try: + while True: + seen.append(next(g)) + except StopIteration as e: + self.assertEqual(e.value, size) + self.assertEqual(len(seen), size) + + def test_send_throw_through_chain(self): + for i in range(ROUNDS): + g = top(i) + self.assertEqual(next(g), (i, 0)) + self.assertEqual(g.send("a"), (i, 1)) + self.assertEqual(g.send("b"), (i, 2)) + self.assertIsNotNone(g.gi_yieldfrom) + self.assertIsNotNone(g.gi_yieldfrom.gi_yieldfrom) + r = g.throw(KeyError("k")) + self.assertEqual(r, ("middle-got", (i, ["a", "b", "closed"], ("k",)))) + self.assertEqual(next(g), ("top-got", (i, ["a", "b", "closed"], ("k",)))) + with self.assertRaises(StopIteration): + next(g) + + def test_close_through_chain(self): + for i in range(ROUNDS): + g = top(i) + next(g) + g.send(1) + g.close() + self.assertIsNone(g.gi_frame) + with self.assertRaises(StopIteration): + next(g) + + def test_error_deep(self): + def bad(k): + yield k + raise ValueError(k) + + def mid(k): + yield from bad(k) + + def outer(k): + yield -1 + yield from mid(k) + + for i in range(ROUNDS): + g = outer(i) + self.assertEqual(next(g), -1) + self.assertEqual(next(g), i) + with self.assertRaises(ValueError) as cm: + next(g) + self.assertEqual(cm.exception.args, (i,)) + + def test_partial_walks(self): + t = tree(3) + want = preorder(t, []) + for i in range(ROUNDS): + k = i % len(want) + g = t.walk() + got = [next(g) for _ in range(k)] + self.assertEqual(got, want[:k]) + g.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_generator_source_adapter_drains.py b/tests/regrtest/test_generator_source_adapter_drains.py new file mode 100644 index 000000000..cbc9c92d7 --- /dev/null +++ b/tests/regrtest/test_generator_source_adapter_drains.py @@ -0,0 +1,54 @@ +"""list() of zip, map, filter and enumerate adapters with a generator +among their sources (each step taken by the general path, the pure one +skipped): results, a generator first or second in a zip and how far each +source is consumed, a map with a generator and a list, a filter whose +generator raises partway, and sources that mix generators with plain +cursors, each matching CPython.""" + +import unittest + + +def gen(n, fail_at=None): + for i in range(n): + if i == fail_at: + raise ValueError(i) + yield i + + +class AdapterGeneratorTests(unittest.TestCase): + def test_results(self): + for k in range(300): + z = list(zip([1, 2, 3], gen(5))) + m = list(map(lambda a, b: a + b, gen(3), [10, 20, 30, 40])) + f = list(filter(None, gen(4))) + e = list(enumerate(gen(2), 1)) + self.assertEqual(z, [(1, 0), (2, 1), (3, 2)]) + self.assertEqual(m, [10, 21, 32]) + self.assertEqual(f, [1, 2, 3]) + self.assertEqual(e, [(1, 0), (2, 1)]) + + def test_consumption(self): + g = gen(5) + self.assertEqual(list(zip([1, 2], g)), [(1, 0), (2, 1)]) + self.assertEqual(list(g), [2, 3, 4]) + g = gen(5) + it = iter([1, 2]) + self.assertEqual(list(zip(g, it)), [(0, 1), (1, 2)]) + self.assertEqual(list(g), [3, 4]) + g = gen(2) + xs = iter([1, 2, 3, 4]) + self.assertEqual(list(map(max, g, xs)), [1, 2]) + self.assertEqual(list(xs), [3, 4]) + + def test_raise_partway(self): + out = [] + with self.assertRaises(ValueError): + for x in filter(None, gen(5, fail_at=3)): + out.append(x) + self.assertEqual(out, [1, 2]) + with self.assertRaises(ValueError): + list(zip(gen(5, fail_at=2), [1, 2, 3])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_generator_step_properties.py b/tests/regrtest/test_generator_step_properties.py new file mode 100644 index 000000000..5623df429 --- /dev/null +++ b/tests/regrtest/test_generator_step_properties.py @@ -0,0 +1,84 @@ +"""Generator steps over builtin-subclass values, past the compile threshold. + +`email`'s header parser runs generator expressions over a `list` subclass +whose items are `str` subclasses with properties: `iter()` of a list or +tuple subclass that keeps `__iter__` iterates its value; a property read in +a generator's step runs its getter (a pure one in place, any other through +the interpreter); and the truth of a builtin subclass is its value's, +unless the class overrides `__bool__` or `__len__`. +""" + + +class Term(str): + @property + def value(self): + return self + + @property + def defects(self): + return [] + + +class Raises(str): + @property + def value(self): + raise KeyError(self) + + +class Tokens(list): + @property + def value(self): + return "".join(x.value for x in self if x.value) + + @property + def defects(self): + return sum((x.defects for x in self), []) + + def __str__(self): + return "".join(str(x) for x in self) + + +class Reversed(list): + def __iter__(self): + return iter(list.__iter__(self).__reduce__()[1][0][::-1]) + + +class Empty(str): + def __len__(self): + return 0 + + +class Falsy(str): + def __bool__(self): + return False + + +class Pair(tuple): + pass + + +toks = Tokens([Term("a"), Term(""), Term("b")]) +for _ in range(3000): + assert toks.value == "ab", toks.value + assert toks.defects == [] + assert str(toks) == "ab" + assert [x for x in Reversed([1, 2, 3])] == [3, 2, 1] + assert sum(x for x in Pair((1, 2))) == 3 + assert [bool(x) for x in (Term(""), Term("x"), Empty("x"), Falsy("x"))] == [ + False, + True, + False, + False, + ] + try: + "".join(x.value for x in Tokens([Raises("k")])) + except KeyError as e: + assert e.args == ("k",), e + else: + raise AssertionError("no KeyError") + +grow = Tokens([Term("a")]) +it = (x.value for x in grow) +assert next(it) == "a" +grow.append(Term("z")) +assert list(it) == ["z"] diff --git a/tests/regrtest/test_generator_step_stalls.py b/tests/regrtest/test_generator_step_stalls.py new file mode 100644 index 000000000..a83cbf327 --- /dev/null +++ b/tests/regrtest/test_generator_step_stalls.py @@ -0,0 +1,103 @@ +"""Generators whose bodies call Python code at every step. + +A generator body that subscripts an object with a Python `__getitem__` +(`collections.abc.Sequence.__iter__`, behind `x in path.parents`) can't +finish a native step without a call; once its steps keep stopping there, +a loop over it resumes it so the call is made directly. Results, the +`IndexError` that ends the iteration, a body whose receivers change kind, +and `Sequence`'s `in` and iteration all behave as before. +""" + +import unittest +from collections.abc import Sequence + +N = 3000 + + +class Seq: + def __init__(self, n): + self.n = n + + def __getitem__(self, i): + if i >= self.n: + raise IndexError(i) + return i * 2 + + +def gen_try(s): + i = 0 + try: + while True: + v = s[i] + yield v + i += 1 + except IndexError: + return + + +def gen_bounded(s, n): + for i in range(n): + yield s[i] + + +class Parents(Sequence): + def __init__(self, items): + self._items = items + + def __len__(self): + return len(self._items) + + def __getitem__(self, i): + return self._items[i] + + +class GeneratorStepStallTests(unittest.TestCase): + def test_python_getitem(self): + s = Seq(5) + for _ in range(N): + a = [v for v in gen_try(s)] + b = list(gen_bounded(s, 5)) + total = 0 + for v in gen_try(s): + total += v + self.assertEqual(a, [0, 2, 4, 6, 8]) + self.assertEqual(b, a) + self.assertEqual(total, 20) + + def test_receivers_change_kind(self): + out = [] + for k in range(N): + src = Seq(3) if k % 3 else [10, 20, 30] + out.append(sum(v for v in gen_bounded(src, 3))) + self.assertEqual(out[:3], [60, 6, 6]) + self.assertEqual(sum(out), (N // 3) * 60 + (N - N // 3) * 6) + + def test_errors_propagate(self): + s = Seq(2) + for _ in range(500): + with self.assertRaises(IndexError): + list(gen_bounded(s, 3)) + g = gen_bounded(s, 3) + self.assertEqual((next(g), next(g)), (0, 2)) + with self.assertRaises(IndexError): + next(g) + + def test_sequence_mixins(self): + p = Parents(["/a/b", "/a", "/"]) + for _ in range(N): + r = ("/a" in p, "/x" in p, list(p), p.index("/"), p.count("/a")) + self.assertEqual(r, (True, False, ["/a/b", "/a", "/"], 2, 1)) + + def test_generator_close_mid_iteration(self): + s = Seq(100) + for _ in range(N): + g = gen_try(s) + for v in g: + if v >= 4: + break + g.close() + self.assertEqual(v, 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_generator_throw_unstarted.py b/tests/regrtest/test_generator_throw_unstarted.py new file mode 100644 index 000000000..c1d8bea38 --- /dev/null +++ b/tests/regrtest/test_generator_throw_unstarted.py @@ -0,0 +1,43 @@ +"""`throw()` into a generator that never started. + +A `StopIteration` thrown into a generator before its first step escapes +unconverted (PEP 479's conversion covers the body past its start) and +finishes the generator; one thrown into a started generator becomes a +`RuntimeError`, and other exceptions behave as before. +""" + +import unittest + + +def gen(): + yield 1 + yield 2 + + +class ThrowUnstartedTests(unittest.TestCase): + def test_unstarted_stop_iteration(self): + for g in (gen(), (x for x in [1, 2])): + with self.assertRaises(StopIteration) as cm: + g.throw(StopIteration(5)) + self.assertEqual(cm.exception.args, (5,)) + self.assertEqual(list(g), []) + + def test_started_stop_iteration(self): + g = gen() + next(g) + with self.assertRaises(RuntimeError) as cm: + g.throw(StopIteration) + self.assertIsInstance(cm.exception.__cause__, StopIteration) + + def test_other_exceptions(self): + g = gen() + with self.assertRaises(KeyError): + g.throw(KeyError("k")) + self.assertEqual(list(g), []) + g = gen() + g.close() + self.assertEqual(list(g), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_generator_unpacking_steps.py b/tests/regrtest/test_generator_unpacking_steps.py new file mode 100644 index 000000000..2dcad5200 --- /dev/null +++ b/tests/regrtest/test_generator_unpacking_steps.py @@ -0,0 +1,301 @@ +"""Generators whose loops unpack each item (`for k, v in pairs: yield ...`). + +A body that unpacks takes the same in-place resume from a `for` loop as +one that doesn't. Exact tuples and lists unpack in the step; anything +else (a namedtuple with its own `__iter__`, an object, a generator, a +wrong length) is finished by the general resume, with CPython's results, +errors and release order. A body that calls at every step, which no +in-place step runs, still gives the same results. +""" + +import collections +import sys +import unittest + +N = 400 +PAIRS = [(i, str(i)) for i in range(12)] +NT = collections.namedtuple("NT", "a b") + + +class It: + def __init__(self, a, b): + self.a, self.b = a, b + + def __iter__(self): + return iter((self.a, self.b)) + + +class Tracked: + log = [] + + def __init__(self, n): + self.n = n + + def __del__(self): + Tracked.log.append(self.n) + + +def swapped(ps): + for a, b in ps: + yield b, a + + +def second(ps): + for a, b in ps: + yield b + + +def items(d): + for k, v in d.items(): + yield k, v + + +def numbered(xs): + for i, x in enumerate(xs): + yield i, x + + +def zipped(xs, ys): + for x, y in zip(xs, ys): + yield x + y + + +def triples(ts): + for a, b, c in ts: + yield a + b + c + + +def inner(xs): + for x in xs: + a, b = x + yield a + yield b + + +def caught(ps): + for p in ps: + try: + a, b = p + except (ValueError, TypeError) as e: + yield type(e).__name__ + else: + yield a + b + + +def helper(x): + return x + 1 + + +def calling(xs): + for x in xs: + yield helper(x) + + +def formatting(xs): + for x in xs: + yield str(x) + + +def drive(g): + out = [] + try: + for v in g: + out.append(v) + except Exception as e: + out.append((type(e).__name__, str(e))) + return out + + +def repeat(f, n=N): + last = None + for _ in range(n): + last = f() + return last + + +class UnpackingBodies(unittest.TestCase): + def test_tuples_lists_and_views(self): + self.assertEqual(repeat(lambda: drive(swapped(PAIRS))), [(b, a) for a, b in PAIRS]) + self.assertEqual(repeat(lambda: drive(second(PAIRS))), [b for _, b in PAIRS]) + lists = [[i, i + 1] for i in range(12)] + self.assertEqual(repeat(lambda: drive(swapped(lists))), [(i + 1, i) for i in range(12)]) + d = dict(PAIRS) + self.assertEqual(repeat(lambda: drive(items(d))), PAIRS) + self.assertEqual(repeat(lambda: drive(numbered("abc"))), [(0, "a"), (1, "b"), (2, "c")]) + self.assertEqual(repeat(lambda: drive(zipped(range(5), range(5, 10)))), [5, 7, 9, 11, 13]) + ts = [(i, i, i) for i in range(6)] + self.assertEqual(repeat(lambda: drive(triples(ts))), [0, 3, 6, 9, 12, 15]) + self.assertEqual(repeat(lambda: drive(inner(PAIRS[:2]))), [0, "0", 1, "1"]) + + def test_other_iterables_unpack_through_the_general_resume(self): + def mixed(): + ms = [ + (1, 2), + [3, 4], + NT(5, 6), + It(7, 8), + "ab", + {1: 2, 3: 4}.keys(), + range(2), + (x for x in (9, 10)), + ] + return drive(swapped(ms)) + + want = [(2, 1), (4, 3), (6, 5), (8, 7), ("b", "a"), (3, 1), (1, 0), (10, 9)] + self.assertEqual(repeat(mixed), want) + + def test_wrong_shapes_raise_where_they_are_met(self): + for bad, message in [ + ((1,), "not enough values to unpack (expected 2, got 1)"), + ((1, 2, 3), "too many values to unpack (expected 2, got 3)"), + ([1], "not enough values to unpack (expected 2, got 1)"), + ("abc", "too many values to unpack (expected 2)"), + ]: + for at in (0, 5, 11): + repeat(lambda: drive(swapped(PAIRS)), 100) + ps = list(PAIRS) + ps[at] = bad + want = [(b, a) for a, b in PAIRS[:at]] + [("ValueError", message)] + self.assertEqual(drive(swapped(ps)), want, (bad, at)) + ps = list(PAIRS) + ps[4] = 5 + got = drive(swapped(ps)) + self.assertEqual(got[:4], [(b, a) for a, b in PAIRS[:4]]) + self.assertEqual(got[4][0], "TypeError") + + def test_errors_caught_in_the_body(self): + def run(at, bad): + ps = [(i, i) for i in range(8)] + ps[at] = bad + return drive(caught(ps)) + + self.assertEqual(repeat(lambda: run(0, (1,)), 60), ["ValueError", 2, 4, 6, 8, 10, 12, 14]) + self.assertEqual(repeat(lambda: run(5, None), 60), [0, 2, 4, 6, 8, "TypeError", 12, 14]) + self.assertEqual(repeat(lambda: run(7, (1, 2, 3)), 60), [0, 2, 4, 6, 8, 10, 12, "ValueError"]) + + def test_next_send_throw_and_close(self): + def manual(): + g = swapped(PAIRS) + out = [next(g), next(g), g.send(None)] + try: + g.throw(KeyError("k")) + except KeyError as e: + out.append(str(e)) + out.append(list(g)) + g2 = second(PAIRS) + out.append(next(g2)) + g2.close() + out.append(list(g2)) + return out + + want = [("0", 0), ("1", 1), ("2", 2), "'k'", [], "0", []] + self.assertEqual(repeat(manual), want) + + def test_native_consumers(self): + self.assertEqual(repeat(lambda: list(second(PAIRS))), [b for _, b in PAIRS]) + self.assertEqual(repeat(lambda: sum(zipped(range(50), range(50)))), 2450) + self.assertEqual(repeat(lambda: tuple(numbered("xy"))), ((0, "x"), (1, "y"))) + self.assertEqual(repeat(lambda: dict(items({1: 2, 3: 4}))), {1: 2, 3: 4}) + self.assertEqual(repeat(lambda: ",".join(second(PAIRS[:4]))), "0,1,2,3") + self.assertEqual( + repeat(lambda: [v for v in second(swapped(swapped(PAIRS)))]), + [b for _, b in PAIRS], + ) + + def test_unpacked_values_are_released_in_order(self): + def owned(): + Tracked.log.clear() + + def src(): + for i in range(5): + yield (Tracked(i), i) + + out = [] + for b in second(src()): + out.append((b, list(Tracked.log))) + return out + + want = [(0, []), (1, [0]), (2, [0, 1]), (3, [0, 1, 2]), (4, [0, 1, 2, 3])] + self.assertEqual(repeat(owned), want) + + def test_a_pair_changed_while_suspended(self): + def mutated(): + ps = [[i, i + 1] for i in range(6)] + out = [] + try: + for b, a in swapped(ps): + out.append((a, b)) + if a == 2: + ps[3].append(99) + except ValueError as e: + out.append(str(e)) + return out + + want = [(0, 1), (1, 2), (2, 3), "too many values to unpack (expected 2, got 3)"] + self.assertEqual(repeat(mutated, 100), want) + + def test_tracing_sees_every_resume(self): + repeat(lambda: drive(swapped(PAIRS))) + events = [] + + def tracer(frame, event, arg): + if frame.f_code is swapped.__code__: + events.append((event, frame.f_lineno - frame.f_code.co_firstlineno)) + return tracer + + sys.settrace(tracer) + try: + got = drive(swapped(PAIRS[:3])) + finally: + sys.settrace(None) + self.assertEqual(got, [("0", 0), ("1", 1), ("2", 2)]) + first = [("call", 0), ("line", 1), ("line", 2), ("return", 2)] + later = [("call", 2), ("line", 1), ("line", 2), ("return", 2)] + last = [("call", 2), ("line", 1), ("return", 1)] + self.assertEqual(events, first + later * 2 + last) + self.assertEqual(repeat(lambda: drive(swapped(PAIRS))), [(b, a) for a, b in PAIRS]) + + def test_suspended_frames_are_inspectable(self): + def frames(): + g = numbered("abc") + out = [] + for i, x in g: + frame = g.gi_frame + out.append((frame.f_lineno - g.gi_code.co_firstlineno, sorted(frame.f_locals))) + out.append(g.gi_frame) + return out + + want = [(2, ["i", "x", "xs"])] * 3 + [None] + self.assertEqual(repeat(frames), want) + + +class BodiesNoStepRuns(unittest.TestCase): + def test_bodies_that_call(self): + xs = list(range(20)) + self.assertEqual(repeat(lambda: drive(calling(xs))), [x + 1 for x in xs]) + self.assertEqual(repeat(lambda: drive(formatting(xs))), [str(x) for x in xs]) + self.assertEqual(repeat(lambda: list(calling(xs))), [x + 1 for x in xs]) + self.assertEqual(repeat(lambda: sum(calling(xs))), 210) + + def test_a_call_that_raises(self): + def run(): + return drive(calling([1, 2, "x", 4])) + + got = repeat(run, 100) + self.assertEqual(got[:2], [2, 3]) + self.assertEqual(got[2][0], "TypeError") + self.assertEqual(len(got), 3) + + def test_next_and_send(self): + def manual(): + g = calling([1, 2, 3]) + out = [next(g), g.send(None)] + g.close() + out.append(next(g, "done")) + return out + + self.assertEqual(repeat(manual), [2, 3, "done"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_genexp_drain_calls.py b/tests/regrtest/test_genexp_drain_calls.py new file mode 100644 index 000000000..74456f8fe --- /dev/null +++ b/tests/regrtest/test_genexp_drain_calls.py @@ -0,0 +1,89 @@ +"""Inlined `any`, `all`, `list` and `tuple` of a generator expression that +calls a function, in compiled code. + +The generator's resume drains it into the consumer, as `sum()`'s does, +when its body calls. Deciding items stop the drain where CPython stops; +an item whose truth only `__bool__` can tell goes through it; a raise +from the body reaches the consumer's handler with the items before it +consumed; the collected items keep their order. Items are heap objects. +Run it past the compile threshold. +""" + + +class Item: + pass + + +class Truth: + def __init__(self, v): + self.v = v + + def __bool__(self): + seen.append(self.v) + return self.v + + +seen = [] +items = [Item() for _ in range(5)] + + +def ident(x): + return x + + +def neg(x): + return x < 0 + + +def boom(x): + if x == 3: + raise ValueError(x) + return x + + +def any_neg(xs): + return any(neg(x) for x in xs) + + +def all_neg(xs): + return all(neg(x) for x in xs) + + +def collect(xs): + return list(ident(x) for x in xs) + + +def as_tuple(xs): + return tuple(ident(x) for x in xs) + + +def truths(vs): + return any(Truth(v) for v in vs) + + +def raising(): + consumed = [] + try: + return list(consumed.append(x) or boom(x) for x in range(6)) + except ValueError as e: + return ("raised", e.args[0], consumed) + + +def stops_early(): + consumed = [] + found = any(consumed.append(x) or neg(x) for x in [1, -2, 3, 4]) + return found, consumed + + +for _ in range(3000): + assert any_neg([1, 2, 3]) is False and any_neg([1, -2, 3]) is True + assert all_neg([-1, -2]) is True and all_neg([-1, 2, -3]) is False + assert collect(items) == items and as_tuple(items) == tuple(items) + assert collect([]) == [] and as_tuple(()) == () + del seen[:] + assert truths([False, False, True, False]) is True + assert seen == [False, False, True], seen + del seen[:] + assert truths([False, False]) is False and seen == [False, False] + assert raising() == ("raised", 3, [0, 1, 2, 3]) + assert stops_early() == (True, [1, -2]) diff --git a/tests/regrtest/test_genexpr_heap_item_folds.py b/tests/regrtest/test_genexpr_heap_item_folds.py new file mode 100644 index 000000000..bba4ff53d --- /dev/null +++ b/tests/regrtest/test_genexpr_heap_item_folds.py @@ -0,0 +1,343 @@ +"""`all()` and `any()` over a generator that yields strings, containers +and plain instances, and `sum(lists, start)` over one that yields lists, +take those items in place: every answer, the item that decides, the +items left unconsumed, errors, and classes that change under a warm loop +match the item-by-item protocol.""" + +import unittest + +N = 1500 + + +class Plain: + def __init__(self, v): + self.v = v + + @property + def val(self): + return self.v + + +class Falsy: + def __init__(self, v): + self.v = v + + def __bool__(self): + return bool(self.v) + + +class Sized: + def __init__(self, n): + self.n = n + + def __len__(self): + return self.n + + +class Words(list): + pass + + +def consumed(make, fn): + """`fn` over a generator of `make()`'s items, and how many it took.""" + items = make() + it = iter(items) + taken = [0] + + def gen(): + for x in it: + taken[0] += 1 + yield x + + return fn(gen()), taken[0] + + +class TruthFolds(unittest.TestCase): + def test_strings(self): + strs = ["a%d" % i for i in range(10)] + objs = [Plain(s) for s in strs] + for _ in range(N): + self.assertTrue(all(x for x in strs)) + self.assertTrue(all(o.v for o in objs)) + self.assertTrue(all(o.val for o in objs)) + self.assertTrue(any(o.v for o in objs)) + self.assertFalse(any(o.v[:0] for o in objs)) + self.assertFalse(all(o.v[:0] for o in objs)) + objs[6].v = "" + for _ in range(N): + self.assertFalse(all(o.v for o in objs)) + self.assertTrue(any(o.v for o in objs)) + self.assertEqual(consumed(lambda: [o.v for o in objs], all), (False, 7)) + self.assertEqual(consumed(lambda: [o.v for o in objs], any), (True, 1)) + self.assertEqual(consumed(lambda: ["", "", "x", ""], any), (True, 3)) + self.assertEqual(consumed(lambda: ["", ""], any), (False, 2)) + self.assertEqual(consumed(lambda: ["x", "y"], all), (True, 2)) + + def test_containers(self): + full = [(1,), [1], {1: 2}, {1}, frozenset([1]), b"x", "s"] + empty = [(), [], {}, set(), frozenset(), b"", ""] + for _ in range(N): + self.assertTrue(all(x for x in full)) + self.assertFalse(any(x for x in empty)) + self.assertFalse(all(x for x in empty)) + self.assertTrue(any(x for x in full)) + for i, e in enumerate(empty): + mixed = full[:i] + [e] + full[i:] + self.assertEqual(consumed(lambda: list(mixed), all), (False, i + 1)) + mixed = empty[:i] + [full[i]] + empty[i:] + self.assertEqual(consumed(lambda: list(mixed), any), (True, i + 1)) + + def test_containers_change_between_scans(self): + rows = [[1], [2], [3]] + for _ in range(N): + self.assertTrue(all(r for r in rows)) + rows[1].clear() + self.assertFalse(all(r for r in rows)) + self.assertEqual(consumed(lambda: rows, all), (False, 2)) + rows[1].append(0) + self.assertTrue(all(r for r in rows)) + + def test_fresh_items(self): + # (Items nothing else holds go back to the consumer.) + for _ in range(N): + self.assertTrue(all([i] for i in range(5))) + self.assertTrue(all((i,) for i in range(5))) + self.assertFalse(any([] for i in range(5))) + self.assertTrue(all(Plain(i) for i in range(5))) + self.assertTrue(all(str(i) for i in range(5))) + self.assertFalse(all("x" * i for i in range(5))) + + def test_instances(self): + plain = [Plain(i) for i in range(8)] + falsy = [Falsy(1) for _ in range(8)] + sized = [Sized(2) for _ in range(8)] + words = [Words(["w"]) for _ in range(8)] + for _ in range(N): + self.assertTrue(all(p for p in plain)) + self.assertTrue(all(f for f in falsy)) + self.assertTrue(all(s for s in sized)) + self.assertTrue(all(w for w in words)) + self.assertFalse(any(not p for p in plain)) + falsy[5].v = 0 + sized[3].n = 0 + words[2].clear() + self.assertEqual(consumed(lambda: falsy, all), (False, 6)) + self.assertEqual(consumed(lambda: sized, all), (False, 4)) + self.assertEqual(consumed(lambda: words, all), (False, 3)) + self.assertEqual(consumed(lambda: plain, all), (True, 8)) + self.assertEqual(consumed(lambda: plain, any), (True, 1)) + + def test_class_gains_and_loses_truth_methods(self): + class Thing: + def __init__(self, v): + self.v = v + + things = [Thing(i) for i in range(6)] + + def scan(): + return all(t for t in things), any(t for t in things) + + for _ in range(N): + self.assertEqual(scan(), (True, True)) + Thing.__bool__ = lambda self: self.v != 3 + for _ in range(N): + self.assertEqual(scan(), (False, True)) + del Thing.__bool__ + self.assertEqual(scan(), (True, True)) + Thing.__len__ = lambda self: 0 + for _ in range(N): + self.assertEqual(scan(), (False, False)) + del Thing.__len__ + self.assertEqual(scan(), (True, True)) + + class Base: + pass + + class Derived(Base): + pass + + ds = [Derived() for _ in range(4)] + for _ in range(N): + self.assertTrue(all(d for d in ds)) + Base.__bool__ = lambda self: False + self.assertFalse(any(d for d in ds)) + del Base.__bool__ + self.assertTrue(all(d for d in ds)) + + def test_truth_that_raises(self): + class Bad: + def __bool__(self): + raise ValueError("no truth") + + items = ["a", "b", Bad(), "c"] + for _ in range(20): + with self.assertRaises(ValueError): + all(x for x in items) + self.assertTrue(any(x for x in items)) + + def test_generator_raises_after_folded_items(self): + def gen(items): + for x in items: + yield x + raise KeyError("end") + + for _ in range(20): + with self.assertRaises(KeyError): + all(gen(["a", "b", (1,)])) + self.assertFalse(all(gen(["a", "", "b"]))) + + def test_finalizers_run_in_order(self): + log = [] + + class Temp: + def __init__(self, i): + self.i = i + + def __del__(self): + log.append(self.i) + + def gen(n): + for i in range(n): + yield Temp(i) + log.append(("after", i)) + + self.assertTrue(all(gen(4))) + self.assertEqual( + log, [0, ("after", 0), 1, ("after", 1), 2, ("after", 2), 3, ("after", 3)] + ) + + def test_nested_scans(self): + class Node(list): + leaf_ok = "yes" + + @property + def ok(self): + return all(part.ok for part in self) + + class Leaf: + def __init__(self, ok): + self.ok = ok + + tree = Node([Node([Leaf("a"), Leaf("b")]), Node([Leaf("c")]), Leaf("d")]) + for _ in range(N): + self.assertTrue(tree.ok) + tree[1][0].ok = "" + self.assertFalse(tree.ok) + + +class ListSumFolds(unittest.TestCase): + def test_shared_lists(self): + rows = [[i, str(i)] for i in range(6)] + want = [x for r in rows for x in r] + for _ in range(N): + start = [] + out = sum((r for r in rows), start) + self.assertEqual(out, want) + self.assertEqual(start, []) + self.assertIsNot(out, start) + self.assertEqual(rows, [[i, str(i)] for i in range(6)]) + + def test_fresh_lists(self): + for _ in range(N): + self.assertEqual(sum(([i, [i]] for i in range(4)), []), [0, [0], 1, [1], 2, [2], 3, [3]]) + self.assertEqual(sum((list("ab") for _ in range(3)), ["s"]), ["s"] + list("ab") * 3) + + def test_attribute_lists(self): + class Part: + def __init__(self, i): + self.defects = ["d%d" % i] + + @property + def all_defects(self): + return list(self.defects) + + parts = [Part(i) for i in range(5)] + want = ["d%d" % i for i in range(5)] + for _ in range(N): + self.assertEqual(sum((p.defects for p in parts), []), want) + self.assertEqual(sum((p.all_defects for p in parts), []), want) + self.assertEqual([p.defects for p in parts], [[w] for w in want]) + + def test_the_start_list_as_an_item(self): + s = [1, 2] + for _ in range(20): + self.assertEqual(sum((s for _ in range(3)), s), [1, 2] * 4) + self.assertEqual(s, [1, 2]) + row = ["r"] + self.assertEqual(sum((row for _ in range(4)), []), ["r"] * 4) + + def test_other_items(self): + class Rows(list): + pass + + for _ in range(20): + out = sum((x for x in [[1], Rows([2]), [3], Rows([4])]), []) + self.assertEqual(out, [1, 2, 3, 4]) + self.assertIs(type(out), list) + with self.assertRaises(TypeError): + sum((x for x in [[1], [2], (3,), [4]]), []) + with self.assertRaises(TypeError): + sum((x for x in [[1], [2], 3]), []) + + def test_radd_takes_over(self): + class Tail: + def __radd__(self, other): + return ("tail", list(other)) + + for _ in range(20): + self.assertEqual(sum((x for x in [[1], [2], Tail()]), []), ("tail", [1, 2])) + + def test_generator_raises_part_way(self): + def gen(): + yield [1] + yield [2] + yield [3] + raise KeyError("stop") + + for _ in range(20): + with self.assertRaises(KeyError): + sum(gen(), []) + + def test_items_released(self): + log = [] + + class Temp: + def __init__(self, i): + self.i = i + + def __del__(self): + log.append(self.i) + + def gen(n): + for i in range(n): + yield [Temp(i)] + + out = sum(gen(4), []) + self.assertEqual(log, []) + self.assertEqual([t.i for t in out], [0, 1, 2, 3]) + del out + self.assertEqual(sorted(log), [0, 1, 2, 3]) + + def test_nested_sums(self): + class Node(list): + def __init__(self, *a): + super().__init__(*a) + self.defects = ["n"] + + @property + def all_defects(self): + return sum((x.all_defects for x in self), self.defects) + + class Leaf: + def __init__(self, d): + self.all_defects = [d] + + tree = Node([Node([Leaf("a"), Leaf("b")]), Node([Leaf("c")]), Leaf("d")]) + for _ in range(N): + self.assertEqual(tree.all_defects, ["n", "n", "a", "b", "n", "c", "d"]) + self.assertEqual(tree.defects, ["n"]) + self.assertEqual(tree[0].defects, ["n"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_genexpr_str_and_property_items.py b/tests/regrtest/test_genexpr_str_and_property_items.py new file mode 100644 index 000000000..273c32578 --- /dev/null +++ b/tests/regrtest/test_genexpr_str_and_property_items.py @@ -0,0 +1,244 @@ +"""Generator expressions that call `str()` on each item or read a property +of it, as `''.join(str(x) for x in parts)` and `all(p.ok for p in parts)` +do: `str(s)` of an exact string is the string, of a `str` subclass its +plain text, and a property stays ahead of every other read of its name +when classes, getters and instances change under a warm site.""" + +import enum +import unittest + +N = 1500 + + +class Term(str): + kind = "term" + + @property + def value(self): + return self + + +class Shout(str): + def __str__(self): + return self.upper() + + +class Color(enum.StrEnum): + RED = "red" + + +class Mixed(str, enum.Enum): + A = "a" + + +class Named: + def __init__(self, name): + self.name = name + + def __str__(self): + return self.name + + +class StrOfItems(unittest.TestCase): + def test_exact_strings_are_themselves(self): + strs = ["a%d" % i for i in range(8)] + for _ in range(N): + self.assertEqual("".join(str(x) for x in strs), "a0a1a2a3a4a5a6a7") + got = [str(x) for x in strs] + self.assertTrue(all(a is b for a, b in zip(got, strs))) + got = list(str(x) for x in strs) + self.assertTrue(all(a is b for a, b in zip(got, strs))) + + def test_str_subclass_items(self): + terms = [Term("t%d" % i) for i in range(8)] + for _ in range(N): + self.assertEqual("".join(str(x) for x in terms), "t0t1t2t3t4t5t6t7") + got = [str(x) for x in terms] + self.assertEqual({type(x) for x in got}, {str}) + self.assertEqual(got, ["t%d" % i for i in range(8)]) + self.assertEqual({type(x) for x in terms}, {Term}) + + def test_mixed_items(self): + items = ["s", Term("t"), Shout("loud"), Color.RED, Mixed.A, Named("n"), 7, 2.5, None, b"b"] + want = ["s", "t", "LOUD", "red", "Mixed.A", "n", "7", "2.5", "None", "b'b'"] + for _ in range(N): + self.assertEqual([str(x) for x in items], want) + self.assertEqual("|".join(str(x) for x in items), "|".join(want)) + + def test_class_gains_and_loses_str(self): + class Word(str): + pass + + words = [Word("w%d" % i) for i in range(4)] + + def text(): + return "".join(str(w) for w in words) + + for _ in range(N): + self.assertEqual(text(), "w0w1w2w3") + Word.__str__ = lambda self: "<" + self.lower() + ">" + for _ in range(N): + self.assertEqual(text(), "") + del Word.__str__ + self.assertEqual(text(), "w0w1w2w3") + Word.__repr__ = lambda self: "R" + self.assertEqual(text(), "w0w1w2w3") + + def test_shadowed_str(self): + def text(items, str=lambda x: "!"): + return "".join(str(x) for x in items) + + for _ in range(50): + self.assertEqual(text(["a", "b"]), "!!") + + def test_nested_token_lists(self): + class Tokens(list): + def __str__(self): + return "".join(str(x) for x in self) + + @property + def value(self): + return "".join(x.value for x in self if x.value) + + tree = Tokens([Tokens([Tokens([Term("a"), Term("b")]), Term("@")]), Tokens([Term("c")]), Term("")]) + for _ in range(N): + self.assertEqual(str(tree), "ab@c") + self.assertEqual(tree.value, "ab@c") + tree[0][0].append(Term("z")) + self.assertEqual((str(tree), tree.value), ("abz@c", "abz@c")) + + +class Part: + def __init__(self, v): + self.v = v + + @property + def val(self): + return self.v + + @property + def me(self): + return self + + +class Field: + def __init__(self, v): + self.val = v + + +class PropertyItems(unittest.TestCase): + def test_reads(self): + parts = [Part("p%d" % i) for i in range(8)] + for _ in range(N): + self.assertEqual("".join(p.val for p in parts), "p0p1p2p3p4p5p6p7") + self.assertTrue(all(p.val for p in parts)) + self.assertTrue(all(p.me is p for p in parts)) + + def test_property_and_field_at_one_site(self): + items = [Part("a"), Field("b"), Part("c"), Field("d")] * 2 + + def text(): + return "".join(x.val for x in items) + + for _ in range(N): + self.assertEqual(text(), "abcdabcd") + + def test_instance_dict_does_not_shadow(self): + parts = [Part("x") for _ in range(4)] + for _ in range(N): + self.assertEqual([p.val for p in parts], ["x"] * 4) + parts[2].__dict__["val"] = "shadow" + for _ in range(50): + self.assertEqual([p.val for p in parts], ["x"] * 4) + self.assertEqual("".join(p.val for p in parts), "xxxx") + + def test_getter_and_class_changes(self): + class Own: + def __init__(self, v): + self.v = v + + @property + def val(self): + return self.v + + items = [Own("a"), Own("b")] + + def text(): + return "".join(x.val for x in items) + + for _ in range(N): + self.assertEqual(text(), "ab") + Own.val = property(lambda self: self.v.upper()) + for _ in range(N): + self.assertEqual(text(), "AB") + + def loops(self): + out = "" + for ch in self.v: + out += ch * 2 + return out + + Own.val = property(loops) + for _ in range(N): + self.assertEqual(text(), "aabb") + Own.val = "plain" + self.assertEqual(text(), "plainplain") + items[0].val = "own" + self.assertEqual(text(), "ownplain") + del Own.val + with self.assertRaises(AttributeError): + text() + + def test_getter_that_raises(self): + class Maybe: + def __init__(self, v): + self.v = v + + @property + def val(self): + if self.v is None: + raise AttributeError("unset") + return self.v + + def __getattr__(self, name): + return "fallback" + + items = [Maybe("a"), Maybe("b"), Maybe("c")] + + def text(): + return "".join(x.val for x in items) + + for _ in range(N): + self.assertEqual(text(), "abc") + items[1].v = None + for _ in range(50): + self.assertEqual(text(), "afallbackc") + + def test_receivers_released(self): + log = [] + + class Temp: + def __init__(self, i): + self.i = i + + @property + def val(self): + return self.i + + def __del__(self): + log.append(self.i) + + def run(n): + t = 0 + for i in range(n): + t += Temp(i).val + if len(log) != i + 1: + return ("late", i, len(log)) + return t + + self.assertEqual(run(N), N * (N - 1) // 2) + self.assertEqual(sum(Temp(i).val for i in range(100, 110)), 1045) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getattr_builtin_methods.py b/tests/regrtest/test_getattr_builtin_methods.py new file mode 100644 index 000000000..e2e7db1e2 --- /dev/null +++ b/tests/regrtest/test_getattr_builtin_methods.py @@ -0,0 +1,53 @@ +"""`getattr` of a string's or container's method runs in place. + +The bound method is the one the attribute load makes (equal to it, bound +to the same receiver); a missing name still raises or takes the default, +and dunders and `hasattr` keep their own paths. +""" + +import unittest + +N = 3000 + + +class GetattrBuiltinMethodTests(unittest.TestCase): + def test_bound_like_attribute_load(self): + s, L, d = "ab", [1], {"k": 2} + for _ in range(N): + g = getattr(s, "upper") + h = getattr(L, "append") + k = getattr(d, "get") + t = getattr((1, 2, 1), "count") + b = getattr(b"x", "hex") + self.assertEqual(g, s.upper) + self.assertIs(g.__self__, s) + self.assertEqual(g(), "AB") + self.assertEqual(h, L.append) + h(5) + self.assertEqual(L, [1, 5]) + self.assertEqual(k("k"), 2) + self.assertEqual(t(1), 2) + self.assertEqual(b(), "78") + + def test_missing_and_default(self): + for _ in range(N): + r = getattr("ab", "nope", "dflt") + self.assertEqual(r, "dflt") + with self.assertRaises(AttributeError): + getattr([], "nope") + self.assertEqual(getattr([1], "__len__")(), 1) + self.assertTrue(hasattr("", "join")) + self.assertFalse(hasattr("", "nope")) + + def test_subclass_receiver(self): + class S(str): + def upper(self): + return "mine" + + for _ in range(N): + r = getattr(S("a"), "upper")() + self.assertEqual(r, "mine") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getattr_default_misses.py b/tests/regrtest/test_getattr_default_misses.py new file mode 100644 index 000000000..303a08312 --- /dev/null +++ b/tests/regrtest/test_getattr_default_misses.py @@ -0,0 +1,111 @@ +"""getattr(obj, name, default) and hasattr(obj, name) from compiled loops +when the attribute is missing: on modules (with and without a module +__getattr__, and a module that gains the name or the hook mid-loop), on +strings and containers (a method that is there, a name that isn't, and a +classmethod reached through an instance), and the built-in leaves for +int.bit_count, bytes.find and bytes.hex.""" + +import types +import unittest + + +def module_misses(m, n): + got = [] + for i in range(n): + got.append(getattr(m, "nope", i)) + got.append(hasattr(m, "nope")) + return got + + +def builtin_misses(n): + out = [] + for i in range(n): + d = {} + s = "x" + out.append(( + getattr(d, "nope", None), + getattr(s, "nope", 0), + getattr([], "nope", 1), + getattr(b"", "nope", 2), + getattr(d, "fromkeys", None) is not None, + getattr(b"", "fromhex", None) is not None, + getattr(s, "maketrans", None) is not None, + getattr(s, "upper", None)(), + )) + return out + + +class Tests(unittest.TestCase): + def test_module_without_hook(self): + m = types.ModuleType("m") + got = module_misses(m, 2000) + self.assertEqual(got[:4], [0, False, 1, False]) + self.assertEqual(got[-2:], [1999, False]) + + def test_module_with_hook(self): + m = types.ModuleType("m") + m.__getattr__ = lambda name: "hooked:" + name + got = module_misses(m, 2000) + self.assertEqual(got[:2], ["hooked:nope", True]) + self.assertEqual(got[-2:], ["hooked:nope", True]) + + def test_module_changes_mid_loop(self): + m = types.ModuleType("m") + got = [] + for i in range(3000): + if i == 1000: + m.nope = "here" + if i == 2000: + del m.nope + m.__getattr__ = lambda name: "late" + got.append(getattr(m, "nope", None)) + self.assertEqual(got[999], None) + self.assertEqual(got[1000], "here") + self.assertEqual(got[1999], "here") + self.assertEqual(got[2000], "late") + self.assertEqual(got[-1], "late") + + def test_hook_raising_attribute_error(self): + m = types.ModuleType("m") + + def hook(name): + raise AttributeError(name) + + m.__getattr__ = hook + self.assertEqual(module_misses(m, 1000)[-2:], [999, False]) + + def test_builtin_values(self): + out = builtin_misses(2000) + self.assertEqual(out[0], (None, 0, 1, 2, True, True, True, "X")) + self.assertEqual(out[-1], out[0]) + + def test_leaves(self): + acc = [] + for i in range(2000): + b = bytes([i % 256, 2, 3]) + acc.append(( + (i * 2654435761).bit_count(), + b.find(b"\x03"), + b.find(3, 1, 3), + b.find(b"\x09"), + b.hex(), + b.hex(":"), + b.hex(b"-", 2), + )) + i = 1999 + b = bytes([i % 256, 2, 3]) + self.assertEqual(acc[-1], (bin(i * 2654435761).count("1"), 2, 2, -1, + b.hex(), b.hex(":"), b.hex(b"-", 2))) + self.assertEqual(acc[5][5], "05:02:03") + self.assertEqual(acc[5][6], "05-0203") + caught = 0 + for i in range(500): + try: + b"ab".hex("::") + except ValueError: + caught += 1 + self.assertEqual(caught, 500) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getattr_hook_colliding_key_frames.py b/tests/regrtest/test_getattr_hook_colliding_key_frames.py new file mode 100644 index 000000000..cbcadcb8e --- /dev/null +++ b/tests/regrtest/test_getattr_hook_colliding_key_frames.py @@ -0,0 +1,70 @@ +"""A colliding instance-dict key's `__eq__` sees its real caller. + +An object with `__getattr__` and an instance dict holding a key whose hash +collides with an attribute name: the generic lookup compares that key +with the name, calling its Python `__eq__`. Compiled code's check for a +certain miss must not make that call itself (frameless, the `__eq__` saw +the caller's caller); it leaves it to the full lookup. Run under each +tier setting. +""" + +import os +import subprocess +import sys + +PROGRAM = r''' +import sys + +class Missing: + def __init__(self): + self._value = 7 + def __getattr__(self, name): + if name == "value": + return self._value + if name == "other": + return self._value + 4 + raise AttributeError(name) + +def key_read(root, n): + total = 0 + for _ in range(n): + total += root.value + total += root.other + return total + +missing = Missing() +for _ in range(2): + assert key_read(missing, 1200) == 21600 + +events = [] + +class Key: + def __hash__(self): + return hash("value") + def __eq__(self, name): + events.append(sys._getframe(1).f_code.co_name) + return name == "value" + +missing.__dict__[Key()] = 23 +assert key_read(missing, 3) == 102 +print(events) +''' + +EXPECTED = "['key_read', 'key_read', 'key_read']\n" + +SETTINGS = [ + {}, + {"WEAVEPY_TIER2": "0"}, + {"WEAVEPY_TIER2": "0", "WEAVEPY_FRAME_JIT_SYNC": "1"}, + {"WEAVEPY_JIT": "0", "WEAVEPY_FRAME_JIT": "0"}, + {"WEAVEPY_JIT_THRESHOLD": "2"}, +] + +for extra in SETTINGS: + env = dict(os.environ, **extra) + result = subprocess.run([sys.executable, "-c", PROGRAM], env=env, + capture_output=True, text=True, timeout=120) + assert result.returncode == 0, (extra, result.stderr) + assert result.stdout == EXPECTED, (extra, result.stdout) + +print("colliding key frames: ok") diff --git a/tests/regrtest/test_getattr_hook_direct_calls.py b/tests/regrtest/test_getattr_hook_direct_calls.py new file mode 100644 index 000000000..661834f7b --- /dev/null +++ b/tests/regrtest/test_getattr_hook_direct_calls.py @@ -0,0 +1,482 @@ +"""A `__getattr__` that runs as an activation (a loop, a call or a handler +in its body) is called straight from a warm read site: values, errors and +their `name` and `obj`, tracebacks, recursion, receivers that die with the +read, and every change that must send the read back to the full lookup. +An `AttributeError` built by Python code takes the read's name and +receiver exactly once, and its subclasses take the keyword fields.""" + +import copy +import pickle +import sys +import traceback +import unittest + +N = 3000 + + +def helper(d, k): + for _ in (1,): + pass + return d[k] + + +class Loop: + def __init__(self, **kw): + self.d = kw + + def __getattr__(self, k): + for d in (self.d,): + if k in d: + return d[k] + raise AttributeError(k) + + +class Call: + def __init__(self, **kw): + self.d = kw + + def __getattr__(self, k): + return helper(self.d, k) + + +class Try(dict): + def __getattr__(self, k): + try: + return self[k] + except KeyError: + raise AttributeError("no " + k) from None + + +class Find(list): + def __getattr__(self, k): + for i, x in enumerate(self): + if x == k: + return i + raise AttributeError(k) + + +def read_x(o, n=N): + t = 0 + for _ in range(n): + t += o.x + return t + + +def read_stack(objs, n=N): + t = 0 + for i in range(n): + t += objs[i & 1].x + return t + + +def read_caught(o, n=N): + k = 0 + last = None + for _ in range(n): + try: + o.nope + except AttributeError as e: + k += 1 + last = (str(e), e.name, e.obj is o) + except KeyError as e: + k += 2 + last = (str(e),) + return k, last + + +class DirectHookCalls(unittest.TestCase): + def test_values(self): + lo, ca, tr, fi = Loop(x=1), Call(x=2), Try(x=3), Find(["a", "x"]) + self.assertEqual([read_x(o) for o in (lo, ca, tr, fi)], [N, 2 * N, 3 * N, N]) + self.assertEqual(read_stack([lo, Loop(x=5)]), 3 * N) + self.assertEqual(read_stack([ca, tr]), 5 * N // 2) + self.assertEqual(read_stack([fi, lo]), N) + + def test_errors_name_the_read(self): + lo, ca, tr, fi = Loop(x=1), Call(x=2), Try(x=3), Find(["a", "x"]) + self.assertEqual(read_caught(lo), (N, ("nope", "nope", True))) + self.assertEqual(read_caught(ca), (2 * N, ("'nope'",))) + self.assertEqual(read_caught(tr), (N, ("no nope", "nope", True))) + self.assertEqual(read_caught(fi), (N, ("nope", "nope", True))) + + def test_values_arrive_and_leave(self): + class Own(Loop): + pass + + lo, fi = Own(x=1), Find(["a", "x"]) + self.assertEqual(read_x(lo), N) + lo.__dict__["x"] = 10 + self.assertEqual(read_x(lo), 10 * N) + del lo.__dict__["x"] + self.assertEqual(read_x(lo), N) + Own.x = 100 + self.assertEqual(read_x(lo), 100 * N) + del Own.x + self.assertEqual(read_x(lo), N) + self.assertEqual(read_x(fi), N) + fi.x = 7 + self.assertEqual(read_x(fi), 7 * N) + del fi.x + self.assertEqual(read_x(fi), N) + + def test_hook_replaced_and_removed(self): + class Own(Loop): + def __getattr__(self, k): + for d in (self.d,): + if k in d: + return d[k] + raise AttributeError(k) + + lo = Own(x=1) + old = Own.__getattr__ + self.assertEqual(read_x(lo), N) + Own.__getattr__ = lambda self, k: 1000 + self.assertEqual(read_x(lo), 1000 * N) + Own.__getattr__ = old + self.assertEqual(read_x(lo), N) + del Own.__getattr__ + self.assertEqual(read_x(lo), N) # Loop's + Own.__getattr__ = old + self.assertEqual(read_x(lo), N) + + class Bare: + def __getattr__(self, k): + for _ in (1,): + pass + return 1 + + b = Bare() + self.assertEqual(read_x(b), N) + del Bare.__getattr__ + with self.assertRaises(AttributeError) as cm: + read_x(b) + self.assertEqual(str(cm.exception), "'Bare' object has no attribute 'x'") + self.assertEqual(cm.exception.name, "x") + self.assertIs(cm.exception.obj, b) + + def test_shapes_the_direct_call_does_not_bind(self): + class Dflt: + def __getattr__(self, k, extra=3): + for _ in (1,): + pass + return (k, extra) + + class Var: + def __getattr__(self, *a): + for _ in (1,): + pass + return a[0] + + class Gen: + def __getattr__(self, k): + yield k + + class Frame: + def __getattr__(self, k): + for _ in (1,): + pass + f = sys._getframe() + return (f.f_code.co_name, f.f_back.f_code.co_name, k) + + def read_k(o, n=N): + r = None + for _ in range(n): + r = o.key + return r + + self.assertEqual(read_k(Dflt()), ("key", 3)) + self.assertEqual(read_k(Var()), "key") + self.assertEqual(type(read_k(Gen())).__name__, "generator") + self.assertEqual(read_k(Frame()), ("__getattr__", "read_k", "key")) + + def test_other_errors_and_tracebacks(self): + class Boom: + def __getattr__(self, k): + for _ in (1,): + pass + if k == "zero": + return 1 // 0 + if k == "deep": + return self.deeper + if k == "named": + raise AttributeError(k, name="custom", obj=None) + raise AttributeError(k) + + def read_boom(o, name, n=N): + last = None + for _ in range(n): + try: + if name == "zero": + o.zero + elif name == "deep": + o.deep + elif name == "named": + o.named + else: + o.other + except ZeroDivisionError as e: + last = ("zde", [f.name for f in traceback.extract_tb(e.__traceback__)]) + except AttributeError as e: + last = ( + "ae", str(e), e.name, e.obj is o, + [f.name for f in traceback.extract_tb(e.__traceback__)], + ) + return last + + b = Boom() + self.assertEqual(read_boom(b, "zero"), ("zde", ["read_boom", "__getattr__"])) + self.assertEqual( + read_boom(b, "deep"), + ("ae", "deeper", "deeper", True, ["read_boom", "__getattr__", "__getattr__"]), + ) + self.assertEqual( + read_boom(b, "named"), ("ae", "named", "custom", False, ["read_boom", "__getattr__"]) + ) + self.assertEqual( + read_boom(b, "other"), ("ae", "other", "other", True, ["read_boom", "__getattr__"]) + ) + + def test_recursion(self): + class Rec: + def __getattr__(self, k): + for _ in (1,): + pass + return self.again + + o = Rec() + k = 0 + for _ in range(20): + try: + o.x + except RecursionError: + k += 1 + self.assertEqual(k, 20) + + def test_receivers_that_die_with_the_read(self): + log = [] + + class Temp: + def __init__(self, i): + self.i = i + + def __getattr__(self, k): + for _ in (1,): + pass + return self.i + + def __del__(self): + log.append(self.i) + + t = 0 + for i in range(N): + t += Temp(i).x + self.assertEqual(len(log), i + 1) + self.assertEqual(t, N * (N - 1) // 2) + + def test_probes(self): + def probes(o, n=N): + k = 0 + for _ in range(n): + if hasattr(o, "x"): + k += 1 + if hasattr(o, "nope"): + k += 10 + if getattr(o, "nope", None) is None: + k += 100 + k += getattr(o, "x", 0) + return k + + self.assertEqual(probes(Loop(x=1)), 102 * N) + self.assertEqual(probes(Try(x=3)), 104 * N) + self.assertEqual(probes(Find(["a", "x"])), 102 * N) + + def test_generators_and_comprehensions(self): + lo, ca, tr, fi = Loop(x=1), Call(x=2), Try(x=3), Find(["a", "x"]) + + def gen(objs): + for o in objs: + yield o.x + + self.assertEqual(sum(gen([lo, tr, fi] * 2000)), 10000) + self.assertEqual(sum([o.x for o in [lo, ca] * 2000]), 6000) + self.assertEqual(sum(o.x for o in [tr, fi] * 2000), 8000) + + def test_hook_reads_through_itself(self): + class Chain: + def __init__(self): + self.d = {"a": 1} + + def __getattr__(self, k): + for _ in (1,): + pass + if k == "b": + return self.a + 1 + if k == "c": + return self.b + 1 + return self.d[k] + + o = Chain() + t = 0 + for _ in range(N): + t += o.c + self.assertEqual(t, 3 * N) + + +def fields(e): + return (type(e).__name__, e.args, e.name, e.obj, sorted(e.__dict__), str(e), repr(e)) + + +class Raiser: + def __init__(self, exc): + self.exc = exc + + def __getattr__(self, k): + raise self.exc + + +def through(o, attr): + try: + getattr(o, attr) + except AttributeError as e: + return e + + +class Sub(AttributeError): + pass + + +class PythonBuiltAttributeErrors(unittest.TestCase): + def test_construction(self): + self.assertEqual( + fields(AttributeError("x")), + ("AttributeError", ("x",), None, None, [], "x", "AttributeError('x')"), + ) + self.assertEqual(fields(AttributeError())[1:4], ((), None, None)) + self.assertEqual(fields(AttributeError("a", 2))[1:6], (("a", 2), None, None, [], "('a', 2)")) + self.assertEqual(fields(AttributeError("x", name="n", obj=5))[1:5], (("x",), "n", 5, [])) + self.assertEqual(fields(AttributeError("x", name="n"))[1:5], (("x",), "n", None, [])) + self.assertEqual(fields(AttributeError("x", name=None, obj=None))[2:4], (None, None)) + with self.assertRaises(TypeError) as cm: + AttributeError("x", bogus=1) + self.assertEqual( + str(cm.exception), "AttributeError() got an unexpected keyword argument 'bogus'" + ) + + def test_fields_set_and_deleted(self): + e = AttributeError("x") + e.name = "set" + e.obj = 7 + self.assertEqual(fields(e)[2:5], ("set", 7, [])) + del e.name + self.assertEqual(fields(e)[2:5], (None, 7, [])) + e.extra = 1 + e.add_note("note") + self.assertEqual(fields(e)[2:5], (None, 7, ["__notes__", "extra"])) + self.assertEqual(e.__notes__, ["note"]) + + def test_copies(self): + for proto in (2, pickle.HIGHEST_PROTOCOL): + r = pickle.loads(pickle.dumps(AttributeError("p", name="n", obj=3), proto)) + self.assertEqual(fields(r)[1:5], (("p",), "n", None, [])) + r = pickle.loads(pickle.dumps(AttributeError("q"), proto)) + self.assertEqual(fields(r)[1:5], (("q",), None, None, [])) + self.assertEqual(fields(copy.copy(AttributeError("c", name="n")))[1:4], (("c",), "n", None)) + self.assertEqual(fields(copy.deepcopy(AttributeError("d")))[1:4], (("d",), None, None)) + + def test_subclasses_take_the_keyword_fields(self): + self.assertEqual(fields(Sub("s"))[:5], ("Sub", ("s",), None, None, [])) + self.assertEqual(fields(Sub("s", name="n", obj=1))[:5], ("Sub", ("s",), "n", 1, [])) + + class Passes(AttributeError): + def __init__(self, msg, name): + super().__init__(msg, name=name) + + self.assertEqual(fields(Passes("m", "nm"))[1:4], (("m",), "nm", None)) + + class Imp(ImportError): + pass + + e = Imp("i", name="mod", path="/p") + self.assertEqual((e.args, e.name, e.path), (("i",), "mod", "/p")) + + class Nm(NameError): + pass + + self.assertEqual(Nm("n", name="who").name, "who") + with self.assertRaises(TypeError) as cm: + Sub("s", bogus=1) + self.assertEqual( + str(cm.exception), "AttributeError() got an unexpected keyword argument 'bogus'" + ) + + class Val(ValueError): + pass + + with self.assertRaises(TypeError) as cm: + Val("v", name=1) + self.assertEqual(str(cm.exception), "Val() takes no keyword arguments") + + def test_the_first_read_names_the_error(self): + shared = AttributeError("shared") + h1, h2 = Raiser(shared), Raiser(shared) + self.assertIs(through(h1, "one"), shared) + self.assertEqual((shared.name, shared.obj), ("one", h1)) + self.assertIs(through(h2, "two"), shared) + self.assertEqual((shared.name, shared.obj), ("one", h1)) + + def test_fields_already_set_are_kept(self): + pre = AttributeError("pre", name="kept") + through(Raiser(pre), "other") + self.assertEqual((pre.name, pre.obj), ("kept", None)) + preo = AttributeError("preo", obj=9) + through(Raiser(preo), "other") + self.assertEqual((preo.name, preo.obj), (None, 9)) + + def test_other_storage(self): + sub = Sub("subbed") + h = Raiser(sub) + through(h, "zz") + self.assertEqual((sub.name, sub.obj), ("zz", h)) + noted = AttributeError("noted") + noted.add_note("n1") + h = Raiser(noted) + through(h, "yy") + self.assertEqual((noted.name, noted.obj, noted.__notes__), ("yy", h, ["n1"])) + dicty = AttributeError("dicty") + dicty.other = 1 + h = Raiser(dicty) + through(h, "ww") + self.assertEqual((dicty.name, dicty.obj, dicty.other), ("ww", h, 1)) + + def test_property_then_hook(self): + class P: + @property + def prop(self): + raise AttributeError("from prop") + + def __getattr__(self, k): + raise AttributeError("hook " + k) + + p = P() + e = through(p, "prop") + self.assertEqual((e.args, e.name, e.obj), (("hook prop",), "prop", p)) + + def test_warm_loop(self): + o = Raiser(None) + last = None + for i in range(N): + o.exc = AttributeError("m%d" % (i & 3)) + try: + o.attr + except AttributeError as e: + last = ( + e.args, e.name, e.obj is o, e.__context__, e.__cause__, + e.__suppress_context__, type(e.__traceback__).__name__, + ) + self.assertFalse(hasattr(o, "attr")) + self.assertEqual(getattr(o, "attr", 5), 5) + self.assertEqual(last, (("m3",), "attr", True, None, None, False, "traceback")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getattr_hook_known_class.py b/tests/regrtest/test_getattr_hook_known_class.py new file mode 100644 index 000000000..ed02906e3 --- /dev/null +++ b/tests/regrtest/test_getattr_hook_known_class.py @@ -0,0 +1,169 @@ +"""A read that a class's Python `__getattr__` answers, at a site that saw +the hook answer before for the class's version: an instance that gains +the attribute, a class that gains it, a slot member, a replaced hook, a +receiver of another class, and a hook body that calls `dict.get` with a +missing key, a present one and an unhashable one all read as the full +lookup reads them.""" + +import unittest + + +class C: + def __init__(self): + self.data = {"x": 1, "y": 2} + + def __getattr__(self, name): + return self.data.get(name, 0) + + +def read_x(o, n): + out = [] + for _ in range(n): + out.append(o.x) + return out + + +def read_z(o, n): + out = [] + for _ in range(n): + out.append(o.z) + return out + + +N = 3000 + + +class GetattrHookKnownClassTests(unittest.TestCase): + def test_hook_answers(self): + self.assertEqual(read_x(C(), N), [1] * N) + self.assertEqual(read_z(C(), N), [0] * N) + + def test_instance_gains_attribute(self): + o = C() + self.assertEqual(read_x(o, N), [1] * N) + o.x = 7 + self.assertEqual(read_x(o, 3), [7] * 3) + del o.x + self.assertEqual(read_x(o, 3), [1] * 3) + + def test_instance_dict_replaced(self): + o = C() + read_x(o, N) + o.__dict__ = {"data": {"x": 5}, "x": 9} + self.assertEqual(read_x(o, 3), [9] * 3) + + def test_class_gains_attribute(self): + class K(C): + pass + + o = K() + self.assertEqual(read_x(o, N), [1] * N) + K.x = 42 + self.assertEqual(read_x(o, 3), [42] * 3) + del K.x + self.assertEqual(read_x(o, 3), [1] * 3) + + def test_base_gains_property(self): + class B: + def __getattr__(self, name): + return "hook" + + class K(B): + pass + + o = K() + self.assertEqual(read_x(o, N), ["hook"] * N) + B.x = property(lambda self: "prop") + self.assertEqual(read_x(o, 3), ["prop"] * 3) + + def test_hook_replaced(self): + class K(C): + pass + + o = K() + read_x(o, N) + K.__getattr__ = lambda self, name: name * 2 + self.assertEqual(read_x(o, 3), ["xx"] * 3) + + def test_unset_slot_member(self): + class K: + __slots__ = ("x",) + + def __getattr__(self, name): + return "hook-" + name + + o = K() + self.assertEqual(read_x(o, N), ["hook-x"] * N) + o.x = 3 + self.assertEqual(read_x(o, 3), [3] * 3) + del o.x + self.assertEqual(read_x(o, 3), ["hook-x"] * 3) + + def test_several_classes(self): + class D: + def __getattr__(self, name): + return -1 + + class Plain: + x = "plain" + + objs = [C(), D(), Plain(), C()] + for _ in range(N // 10): + self.assertEqual([o.x for o in objs], [1, -1, "plain", 1]) + + def test_dict_get_keys(self): + d = {"a": 1, 2: "two", (1, 2): "pair"} + + def get(k): + return d.get(k, "missing") + + for _ in range(N): + self.assertEqual(get("a"), 1) + self.assertEqual(get(2), "two") + self.assertEqual(get(2.0), "two") + self.assertEqual(get("b"), "missing") + self.assertEqual(get((1, 2)), "pair") + with self.assertRaises(TypeError): + get([1]) + + def test_dict_get_subclass(self): + class M(dict): + def get(self, key, default=None): + return "sub" + + class K: + def __init__(self, data): + self.data = data + + def __getattr__(self, name): + return self.data.get(name, 0) + + plain, sub = K({"x": 1}), K(M(x=1)) + for _ in range(N // 10): + self.assertEqual(plain.x, 1) + self.assertEqual(sub.x, "sub") + + def test_dict_get_key_with_eq(self): + class Key: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return other == self.v + + d = {"k": 1} + + def get(k): + return d.get(k, 0) + + for _ in range(N): + self.assertEqual(get("k"), 1) + self.assertEqual(get(Key("k")), 1) + self.assertEqual(get(Key("q")), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getattr_hook_method_calls.py b/tests/regrtest/test_getattr_hook_method_calls.py new file mode 100644 index 000000000..a278c450b --- /dev/null +++ b/tests/regrtest/test_getattr_hook_method_calls.py @@ -0,0 +1,74 @@ +"""Method calls through a class's __getattr__ from compiled loops: a +wrapper delegating to its target's bound methods, a hook returning a +plain function or a lambda (no self bound), a hook that raises +AttributeError for some names, an instance attribute or class method +that shadows the hook, and a hook replaced partway, each matching +CPython.""" + +import unittest + + +class Wrap: + def __init__(self, o): + self._o = o + + def __getattr__(self, name): + return getattr(self._o, name) + + +class Picky: + def __getattr__(self, name): + if name.startswith("ok"): + return len + raise AttributeError(name) + + +class Shadow(Wrap): + def count(self, x): + return -1 + + +def calls(n, w, x): + out = None + for i in range(n): + out = w.count(x) + return out + + +class HookTests(unittest.TestCase): + def test_delegate(self): + for n in (1, 400): + self.assertEqual(calls(n, Wrap([1, 2, 1]), 1), 2) + self.assertEqual(calls(n, Wrap("abca"), "a"), 2) + self.assertEqual(calls(n, Shadow([1]), 1), -1) + + def test_plain_function(self): + def run(n): + p = Picky() + out = None + for i in range(n): + out = p.ok_len("abc") + return out + + self.assertEqual(run(400), 3) + with self.assertRaises(AttributeError): + for i in range(400): + Picky().nope() + + def test_instance_shadow(self): + w = Wrap([1, 2]) + w.count = lambda x: "own" + self.assertEqual(calls(400, w, 1), "own") + + def test_replaced_hook(self): + class W(Wrap): + pass + + w = W([1]) + self.assertEqual(calls(400, w, 1), 1) + W.__getattr__ = lambda self, name: (lambda x: "new") + self.assertEqual(calls(400, w, 1), "new") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getattr_hook_probes.py b/tests/regrtest/test_getattr_hook_probes.py new file mode 100644 index 000000000..7b58bd22f --- /dev/null +++ b/tests/regrtest/test_getattr_hook_probes.py @@ -0,0 +1,577 @@ +"""`hasattr(obj, name)` and `getattr(obj, name, default)` of an instance whose +class has a Python `__getattr__`, and `next(obj)` of one with a Python +`__next__`, in warm loops: the hook's answer (a false one is still found), +an `AttributeError` it raises (a fresh one, a subclass's, one kept or raised +again, one raised from a handler) read as the miss, any other error +propagating with its traceback, when the hook's locals die, hooks that call +on, classes that override `__getattribute__`, names held in variables and +`str` subclasses, the handled exception around a probe, and the error a +plain read of the same attribute gives (its name, receiver, traceback and +context). `next()` keeps the `StopIteration` its method raises, value and +traceback, and a default covers only that. + +The checks run at import, in the order written (several watch when objects +die), and their printed results are compared with CPython's, kept at the +end of the file: rerun with `--emit` under CPython to refresh them.""" + +import builtins +import unittest + +_lines = [] + + +def print(*args): + _lines.append(" ".join(str(a) for a in args)) + + +import sys, gc, weakref + +N = 4000 +log = [] + +def tb_names(e): + out = [] + tb = e.__traceback__ + while tb is not None: + out.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + return tuple(out) + +class Plain: + calls = 0 + def __init__(self): + self.own = 5 + def __getattr__(self, name): + Plain.calls += 1 + if name == "zz": + raise AttributeError(name) + if name == "false": + return False + if name == "none": + return None + if name == "key": + raise KeyError(name) + return 1 + +class Proxy: + def __init__(self): + self._data = {"a": 1, "f": False} + def __getattr__(self, name): + try: + return self._data[name] + except KeyError: + raise AttributeError(name) + +class ProxyNone: + def __init__(self): + self._data = {"a": 1} + def __getattr__(self, name): + try: + return self._data[name] + except KeyError: + raise AttributeError(name) from None + +class Catches: + def __getattr__(self, name): + try: + raise KeyError(name) + except KeyError: + pass + if name == "zz": + raise AttributeError(name) + return name == "t" + +class Sub(AttributeError): + pass + +class RaisesSub: + def __getattr__(self, name): + raise Sub(name) + +class Stored: + def __init__(self): + self.err = AttributeError("stored") + def __getattr__(self, name): + raise self.err + +class Keeps: + def __init__(self): + self.last = None + def __getattr__(self, name): + e = AttributeError(name) + self.__dict__["last"] = e + raise e + +class Noisy: + def __init__(self, tag): + self.tag = tag + def __del__(self): + log.append(("del", self.tag)) + +class WithLocal: + def __getattr__(self, name): + local = Noisy(name) + log.append(("in", name)) + raise AttributeError(name) + +class Nested: + def __init__(self): + self.inner = Plain() + def __getattr__(self, name): + if hasattr(self.inner, name): + return getattr(self.inner, name, 7) + raise AttributeError(name) + +class Deep: + def helper(self, name): + raise AttributeError(name) + def __getattr__(self, name): + return self.helper(name) + +class Override: + def __getattribute__(self, name): + if name == "zz": + raise AttributeError(name) + return 3 + +class Both: + def __getattribute__(self, name): + raise AttributeError(name) + def __getattr__(self, name): + if name == "zz": + raise AttributeError(name) + return 4 + +class Preset: + def __getattr__(self, name): + raise AttributeError(name, name="preset", obj=17) + +class StrSub(str): + pass + +SENTINEL = object() + +def probes(obj, names): + seen = {} + for i in range(N): + for n in names: + r = (hasattr(obj, n), getattr(obj, n, SENTINEL) is SENTINEL, getattr(obj, n, 9)) + if seen.get(n) != r: + seen[n] = r + log.append((type(obj).__name__, n, r, i)) + +probes(Plain(), ["zz", "false", "none", "other", "own"]) +print("plain calls", Plain.calls) +probes(Proxy(), ["zz", "a", "f"]) +probes(ProxyNone(), ["zz", "a"]) +probes(Catches(), ["zz", "t", "u"]) +probes(RaisesSub(), ["zz"]) +probes(Nested(), ["zz", "false", "q"]) +probes(Deep(), ["zz"]) +probes(Override(), ["zz", "a"]) +probes(Both(), ["zz", "a"]) +probes(Preset(), ["zz"]) +for item in log: + print(item) +log.clear() + +def stored(): + s = Stored() + for i in range(N): + hasattr(s, "zz") + getattr(s, "zz", None) + n = 0 + tb = s.err.__traceback__ + names = set() + while tb is not None: + n += 1 + names.add(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + print("stored", n, sorted(names)) +stored() + +def keeps(): + k = Keeps() + shapes = set() + for i in range(N): + hasattr(k, "zz") + e = k.last + shapes.add((tb_names(e), e.__context__ is None, e.args)) + getattr(k, "yy", None) + e = k.last + shapes.add((tb_names(e), e.__context__ is None, e.args)) + print("keeps", sorted(shapes, key=repr)) +keeps() + +def with_local(): + w = WithLocal() + shapes = set() + for i in range(N): + del log[:] + r = hasattr(w, "zz") + log.append(("after", r)) + shapes.add(tuple(log)) + del log[:] + r = getattr(w, "zz", 5) + log.append(("after", r)) + shapes.add(tuple(log)) + del log[:] + print("with_local", sorted(shapes, key=repr)) +with_local() + +def propagates(): + p = Plain() + shapes = set() + for i in range(N): + try: + hasattr(p, "key") + except KeyError as e: + shapes.add(("hasattr", tb_names(e), e.args)) + try: + getattr(p, "key", None) + except KeyError as e: + shapes.add(("getattr", tb_names(e), e.args)) + print("propagates", sorted(shapes, key=repr)) +propagates() + +def in_handler(): + p = Plain() + px = Proxy() + shapes = set() + for i in range(N): + try: + raise ValueError(i) + except ValueError as outer: + a = hasattr(p, "zz") + b = getattr(px, "zz", 3) + c = sys.exception() is outer + shapes.add((a, b, c)) + print("in_handler", sorted(shapes, key=repr), sys.exception()) +in_handler() + +def reads(): + shapes = set() + objs = [Plain(), Proxy(), ProxyNone(), Catches(), RaisesSub(), Deep(), Preset()] + for i in range(N): + for o in objs: + try: + o.zz + except AttributeError as e: + ctx = e.__context__ + shapes.add((type(o).__name__, tb_names(e), e.name, e.obj is o or e.obj, + type(ctx).__name__, e.__suppress_context__, + tb_names(ctx) if ctx is not None else None)) + for s in sorted(shapes, key=repr): + print("read", s) +reads() + +def read_frames(): + o = Deep() + shapes = set() + for i in range(N): + try: + o.zz + except AttributeError as e: + tb = e.__traceback__ + frames = [] + while tb is not None: + f = tb.tb_frame + frames.append((f.f_code.co_name, sorted(f.f_locals), + f.f_back.f_code.co_name if f.f_back is not None else None)) + tb = tb.tb_next + shapes.add(repr(frames)) + for s in sorted(shapes): + print("frames", s) +read_frames() + +def dynamic_names(): + p = Plain() + names = ["zz", StrSub("zz"), "own", "other", StrSub("other")] + shapes = set() + for i in range(N): + for n in names: + shapes.add((type(n).__name__, str(n), hasattr(p, n), getattr(p, n, 2))) + try: + hasattr(p, 3) + except TypeError as e: + print("bad name", e) + try: + getattr(p, 3, None) + except TypeError as e: + print("bad name", e) + print("dynamic", sorted(shapes, key=repr)) +dynamic_names() + +def defaults(): + p = Plain() + d = Noisy("default") + ids = set() + for i in range(N): + ids.add(getattr(p, "zz", d) is d) + ids.add(getattr(p, "zz", None) is None) + del d + gc.collect() + print("defaults", ids, log) + del log[:] +defaults() + +class Count: + def __init__(self, n, value=False): + self.i = 0 + self.n = n + self.value = value + def __iter__(self): + return self + def __next__(self): + if self.i >= self.n: + if self.value: + raise StopIteration(self.i) + raise StopIteration + self.i += 1 + return self.i + +class Broken: + def __next__(self): + raise ValueError("broken") + +class Chained: + def __init__(self): + self.d = {} + def __next__(self): + try: + return self.d["k"] + except KeyError: + raise StopIteration("done") + +def nexts(): + shapes = set() + for i in range(N): + it = Count(2) + a = next(it), next(it) + try: + next(it) + except StopIteration as e: + shapes.add(("plain", a, e.args, tb_names(e), e.value)) + it = Count(1, True) + next(it) + try: + next(it) + except StopIteration as e: + shapes.add(("value", e.args, tb_names(e), e.value)) + shapes.add(("default", next(it, "d"), next(Count(0), None))) + try: + next(Broken()) + except ValueError as e: + shapes.add(("broken", e.args, tb_names(e))) + shapes.add(("broken default", ) + broken_default()) + try: + next(Chained()) + except StopIteration as e: + shapes.add(("chained", e.args, tb_names(e), type(e.__context__).__name__)) + for s in sorted(shapes, key=repr): + print("next", s) + +def broken_default(): + try: + next(Broken(), 1) + except ValueError as e: + return (e.args, tb_names(e)) + return () +nexts() + +def gen_user(): + def g(it): + while True: + try: + yield next(it) + except StopIteration: + return + t = 0 + for i in range(N // 4): + for x in g(Count(3)): + t += x + print("gen", t) +gen_user() + +def weak(): + p = Plain() + refs = [] + class E(AttributeError): + pass + class H: + def __getattr__(self, name): + e = E(name) + refs.append(weakref.ref(e)) + raise e + h = H() + alive = set() + for i in range(200): + hasattr(h, "zz") + alive.add(refs[-1]() is None) + print("weak", alive, len(refs)) +weak() +class NoisyArg: + def __getattr__(self, name): + raise AttributeError(Noisy("arg " + name)) + +def noisy_arg(): + w = NoisyArg() + shapes = set() + for i in range(N): + del log[:] + r = hasattr(w, "zz") + log.append(("after", r)) + shapes.add(tuple(log)) + del log[:] + r = getattr(w, "zz", 5) + log.append(("after", r)) + shapes.add(tuple(log)) + del log[:] + print("noisy_arg", sorted(shapes, key=repr)) +noisy_arg() + +def has(o, n): + return hasattr(o, n) + +def get(o, n, d=None): + return getattr(o, n, d) + +class User: + def __init__(self, o): + self.o = o + def has(self, n): + return hasattr(self.o, n) + @property + def zz(self): + return getattr(self.o, "zz", "prop") + +def through_calls(): + p = Plain() + x = Proxy() + u = User(p) + ux = User(x) + shapes = set() + t = 0 + for i in range(N): + shapes.add((has(p, "zz"), has(p, "q"), get(p, "zz"), get(p, "zz", 4), get(x, "a"), + u.has("zz"), u.has("own"), u.zz, ux.has("zz"), ux.has("a"), ux.zz)) + t += sum(hasattr(p, n) for n in ("zz", "a", "zz", "own")) + t += len([n for n in ("zz", "a") if getattr(x, n, None) is not None]) + print("through", sorted(shapes, key=repr), t) +through_calls() + +class Rec: + def __init__(self, depth): + self.depth = depth + def __getattr__(self, name): + if len(name) < self.depth and hasattr(self, name + "x"): + return len(name) + if name.endswith("xxx"): + return 0 + raise AttributeError(name) + +def recursive(): + shapes = set() + for i in range(N // 4): + shapes.add((hasattr(Rec(5), "a"), hasattr(Rec(2), "a"), getattr(Rec(3), "a", "d"), + getattr(Rec(0), "xxx", "d"), hasattr(Rec(0), "y"))) + print("recursive", sorted(shapes, key=repr)) +recursive() + +def changing_class(): + class K: + def __getattr__(self, name): + raise AttributeError(name) + k = K() + out = [] + for i in range(N): + if i == N // 2: + K.zz = 11 + if i == N // 2 + 100: + del K.zz + k.zz = 12 + if i == N // 2 + 200: + del k.zz + K.__getattr__ = lambda self, name: 13 + if i == N // 2 + 300: + del K.__getattr__ + r = (hasattr(k, "zz"), getattr(k, "zz", None)) + if not out or out[-1][1] != r: + out.append((i, r)) + print("changing", out) +changing_class() +print("done") + + +EXPECTED = r""" +plain calls 48000 +('Plain', 'zz', (False, True, 9), 0) +('Plain', 'false', (True, False, False), 0) +('Plain', 'none', (True, False, None), 0) +('Plain', 'other', (True, False, 1), 0) +('Plain', 'own', (True, False, 5), 0) +('Proxy', 'zz', (False, True, 9), 0) +('Proxy', 'a', (True, False, 1), 0) +('Proxy', 'f', (True, False, False), 0) +('ProxyNone', 'zz', (False, True, 9), 0) +('ProxyNone', 'a', (True, False, 1), 0) +('Catches', 'zz', (False, True, 9), 0) +('Catches', 't', (True, False, True), 0) +('Catches', 'u', (True, False, False), 0) +('RaisesSub', 'zz', (False, True, 9), 0) +('Nested', 'zz', (False, True, 9), 0) +('Nested', 'false', (True, False, False), 0) +('Nested', 'q', (True, False, 1), 0) +('Deep', 'zz', (False, True, 9), 0) +('Override', 'zz', (False, True, 9), 0) +('Override', 'a', (True, False, 3), 0) +('Both', 'zz', (False, True, 9), 0) +('Both', 'a', (True, False, 4), 0) +('Preset', 'zz', (False, True, 9), 0) +stored 8000 ['__getattr__'] +keeps [(('__getattr__',), True, ('yy',)), (('__getattr__',), True, ('zz',))] +with_local [(('in', 'zz'), ('del', 'zz'), ('after', 5)), (('in', 'zz'), ('del', 'zz'), ('after', False))] +propagates [('getattr', ('propagates', '__getattr__'), ('key',)), ('hasattr', ('propagates', '__getattr__'), ('key',))] +in_handler [(False, 3, True)] None +read ('Catches', ('reads', '__getattr__'), 'zz', True, 'NoneType', False, None) +read ('Deep', ('reads', '__getattr__', 'helper'), 'zz', True, 'NoneType', False, None) +read ('Plain', ('reads', '__getattr__'), 'zz', True, 'NoneType', False, None) +read ('Preset', ('reads', '__getattr__'), 'preset', 17, 'NoneType', False, None) +read ('Proxy', ('reads', '__getattr__'), 'zz', True, 'KeyError', False, ('__getattr__',)) +read ('ProxyNone', ('reads', '__getattr__'), 'zz', True, 'KeyError', True, ('__getattr__',)) +read ('RaisesSub', ('reads', '__getattr__'), 'zz', True, 'NoneType', False, None) +frames [('read_frames', ['e', 'f', 'frames', 'i', 'o', 'shapes', 'tb'], ''), ('__getattr__', ['name', 'self'], 'read_frames'), ('helper', ['name', 'self'], '__getattr__')] +bad name attribute name must be string, not 'int' +bad name attribute name must be string, not 'int' +dynamic [('StrSub', 'other', True, 1), ('StrSub', 'zz', False, 2), ('str', 'other', True, 1), ('str', 'own', True, 5), ('str', 'zz', False, 2)] +defaults {True} [('del', 'default')] +next ('broken default', ('broken',), ('broken_default', '__next__')) +next ('broken', ('broken',), ('nexts', '__next__')) +next ('chained', ('done',), ('nexts', '__next__'), 'KeyError') +next ('default', 'd', None) +next ('plain', (1, 2), (), ('nexts', '__next__'), None) +next ('value', (1,), ('nexts', '__next__'), 1) +gen 6000 +weak {False} 200 +noisy_arg [(('del', 'arg zz'), ('after', 5)), (('del', 'arg zz'), ('after', False))] +through [(False, True, None, 4, 1, False, True, 'prop', False, True, 'prop')] 12000 +recursive [(True, False, 'd', 0, False)] +changing [(0, (False, None)), (2000, (True, 11)), (2100, (True, 12)), (2200, (True, 13)), (2300, (False, None))] +done +""" + + +class OutputTest(unittest.TestCase): + maxDiff = None + + def test_output(self): + self.assertEqual(_lines, EXPECTED.splitlines()[1:]) + + +if __name__ == "__main__": + import sys as _sys + + if "--emit" in _sys.argv: + builtins.print("\n".join(_lines)) + else: + unittest.main() diff --git a/tests/regrtest/test_getattr_hook_site_memo.py b/tests/regrtest/test_getattr_hook_site_memo.py new file mode 100644 index 000000000..caa97d051 --- /dev/null +++ b/tests/regrtest/test_getattr_hook_site_memo.py @@ -0,0 +1,101 @@ +"""A read site that a class's pure `__getattr__` answered tries the hook +first; reads the default lookup can answer, class changes, and hooks that +raise still behave as the full lookup does.""" + +import unittest + + +class G: + def __init__(self): + self.d = {"a": 1} + + def __getattr__(self, k): + return self.d.get(k, 0) + + +class R: + def __getattr__(self, k): + if k == "boom": + raise AttributeError(k) + return len(k) + + +class HookSiteMemo(unittest.TestCase): + def test_reads(self): + g = G() + for _ in range(500): + self.assertEqual(g.a, 1) + self.assertEqual(g.zz, 0) + + def test_instance_gains_attribute(self): + g = G() + out = [] + for i in range(400): + if i == 200: + g.a = 99 + out.append(g.a) + self.assertEqual(out[:200], [1] * 200) + self.assertEqual(out[200:], [99] * 200) + del g.a + self.assertEqual(g.a, 1) + + def test_class_gains_attribute(self): + class H(G): + pass + h = H() + for _ in range(300): + self.assertEqual(h.q, 0) + H.q = "class" + self.assertEqual(h.q, "class") + del H.q + self.assertEqual(h.q, 0) + H.__getattr__ = lambda self, k: "new" + self.assertEqual(h.q, "new") + + def test_hook_raises(self): + r = R() + for _ in range(300): + self.assertEqual(r.abc, 3) + with self.assertRaises(AttributeError): + r.boom + self.assertEqual(getattr(r, "boom", "d"), "d") + + def test_mixed_receivers(self): + class P: + a = 5 + objs = [G(), P(), G(), P()] + for _ in range(200): + self.assertEqual([o.a for o in objs], [1, 5, 1, 5]) + + + def test_stack_receivers(self): + # Receivers that live on the stack, not in a local: a global, an + # attribute chain, a call's result. + global G_OBJ + G_OBJ = G() + + class Box: + pass + + box = Box() + box.g = G() + out = [] + for i in range(600): + if i == 300: + G_OBJ.a = 7 + box.g.a = 8 + out.append((G_OBJ.a, G_OBJ.zz, box.g.a, G().a)) + self.assertEqual(out[0], (1, 0, 1, 1)) + self.assertEqual(out[-1], (7, 0, 8, 1)) + self.assertEqual(out.count((1, 0, 1, 1)), 300) + + def test_stack_receiver_raises(self): + holder = [R()] + for _ in range(300): + self.assertEqual(holder[0].abcd, 4) + with self.assertRaises(AttributeError): + holder[0].boom + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getattr_in_leaf_bodies.py b/tests/regrtest/test_getattr_in_leaf_bodies.py new file mode 100644 index 000000000..4a7e28b43 --- /dev/null +++ b/tests/regrtest/test_getattr_in_leaf_bodies.py @@ -0,0 +1,58 @@ +"""Functions whose bodies call getattr(), run often enough to evaluate +frameless: an instance attribute by a computed name, a default for a +miss, a builtin value's bound method, a property (plain and raising), +and a miss with no default (AttributeError), each matching CPython.""" + +import unittest + + +class Obj: + def __init__(self): + self.a = 1 + + @property + def p(self): + return self.a + 1 + + @property + def bad(self): + raise RuntimeError("bad") + + +def get(o, name): + return getattr(o, name) + + +def get_d(o, name): + return getattr(o, name, "dflt") + + +def run(n, f, *args): + out = None + for i in range(n): + out = f(*args) + return out + + +class GetattrLeafTests(unittest.TestCase): + def test_values(self): + o = Obj() + for n in (1, 400): + self.assertEqual(run(n, get, o, "a"), 1) + self.assertEqual(run(n, get, o, "p"), 2) + self.assertEqual(run(n, get_d, o, "zz"), "dflt") + self.assertEqual(run(n, get, [1, 1], "count")(1), 2) + self.assertEqual(run(n, get, "ab", "upper")(), "AB") + + def test_errors(self): + o = Obj() + with self.assertRaises(AttributeError): + run(400, get, o, "zz") + with self.assertRaises(RuntimeError): + run(400, get, o, "bad") + with self.assertRaises(RuntimeError): + run(400, get_d, o, "bad") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getattr_on_classes_memo.py b/tests/regrtest/test_getattr_on_classes_memo.py new file mode 100644 index 000000000..f9a52c339 --- /dev/null +++ b/tests/regrtest/test_getattr_on_classes_memo.py @@ -0,0 +1,250 @@ +"""`getattr(cls, name[, default])` answers that are remembered per class. + +The answer for a class under plain `type` is kept by the class's version +and the name: a missing name with a default, a value found on the MRO, +the class's own `__name__`. Every change that could alter the answer +must be seen at once: an attribute set, replaced or deleted on the class +or a base, a base swapped, a metaclass with its own answers, and a value +the class stops holding must die when it does. +""" + +import gc +import unittest +import weakref + +ROUNDS = 2000 + + +def read(cls, name, *default): + return getattr(cls, name, *default) + + +def has(cls, name): + return hasattr(cls, name) + + +class Base: + shared = "base" + + def method(self): + return "base method" + + @staticmethod + def static(): + return "static" + + +class Child(Base): + count = 3 + flag = True + ratio = 1.5 + data = b"bytes" + nothing = None + items = (1, 2) + table = {"k": 1} + + def own(self): + return "own" + + +class Token: + pass + + +class GetattrOnClassesTests(unittest.TestCase): + def test_missing_with_default_then_defined(self): + class C(Base): + pass + + marker = object() + for _ in range(ROUNDS): + self.assertIs(read(C, "__wrapped__", marker), marker) + self.assertIsNone(read(C, "later", None)) + self.assertFalse(has(C, "later")) + C.later = 7 + self.assertEqual(read(C, "later", None), 7) + self.assertTrue(has(C, "later")) + C.__wrapped__ = len + self.assertIs(read(C, "__wrapped__", marker), len) + del C.later + self.assertIsNone(read(C, "later", None)) + with self.assertRaises(AttributeError): + read(C, "later") + + def test_missing_then_defined_on_a_base(self): + class A: + pass + + class B(A): + pass + + for _ in range(ROUNDS): + self.assertEqual(read(B, "color", "none"), "none") + A.color = "red" + self.assertEqual(read(B, "color", "none"), "red") + B.color = "blue" + self.assertEqual(read(B, "color", "none"), "blue") + self.assertEqual(read(A, "color", "none"), "red") + del B.color + del A.color + self.assertEqual(read(B, "color", "none"), "none") + + def test_values_of_every_kind(self): + for _ in range(ROUNDS): + self.assertEqual(read(Child, "count"), 3) + self.assertIs(read(Child, "flag"), True) + self.assertEqual(read(Child, "ratio"), 1.5) + self.assertEqual(read(Child, "data"), b"bytes") + self.assertIsNone(read(Child, "nothing", 1)) + self.assertIs(read(Child, "items"), Child.__dict__["items"]) + self.assertIs(read(Child, "table"), Child.__dict__["table"]) + self.assertEqual(read(Child, "shared"), "base") + self.assertIs(read(Child, "method"), Base.__dict__["method"]) + self.assertIs(read(Child, "own"), Child.__dict__["own"]) + self.assertIs(read(Child, "static"), Base.__dict__["static"].__func__) + self.assertIs(read(Child, "__init__"), object.__init__) + + def test_replaced_values(self): + class C: + x = 1 + f = len + + def m(self): + return 1 + + first = C.__dict__["m"] + for _ in range(ROUNDS): + self.assertEqual(read(C, "x"), 1) + self.assertIs(read(C, "m"), first) + self.assertIs(read(C, "f"), len) + C.x = 2 + C.f = repr + + def second(self): + return 2 + + C.m = second + for _ in range(50): + self.assertEqual(read(C, "x"), 2) + self.assertIs(read(C, "m"), second) + self.assertIs(read(C, "f"), repr) + + def test_a_dropped_value_dies_at_once(self): + class C: + pass + + for kind in (Token, dict, list): + value = kind() + C.held = value + ref = weakref.ref(value) if kind is Token else None + for _ in range(ROUNDS): + self.assertIs(read(C, "held"), value) + del value + if ref is not None: + self.assertIsNotNone(ref()) + del C.held + self.assertIsNone(ref()) + else: + del C.held + self.assertEqual(read(C, "held", "gone"), "gone") + + def make(): + def f(self): + return 1 + + return f + + C.fn = make() + ref = weakref.ref(C.fn) + for _ in range(ROUNDS): + self.assertIs(read(C, "fn"), ref()) + C.fn = None + gc.collect() + self.assertIsNone(ref()) + self.assertIsNone(read(C, "fn", 1)) + + def test_a_class_that_dies(self): + refs = [] + for i in range(200): + + class Temp: + tag = (i, i) + + for _ in range(20): + self.assertEqual(read(Temp, "tag"), (i, i)) + self.assertEqual(read(Temp, "missing", i), i) + refs.append(weakref.ref(Temp)) + del Temp + gc.collect() + self.assertTrue(all(r() is None for r in refs)) + + def test_names(self): + class Outer: + class Inner: + pass + + for _ in range(ROUNDS): + self.assertEqual(read(Outer.Inner, "__name__"), "Inner") + self.assertTrue(read(Outer.Inner, "__qualname__").endswith("Outer.Inner")) + self.assertEqual(read(int, "__name__"), "int") + self.assertEqual(read(dict, "__qualname__"), "dict") + Outer.Inner.__name__ = "Renamed" + self.assertEqual(read(Outer.Inner, "__name__"), "Renamed") + Outer.Inner.__qualname__ = "Q.Renamed" + self.assertEqual(read(Outer.Inner, "__qualname__"), "Q.Renamed") + self.assertIs(read(Outer.Inner, "__name__"), read(Outer.Inner, "__name__")) + dynamic = type("Dyn", (Outer.Inner,), {}) + self.assertEqual(read(dynamic, "__name__"), "Dyn") + self.assertEqual(read(dynamic, "__qualname__"), "Dyn") + + def test_metaclass_answers_first(self): + class Meta(type): + @property + def shared(cls): + return "from the metaclass" + + def __getattr__(cls, name): + if name == "dynamic": + return "made up" + raise AttributeError(name) + + class M(Base, metaclass=Meta): + pass + + for _ in range(ROUNDS): + self.assertEqual(read(M, "shared"), "from the metaclass") + self.assertEqual(read(M, "dynamic", None), "made up") + self.assertIsNone(read(M, "absent", None)) + self.assertEqual(read(M, "__name__"), "M") + + def test_bases_swapped(self): + class A: + who = "a" + + class B: + who = "b" + + class C(A): + pass + + for _ in range(ROUNDS): + self.assertEqual(read(C, "who"), "a") + self.assertEqual(read(C, "only_b", 0), 0) + B.only_b = 9 + C.__bases__ = (B,) + self.assertEqual(read(C, "who"), "b") + self.assertEqual(read(C, "only_b", 0), 9) + + def test_same_text_different_name_objects(self): + class C: + value = 1 + + for i in range(ROUNDS): + name = "".join(["va", "lue"]) + self.assertEqual(read(C, name), 1) + other = "".join(["val", "ue%d" % (i % 3)]) + self.assertEqual(read(C, other, -1), -1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getitem_sequences_through_builtins.py b/tests/regrtest/test_getitem_sequences_through_builtins.py new file mode 100644 index 000000000..248927b0d --- /dev/null +++ b/tests/regrtest/test_getitem_sequences_through_builtins.py @@ -0,0 +1,341 @@ +"""Classes that are sequences by `__getitem__` alone, handed to builtins. + +`iter(seq)` of a class with `__getitem__` and no `__iter__` asks +`seq[0]`, `seq[1]`, ... until an `IndexError`. `list`, `tuple`, `zip`, +`enumerate`, `sum`, `sorted`, `in`, unpacking and `reversed` all step +that iterator, and a body such as `return self.items[i]` is read with no +call at all. These tests pin what each consumer gets, how the iteration +ends, what the iterator keeps afterwards, and what a tracer still sees. +""" + +import operator +import sys +import unittest + +ROUNDS = 300 + + +class Wraps: + def __init__(self, xs): + self.xs = xs + + def __len__(self): + return len(self.xs) + + def __getitem__(self, i): + return self.xs[i] + + +class Computed: + def __init__(self, n): + self.n = n + + def __len__(self): + return self.n + + def __getitem__(self, i): + if i >= self.n: + raise IndexError(i) + return i * i + + +class Bare: + def __getitem__(self, i): + if i >= 4: + raise IndexError + return i + + +class Stops: + def __getitem__(self, i): + if i >= 3: + raise StopIteration + return i + + +class Fails: + def __len__(self): + return 5 + + def __getitem__(self, i): + if i == 2: + raise ValueError("two") + if i >= 5: + raise IndexError + return i + + +class Keyed: + def __init__(self): + self.d = {0: "a", 1: "b"} + + def __len__(self): + return 3 + + def __getitem__(self, i): + return self.d[i] + + +class Text: + def __init__(self): + self.s = "héllo" + + def __len__(self): + return 5 + + def __getitem__(self, i): + return self.s[i] + + +class Shifted: + def __init__(self): + self.xs = [1, 2, 3] + + def __len__(self): + return 3 + + def __getitem__(self, i): + return self.xs[i - 3] + + +def outcome(f): + try: + return f() + except Exception as e: + return type(e).__name__, str(e) + + +class Consumers(unittest.TestCase): + def check(self, make, want): + for _ in range(ROUNDS): + q = make() + self.assertEqual(list(q), want) + self.assertEqual(tuple(q), tuple(want)) + self.assertEqual([v for v in q], want) + self.assertEqual(list(zip(q, q)), list(zip(want, want))) + self.assertEqual(list(enumerate(q)), list(enumerate(want))) + self.assertEqual(list(map(str, q)), [str(v) for v in want]) + self.assertEqual(sorted(q, key=repr), sorted(want, key=repr)) + self.assertEqual([*q, *q], want + want) + self.assertEqual(set(q), set(want)) + self.assertEqual(dict.fromkeys(q), dict.fromkeys(want)) + self.assertEqual((want[0] in q) if want else None, True if want else None) + self.assertFalse(object() in q) + + def test_a_wrapped_list(self): + for n in (0, 1, 2, 7, 40): + xs = list(range(n)) + self.check(lambda: Wraps(xs), xs) + + def test_a_wrapped_tuple_and_string(self): + self.check(lambda: Wraps(("a", "b", "c")), ["a", "b", "c"]) + self.check(Text, ["h", "é", "l", "l", "o"]) + + def test_a_computed_item(self): + for n in (0, 1, 5): + self.check(lambda: Computed(n), [i * i for i in range(n)]) + + def test_an_index_the_body_shifts(self): + # Indexes -3 to 2 all answer: the walk ends at the seventh read. + self.check(Shifted, [1, 2, 3, 1, 2, 3]) + + def test_reversed(self): + for _ in range(ROUNDS): + for n in (0, 1, 2, 7): + xs = list(range(n)) + self.assertEqual(list(reversed(Wraps(xs))), xs[::-1]) + self.assertEqual( + list(reversed(Computed(n))), [i * i for i in range(n)][::-1] + ) + self.assertEqual( + list(zip(reversed(Wraps(xs)), Wraps(xs))), list(zip(xs[::-1], xs)) + ) + self.assertEqual(sum(reversed(Computed(5))), 30) + + +class Ends(unittest.TestCase): + def test_a_bare_raise_ends_quietly(self): + for _ in range(ROUNDS): + self.assertEqual(list(Bare()), [0, 1, 2, 3]) + self.assertEqual([v for v in Bare()], [0, 1, 2, 3]) + self.assertEqual(list(zip(Bare(), range(10))), [(i, i) for i in range(4)]) + self.assertEqual(list(Stops()), [0, 1, 2]) + self.assertEqual([v for v in Stops()], [0, 1, 2]) + + def test_any_other_error_passes_through(self): + for _ in range(ROUNDS): + for f in ( + lambda: list(Fails()), + lambda: [v for v in Fails()], + lambda: list(zip(Fails(), range(10))), + lambda: list(reversed(Fails())), + lambda: sum(Fails()), + ): + self.assertEqual(outcome(f), ("ValueError", "two")) + self.assertEqual(outcome(lambda: list(Keyed())), ("KeyError", "2")) + self.assertEqual(outcome(lambda: [v for v in Keyed()]), ("KeyError", "2")) + self.assertEqual( + outcome(lambda: list(reversed(Keyed()))), ("KeyError", "2") + ) + + def test_next_at_the_end(self): + for _ in range(ROUNDS): + it = iter(Wraps([1])) + self.assertEqual((next(it), next(it, "d"), next(it, "d")), (1, "d", "d")) + with self.assertRaises(StopIteration) as caught: + next(it) + self.assertEqual(caught.exception.args, ()) + + +class IteratorState(unittest.TestCase): + def test_exhaustion_sticks(self): + for _ in range(ROUNDS): + s = Wraps([1, 2, 3]) + it = iter(s) + got = [next(it), operator.length_hint(it)] + s.xs.append(4) + got += list(it) + s.xs.append(5) + got += list(it) + self.assertEqual(got, [1, 2, 2, 3, 4]) + r = reversed(s) + got = [next(r), operator.length_hint(r)] + del s.xs[2:] + self.assertEqual(got + list(r) + list(r), [5, 4]) + + def test_setstate_clamps(self): + for _ in range(ROUNDS): + it = iter(Wraps([10, 20, 30, 40])) + next(it) + it.__setstate__(-5) + self.assertEqual(list(it), [10, 20, 30, 40]) + r = reversed(Wraps([1, 2, 3, 4])) + r.__setstate__(1) + self.assertEqual(list(r), [2, 1]) + # Past the end, the index is the last item's. + r = reversed(Wraps([1, 2])) + r.__setstate__(7) + self.assertEqual(list(r), [2, 1]) + r = reversed(Wraps([1, 2])) + r.__setstate__(-9) + self.assertEqual(list(r), []) + # An exhausted iterator ignores the state. + r = reversed(Wraps([1])) + self.assertEqual(list(r), [1]) + r.__setstate__(0) + self.assertEqual(list(r), []) + + def test_a_getitem_that_steps_its_own_iterator(self): + class Reenters: + def __init__(self): + self.it = None + self.xs = list(range(8)) + + def __getitem__(self, i): + if i == 2 and self.it is not None: + it, self.it = self.it, None + return ("re", next(it)) + return self.xs[i] + + for _ in range(ROUNDS): + r = Reenters() + r.it = it = iter(r) + self.assertEqual(list(it), [0, 1, ("re", 2), 4, 5, 6, 7]) + + def test_the_sequence_is_released_at_the_end(self): + log = [] + + class Logged: + def __init__(self): + self.xs = [1, 2] + + def __getitem__(self, i): + return self.xs[i] + + def __del__(self): + log.append("del") + + for _ in range(ROUNDS): + del log[:] + it = iter(Logged()) + self.assertEqual(list(it), [1, 2]) + log.append("after") + self.assertEqual(log, ["del", "after"]) + + +class ClassChanges(unittest.TestCase): + def test_a_class_that_gains_and_loses_iter(self): + class Base: + def __init__(self): + self.xs = [1, 2, 3] + + def __getitem__(self, i): + return self.xs[i] + + class Derived(Base): + pass + + for _ in range(ROUNDS): + self.assertEqual([list(Base()), list(Derived())], [[1, 2, 3], [1, 2, 3]]) + Base.__iter__ = lambda self: iter("ab") + self.assertEqual([list(Base()), list(Derived())], [["a", "b"], ["a", "b"]]) + del Base.__iter__ + self.assertEqual([list(Base()), list(Derived())], [[1, 2, 3], [1, 2, 3]]) + Derived.__iter__ = None + with self.assertRaises(TypeError): + list(Derived()) + del Derived.__iter__ + # An instance attribute is not the class's slot. + b = Base() + b.__iter__ = lambda: iter("zz") + self.assertEqual(list(b), [1, 2, 3]) + + def test_a_getitem_swapped_between_steps(self): + class Swapped: + def __init__(self): + self.xs = [1, 2, 3, 4, 5, 6] + + def __getitem__(self, i): + return self.xs[i] + + plain = Swapped.__getitem__ + for _ in range(ROUNDS): + it = iter(Swapped()) + got = [next(it), next(it)] + Swapped.__getitem__ = lambda self, i: -self.xs[i] + got.append(next(it)) + Swapped.__getitem__ = plain + self.assertEqual(got + list(it), [1, 2, -3, 4, 5, 6]) + + +class Tracing(unittest.TestCase): + def test_a_tracer_sees_every_getitem_call(self): + def run(): + s = Wraps([1, 2, 3]) + return [list(s), [v for v in s], list(reversed(s)), list(zip(s, s))] + + for _ in range(ROUNDS): + want = run() + calls = [] + + def tracer(frame, event, arg): + if event == "call": + calls.append(frame.f_code.co_name) + + sys.settrace(tracer) + try: + got = run() + finally: + sys.settrace(None) + self.assertEqual(got, want) + # Four reads for each forward pass but `zip`'s second (which is + # never asked past the first's end), three for `reversed`. + self.assertEqual(calls.count("__getitem__"), 18) + self.assertEqual( + set(calls) - {"run", "__init__", "__getitem__", "__len__", ""}, + set(), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getter_instance_calls.py b/tests/regrtest/test_getter_instance_calls.py new file mode 100644 index 000000000..47a62ec4f --- /dev/null +++ b/tests/regrtest/test_getter_instance_calls.py @@ -0,0 +1,53 @@ +"""Calls of `itemgetter`, `attrgetter` and `partial` instances in a loop. + +A call site settled on the instance's native `__call__` runs its fast +half with the instance first; a miss raises as the full call does, and +a different callee at the same site still works. Items are heap objects. +Run it past the compile threshold. +""" + +import functools +from operator import attrgetter, itemgetter + + +class P: + def __init__(self, x): + self.x = x + + +def run(n): + ig, ag = itemgetter(1), attrgetter("x") + many = itemgetter(0, 2) + part = functools.partial(max, 3) + rows = [("a", [i]) for i in range(4)] + total = 0 + for i in range(n): + for f, arg in ((ig, rows[i % 4]), (ag, P([i])), (part, i % 7)): + r = f(arg) + total += r[0] if isinstance(r, list) else r + assert many(("p", "q", "r")) == ("p", "r") + assert ig({1: "one"}) == "one" + try: + ig(("only",)) + except IndexError: + pass + else: + raise AssertionError("short tuple") + try: + ig({}) + except KeyError: + pass + else: + raise AssertionError("missing key") + try: + ag(1) + except AttributeError: + pass + else: + raise AssertionError("missing attribute") + return total + + +expected = sum((i % 4) + i + max(3, i % 7) for i in range(2000)) +assert run(2000) == expected +print("ok") diff --git a/tests/regrtest/test_getters_and_dunders_called_directly.py b/tests/regrtest/test_getters_and_dunders_called_directly.py new file mode 100644 index 000000000..d7fca2425 --- /dev/null +++ b/tests/regrtest/test_getters_and_dunders_called_directly.py @@ -0,0 +1,205 @@ +"""itemgetter on built-in subclasses, methodcaller's direct method call, and +`str()` / `repr()` / `f'{x!r}'` of instances with Python dunders. + +itemgetter's fast half reads a subclass's payload (a named tuple) when its +`__getitem__` is still the base's own; methodcaller calls a plain +instance's Python method with the instance first; `!r` and `str()` call a +Python `__repr__` directly. Each must keep the semantics of the full path. +""" + +import collections +import operator +import unittest + + +class Overrides(tuple): + def __getitem__(self, i): + return ("over", i) + + +class MissingDict(dict): + def __missing__(self, key): + return ("missing", key) + + +class GetitemDict(dict): + def __getitem__(self, key): + return ("own", key) + + +class ItemgetterTests(unittest.TestCase): + def test_named_tuple(self): + NT = collections.namedtuple("NT", "a b c") + t = NT(1, [2], "c") + g = operator.itemgetter(1) + for _ in range(3000): + self.assertEqual(g(t), [2]) + self.assertIs(operator.itemgetter(1)(t), t[1]) + self.assertEqual(operator.itemgetter(-1)(t), "c") + self.assertEqual(operator.itemgetter(0, 2)(t), (1, "c")) + with self.assertRaises(IndexError): + operator.itemgetter(5)(t) + self.assertEqual(operator.itemgetter(slice(0, 2))(t), (1, [2])) + + def test_overridden_getitem_runs(self): + g = operator.itemgetter(1) + for _ in range(3000): + self.assertEqual(g(Overrides((1, 2))), ("over", 1)) + + def test_dict_subclasses(self): + g = operator.itemgetter("k") + m = MissingDict(k=1) + for _ in range(3000): + self.assertEqual(g(m), 1) + self.assertEqual(g(MissingDict()), ("missing", "k")) + self.assertEqual(g(GetitemDict(k=1)), ("own", "k")) + with self.assertRaises(KeyError): + g(collections.OrderedDict()) + + def test_list_subclass(self): + class L(list): + pass + g = operator.itemgetter(0) + for _ in range(3000): + self.assertEqual(g(L(["x"])), "x") + with self.assertRaises(IndexError): + g(L()) + + +class Target: + def __init__(self): + self.calls = [] + + def m(self, *args, **kwargs): + self.calls.append((args, kwargs)) + return len(self.calls) + + def one(self, a): + return a * 2 + + +class MethodcallerTests(unittest.TestCase): + def test_positional_and_keywords(self): + t = Target() + self.assertEqual(operator.methodcaller("m")(t), 1) + self.assertEqual(operator.methodcaller("m", 1, 2)(t), 2) + self.assertEqual(operator.methodcaller("m", 1, k=3)(t), 3) + self.assertEqual(t.calls, [((), {}), ((1, 2), {}), ((1,), {"k": 3})]) + + def test_hot_loop(self): + g = operator.methodcaller("one", [7]) + t = Target() + for _ in range(5000): + self.assertEqual(g(t), [7, 7]) + + def test_instance_attribute_shadows(self): + t = Target() + t.one = lambda a: ("own", a) + self.assertEqual(operator.methodcaller("one", 1)(t), ("own", 1)) + + def test_getattribute_override(self): + class G(Target): + def __getattribute__(self, name): + if name == "one": + return lambda a: ("ga", a) + return object.__getattribute__(self, name) + self.assertEqual(operator.methodcaller("one", 1)(G()), ("ga", 1)) + + def test_wrong_arity_and_missing(self): + with self.assertRaises(TypeError): + operator.methodcaller("one")(Target()) + with self.assertRaises(AttributeError): + operator.methodcaller("nope")(Target()) + + def test_builtin_receivers(self): + self.assertEqual(operator.methodcaller("upper")("ab"), "AB") + self.assertEqual(operator.methodcaller("count", 1)([1, 1, 2]), 2) + + def test_class_method_replaced(self): + class C: + def m(self): + return 1 + g = operator.methodcaller("m") + c = C() + for _ in range(3000): + self.assertEqual(g(c), 1) + C.m = lambda self: 2 + self.assertEqual(g(c), 2) + + +class StrSub(str): + pass + + +class ReprOnly: + def __repr__(self): + return "R!" + + +class ReprSub: + def __repr__(self): + return StrSub("RS") + + +class BadRepr: + def __repr__(self): + return 5 + + +class Both: + def __str__(self): + return "S" + + def __repr__(self): + return "R" + + +class ReprDunderTests(unittest.TestCase): + def test_conversions(self): + for _ in range(3000): + self.assertEqual(f"{ReprOnly()!r}", "R!") + self.assertEqual(str(ReprOnly()), "R!") + self.assertEqual(f"{Both()!r}|{Both()!s}|{Both()}", "R|S|S") + self.assertEqual(str(Both()), "S") + self.assertEqual(f"{ReprSub()!r}", "RS") + self.assertIs(type(repr(ReprSub())), StrSub) + self.assertIs(type(str(ReprSub())), StrSub) + + def test_non_string_result(self): + with self.assertRaises(TypeError): + f"{BadRepr()!r}" + with self.assertRaises(TypeError): + repr(BadRepr()) + with self.assertRaises(TypeError): + str(BadRepr()) + + def test_class_changes_seen(self): + class C: + def __repr__(self): + return "one" + c = C() + for _ in range(3000): + self.assertEqual(str(c), "one") + C.__str__ = lambda self: "str" + self.assertEqual(str(c), "str") + del C.__str__ + self.assertEqual(str(c), "one") + C.__repr__ = lambda self: "two" + self.assertEqual(f"{c!r}", "two") + self.assertEqual(str(c), "two") + + def test_base_gains_str(self): + class Base: + def __repr__(self): + return "base" + class Sub(Base): + pass + s = Sub() + for _ in range(3000): + self.assertEqual(str(s), "base") + Base.__str__ = lambda self: "base-str" + self.assertEqual(str(s), "base-str") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_getters_over_class_defaults.py b/tests/regrtest/test_getters_over_class_defaults.py new file mode 100644 index 000000000..755f7a1ed --- /dev/null +++ b/tests/regrtest/test_getters_over_class_defaults.py @@ -0,0 +1,142 @@ +"""Reading a name off instances whose class also holds a plain value for it. + +A dataclass field with a default, or a class-level default an +`__init__` overwrites, leaves a plain value on the class under the same +name the instance stores. `attrgetter`, `getattr`, `hasattr` and key +functions built on them read the instance's own value at the place its +class's instances keep the name, and the class's value only where an +instance has none. These tests pin which value each read gets, for +instances laid out differently, and across changes to the class. +""" + +import dataclasses +import operator +import unittest + +ROUNDS = 300 + + +@dataclasses.dataclass +class Record: + x: int + y: int = 0 + name: str = "n" + pair: tuple = () + nothing: object = None + ratio: float = 1.5 + + +class Config: + y = 0 + label = "class" + + def describe(self): + return "method" + + def __init__(self, y=None): + if y is not None: + self.y = y + + +class Derived(Config): + pass + + +def reads(objs, name): + get = operator.attrgetter(name) + return ( + [get(o) for o in objs], + list(map(get, objs)), + [getattr(o, name) for o in objs], + [getattr(o, name, "default") for o in objs], + [hasattr(o, name) for o in objs], + min(map(get, objs)), + ) + + +class InstanceOrClass(unittest.TestCase): + def test_dataclass_fields_with_defaults(self): + for _ in range(ROUNDS): + rs = [Record(i, i % 3) for i in range(6)] + [Record(9)] + xs, ys = [0, 1, 2, 3, 4, 5, 9], [0, 1, 2, 0, 1, 2, 0] + self.assertEqual(reads(rs, "x"), (xs, xs, xs, xs, [True] * 7, 0)) + self.assertEqual(reads(rs, "y"), (ys, ys, ys, ys, [True] * 7, 0)) + names = ["n"] * 7 + self.assertEqual(reads(rs, "name"), (names, names, names, names, [True] * 7, "n")) + self.assertEqual(sorted(rs, key=operator.attrgetter("y"))[0].x, 0) + self.assertEqual(max(rs, key=operator.attrgetter("y")).x, 2) + self.assertEqual([r.x for r in sorted(rs, key=operator.attrgetter("ratio", "x"))], xs) + + def test_instances_with_and_without_their_own_value(self): + for _ in range(ROUNDS): + cs = [Config(), Config(5), Derived(), Derived(7), Config()] + ys = [0, 5, 0, 7, 0] + self.assertEqual(reads(cs, "y"), (ys, ys, ys, ys, [True] * 5, 0)) + labels = ["class"] * 5 + self.assertEqual(reads(cs, "label")[:3], (labels, labels, labels)) + + def test_an_instance_that_drops_its_value(self): + get = operator.attrgetter("y") + for _ in range(ROUNDS): + r = Record(1, 2) + self.assertEqual((get(r), getattr(r, "y")), (2, 2)) + del r.y + self.assertEqual((get(r), getattr(r, "y"), hasattr(r, "y")), (0, 0, True)) + + def test_a_method_one_instance_shadows(self): + get = operator.attrgetter("describe") + for _ in range(ROUNDS): + a, b = Config(), Config() + b.describe = "own" + self.assertEqual(getattr(b, "describe"), "own") + self.assertEqual(getattr(a, "describe")(), "method") + self.assertEqual([type(v).__name__ for v in map(get, [a, b])], ["method", "str"]) + + def test_instances_laid_out_differently(self): + get = operator.attrgetter("y") + for _ in range(ROUNDS): + first = Config(1) + late = Config.__new__(Config) + late.other = 1 + late.y = 2 + through_dict = Config.__new__(Config) + through_dict.__dict__["y"] = 3 + without = Config() + objs = [first, late, through_dict, without, first] + self.assertEqual(list(map(get, objs)), [1, 2, 3, 0, 1]) + self.assertEqual([getattr(o, "y") for o in objs], [1, 2, 3, 0, 1]) + self.assertIs(sorted(objs[:4], key=get)[0], without) + + +class ClassChanges(unittest.TestCase): + def test_a_property_then_a_value_then_nothing(self): + class Shifting: + y = 0 + + def __init__(self, y): + self.y = y + + get = operator.attrgetter("y") + cs = [Shifting(i) for i in range(1, 5)] + for _ in range(ROUNDS): + self.assertEqual(list(map(get, cs)), [1, 2, 3, 4]) + self.assertEqual([getattr(c, "y") for c in cs], [1, 2, 3, 4]) + # A property is a data descriptor: it wins over every instance. + Shifting.y = property(lambda self: "prop") + for _ in range(ROUNDS): + self.assertEqual(list(map(get, cs)), ["prop"] * 4) + self.assertEqual([getattr(c, "y") for c in cs], ["prop"] * 4) + Shifting.y = 10 + bare = Shifting.__new__(Shifting) + for _ in range(ROUNDS): + self.assertEqual(list(map(get, cs + [bare])), [1, 2, 3, 4, 10]) + del Shifting.y + for _ in range(ROUNDS): + self.assertEqual(list(map(get, cs)), [1, 2, 3, 4]) + self.assertEqual((getattr(bare, "y", "default"), hasattr(bare, "y")), ("default", False)) + with self.assertRaises(AttributeError): + get(bare) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_gil_switch_interval.py b/tests/regrtest/test_gil_switch_interval.py new file mode 100644 index 000000000..7e44fa8ee --- /dev/null +++ b/tests/regrtest/test_gil_switch_interval.py @@ -0,0 +1,100 @@ +"""A thread back from a blocking call gets the GIL within the switch interval. + +A busy thread keeps the GIL for `sys.getswitchinterval()` once another +thread asks for it, then hands it over. The interval is the one the +program set, and it is counted once: from the moment the other thread +started to wait, not again from when the busy thread's own turn ran out. +""" + +import sys +import threading +import time +import unittest + + +def waits_behind_a_busy_thread(interval, wanted=3, tries=60): + """How long `time.sleep` calls took to come back while a busy thread ran. + + Only the calls during which the busy thread got to run count: on a + loaded machine it may not be scheduled before the sleeper is back, and + the sleeper then finds the GIL free. A call it did run through waits at + least the interval the busy thread is owed; load can only add to that. + """ + before = sys.getswitchinterval() + sys.setswitchinterval(interval) + stop = False + spins = [0] + + def spin(): + xs = [] + while not stop: + xs.append(1) + if len(xs) > 100: + del xs[:50] + spins[0] += 1 + + t = threading.Thread(target=spin) + t.start() + try: + took = [] + for _ in range(tries): + seen = spins[0] + t0 = time.perf_counter() + time.sleep(0.0002) + wait = time.perf_counter() - t0 + if spins[0] != seen: + took.append(wait) + if len(took) >= wanted: + break + finally: + stop = True + t.join() + sys.setswitchinterval(before) + return took + + +class SwitchIntervalTests(unittest.TestCase): + def test_interval_round_trips(self): + before = sys.getswitchinterval() + try: + for value in (0.0001, 0.005, 0.02): + sys.setswitchinterval(value) + self.assertAlmostEqual(sys.getswitchinterval(), value, places=6) + finally: + sys.setswitchinterval(before) + + def check(self, interval): + waits = waits_behind_a_busy_thread(interval) + if not waits: + self.skipTest("the busy thread never got to run") + # The busy thread keeps the GIL for the interval the program set... + self.assertGreater(min(waits), interval * 0.5, waits) + # ...counted once, from when the other thread started to wait: + # one interval, not two (the shortest wait is the one the load + # stretched least). + self.assertLess(min(waits), interval * 1.6, waits) + + def test_long_interval(self): + self.check(0.1) + + def test_short_interval(self): + # (Not so short that one scheduling quantum, 10 ms on a saturated + # machine, reads as a second interval: the sleeper can be that late + # getting a processor before it even asks for the GIL.) + self.check(0.03) + + def test_a_busy_thread_alone_is_not_slowed(self): + # With nobody waiting, the interval changes nothing a thread does. + before = sys.getswitchinterval() + sys.setswitchinterval(1e-6) + try: + total = 0 + for i in range(200000): + total += i + self.assertEqual(total, 199999 * 200000 // 2) + finally: + sys.setswitchinterval(before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_global_receiver_attr_reads.py b/tests/regrtest/test_global_receiver_attr_reads.py new file mode 100644 index 000000000..48a9a7071 --- /dev/null +++ b/tests/regrtest/test_global_receiver_attr_reads.py @@ -0,0 +1,134 @@ +"""Attribute reads of a receiver that isn't a local (`p.x` of a global). + +Compiled code reads a `__slots__` member, a class's plain value through an +instance, and a named tuple's field of a receiver on the stack as it reads +a local's. Changes to the class, an instance entry shadowing a class +value, a deleted slot, and receivers of other classes at the same site +read as CPython reads them. +""" + +import unittest +from collections import namedtuple + +N = 30000 + + +class S: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x = x + self.y = y + + +class O: + K = 5 + + def __init__(self): + self.v = 1 + + +NT = namedtuple("NT", "a b c") + +p = S(1, 2) +o = O() +nt = NT(1, 2, 3) + + +def read_slot(): + return p.x + + +def read_class(): + return o.K + + +def read_field(): + return nt.b + + +class GlobalReceiverReadTests(unittest.TestCase): + def test_slot(self): + global p + out = [] + for i in range(N): + if i == N // 3: + p.x = 7 + if i == N // 2: + p = S(9, 9) + out.append(read_slot()) + self.assertEqual((out[0], out[N // 3], out[-1]), (1, 7, 9)) + del p.x + with self.assertRaises(AttributeError): + read_slot() + p = S(1, 2) + + def test_class_value(self): + out = [] + for i in range(N): + if i == N // 4: + O.K = 6 + if i == N // 2: + o.K = "own" + if i == 3 * N // 4: + del o.K + out.append(read_class()) + self.assertEqual(out[0], 5) + self.assertEqual(out[N // 4], 6) + self.assertEqual(out[N // 2], "own") + self.assertEqual(out[-1], 6) + O.K = 5 + + def test_class_value_becomes_property(self): + class C: + K = 1 + + global c_inst + c_inst = C() + + def rd(): + return c_inst.K + + out = [] + for i in range(N): + if i == N // 2: + C.K = property(lambda self: "prop") + out.append(rd()) + self.assertEqual((out[0], out[-1]), (1, "prop")) + + def test_named_tuple_field(self): + global nt + out = [] + for i in range(N): + if i == N // 2: + nt = NT(4, 5, 6) + out.append(read_field()) + self.assertEqual((out[0], out[-1]), (2, 5)) + + def test_mixed_receivers(self): + class A: + __slots__ = ("x",) + + def __init__(self): + self.x = "a" + + class B: + def __init__(self): + self.x = "b" + + global mixed + items = [A(), B(), S(3, 4)] + out = [] + for i in range(N): + mixed = items[i % 3] + out.append(mixed_read()) + self.assertEqual(out[:3], ["a", "b", 3]) + self.assertEqual(out[-3:], ["a", "b", 3]) + + +def mixed_read(): + return mixed.x + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_global_stores_in_compiled_code.py b/tests/regrtest/test_global_stores_in_compiled_code.py new file mode 100644 index 000000000..cbf23c7db --- /dev/null +++ b/tests/regrtest/test_global_stores_in_compiled_code.py @@ -0,0 +1,220 @@ +"""`STORE_GLOBAL` runs in compiled code. + +A function that rebinds a module global (`global n; n += 1`) used to leave +its native code at every store. These tests pin what the store must still +do from there: every reader sees the new value at once, a new name is +bound, the displaced value is released on time, and the store goes to the +running function's own globals, whichever dictionary that is. +""" + +import sys +import types +import unittest + +N = 5000 + +counter = 0 +total = 0.0 +label = "start" +flag = None +held = None +events = [] + + +def bump(): + global counter + counter += 1 + + +def bump_by(k): + global counter, total + counter += k + total += k / 2 + + +def read_counter(): + return counter + + +def relabel(i): + global label + label = "n%d" % (i & 7) + return label + + +def set_flag(v): + global flag + flag = v + + +def hold(v): + global held + held = v + + +class Tracked: + def __init__(self, tag): + self.tag = tag + + def __del__(self): + events.append(self.tag) + + +class GlobalStores(unittest.TestCase): + def setUp(self): + global counter, total, label, flag, held + counter, total, label, flag, held = 0, 0.0, "start", None, None + events.clear() + + def test_counter_in_a_hot_loop(self): + for _ in range(N): + bump() + self.assertEqual(counter, N) + self.assertEqual(read_counter(), N) + self.assertEqual(sys.modules[__name__].counter, N) + + def test_readers_see_each_store(self): + seen = [] + for i in range(N): + bump_by(2) + if i % 1000 == 0: + seen.append((read_counter(), counter, total)) + self.assertEqual(seen, [(2 * i + 2, 2 * i + 2, float(i + 1)) for i in range(0, N, 1000)]) + + def test_strings_none_and_objects(self): + for i in range(N): + got = relabel(i) + set_flag(None if i & 1 else i) + self.assertEqual((got, label, flag), ("n%d" % ((N - 1) & 7),) * 2 + (None,)) + set_flag([1, 2]) + self.assertEqual(flag, [1, 2]) + + def test_displaced_values_are_released_on_time(self): + for i in range(50): + hold(Tracked(i)) + self.assertEqual(events, list(range(i))) + hold(None) + self.assertEqual(events, list(range(50))) + + def test_new_names_are_bound(self): + def make(i): + global fresh_name_a, fresh_name_b + fresh_name_a = i + if i == N - 1: + fresh_name_b = "late" + + g = globals() + g.pop("fresh_name_a", None) + g.pop("fresh_name_b", None) + for i in range(N): + make(i) + self.assertEqual((g["fresh_name_a"], g["fresh_name_b"]), (N - 1, "late")) + del g["fresh_name_a"], g["fresh_name_b"] + + def test_delete_then_store_again(self): + def cycle(i): + global temp_name + temp_name = i + v = temp_name + del temp_name + return v + + self.assertEqual(sum(cycle(i) for i in range(N)), sum(range(N))) + self.assertNotIn("temp_name", globals()) + + def test_shadowing_a_builtin_and_back(self): + def shadow(v): + global len + len = v + + def measure(xs): + return len(xs) + + for _ in range(200): + self.assertEqual(measure([1, 2, 3]), 3) + shadow(lambda xs: "shadowed") + self.assertEqual(measure([1, 2, 3]), "shadowed") + del globals()["len"] + self.assertEqual(measure([1, 2, 3]), 3) + + def test_one_code_object_two_globals(self): + def body(): + global hits + hits = hits + 1 + return hits + + first, second = {"hits": 0}, {"hits": 100} + f = types.FunctionType(body.__code__, first) + g = types.FunctionType(body.__code__, second) + for _ in range(N): + f() + g() + self.assertEqual((first["hits"], second["hits"]), (N, 100 + N)) + self.assertNotIn("hits", globals()) + + def test_exec_with_its_own_globals(self): + source = "def tick():\n global n\n n += 1\n\nfor _ in range(%d):\n tick()\n" % N + plain = {"n": 0} + exec(source, plain) + self.assertEqual(plain["n"], N) + + class Recording(dict): + stored = [] + + def __setitem__(self, key, value): + Recording.stored.append(key) + dict.__setitem__(self, key, value) + + recording = Recording(n=5) + exec(source, recording) + self.assertEqual(dict.__getitem__(recording, "n"), N + 5) + # (A function's global store goes to the dict itself; the module + # level's name stores go through the mapping.) + self.assertNotIn("n", Recording.stored) + self.assertIn("tick", Recording.stored) + + def test_generators_and_nested_functions(self): + def gen(n): + global counter + for i in range(n): + counter += 1 + yield counter + + def outer(n): + def inner(): + global counter + counter += 10 + return counter + + return [inner() for _ in range(n)] + + self.assertEqual(list(gen(5)), [1, 2, 3, 4, 5]) + self.assertEqual(outer(3), [15, 25, 35]) + self.assertEqual(sum(1 for _ in gen(N)), N) + self.assertEqual(counter, 35 + N) + + def test_recursive_stores(self): + def descend(n): + global counter + counter += 1 + if n: + descend(n - 1) + counter += 1 + + for _ in range(200): + descend(20) + self.assertEqual(counter, 200 * 42) + + def test_store_of_the_value_being_read(self): + def swap(): + global label, flag + label, flag = flag, label + + set_flag("other") + for _ in range(N + 1): + swap() + self.assertEqual((label, flag), ("other", "start")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_globals_missing_cycle.py b/tests/regrtest/test_globals_missing_cycle.py new file mode 100644 index 000000000..5987fc7a5 --- /dev/null +++ b/tests/regrtest/test_globals_missing_cycle.py @@ -0,0 +1,83 @@ +"""A dict subclass with `__missing__` used as globals, then kept alive only +by a reference cycle through its own values. + +Builtin lookups elsewhere ask whether such globals may serve them. Once no +code runs with the owner's dict, the answer must go back to the fast +paths, even while the cycle keeps the owner alive, and a function still +running with the dict must keep its misses going to `__missing__`. A pure +`__hash__` evaluated meanwhile must keep working (`typing.NamedTuple` +evaluates its annotations under such globals). +""" + +import dataclasses +import gc +import typing +import unittest +import weakref + + +class Fallback(dict): + def __missing__(self, key): + if key == "magic": + return 42 + raise KeyError(key) + + +@dataclasses.dataclass(frozen=True) +class Before: + a: int + b: int = 0 + + +class Later(typing.NamedTuple): + x: int + y: "Undefined" = 0 # noqa: F821 + + +class GlobalsMissingCycle(unittest.TestCase): + def test_cyclic_owner_released(self): + g = Fallback() + g["me"] = g + r = weakref.ref(g) + exec("def f():\n return magic + len('ab')\n", g) + # (Out of the dict, as `annotationlib` drops its function: a + # function stored in its own globals is a cycle through the dict.) + f = g.pop("f") + for _ in range(3000): + self.assertEqual(f(), 44) + del g + for _ in range(3000): + self.assertEqual(f(), 44) + del f + total = 0 + for i in range(3000): + total += abs(-i) + len("xy") + self.assertEqual(total, sum(range(3000)) + 6000) + gc.collect() + self.assertIsNone(r()) + + def test_running_code_keeps_missing(self): + g = Fallback() + g["me"] = g + exec( + "def run(n):\n" + " t = 0\n" + " for i in range(n):\n" + " t += magic + len('a')\n" + " return t\n", + g, + ) + run = g["run"] + del g + self.assertEqual(run(5000), 5000 * 43) + + def test_leaf_hash_after_namedtuple(self): + for i in range(5000): + d = {Before(i % 7): i} + self.assertEqual(d[Before(i % 7)], i) + self.assertEqual(hash(Before(i)), hash((i, 0))) + self.assertEqual(Later(1), (1, 0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_groupby_group_drain.py b/tests/regrtest/test_groupby_group_drain.py new file mode 100644 index 000000000..4c6679fc6 --- /dev/null +++ b/tests/regrtest/test_groupby_group_drain.py @@ -0,0 +1,55 @@ +"""`list(g)` of a `groupby` group over a plain list or tuple takes the +group's items in one loop; groups, the parent's state, and the general +cases match `itertools.groupby`.""" + +import itertools +import unittest + + +class GroupDrain(unittest.TestCase): + def test_groups(self): + for xs in ([], [1], [1, 1, 2, 2, 2, 3], (5, 5, 5), list("aabbbc"), + [1, 1.0, True, 2], [None, None, 0]): + for _ in range(50): + got = [(k, list(g)) for k, g in itertools.groupby(xs)] + want = [] + for x in xs: + if want and want[-1][0] == x: + want[-1][1].append(x) + else: + want.append((x, [x])) + self.assertEqual(got, want) + + def test_partial_then_drain(self): + it = itertools.groupby([1, 1, 1, 2, 2, 3]) + k, g = next(it) + self.assertEqual(next(g), 1) + self.assertEqual(list(g), [1, 1]) + self.assertEqual(list(g), []) + k2, g2 = next(it) + self.assertEqual((k2, list(g2)), (2, [2, 2])) + self.assertEqual([(k, list(g)) for k, g in it], [(3, [3])]) + + def test_skipped_group_and_stale_grouper(self): + it = itertools.groupby("aaabbc") + _, ga = next(it) + _, gb = next(it) + self.assertEqual(list(ga), []) + self.assertEqual(list(gb), ["b", "b"]) + self.assertEqual(next(it)[0], "c") + + def test_keyfunc_and_objects(self): + class K: + def __init__(self, v): + self.v = v + + def __eq__(self, o): + return self.v == o.v + ks = [K(1), K(1), K(2)] + self.assertEqual([len(list(g)) for _, g in itertools.groupby(ks)], [2, 1]) + self.assertEqual([(k, list(g)) for k, g in itertools.groupby(range(6), key=lambda x: x // 3)], + [(0, [0, 1, 2]), (1, [3, 4, 5])]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_hash_dunder_direct.py b/tests/regrtest/test_hash_dunder_direct.py new file mode 100644 index 000000000..3134c8594 --- /dev/null +++ b/tests/regrtest/test_hash_dunder_direct.py @@ -0,0 +1,125 @@ +"""Compiled `hash(obj)` of an instance whose class's `__hash__` is a Python +function calls it directly; the hashes, a `-1` result (`-2`), a big or +`bool` result, an `int` subclass result, a non-integer result's TypeError, +a raise, `__hash__ = None`, an enum member, a `Decimal`, a frozen +dataclass, and a method replaced later match the general call. Also +`template % obj` of a tuple subclass's instance (a namedtuple's +`__repr__`): its items are the arguments, even past an overridden +`__getitem__`.""" + +import collections +import dataclasses +import decimal +import enum +import unittest + + +class H: + def __init__(self, n): + self.n = n + + def __hash__(self): + return self.n + + +class Big: + def __hash__(self): + return 2**70 + + +class Flag: + def __hash__(self): + return True + + +class MyInt(int): + pass + + +class Sub: + def __hash__(self): + return MyInt(7) + + +class Bad: + def __hash__(self): + return "x" + + +class Boom: + def __hash__(self): + raise KeyError("hash") + + +class Unhashable: + __hash__ = None + + +class Color(enum.Enum): + RED = 1 + + +@dataclasses.dataclass(frozen=True) +class FD: + x: int + y: int + + +P = collections.namedtuple("P", "x y") + + +class T(tuple): + def __getitem__(self, i): + return "overridden" + + +class HashDunderDirect(unittest.TestCase): + def test_values(self): + objs = [H(5), H(-1), H(-2), Big(), Flag(), Sub(), FD(1, 2)] + out = [] + for i in range(3000): + out.append(tuple(hash(o) for o in objs)) + out.append((hash(H(i)), hash(Color.RED), hash(decimal.Decimal(i)))) + self.assertEqual(out[0], (5, -2, -2, hash(2**70), 1, 7, hash((1, 2)))) + self.assertEqual(out[7], (3, hash("RED"), hash(3))) + self.assertEqual(out[-1][0], 2999) + + def test_errors(self): + for i in range(1000): + with self.assertRaises(TypeError) as cm: + hash(Bad()) + with self.assertRaises(KeyError): + hash(Boom()) + with self.assertRaises(TypeError) as um: + hash(Unhashable()) + self.assertEqual(str(cm.exception), "__hash__ method should return an integer") + self.assertEqual(str(um.exception), "unhashable type: 'Unhashable'") + + def test_replaced(self): + class K: + def __hash__(self): + return 1 + + k = K() + out = [] + for i in range(2000): + out.append(hash(k)) + K.__hash__ = lambda self: 2 + for i in range(2000): + out.append(hash(k)) + self.assertEqual((out.count(1), out.count(2)), (2000, 2000)) + + def test_percent_tuple_subclass(self): + p, q = P(1, "a"), P(2.5, None) + t = T((1, 2)) + out = [] + for i in range(3000): + out.append((repr(p), repr(q), "%r-%s" % t, "(%r, %r)" % P(i, i))) + self.assertEqual(out[3], ("P(x=1, y='a')", "P(x=2.5, y=None)", "1-2", "(3, 3)")) + with self.assertRaises(TypeError): + "%r" % P(1, 2) + self.assertEqual(repr(P(H(1), [2])).startswith("P(x=<"), True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_hash_of_built_tuple.py b/tests/regrtest/test_hash_of_built_tuple.py new file mode 100644 index 000000000..51b3933ab --- /dev/null +++ b/tests/regrtest/test_hash_of_built_tuple.py @@ -0,0 +1,109 @@ +"""`__hash__` bodies that return `hash((self.a, self.b))`. + +Such a body hashes the items without building the tuple once it runs as a +compiled leaf; the result must equal `hash` of the real tuple for every +kind of item (ints, strings, floats, `None`, bools, nested tuples, +instances hashed by identity, and items that need the full path: a NaN, +an instance with its own `__hash__`), with one to three items, and a +module that rebinds `hash` must still get its own function. +""" + +import unittest + + +class Two: + __slots__ = ("a", "b") + + def __init__(self, a, b): + self.a = a + self.b = b + + def __hash__(self): + return hash((self.a, self.b)) + + def __eq__(self, other): + return self.a == other.a and self.b == other.b + + +class One: + def __init__(self, a): + self.a = a + + def __hash__(self): + return hash((self.a,)) + + +class Three: + def __init__(self, a, b, c): + self.a, self.b, self.c = a, b, c + + def __hash__(self): + return hash((self.a, self.b, self.c)) + + +class Plain: + pass + + +class Custom: + def __hash__(self): + return 12345 + + +NAN = float("nan") +ITEMS = [ + 0, 1, -1, -2, 2**61 - 1, 2**62, -(2**63), "", "key", "\u20ac" * 3, + 1.5, -0.0, 1e300, None, True, False, (1, "a"), ((1, 2), (3,)), + Plain(), Custom(), NAN, b"bytes", +] + + +class HashOfBuiltTupleTests(unittest.TestCase): + def test_pairs_match_tuple_hash(self): + for a in ITEMS: + for b in ITEMS[::3]: + obj = Two(a, b) + want = hash((a, b)) + for _ in range(60): + self.assertEqual(hash(obj), want, (a, b)) + + def test_one_and_three_items(self): + for a in ITEMS: + o1, o3 = One(a), Three(a, "x", 7) + for _ in range(60): + self.assertEqual(hash(o1), hash((a,))) + self.assertEqual(hash(o3), hash((a, "x", 7))) + + def test_lookups_use_it(self): + keys = [Two(i, str(i)) for i in range(64)] + d = {k: i for i, k in enumerate(keys)} + for _ in range(100): + for i in range(64): + self.assertEqual(d[Two(i, str(i))], i) + self.assertNotIn(Two(1, "2"), d) + + def test_rebound_hash(self): + ns = {} + exec( + "hash = lambda t: 42\n" + "class K:\n" + " def __init__(self, a, b): self.a, self.b = a, b\n" + " def __hash__(self): return hash((self.a, self.b))\n", + ns, + ) + k = ns["K"](1, 2) + for _ in range(300): + self.assertEqual(hash(k), 42) + ns["hash"] = lambda t: len(t) + 100 + for _ in range(300): + self.assertEqual(hash(k), 102) + + def test_unhashable_item_raises(self): + obj = Two([1], 2) + for _ in range(60): + with self.assertRaises(TypeError): + hash(obj) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_hashlib_sha_digests.py b/tests/regrtest/test_hashlib_sha_digests.py new file mode 100644 index 000000000..92454abf3 --- /dev/null +++ b/tests/regrtest/test_hashlib_sha_digests.py @@ -0,0 +1,91 @@ +"""SHA-1 and SHA-2 digests match the NIST test vectors however data arrives. + +`sha1`, `sha224`, `sha256`, `sha384` and `sha512` of the FIPS 180 vectors, +fed at once, in chunks that straddle the block size, and through +`hashlib.new`; `copy()` gives an independent hasher, `digest()` doesn't +finish the hasher it is asked of, and the sizes and names are CPython's. +""" + +import hashlib +import unittest + +ABC = { + "sha1": "a9993e364706816aba3e25717850c26c9cd0d89d", + "sha224": "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", + "sha256": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + "sha384": "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed" + "8086072ba1e7cc2358baeca134c825a7", + "sha512": "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" + "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", +} +MILLION_A = { + "sha1": "34aa973cd4c4daa4f61eeb2bdbad27316534016f", + "sha256": "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0", + "sha512": "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" + "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b", +} +SIZES = {"sha1": (20, 64), "sha224": (28, 64), "sha256": (32, 64), "sha384": (48, 128), + "sha512": (64, 128)} + + +class ShaTests(unittest.TestCase): + def test_vectors(self): + for name, want in ABC.items(): + self.assertEqual(getattr(hashlib, name)(b"abc").hexdigest(), want) + self.assertEqual(hashlib.new(name, b"abc").hexdigest(), want) + h = hashlib.new(name) + self.assertEqual((h.name, h.digest_size, h.block_size), (name,) + SIZES[name]) + data = b"a" * 1_000_000 + for name, want in MILLION_A.items(): + self.assertEqual(getattr(hashlib, name)(data).hexdigest(), want) + h = getattr(hashlib, name)() + for at in range(0, len(data), 999): + h.update(data[at:at + 999]) + self.assertEqual(h.hexdigest(), want) + + def test_chunks_copy_and_repeat(self): + blob = bytes(range(256)) * 9 + for name in ABC: + whole = getattr(hashlib, name)(blob).digest() + for step in (1, 63, 64, 65, 127, 128, 129, 1000): + h = getattr(hashlib, name)() + for at in range(0, len(blob), step): + h.update(memoryview(blob)[at:at + step]) + self.assertEqual(h.digest(), whole, (name, step)) + self.assertEqual(h.digest(), whole) + h = getattr(hashlib, name)(blob[:100]) + c = h.copy() + c.update(blob[100:]) + self.assertEqual(c.digest(), whole) + self.assertEqual(h.digest(), getattr(hashlib, name)(blob[:100]).digest()) + h.update(blob[100:]) + self.assertEqual(h.hexdigest(), whole.hex()) + + def test_live_hashers_outlast_dead_ones(self): + keep = [hashlib.sha256(b"keep %d" % i) for i in range(50)] + for i in range(5000): + hashlib.sha256(b"x").digest() + hashlib.md5(b"y").hexdigest() + if i % 100 == 0: + keep[i // 100].update(b"!") + for i, h in enumerate(keep): + want = b"keep %d" % i + (b"!" if i < 50 else b"") + self.assertEqual(h.hexdigest(), hashlib.sha256(want).hexdigest(), i) + self.assertEqual(h.copy().digest(), h.digest()) + + def test_updates_in_a_loop(self): + ba = bytearray(b"0123456789abcdef") + for name in ("sha1", "sha256", "sha512", "md5"): + h = hashlib.new(name) + for i in range(3000): + h.update(ba if i % 3 else memoryview(ba)[2:9]) + if i % 1000 == 0: + h.hexdigest() + want = hashlib.new(name, (bytes(ba[2:9]) + bytes(ba) * 2) * 1000).hexdigest() + self.assertEqual(h.hexdigest(), want, name) + with self.assertRaises(TypeError): + h.update("text") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_heapq_push_pop_leaf_halves.py b/tests/regrtest/test_heapq_push_pop_leaf_halves.py new file mode 100644 index 000000000..76c0c6775 --- /dev/null +++ b/tests/regrtest/test_heapq_push_pop_leaf_halves.py @@ -0,0 +1,150 @@ +"""`heapq.heappush` and `heappop` on heaps of plain items. + +When every comparison a push or pop makes is between plain numbers, +strings, or tuples that differ at such a pair, both run their +comparisons first and then move the items. The heap's layout after each +call, the item returned, and what happens with items that only their own +`__lt__` orders, items that can't be ordered, and NaNs must all match +the pure-Python algorithm exactly. +""" + +import heapq +import random +import unittest + + +def ref_siftdown(heap, startpos, pos): + newitem = heap[pos] + while pos > startpos: + parentpos = (pos - 1) >> 1 + parent = heap[parentpos] + if newitem < parent: + heap[pos] = parent + pos = parentpos + continue + break + heap[pos] = newitem + + +def ref_siftup(heap, pos): + endpos = len(heap) + startpos = pos + newitem = heap[pos] + childpos = 2 * pos + 1 + while childpos < endpos: + rightpos = childpos + 1 + if rightpos < endpos and not heap[childpos] < heap[rightpos]: + childpos = rightpos + heap[pos] = heap[childpos] + pos = childpos + childpos = 2 * pos + 1 + heap[pos] = newitem + ref_siftdown(heap, startpos, pos) + + +def ref_push(heap, item): + heap.append(item) + ref_siftdown(heap, 0, len(heap) - 1) + + +def ref_pop(heap): + lastelt = heap.pop() + if heap: + returnitem = heap[0] + heap[0] = lastelt + ref_siftup(heap, 0) + return returnitem + return lastelt + + +class Key: + def __init__(self, v): + self.v = v + + def __lt__(self, other): + return self.v < other.v + + def __eq__(self, other): + return self.v == other.v + + def __repr__(self): + return f"Key({self.v})" + + +class HeapLeafHalfTests(unittest.TestCase): + def run_mix(self, make, seed): + rng = random.Random(seed) + for _ in range(60): + h, r = [], [] + for _ in range(rng.randrange(1, 120)): + if rng.random() < 0.6 or not h: + item = make(rng) + heapq.heappush(h, item) + ref_push(r, item) + else: + self.assertEqual(heapq.heappop(h), ref_pop(r)) + self.assertEqual(h, r) + while h: + self.assertEqual(heapq.heappop(h), ref_pop(r)) + self.assertEqual(r, []) + + def test_ints(self): + self.run_mix(lambda rng: rng.randrange(-20, 20), 1) + + def test_floats_and_mixed_numbers(self): + self.run_mix(lambda rng: rng.choice([rng.random(), 1, True, -2, 0.5]), 2) + + def test_strings(self): + self.run_mix(lambda rng: rng.choice("abcde") * rng.randrange(1, 3), 3) + + def test_tuples(self): + self.run_mix(lambda rng: (rng.randrange(4), rng.randrange(50), "x"), 4) + + def test_instances(self): + self.run_mix(lambda rng: Key(rng.randrange(10)), 5) + + def test_mixed_tuples_and_instances(self): + self.run_mix(lambda rng: (rng.randrange(3), Key(rng.randrange(5))), 6) + + def test_unorderable_item(self): + h = [1, 2, 3] + with self.assertRaises(TypeError): + heapq.heappush(h, "x") + # (The item went in before the comparison failed, as in CPython.) + self.assertEqual(h, [1, 2, 3, "x"]) + h = [1, "a", 2] + with self.assertRaises(TypeError): + heapq.heappop(h) + with self.assertRaises(IndexError): + heapq.heappop([]) + with self.assertRaises(TypeError): + heapq.heappush((), 1) + + def test_nans(self): + nan = float("nan") + h, r = [], [] + for x in [3, nan, 1, 2, nan, 0.5, (1, nan), (1, 2)][:6]: + heapq.heappush(h, x) + ref_push(r, x) + self.assertEqual(repr(h), repr(r)) + self.assertEqual(repr([heapq.heappop(h) for _ in range(6)]), + repr([ref_pop(r) for _ in range(6)])) + h = [(1, nan)] + heapq.heappush(h, (1, nan)) + heapq.heappush(h, (0, 0)) + self.assertEqual(h[0], (0, 0)) + + def test_hot_small_heaps(self): + for i in range(3000): + h = [] + heapq.heappush(h, 3) + heapq.heappush(h, 1) + heapq.heappush(h, 2) + self.assertEqual(heapq.heappop(h), 1) + self.assertEqual(h, [2, 3]) + self.assertEqual(heapq.heappop(h), 2) + self.assertEqual(heapq.heappop(h), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_heapq_sift_and_product_pools.py b/tests/regrtest/test_heapq_sift_and_product_pools.py new file mode 100644 index 000000000..e022508da --- /dev/null +++ b/tests/regrtest/test_heapq_sift_and_product_pools.py @@ -0,0 +1,110 @@ +"""heapq's sifts compare and swap native scalars in place, and +itertools.product (and its kin) take a str's characters as a pool from +compiled code: heap orders for ints, floats and strs, mixed int and +float heaps, max-heaps, tuples and instances whose __lt__ runs Python +(the general path), a __lt__ that changes the heap, NaNs, and products, +permutations and combinations over strs with repeat=, each matching +CPython.""" + +import heapq +import itertools +import unittest + + +class Rev: + def __init__(self, v): + self.v = v + + def __lt__(self, other): + return self.v > other.v + + +def churn(n, h, items): + out = [] + for i in range(n): + for x in items: + heapq.heappush(h, x) + out.append(heapq.heappop(h)) + return out + + +class HeapTests(unittest.TestCase): + def test_scalar_heaps(self): + for n in (1, 300): + h = list(range(10, 0, -1)) + heapq.heapify(h) + r = churn(n, h, [5, 3]) + self.assertEqual(r[:3], [1, 2, 3][: len(r[:3])]) + self.assertEqual(sorted(h), sorted(h)) + self.assertEqual(h[0], min(h)) + f = churn(n, [], [2.5, 1.5, 3]) + self.assertEqual(f[0], 1.5) + s = churn(n, [], ["b", "a", "c"]) + self.assertEqual(s[0], "a") + h = [3, 1, 2] + heapq.heapify(h) + self.assertEqual([heapq.heappop(h) for _ in range(3)], [1, 2, 3]) + + def test_max_heap(self): + h = [1, 5, 3, 4] + heapq.heapify_max(h) + for i in range(300): + heapq.heappush_max(h, i % 7) + heapq.heappop_max(h) + self.assertEqual(h[0], max(h)) + out = [heapq.heappop_max(h) for _ in range(len(h))] + self.assertEqual(out, sorted(out, reverse=True)) + + def test_python_lt(self): + h = [] + for i in range(300): + heapq.heappush(h, Rev(i % 10)) + self.assertEqual(heapq.heappop(h).v, 9) + t = [] + for i in range(300): + heapq.heappush(t, (i % 5, str(i))) + self.assertEqual(heapq.heappop(t), (0, "0")) + + def test_mutating_lt(self): + h = [] + + class Bad: + def __lt__(self, other): + h.clear() + return True + + heapq.heappush(h, 1) + heapq.heappush(h, 2) + h.append(Bad()) + with self.assertRaises((RuntimeError, IndexError)): + heapq.heappush(h, Bad()) + + def test_nan(self): + nan = float("nan") + h = [] + for x in (3.0, nan, 1.0, 2.0): + heapq.heappush(h, x) + self.assertEqual(len(h), 4) + self.assertEqual(str(sorted(str(x) for x in h)), str(sorted(["1.0", "2.0", "3.0", "nan"]))) + + +class ProductPoolTests(unittest.TestCase): + def test_str_pools(self): + for i in range(300): + p = list(itertools.product("ab", repeat=2)) + q = list(itertools.product("xy", "z")) + r = list(itertools.permutations("abc", 2)) + c = list(itertools.combinations("abcd", 3)) + self.assertEqual(p, [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")]) + self.assertEqual(q, [("x", "z"), ("y", "z")]) + self.assertEqual(len(r), 6) + self.assertEqual(c[0], ("a", "b", "c")) + self.assertEqual(list(itertools.product("", repeat=2)), []) + self.assertEqual(list(itertools.product("ab", repeat=0)), [()]) + self.assertEqual(list(itertools.product("hé", repeat=1)), [("h",), ("é",)]) + with self.assertRaises(ValueError): + itertools.product("ab", repeat=-1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_heapq_tuple_entries.py b/tests/regrtest/test_heapq_tuple_entries.py new file mode 100644 index 000000000..5ec858c7b --- /dev/null +++ b/tests/regrtest/test_heapq_tuple_entries.py @@ -0,0 +1,144 @@ +"""`heapq` over tuple entries (`(priority, count, item)`): the in-place +comparison of leading ints, floats and strs matches the full one, ties +fall through to later items (and to their `__lt__`), NaNs and mixed +kinds take the full comparison, and an item's `__lt__` may still change +the heap.""" + +import heapq +import random +import unittest + +N = 200 + + +class Task: + def __init__(self, name): + self.name = name + self.compared = 0 + + def __lt__(self, other): + self.compared += 1 + return self.name < other.name + + def __eq__(self, other): + return isinstance(other, Task) and self.name == other.name + + __hash__ = None + + +def drain(h): + out = [] + while h: + out.append(heapq.heappop(h)) + return out + + +class HeapTupleTests(unittest.TestCase): + def test_matches_sorted(self): + rng = random.Random(7) + for _ in range(N): + rows = [ + (rng.randrange(5), rng.random(), rng.choice("abc"), i) + for i in range(40) + ] + h = [] + for r in rows: + heapq.heappush(h, r) + self.assertEqual(drain(h), sorted(rows)) + h = list(rows) + heapq.heapify(h) + self.assertEqual(drain(h), sorted(rows)) + + def test_prefix_and_length(self): + rows = [(1, 2), (1,), (1, 2, 3), (), (0, 9), (1, 2, 0)] + for _ in range(N): + h = [] + for r in rows: + heapq.heappush(h, r) + self.assertEqual(drain(h), sorted(rows)) + + def test_ties_reach_item_lt(self): + for _ in range(N): + a, b, c = Task("a"), Task("b"), Task("c") + h = [] + for t in (c, a, b): + heapq.heappush(h, (1, t)) + self.assertEqual([t.name for _, t in drain(h)], ["a", "b", "c"]) + self.assertGreater(a.compared + b.compared + c.compared, 0) + + def test_counter_breaks_ties_before_items(self): + for _ in range(N): + tasks = [Task(n) for n in "zyxw"] + h = [] + for i, t in enumerate(tasks): + heapq.heappush(h, (5, i, t)) + self.assertEqual([t.name for _, _, t in drain(h)], list("zyxw")) + self.assertEqual(sum(t.compared for t in tasks), 0) + + def test_unorderable_items_raise(self): + h = [] + heapq.heappush(h, (1, {"a": 1})) + with self.assertRaises(TypeError): + heapq.heappush(h, (1, {"b": 2})) + h = [(1, "a")] + with self.assertRaises(TypeError): + heapq.heappush(h, (1, 2)) + + def test_mixed_numbers_and_bools(self): + rows = [(1, "a"), (1.0, "b"), (True, "c"), (0.5, "d"), (2, "e"), (False, "f")] + for _ in range(N): + h = [] + for r in rows: + heapq.heappush(h, r) + got = drain(h) + self.assertEqual([r[0] for r in got], [False, 0.5, 1, 1, 1, 2]) + self.assertEqual(sorted(r[1] for r in got[2:5]), ["a", "b", "c"]) + + def test_nan_entries(self): + nan = float("nan") + for _ in range(N): + # The same NaN object is "equal" to itself inside a tuple. + h = [] + heapq.heappush(h, (nan, 2)) + heapq.heappush(h, (nan, 1)) + self.assertEqual(heapq.heappop(h)[1], 1) + self.assertEqual((nan, 1) < (nan, 2), True) + self.assertEqual((float("nan"), 1) < (float("nan"), 2), False) + + def test_big_ints_and_strs(self): + rows = [(10**30, "x"), (10**30, "w"), (-(10**30), "y"), (3, "é"), (3, "e")] + for _ in range(N): + h = list(rows) + heapq.heapify(h) + self.assertEqual(drain(h), sorted(rows)) + + def test_item_lt_that_mutates_the_heap(self): + h = [] + + class Evil: + def __lt__(self, other): + h.clear() + return True + + heapq.heappush(h, (1, Evil())) + heapq.heappush(h, (0, Evil())) + with self.assertRaises((IndexError, RuntimeError)): + for _ in range(8): + heapq.heappush(h, (1, Evil())) + + def test_merge_nsmallest_replace(self): + rows = [(i % 4, -i) for i in range(30)] + for _ in range(N): + self.assertEqual(heapq.nsmallest(5, rows), sorted(rows)[:5]) + self.assertEqual(heapq.nlargest(5, rows), sorted(rows, reverse=True)[:5]) + h = list(rows) + heapq.heapify(h) + self.assertEqual(heapq.heapreplace(h, (9, 9)), (0, -28)) + self.assertEqual(heapq.heappushpop(h, (-1, 0)), (-1, 0)) + self.assertEqual( + list(heapq.merge(sorted(rows[:10]), sorted(rows[10:]))), sorted(rows) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_hex_oct_bin_leaves.py b/tests/regrtest/test_hex_oct_bin_leaves.py new file mode 100644 index 000000000..6075f3a90 --- /dev/null +++ b/tests/regrtest/test_hex_oct_bin_leaves.py @@ -0,0 +1,46 @@ +"""hex(), oct() and bin() from compiled loops (leaf halves for exact ints, +big ints and bools): small, negative, zero, 64-bit edge and big values, +bools, int subclasses and __index__ objects (the full path), and type +errors, each matching CPython.""" + +import unittest + + +class Idx: + def __index__(self): + return 10 + + +class MyInt(int): + pass + + +def radix(n, x): + out = None + for i in range(n): + out = (hex(x), oct(x), bin(x)) + return out + + +class RadixTests(unittest.TestCase): + def test_values(self): + for n in (1, 300): + self.assertEqual(radix(n, 255), ("0xff", "0o377", "0b11111111")) + self.assertEqual(radix(n, 0), ("0x0", "0o0", "0b0")) + self.assertEqual(radix(n, -5), ("-0x5", "-0o5", "-0b101")) + self.assertEqual(radix(n, True), ("0x1", "0o1", "0b1")) + m = -(2**63) + self.assertEqual(radix(n, m)[0], "-0x8000000000000000") + self.assertEqual(radix(n, 2**64 + 1)[0], "0x10000000000000001") + self.assertEqual(radix(n, -(2**70))[2], "-0b1" + "0" * 70) + self.assertEqual(radix(n, Idx()), ("0xa", "0o12", "0b1010")) + self.assertEqual(radix(n, MyInt(9)), ("0x9", "0o11", "0b1001")) + + def test_errors(self): + for bad in (1.5, "1", None): + with self.assertRaises(TypeError): + radix(300, bad) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_identity_instance_membership_loops.py b/tests/regrtest/test_identity_instance_membership_loops.py new file mode 100644 index 000000000..8725fa541 --- /dev/null +++ b/tests/regrtest/test_identity_instance_membership_loops.py @@ -0,0 +1,137 @@ +"""`obj in container` for instances hashed by identity, and loops over lists +of objects, past the compile thresholds. + +Membership settles by identity for an instance whose class keeps +`object`'s `__hash__`; a stored key of another kind with the instance's +very hash (an `int` equal to `hash(obj)`) still compares through the full +lookup, a class that later gains `__hash__` stops being probed by +identity, and an `int` subclass instance compares by value. Loops over +lists of instances, strings and tuples keep their results when the list +changes mid-loop. +""" + +import unittest + + +class Plain: + pass + + +class EqOnly: + __hash__ = object.__hash__ + + def __eq__(self, other): + return isinstance(other, EqOnly) and other.tag == self.tag + + def __init__(self, tag): + self.tag = tag + + +class Late: + pass + + +class IntSub(int): + pass + + +class MembershipTests(unittest.TestCase): + def test_set_dict_frozenset(self): + keys = [Plain() for _ in range(64)] + others = [Plain() for _ in range(64)] + s, d, fs = set(keys), dict.fromkeys(keys, 1), frozenset(keys) + for _ in range(300): + hits = misses = 0 + for k in keys: + hits += (k in s) + (k in d) + (k in fs) + for k in others: + misses += (k in s) + (k in d) + (k in fs) + self.assertEqual((hits, misses), (192, 0)) + + def test_stored_int_with_the_same_hash(self): + p = Plain() + s = {hash(p), "x"} + d = {hash(p): 1} + for _ in range(300): + self.assertNotIn(p, s) + self.assertNotIn(p, d) + s.add(p) + for _ in range(300): + self.assertIn(p, s) + self.assertIn(hash(p), s) + + def test_python_eq_with_object_hash(self): + a, b = EqOnly(1), EqOnly(1) + s = {a} + for _ in range(300): + self.assertIn(a, s) + # (Different identities hash apart, so `__eq__` never runs.) + self.assertNotIn(b, s) + + def test_class_gains_hash(self): + x, y = Late(), Late() + s = {x} + for _ in range(300): + self.assertIn(x, s) + self.assertNotIn(y, s) + Late.__hash__ = lambda self: 7 + Late.__eq__ = lambda self, other: isinstance(other, Late) + try: + t = {x} + for _ in range(300): + self.assertIn(y, t) + finally: + del Late.__hash__, Late.__eq__ + + def test_int_subclass_by_value(self): + s = {5, 6} + for _ in range(300): + self.assertIn(IntSub(5), s) + self.assertNotIn(IntSub(7), s) + + +class ObjectLoopTests(unittest.TestCase): + def test_loops_over_objects(self): + pts = [Plain() for _ in range(512)] + for i, p in enumerate(pts): + p.x = i + total = 0 + for _ in range(200): + for p in pts: + total += p.x + self.assertEqual(total, 200 * sum(range(512))) + words = [str(i) * 2 for i in range(512)] + n = 0 + for _ in range(200): + for w in words: + if w.startswith("1"): + n += len(w) + self.assertEqual(n, 200 * sum(len(w) for w in words if w.startswith("1"))) + + def test_list_changes_mid_loop(self): + for _ in range(100): + items = [Plain() for _ in range(50)] + seen = [] + for p in items: + seen.append(p) + if len(seen) == 10: + del items[20:] + items.append(Plain()) + self.assertEqual(len(seen), 21) + self.assertIs(seen[-1], items[-1]) + + def test_previous_element_kept(self): + pts = [Plain() for _ in range(300)] + for _ in range(100): + prev = None + pairs = 0 + for p in pts: + if prev is not None and prev is not p: + pairs += 1 + prev = p + self.assertEqual(pairs, 299) + self.assertIs(prev, pts[-1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_import_compilation_scope.py b/tests/regrtest/test_import_compilation_scope.py index 1b0ac4a40..086cbabe5 100644 --- a/tests/regrtest/test_import_compilation_scope.py +++ b/tests/regrtest/test_import_compilation_scope.py @@ -1,4 +1,5 @@ """Nested, failed, and sustained imports retain ordinary Python behavior.""" +import importlib import os import sys import tempfile @@ -7,6 +8,9 @@ def write_module(directory, name, source): with open(os.path.join(directory, name + ".py"), "w") as stream: stream.write(source) + # (A directory's listing is cached by its modification time, which two + # writes close together can share.) + importlib.invalidate_caches() with tempfile.TemporaryDirectory() as directory: diff --git a/tests/regrtest/test_index_dunder_fast.py b/tests/regrtest/test_index_dunder_fast.py new file mode 100644 index 000000000..12533693c --- /dev/null +++ b/tests/regrtest/test_index_dunder_fast.py @@ -0,0 +1,80 @@ +"""An instance used as an index (`xs[obj]`, `range(obj)`, slices) whose +class's `__index__` is a Python function: found on the class and, when a +pure leaf, evaluated in place; the items, negative indexes, an index out +of range (IndexError), a raising `__index__`, a non-int result's +TypeError, an `int` subclass result, a `bool` result, and a method +replaced later all match the general protocol.""" + +import unittest + + +class I: + def __init__(self, v): + self.v = v + + def __index__(self): + return self.v + + +class Boom: + def __index__(self): + raise KeyError("index") + + +class Bad: + def __index__(self): + return "x" + + +class MyInt(int): + pass + + +class Sub: + def __index__(self): + return MyInt(2) + + +class Flag: + def __index__(self): + return True + + +class IndexDunderFast(unittest.TestCase): + def test_items(self): + xs, t, s = [10, 20, 30, 40], (1, 2, 3), "abcd" + out = [] + for i in range(3000): + k = I(i % 4) + out.append((xs[k], t[I(-1)], s[k], len(range(k)), xs[I(1):I(3)], xs[Sub()], xs[Flag()])) + self.assertEqual(out[5], (20, 3, "b", 1, [20, 30], 30, 20)) + + def test_errors(self): + xs = [1, 2] + for i in range(500): + with self.assertRaises(IndexError): + xs[I(5)] + with self.assertRaises(KeyError): + xs[Boom()] + with self.assertRaises(TypeError) as cm: + xs[Bad()] + with self.assertRaises(TypeError): + range(Bad()) + self.assertEqual(str(cm.exception), "__index__ returned non-int (type str)") + + def test_replaced(self): + class K: + def __index__(self): + return 0 + + xs, k, out = ["a", "b"], K(), [] + for i in range(2000): + out.append(xs[k]) + K.__index__ = lambda self: 1 + for i in range(2000): + out.append(xs[k]) + self.assertEqual((out.count("a"), out.count("b")), (2000, 2000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_index_error_in_place.py b/tests/regrtest/test_index_error_in_place.py new file mode 100644 index 000000000..05649db52 --- /dev/null +++ b/tests/regrtest/test_index_error_in_place.py @@ -0,0 +1,56 @@ +"""An out-of-range index of a list, tuple or string raises its IndexError +from compiled code; the message, the traceback line, negative indices, and +every other receiver match CPython.""" + +import traceback +import unittest + + +class L(list): + def __getitem__(self, i): + return "sub" + + +class IndexErrorInPlace(unittest.TestCase): + def test_messages(self): + cases = [([], 0, "list index out of range"), ([1], 1, "list index out of range"), + ([1, 2], -3, "list index out of range"), ((), 0, "tuple index out of range"), + ((1,), -2, "tuple index out of range"), ("", 0, "string index out of range"), + ("ab", 5, "string index out of range"), ("éa", 5, "string index out of range")] + for _ in range(300): + for seq, i, msg in cases: + try: + seq[i] + except IndexError as e: + self.assertEqual(str(e), msg) + else: + self.fail("no raise") + self.assertEqual([1, 2][-2], 1) + self.assertEqual("ab"[-1], "b") + self.assertEqual(L()[5], "sub") + + def test_traceback_line(self): + def f(xs): + return xs[3] + for _ in range(300): + try: + f([]) + except IndexError as e: + tb = traceback.extract_tb(e.__traceback__) + self.assertEqual(tb[-1].name, "f") + self.assertIn("xs[3]", tb[-1].line) + + def test_count_in_loop(self): + data = [[1], [], [2, 3], []] + for _ in range(300): + n = 0 + for d in data: + try: + d[0] + except IndexError: + n += 1 + self.assertEqual(n, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_inline_getitem_sites.py b/tests/regrtest/test_inline_getitem_sites.py new file mode 100644 index 000000000..a2342ab82 --- /dev/null +++ b/tests/regrtest/test_inline_getitem_sites.py @@ -0,0 +1,142 @@ +"""`obj[key]` of a Python `__getitem__` lowered in line by the frame JIT. + +A subscript site that has called a plain instance's Python `__getitem__` +runs its body in line, guarded by the class's version. It must agree with +the full call: any key type, a `NotImplemented` or `None` result taken as +a value, a raise inside the method (with its traceback through the +method), a method rebound or a class swapped mid-loop, a second class at +the same site, a subclass, deep recursion through `__getitem__`, a body +that leaves the compiled code (a generator, a call it can't lower), and a +metaclass `__getitem__`. +""" + +import sys +import traceback +import unittest + + +class Seq: + def __init__(self, d): + self.d = d + + def __getitem__(self, i): + return self.d[i] + + +class Odd: + def __getitem__(self, key): + if key == "ni": + return NotImplemented + if key == "none": + return None + if key == "boom": + raise KeyError("boom") + return (key, key) + + +class Sub(Seq): + pass + + +class Other: + def __getitem__(self, i): + return -i + + +class Deep: + def __getitem__(self, n): + return 0 if n == 0 else self[n - 1] + 1 + + +class Leaves: + def __getitem__(self, n): + return sum(x for x in range(n)) + + +class Meta(type): + def __getitem__(cls, key): + return f"{cls.__name__}[{key}]" + + +class WithMeta(metaclass=Meta): + pass + + +def total(obj, n): + t = 0 + for i in range(n): + t += obj[i % 3] + return t + + +def items(obj, keys): + return [obj[k] for k in keys] + + +class InlineGetitemTests(unittest.TestCase): + def test_values_and_keys(self): + s = Seq([10, 20, 30]) + for _ in range(50): + self.assertEqual(total(s, 300), 6000) + o = Odd() + for _ in range(300): + self.assertIs(o["ni"], NotImplemented) + self.assertIsNone(o["none"]) + self.assertEqual(o[1.5], (1.5, 1.5)) + self.assertEqual(o[(1, 2)], ((1, 2), (1, 2))) + + def test_raise_inside(self): + o = Odd() + for _ in range(300): + with self.assertRaises(KeyError): + o["boom"] + try: + o["boom"] + except KeyError as e: + names = [f.name for f in traceback.extract_tb(e.__traceback__)] + self.assertEqual(names[-1], "__getitem__") + + def test_index_error_in_body(self): + s = Seq([1]) + for _ in range(300): + with self.assertRaises(IndexError): + s[5] + + def test_rebound_and_swapped(self): + class R: + def __getitem__(self, i): + return i * 2 + + r = R() + self.assertEqual(sum(items(r, range(100))), 9900) + for _ in range(30): + items(r, range(100)) + R.__getitem__ = lambda self, i: i * 3 + self.assertEqual(sum(items(r, range(100))), 14850) + r.__class__ = Other + self.assertEqual(sum(items(r, range(100))), -4950) + + def test_polymorphic_site(self): + objs = [Seq([1, 2, 3]), Other(), Sub([4, 5, 6]), Odd()] + for _ in range(100): + got = [o[1] for o in objs] + self.assertEqual(got, [2, -1, 5, (1, 1)]) + + def test_recursion_and_leaving(self): + d = Deep() + for _ in range(100): + self.assertEqual(d[20], 20) + limit = sys.getrecursionlimit() + with self.assertRaises(RecursionError): + d[limit + 100] + lv = Leaves() + for _ in range(200): + self.assertEqual(lv[10], 45) + + def test_metaclass_getitem(self): + for _ in range(300): + self.assertEqual(WithMeta[3], "WithMeta[3]") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_inplace_dunder_direct.py b/tests/regrtest/test_inplace_dunder_direct.py new file mode 100644 index 000000000..4689d42e0 --- /dev/null +++ b/tests/regrtest/test_inplace_dunder_direct.py @@ -0,0 +1,173 @@ +"""Compiled augmented assignments call a class's Python in-place method +(`__iadd__`, ...) directly; the results (`self` or a new object), a +`NotImplemented` that goes on to `__add__` / `__radd__` or to the +augmented operator's TypeError, raises, and methods replaced later match +the general operator.""" + +import unittest + + +class Acc: + def __init__(self): + self.total = 0 + self.calls = 0 + + def __iadd__(self, o): + self.calls += 1 + self.total += o + return self + + +class Fresh: + def __init__(self, v): + self.v = v + + def __imul__(self, o): + return Fresh(self.v * o) + + +class Picky: + def __init__(self, v): + self.v = v + + def __iadd__(self, o): + if not isinstance(o, int): + return NotImplemented + self.v += o + return self + + def __add__(self, o): + if isinstance(o, str): + return Picky(self.v + len(o)) + return NotImplemented + + +class Right: + def __radd__(self, o): + return "radd" + + +class OnlyI: + def __iadd__(self, o): + return NotImplemented + + +class Raiser: + def __iadd__(self, o): + raise KeyError(o) + + +class InplaceDunderDirect(unittest.TestCase): + def test_self_result(self): + a = Acc() + x = a + for i in range(3000): + x += i + self.assertIs(x, a) + self.assertEqual((a.total, a.calls), (sum(range(3000)), 3000)) + + def test_new_result(self): + x = Fresh(1) + for i in range(60): + x *= 2 + self.assertEqual(x.v, 2**60) + for _ in range(1000): + y = Fresh(3) + y *= 2 + self.assertEqual(y.v, 6) + + def test_not_implemented_fallbacks(self): + for i in range(1000): + p = Picky(1) + q = p + q += 2 + self.assertIs(q, p) + self.assertEqual(p.v, 3) + q += "abcd" + self.assertIsNot(q, p) + self.assertEqual(q.v, 7) + r = Picky(0) + r += Right() + self.assertEqual(r, "radd") + with self.assertRaises(TypeError) as cm: + s = Picky(0) + s += 1.5 + self.assertEqual( + str(cm.exception), + "unsupported operand type(s) for +=: 'Picky' and 'float'", + ) + with self.assertRaises(TypeError): + o = OnlyI() + o += 1 + + def test_raises(self): + r = Raiser() + n = 0 + for i in range(1000): + x = r + try: + x += i + except KeyError: + n += 1 + self.assertEqual(n, 1000) + + def bump(o): + o += 1 + return o + + for i in range(1000): + with self.assertRaises(KeyError): + bump(r) + self.assertIsInstance(bump(Acc()), Acc) + + def test_attribute_and_item_targets(self): + class Box: + pass + + b = Box() + b.acc = Acc() + d = {"k": Acc()} + for i in range(1000): + b.acc += 1 + d["k"] += 2 + self.assertEqual(b.acc.total, 1000) + self.assertEqual(d["k"].total, 2000) + + def test_replaced(self): + class C: + def __iadd__(self, o): + return 1 + + n = 0 + for i in range(1000): + x = C() + x += 1 + n += x + C.__iadd__ = lambda self, o: 10 + for i in range(1000): + x = C() + x += 1 + n += x + del C.__iadd__ + C.__add__ = lambda self, o: 100 + for i in range(1000): + x = C() + x += 1 + n += x + self.assertEqual(n, 111000) + + def test_generator_caller(self): + a = Acc() + + def g(): + x = a + for i in range(500): + x += 1 + yield i + + self.assertEqual(sum(g()), sum(range(500))) + self.assertEqual(a.total, 500) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_inst_native_small_args.py b/tests/regrtest/test_inst_native_small_args.py new file mode 100644 index 000000000..c6b2ed558 --- /dev/null +++ b/tests/regrtest/test_inst_native_small_args.py @@ -0,0 +1,84 @@ +"""Native methods of built-in subclasses' instances called with small ints. + +`od.move_to_end(5)`, `xs.pop(0)` and `xs.insert(1, x)` on instances of +built-in subclasses run the native method on the arguments in place from +compiled code: the results, the errors they raise (a missing key, an +index out of range), and a method a subclass shadows or a class changed +mid-loop behave as in CPython. Run it past the compile threshold. +""" + +from collections import OrderedDict + + +class L(list): + pass + + +class D(dict): + pass + + +def moves(od, n): + for _ in range(n): + od.move_to_end(2) + od.move_to_end(0) + return list(od) + + +def pops(xs, n): + out = 0 + for i in range(n): + xs.insert(0, i) + out += xs.pop(0) + xs.insert(1, i) + out -= xs.pop(1) + return out + + +def gets(d, n): + t = 0 + for _ in range(n): + t += d.get(3, 100) + d.get(250, 7) + return t + + +def missing(od, n): + hits = 0 + for _ in range(n): + try: + od.move_to_end(99) + except KeyError as e: + hits += e.args == (99,) + return hits + + +N = 3000 +od = OrderedDict((i, i) for i in range(5)) +assert moves(od, N) == [1, 3, 4, 2, 0] +xs = L([9, 8]) +assert pops(xs, N) == 0 and xs == [9, 8] +d = D({3: 1}) +assert gets(d, N) == 8 * N +assert missing(od, N) == N + + +class Moving(OrderedDict): + pass + + +m = Moving((i, i) for i in range(3)) +assert moves(m, N) == [1, 2, 0] +Moving.move_to_end = lambda self, k, last=True: None +assert moves(m, 10) == [1, 2, 0] +m2 = Moving((i, i) for i in range(3)) +assert moves(m2, 10) == [0, 1, 2] + + +class Shadow(L): + def pop(self, i=-1): + return 0 + + +sh = Shadow([1]) +assert pops(sh, N) == 0 and len(sh) == 1 + 2 * N, len(sh) +print("ok") diff --git a/tests/regrtest/test_instance_classinfo_hooks.py b/tests/regrtest/test_instance_classinfo_hooks.py new file mode 100644 index 000000000..a05a43f4a --- /dev/null +++ b/tests/regrtest/test_instance_classinfo_hooks.py @@ -0,0 +1,86 @@ +"""`isinstance`/`issubclass` hooks: class-like instances and metaclasses. + +A plain function `__instancecheck__`/`__subclasscheck__` on a class-like +instance's class (the `typing` aliases') is called directly, and whether +a metaclass keeps `type`'s own hooks is remembered per metaclass version; +descriptor hooks, errors, and hooks added, replaced or removed behave as +before. +""" + +import typing +import unittest + +N = 3000 + + +class Plain: + def __instancecheck__(self, obj): + return obj == 1 + + def __subclasscheck__(self, cls): + return cls is int + + +class Static: + @staticmethod + def __instancecheck__(obj): + return obj == 2 + + +class Raises: + def __instancecheck__(self, obj): + raise KeyError(obj) + + +class InstanceClassinfoTests(unittest.TestCase): + def test_plain_hooks(self): + p = Plain() + for _ in range(N): + r = (isinstance(1, p), isinstance(2, p), issubclass(int, p), issubclass(str, p)) + self.assertEqual(r, (True, False, True, False)) + for _ in range(N): + r = (isinstance(1, typing.Hashable), isinstance([], typing.Hashable), + issubclass(list, typing.Sequence), isinstance({}, typing.Mapping)) + self.assertEqual(r, (True, False, True, True)) + + def test_descriptor_and_errors(self): + s = Static() + self.assertTrue(isinstance(2, s)) + self.assertFalse(isinstance(3, s)) + with self.assertRaises(KeyError): + isinstance(5, Raises()) + + def test_replaced_hook(self): + class C: + def __instancecheck__(self, obj): + return True + + c = C() + for _ in range(N // 10): + self.assertTrue(isinstance(0, c)) + C.__instancecheck__ = lambda self, obj: False + self.assertFalse(isinstance(0, c)) + del C.__instancecheck__ + with self.assertRaises(TypeError): + isinstance(0, c) + + + def test_metaclass_hooks_change(self): + class M(type): + pass + + class A(metaclass=M): + pass + + for _ in range(N // 10): + r = (isinstance(A(), A), isinstance(1, A), issubclass(int, A)) + self.assertEqual(r, (True, False, False)) + M.__instancecheck__ = lambda cls, obj: obj == 1 + M.__subclasscheck__ = lambda cls, c: c is int + self.assertEqual((isinstance(1, A), isinstance(2, A), issubclass(int, A)), (True, False, True)) + del M.__instancecheck__, M.__subclasscheck__ + self.assertEqual((isinstance(1, A), issubclass(int, A)), (False, False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_instance_dict_site.py b/tests/regrtest/test_instance_dict_site.py new file mode 100644 index 000000000..893fdd40b --- /dev/null +++ b/tests/regrtest/test_instance_dict_site.py @@ -0,0 +1,69 @@ +"""`obj.__dict__` from a site that has read it before. + +Once a site has read an instance's managed dict for a class at its +version, it reads the dict again directly; another class, a class whose +version moved, a `__dict__` property, or a dict subclass's instance takes +the full read. +""" + +import unittest + +N = 3000 + + +class A: + def __init__(self): + self.x = 1 + + +class B: + @property + def __dict__(self): + return {"fake": True} + + +class H: + def __init__(self, o): + self.o = o + + +class InstanceDictSiteTests(unittest.TestCase): + def test_local_and_stack_reads(self): + a = A() + h = H(a) + for _ in range(N): + d = a.__dict__ + e = h.o.__dict__ + self.assertIs(d, e) + self.assertEqual(d, {"x": 1}) + d["y"] = 2 + self.assertEqual(a.y, 2) + + def test_mixed_classes_at_one_site(self): + objs = [A(), B(), A()] + out = [] + for i in range(N): + o = objs[i % 3] + out.append(o.__dict__) + self.assertEqual(out[0], {"x": 1}) + self.assertEqual(out[1], {"fake": True}) + + def test_class_change(self): + class C: + pass + + c = C() + c.v = 1 + out = [] + for i in range(N): + if i == N // 2: + C.other = 1 + c.w = 2 + out.append(c.__dict__) + self.assertEqual(out[0], {"v": 1, "w": 2}) + self.assertIs(out[-1], out[0]) + self.assertEqual(c.__dict__, {"v": 1, "w": 2}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_int_radix_strings.py b/tests/regrtest/test_int_radix_strings.py new file mode 100644 index 000000000..715b18e0d --- /dev/null +++ b/tests/regrtest/test_int_radix_strings.py @@ -0,0 +1,34 @@ +"""`hex`, `oct` and `bin` of ints, as CPython formats them. + +Machine ints (zero, the extremes, negatives), big ints, bools and an +`__index__` object, in a loop past the compile threshold. +""" + +import sys + + +class Idx: + def __index__(self): + return 10 + + +def run(n): + for i in range(n): + assert hex(i) == "0x%x" % i and oct(-i) == ("-0o%o" % i if i else "0o0") + assert bin(i & 7) == "0b" + format(i & 7, "b") + + +run(3000) +cases = { + 0: ("0x0", "0o0", "0b0"), + 255: ("0xff", "0o377", "0b11111111"), + -255: ("-0xff", "-0o377", "-0b11111111"), + sys.maxsize: ("0x7fffffffffffffff", "0o777777777777777777777", "0b" + "1" * 63), + -sys.maxsize - 1: ("-0x8000000000000000", "-0o1000000000000000000000", "-0b1" + "0" * 63), + 2**64: ("0x10000000000000000", "0o2000000000000000000000", "0b1" + "0" * 64), + True: ("0x1", "0o1", "0b1"), +} +for v, (h, o, b) in cases.items(): + assert (hex(v), oct(v), bin(v)) == (h, o, b), v +assert (hex(Idx()), oct(Idx()), bin(Idx())) == ("0xa", "0o12", "0b1010") +print("ok") diff --git a/tests/regrtest/test_int_subclass_and_bytearray_stores.py b/tests/regrtest/test_int_subclass_and_bytearray_stores.py new file mode 100644 index 000000000..8ad9f4fdf --- /dev/null +++ b/tests/regrtest/test_int_subclass_and_bytearray_stores.py @@ -0,0 +1,94 @@ +"""`int()` of an `int` subclass's instance, and `bytearray` item stores. + +`int(x)` of an `int` subclass's instance whose class keeps `int`'s own +`__int__` (`re`'s named opcode constants) answers its value as an exact +`int` in place; a class with its own `__int__` keeps it. `buf[i] = n` of +a `bytearray` by an int index stores in place, and out-of-range indexes +and values raise as before. A compiled pattern's parse tree iterates its +items directly; patterns compile and match as before. +""" + +import re +import unittest + +N = 3000 + + +class Plain(int): + pass + + +class Own(int): + def __int__(self): + return 42 + + +class Big(int): + pass + + +class IntSubclassTests(unittest.TestCase): + def test_values_are_exact(self): + p, o, b = Plain(7), Own(7), Big(2**70) + for _ in range(N): + r = (int(p), int(o), int(b), int(True)) + self.assertEqual(r, (7, 42, 2**70, 1)) + self.assertEqual([type(x) for x in r], [int, int, int, int]) + + def test_class_gains_int(self): + class Late(int): + pass + + x = Late(3) + out = [] + for i in range(N): + if i == N // 2: + Late.__int__ = lambda self: 99 + out.append(int(x)) + self.assertEqual((out[0], out[-1]), (3, 99)) + + +class ByteArrayStoreTests(unittest.TestCase): + def test_stores(self): + b = bytearray(8) + for i in range(N): + b[i % 8] = i % 256 + b[-1] = True + self.assertEqual(b[-1], 1) + self.assertEqual(b[0], (N - 8) % 256) + + def test_errors(self): + b = bytearray(2) + for _ in range(100): + with self.assertRaises(ValueError): + b[0] = 256 + with self.assertRaises(ValueError): + b[0] = -1 + with self.assertRaises(IndexError): + b[2] = 1 + with self.assertRaises(TypeError): + b[0] = "a" + self.assertEqual(b, bytearray(2)) + + def test_view_sees_stores(self): + b = bytearray(4) + m = memoryview(b) + for i in range(N): + b[i % 4] = 7 + self.assertEqual(bytes(m), b"\x07\x07\x07\x07") + m.release() + + +class RegexCompileTests(unittest.TestCase): + def test_patterns(self): + for i in range(200): + p = re.compile(r"(?P\d+)\s*(?P[a-z]+)%d|[^\W\d]\w*x%d" % (i, i)) + self.assertEqual(p.groupindex["b"], 2) + self.assertEqual(p.match("12 ab199").groups(), ("12", "ab")) + self.assertEqual(p.match("zz9x199").group(), "zz9x199") + c = re.compile(r"(?i)[a-fA-F0-9_]{2,4}(?=-)|[^xyz]+?") + self.assertEqual(c.findall("Ab_-q"), ["Ab_", "-", "q"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_int_subclass_operators_compiled.py b/tests/regrtest/test_int_subclass_operators_compiled.py new file mode 100644 index 000000000..ccb5086f9 --- /dev/null +++ b/tests/regrtest/test_int_subclass_operators_compiled.py @@ -0,0 +1,193 @@ +"""Arithmetic and comparisons over int and float subclasses (IntEnum, a +plain `class I(int)`, a float subclass) from compiled loops: exact int, +float and bool results on either side, big ints, in-place operators, a +division by zero, a class that overrides the operator, its reflection or +its in-place form (and one that gains an override later), IntFlag's own +`|`, and finalizers of temporaries, each matching CPython.""" + +import enum +import unittest + + +class I(int): + pass + + +class F(float): + pass + + +class Num(enum.IntEnum): + A = 1 + B = 2 + + +class Perm(enum.IntFlag): + R = 4 + W = 2 + + +class Over(int): + def __add__(self, o): + return "add" + + def __lt__(self, o): + return "lt" + + +class ROver(int): + def __radd__(self, o): + return "radd" + + def __gt__(self, o): + return "gt" + + +class IOver(int): + def __iadd__(self, o): + return "iadd" + + +class Late(int): + pass + + +log = [] + + +class D(int): + def __del__(self): + log.append(int(self)) + + +def ops(n, a, b): + out = None + for i in range(n): + out = (a + b, a - b, a * b, a // b, a % b, a / b, a ** 2, a & b, a | b, a ^ b, a << 1, a >> 1) + return out + + +def fops(n, a, b): + out = None + for i in range(n): + out = (a + b, a - b, a * b, a // b, a % b, a / b, a ** 2) + return out + + +def rops(n, a, b): + out = None + for i in range(n): + out = (b + a, b - a, b * a, b / a) + return out + + +def cmps(n, a, b): + out = None + for i in range(n): + out = (a < b, a <= b, a == b, a != b, a > b, a >= b, b < a, b == a) + return out + + +def iadd(n, a, b): + out = None + for i in range(n): + x = a + x += b + out = x + return out + + +class IntSubclassOperatorTests(unittest.TestCase): + def check_types(self, got, want): + self.assertEqual(got, want) + self.assertEqual([type(x) for x in got], [type(x) for x in want]) + + def test_intenum_and_plain_subclass(self): + for a in (Num.B, I(2)): + want = ops(1, 2, 3) + for n in (1, 400): + self.check_types(ops(n, a, 3), want) + self.check_types(ops(n, a, I(3)), want) + self.check_types(rops(n, a, 7), rops(1, 2, 7)) + self.check_types(cmps(n, a, 3), cmps(1, 2, 3)) + self.check_types(cmps(n, a, 2.0), cmps(1, 2, 2.0)) + self.check_types(cmps(n, a, Num.B), cmps(1, 2, 2)) + + def test_mixed_and_big(self): + big = 1 << 80 + for n in (1, 400): + self.check_types(ops(n, I(big), 3), ops(1, big, 3)) + self.check_types(fops(n, Num.B, 1.5), fops(1, 2, 1.5)) + self.check_types(fops(n, F(2.5), 2), fops(1, 2.5, 2)) + self.check_types(cmps(n, F(2.5), 2), cmps(1, 2.5, 2)) + self.check_types(cmps(n, I(big), big + 1), cmps(1, big, big + 1)) + self.assertEqual(iadd(n, Num.A, 4), 5) + self.assertIs(type(iadd(n, Num.A, 4)), int) + self.assertIs(type(iadd(n, Num.A, True)), int) + + def test_errors(self): + with self.assertRaises(ZeroDivisionError): + ops(300, Num.A, 0) + with self.assertRaises(TypeError): + ops(300, Num.A, "x") + with self.assertRaises(TypeError): + cmps(300, Num.A, "x") + + def test_equality_with_other_types(self): + def eqs(n, a, b): + out = None + for i in range(n): + out = (a == b, a != b) + return out + + for n in (1, 400): + self.assertEqual(eqs(n, Num.A, "x"), (False, True)) + self.assertEqual(eqs(n, Num.A, 1), (True, False)) + self.assertEqual(eqs(n, Num.A, 1.0), (True, False)) + + def test_overrides(self): + def add(n, a, b): + out = None + for i in range(n): + out = (a + b, b + a) + return out + + def lt(n, a, b): + out = None + for i in range(n): + out = (a < b, b < a) + return out + + for n in (1, 400): + self.assertEqual(add(n, Over(1), 2), ("add", 3)) + self.assertEqual(add(n, ROver(1), 2), (3, "radd")) + self.assertEqual(lt(n, Over(1), 2), ("lt", False)) + self.assertEqual(lt(n, ROver(1), 2), (True, "gt")) + self.assertEqual(iadd(n, IOver(1), 2), "iadd") + self.assertEqual(Perm.R | Perm.W, 6) + self.assertIs(type(ops(n, Perm.R, Perm.W)[8]), Perm) + + def test_override_added_later(self): + self.assertEqual(ops(400, Late(4), 2)[0], 6) + Late.__add__ = lambda self, o: "late" + try: + self.assertEqual(ops(400, Late(4), 2)[0], "late") + self.assertEqual(ops(400, Late(4), 2)[1], 2) + finally: + del Late.__add__ + self.assertEqual(ops(400, Late(4), 2)[0], 6) + + def test_temporaries_finalized(self): + def tmp(n): + total = 0 + for i in range(n): + total += D(i) + 1 + return total + + del log[:] + self.assertEqual(tmp(300), sum(range(1, 301))) + self.assertEqual(sorted(log), list(range(300))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_int_wide_arithmetic.py b/tests/regrtest/test_int_wide_arithmetic.py new file mode 100644 index 000000000..29c07202c --- /dev/null +++ b/tests/regrtest/test_int_wide_arithmetic.py @@ -0,0 +1,60 @@ +"""`+`, `-`, `*`, `//` and `%` of ints within 128 bits, done in 128-bit +arithmetic, agree with the same operations on the operands shifted past +128 bits (which take the general bignum path): signs, floor rounding, the +64- and 128-bit edges, results that fit a machine int again, and zero +divisors.""" + +import random +import unittest + +EDGES = [0, 1, -1, 2, -2, 3, -3, 12345, -12345, 2**63 - 1, -2**63, 2**63, -2**63 - 1, + 2**64, -2**64, 2**126, -2**126, 2**127 - 1, -2**127, 2**127, -2**127 - 1, 2**128] +S = 200 + + +def values(): + r = random.Random(7) + out = list(EDGES) + for _ in range(150): + v = r.getrandbits(r.choice((8, 40, 62, 63, 64, 65, 100, 126, 127, 128))) + out.append(-v if r.random() < 0.5 else v) + return out + + +class WideIntArithmeticTests(unittest.TestCase): + def test_against_shifted(self): + vals = values() + for x in vals: + for y in vals[:50]: + X, Y = x << S, y << S + self.assertEqual(x + y, (X + Y) >> S) + self.assertEqual(x - y, (X - Y) >> S) + self.assertEqual(x * y, (X * y) >> S) + if y == 0: + with self.assertRaises(ZeroDivisionError): + x // y + with self.assertRaises(ZeroDivisionError): + x % y + continue + q, m = x // y, x % y + self.assertEqual(q, X // Y) + self.assertEqual(m, (X % Y) >> S) + self.assertEqual(q * y + m, x) + self.assertTrue(0 <= m < y if y > 0 else y < m <= 0) + + def test_results_and_types(self): + n = 987654321 + for _ in range(2000): + self.assertEqual((n * n * n) // 12345, 78041176888902033949657) + self.assertEqual((n * n * n) % 12345, 2496) + self.assertIs(type((n * n * n) // (n * n)), int) + self.assertEqual((n * n * n) // (n * n), n) + self.assertEqual((2**64 + 5) - 2**64, 5) + self.assertEqual(-(2**127) // -1, 2**127) + self.assertEqual(-(2**127) % -1, 0) + self.assertEqual((2**127 - 1) + 1, 2**127) + self.assertEqual(True + (2**64), 2**64 + 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_islice_collect.py b/tests/regrtest/test_islice_collect.py new file mode 100644 index 000000000..d60d7585e --- /dev/null +++ b/tests/regrtest/test_islice_collect.py @@ -0,0 +1,66 @@ +"""Collecting an `itertools.islice` over a list or tuple at once. + +`list(islice(...))`, `tuple(...)` and their kin take the slice in one +pass when the islice holds its sequence's iterator alone, in CPython's +order (the skipped items first, then the stop bound), and leave it +finished with its source released; a shared iterator, a partly consumed +islice, and other sources take the general path. +""" + +import gc +import weakref +from itertools import islice + +lst = list(range(20)) +tup = tuple(lst) +for seq in (lst, tup): + assert list(islice(seq, 5)) == lst[:5] + assert list(islice(seq, 3, 8)) == lst[3:8] + assert list(islice(seq, 1, 15, 4)) == lst[1:15:4] + assert list(islice(seq, 2, None, 3)) == lst[2::3] + assert list(islice(seq, 18, 40)) == [18, 19] + assert list(islice(seq, 25, 30)) == [] + assert list(islice(seq, 0)) == [] and list(islice(seq, 4, 4)) == [] + assert tuple(islice(seq, None)) == tup + s = islice(seq, 2, 9, 2) + assert next(s) == 2 + assert list(s) == [4, 6, 8] and list(s) == [] and next(s, "end") == "end" + s = islice(seq, 3) + assert list(s) == [0, 1, 2] and list(s) == [] + +# A shared source iterator advances as CPython's does. +it = iter(lst) +assert list(islice(it, 3, 6)) == [3, 4, 5] +assert next(it) == 6 +it = iter(tup) +assert list(islice(it, 2, 4)) == [2, 3] and list(it) == lst[4:] +it = iter([1, 2, 3]) +assert list(islice(it, 5, 9)) == [] and list(it) == [] + +# Other sources. +assert list(islice((x * 2 for x in range(10)), 1, 6, 2)) == [2, 6, 10] +assert list(islice("abcdef", 1, None, 2)) == ["b", "d", "f"] +assert list(islice(range(10), 3)) == [0, 1, 2] + + +# The finished islice releases its source. +class Box(list): + pass + + +b = Box([1, 2, 3]) +r = weakref.ref(b) +s = islice(b, 1, None) +del b +assert list(s) == [2, 3] +gc.collect() +assert r() is None + + +def loop(n): + for i in range(n): + assert list(islice(lst, i % 7, 12, 2)) == lst[i % 7:12:2] + + +loop(3000) +print("ok") diff --git a/tests/regrtest/test_islice_generator_drain.py b/tests/regrtest/test_islice_generator_drain.py new file mode 100644 index 000000000..0623c0138 --- /dev/null +++ b/tests/regrtest/test_islice_generator_drain.py @@ -0,0 +1,61 @@ +"""`list(islice(gen, ...))` steps the generator in a row; the items, how +far the generator advances, the slice's state after, and raises match +CPython.""" + +import itertools +import unittest + + +def gen(n): + for i in range(n): + yield i + + +class Boom(Exception): + pass + + +def raising(): + yield 1 + yield 2 + raise Boom + + +def returning(): + yield 1 + return "v" + + +class IsliceGeneratorDrain(unittest.TestCase): + def test_bounds(self): + cases = [(5,), (2, 8), (1, 9, 3), (0, None, 2), (3, 3), (10, 20), (None,)] + for args in cases: + for _ in range(50): + self.assertEqual(list(itertools.islice(gen(12), *args)), + list(itertools.islice(range(12), *args))) + + def test_generator_position(self): + g = gen(10) + self.assertEqual(list(itertools.islice(g, 2, 5)), [2, 3, 4]) + self.assertEqual(next(g), 5) + g = gen(10) + self.assertEqual(list(itertools.islice(g, 3, 3)), []) + self.assertEqual(next(g), 3) + g = gen(10) + s = itertools.islice(g, 0, 6, 2) + self.assertEqual(next(s), 0) + self.assertEqual(list(s), [2, 4]) + self.assertEqual(list(s), []) + # (The item before the stop bound was taken as a skipped one.) + self.assertEqual(next(g), 6) + + def test_raise_and_return(self): + s = itertools.islice(raising(), 5) + with self.assertRaises(Boom): + list(s) + self.assertEqual(list(s), []) + self.assertEqual(list(itertools.islice(returning(), 5)), [1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_islice_list_drain.py b/tests/regrtest/test_islice_list_drain.py new file mode 100644 index 000000000..9250029ff --- /dev/null +++ b/tests/regrtest/test_islice_list_drain.py @@ -0,0 +1,72 @@ +"""`list(islice(src, ..., stop))` over a source whose steps run no code, +taken in one pass, keeps CPython's items and leaves the adapter and its +source where CPython's `islice` leaves them: done and its source let go at +the stop, skipped items consumed, a source shorter than the stop, steps, +and starts past the stop.""" + +import gc +import itertools +import unittest +import weakref + +N = 2000 + + +class Box: + pass + + +class IsliceListDrainTests(unittest.TestCase): + def test_counts_and_cycles(self): + for _ in range(N): + self.assertEqual(list(itertools.islice(itertools.count(), 5)), [0, 1, 2, 3, 4]) + self.assertEqual(list(itertools.islice(itertools.count(10, 3), 2, 6)), [16, 19, 22, 25]) + self.assertEqual(list(itertools.islice(itertools.count(), 0, 9, 4)), [0, 4, 8]) + self.assertEqual(list(itertools.islice(itertools.cycle("ab"), 5)), list("ababa")) + self.assertEqual(list(itertools.islice(itertools.chain([1], (2, 3)), 2)), [1, 2]) + self.assertEqual(list(itertools.islice(itertools.count(), 0)), []) + self.assertEqual(list(itertools.islice(itertools.count(), 3, 3)), []) + self.assertEqual(list(itertools.islice(itertools.count(), 5, 2)), []) + + def test_source_left_in_place(self): + for _ in range(N): + c = itertools.count() + s = itertools.islice(c, 2, 4) + self.assertEqual(list(s), [2, 3]) + self.assertEqual(next(c), 4) + self.assertEqual(list(s), []) + c = itertools.count() + self.assertEqual(list(itertools.islice(c, 5, 2)), []) + self.assertEqual(next(c), 5) + it = iter([1, 2, 3, 4, 5]) + self.assertEqual(list(itertools.islice(it, 3)), [1, 2, 3]) + self.assertEqual(list(it), [4, 5]) + it = iter([1, 2]) + self.assertEqual(list(itertools.islice(it, 5)), [1, 2]) + self.assertEqual(list(it), []) + it = iter(range(10)) + self.assertEqual(list(itertools.islice(it, 1, 7, 2)), [1, 3, 5]) + # (The item skipped before the stop is taken too.) + self.assertEqual(next(it), 7) + + def test_source_released_at_stop(self): + b = Box() + r = weakref.ref(b) + s = itertools.islice(iter([b, 1, 2]), 1) + del b + self.assertEqual(len(list(s)), 1) + gc.collect() + self.assertIsNone(r()) + self.assertEqual(list(s), []) + + def test_objects(self): + items = [Box() for _ in range(6)] + for _ in range(N // 10): + got = list(itertools.islice(itertools.cycle(items), 8)) + self.assertEqual(got, items + items[:2]) + self.assertTrue(all(a is b for a, b in zip(got, items + items[:2]))) + self.assertEqual(tuple(itertools.islice(itertools.count(), 3)), (0, 1, 2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_islice_over_cycle.py b/tests/regrtest/test_islice_over_cycle.py new file mode 100644 index 000000000..6be18554b --- /dev/null +++ b/tests/regrtest/test_islice_over_cycle.py @@ -0,0 +1,38 @@ +"""itertools.islice over itertools.cycle from compiled loops: the first +pass and the replay of the saved items, an empty source, a cycle partly +consumed first, a generator as the cycle's source, a cycle beside other +sources in zip, and the cycle's state after islice stops, each matching +CPython.""" + +import itertools +import unittest + + +def take(n, make, k): + out = None + for i in range(n): + out = list(itertools.islice(make(), k)) + return out + + +class IsliceCycleTests(unittest.TestCase): + def test_shapes(self): + for n in (1, 300): + self.assertEqual(take(n, lambda: itertools.cycle("ab"), 5), list("ababa")) + self.assertEqual(take(n, lambda: itertools.cycle([1, 2, 3]), 7), [1, 2, 3, 1, 2, 3, 1]) + self.assertEqual(take(n, lambda: itertools.cycle(()), 3), []) + self.assertEqual(take(n, lambda: itertools.cycle(x for x in "xy"), 5), list("xyxyx")) + self.assertEqual(take(n, lambda: zip(itertools.cycle("ab"), range(3)), 5), + [("a", 0), ("b", 1), ("a", 2)]) + + def test_resume(self): + for _ in range(300): + c = itertools.cycle([1, 2, 3]) + self.assertEqual(next(c), 1) + self.assertEqual(list(itertools.islice(c, 4)), [2, 3, 1, 2]) + self.assertEqual(next(c), 3) + self.assertEqual(list(itertools.islice(c, 2, 6, 2)), [3, 2]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_iter_builtin_direct.py b/tests/regrtest/test_iter_builtin_direct.py new file mode 100644 index 000000000..64ece7eb1 --- /dev/null +++ b/tests/regrtest/test_iter_builtin_direct.py @@ -0,0 +1,69 @@ +"""Compiled `iter(obj)` of an instance whose class's `__iter__` is a +Python function calls it directly (in place when a warm pure leaf); the +iterators, a generator `__iter__`, a result that isn't an iterator (the +`TypeError` CPython words), a raise, and a method replaced later match +the general call.""" + +import unittest + + +class Box: + def __init__(self, xs): + self.xs = xs + + def __iter__(self): + return iter(self.xs) + + +class Gen: + def __iter__(self): + yield 1 + yield 2 + + +class Bad: + def __iter__(self): + return [1] + + +class Boom: + def __iter__(self): + raise KeyError("iter") + + +class IterBuiltinDirect(unittest.TestCase): + def test_iterators(self): + b = Box([1, 2, 3]) + g = Gen() + total = 0 + for i in range(3000): + it = iter(b) + total += next(it) + next(it) + total += sum(iter(g)) + self.assertEqual(total, 3000 * 6) + + def test_errors(self): + for i in range(1000): + with self.assertRaises(TypeError) as cm: + iter(Bad()) + with self.assertRaises(KeyError): + iter(Boom()) + self.assertEqual(str(cm.exception), "iter() returned non-iterator of type 'list'") + + def test_replaced(self): + class K: + def __iter__(self): + return iter("a") + + k = K() + out = [] + for i in range(2000): + out.append(next(iter(k))) + K.__iter__ = lambda self: iter("b") + for i in range(2000): + out.append(next(iter(k))) + self.assertEqual((out.count("a"), out.count("b")), (2000, 2000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_iter_call_and_native_unpack.py b/tests/regrtest/test_iter_call_and_native_unpack.py new file mode 100644 index 000000000..c77bf7a63 --- /dev/null +++ b/tests/regrtest/test_iter_call_and_native_unpack.py @@ -0,0 +1,88 @@ +"""`iter(obj)` of a Python `__iter__`, and the native `struct.unpack`. + +`iter()` calls a class's Python `__iter__` without a bound method; the +public `struct.unpack` reads `bytes` and `bytearray` buffers natively and +sends everything else through the Python wrapper. Results, errors and +signatures behave as before. +""" + +import array +import inspect +import struct +import unittest + +N = 3000 + + +class Seq: + def __init__(self): + self.d = [1, 2, 3] + + def __iter__(self): + return iter(self.d) + + +class Bad: + def __iter__(self): + return 5 + + +class NoNext: + def __iter__(self): + return self + + +class Raises: + def __iter__(self): + raise KeyError("it") + + +class IterCallTests(unittest.TestCase): + def test_iter(self): + s = Seq() + for _ in range(N): + it = iter(s) + self.assertEqual(list(it), [1, 2, 3]) + self.assertEqual(list(s), [1, 2, 3]) + self.assertEqual(tuple(s), (1, 2, 3)) + + def test_errors(self): + with self.assertRaises(TypeError): + iter(Bad()) + with self.assertRaisesRegex(TypeError, "non-iterator"): + iter(NoNext()) + with self.assertRaises(KeyError): + iter(Raises()) + + def test_instance_dict_ignored(self): + s = Seq() + s.__iter__ = lambda: iter([9]) + self.assertEqual(list(iter(s)), [1, 2, 3]) + + +class NativeUnpackTests(unittest.TestCase): + def test_buffers(self): + pk = struct.pack("= self.n: + raise StopIteration + self.i += 1 + return self.i + + +class NoNext: + def __iter__(self): + return Item() + + +class Boom: + def __iter__(self): + raise ValueError("boom") + + +def total(obj): + n = 0 + for x in obj: + n += 1 + return n + + +items = [Item(), Item(), Item()] +for _ in range(3000): + assert total(Wrap(items)) == 3 + assert total(Gen(2)) == 2 + assert total(Self(4)) == 4 + assert [type(x) for x in Wrap(items)] == [Item] * 3 + try: + total(NoNext()) + except TypeError as e: + assert "non-iterator" in str(e), e + else: + raise AssertionError("no TypeError") + try: + total(Boom()) + except ValueError as e: + assert str(e) == "boom" + else: + raise AssertionError("no ValueError") + +Wrap.__iter__ = lambda self: iter([1, 2]) +for _ in range(100): + assert total(Wrap(items)) == 2 diff --git a/tests/regrtest/test_iter_protocol_paths.py b/tests/regrtest/test_iter_protocol_paths.py new file mode 100644 index 000000000..a624827df --- /dev/null +++ b/tests/regrtest/test_iter_protocol_paths.py @@ -0,0 +1,219 @@ +"""Building containers from instances and iterators in place. + +`list(obj)` of an instance whose `__iter__` and `__len__` evaluate as pure +leaves skips the full protocol, `iter()` runs inside frameless +evaluations, a list or tuple iterator drains at once, and an `__iter__` +returning a non-iterator raises CPython's `TypeError` on every path. +""" + +import unittest + +N = 3000 + + +class Seq: + def __init__(self): + self.d = [1, 2, 3] + + def __len__(self): + return len(self.d) + + def __iter__(self): + return iter(self.d) + + +class BadLen: + def __len__(self): + raise RuntimeError("len") + + def __iter__(self): + return iter([1]) + + +class TypeErrorLen: + def __len__(self): + raise TypeError("t") + + def __iter__(self): + return iter([2]) + + +class Hint: + def __init__(self): + self.calls = 0 + + def __length_hint__(self): + self.calls += 1 + return 1 + + def __iter__(self): + return iter([3]) + + +class NotIter: + def __iter__(self): + return [1] + + +class GenIter: + def __iter__(self): + yield 5 + + +class DictIter: + def __init__(self): + self.m = {"a": 1} + + def __iter__(self): + return iter(self.m) + + +class IterProtocolTests(unittest.TestCase): + def test_collect(self): + for i in range(N): + r = (list(Seq()), tuple(Seq()), list(TypeErrorLen()), list(GenIter()), + list(DictIter()), set(Seq())) + self.assertEqual(r, ([1, 2, 3], (1, 2, 3), [2], [5], ["a"], {1, 2, 3})) + h = Hint() + self.assertEqual(list(h), [3]) + self.assertEqual(h.calls, 1) + + def test_errors(self): + for i in range(N // 10): + with self.assertRaises(RuntimeError): + list(BadLen()) + with self.assertRaises(TypeError) as cm: + list(NotIter()) + self.assertEqual(str(cm.exception), "iter() returned non-iterator of type 'list'") + + def loop(): + for i in range(N): + try: + for x in NotIter(): + pass + except TypeError as e: + msg = str(e) + return msg + + self.assertEqual(loop(), "iter() returned non-iterator of type 'list'") + + def test_partial_iterators(self): + for i in range(N): + xs = [1, 2, 3] + it = iter(xs) + next(it) + first = list(it) + xs.append(4) + r = (first, list(it), next(it, "end")) + t = iter((1, 2)) + r2 = (tuple(t), list(t)) + self.assertEqual(r, ([2, 3], [], "end")) + self.assertEqual(r2, ((1, 2), [])) + + +class ZipDrainTests(unittest.TestCase): + def test_end_semantics(self): + for i in range(N): + a = [1, 2, 3, 4] + b = (5, 6, 7) + c = [8, 9] + ia, ib = iter(a), iter(b) + r1 = list(zip(ia, ib, c)) + rest = (list(ia), list(ib)) + it = iter([1, 2, 3, 4, 5]) + pairs = list(zip(it, it)) + left = list(it) + ja, jb = iter([1, 2, 3]), iter((4, 5, 6)) + full = list(zip(ja, jb)) + after = (next(ja, "end"), next(jb, "end")) + z = zip([1, 2], [3, 4, 5], [6, 7, 8]) + w = (list(z), list(z)) + self.assertEqual(r1, [(1, 5, 8), (2, 6, 9)]) + self.assertEqual(rest, ([4], [])) + self.assertEqual((pairs, left), ([(1, 2), (3, 4)], [])) + self.assertEqual((full, after), ([(1, 4), (2, 5), (3, 6)], ("end", "end"))) + self.assertEqual(w, ([(1, 3, 6), (2, 4, 7)], [])) + + def test_wide_and_mixed(self): + for i in range(N // 10): + big = list(zip(range(3), [1, 2, 3, 4], (5, 6, 7, 8, 9), [0] * 5, "abcdef", + [1] * 9, (2,) * 9, [3] * 9)) + strict_err = None + try: + list(zip([1, 2], (3,), strict=True)) + except ValueError as e: + strict_err = str(e) + self.assertEqual(big[2], (2, 3, 7, 0, "c", 1, 2, 3)) + self.assertEqual(strict_err, "zip() argument 2 is shorter than argument 1") + + +class PythonNextTests(unittest.TestCase): + def test_python_iterator_classes(self): + import sys + + class It: + def __init__(self, n): + self.i = 0 + self.n = n + + def __iter__(self): + return self + + def __next__(self): + if self.i >= self.n: + raise StopIteration + self.i += 1 + return self.i + + class Tracked: + def __init__(self): + self.log = [] + self.k = 0 + + def __iter__(self): + return self + + def __next__(self): + self.k += 1 + if self.k > 3: + raise StopIteration("done") + self.log.append(self.k) + return self.k * 10 + + class Bad: + def __iter__(self): + return self + + def __next__(self): + raise KeyError("x") + + class Framed: + def __iter__(self): + return self + + def __next__(self): + return sys._getframe().f_code.co_name + + for i in range(N): + a = [x for x in It(5)] + t = Tracked() + b = list(t) + c = (t.k, t.log) + totals = (sum(It(4)), max(It(6)), tuple(It(3))) + it = It(3) + next(it) + d = list(it) + try: + for x in Bad(): + pass + except KeyError as e: + k = e.args + g = next(Framed()) + self.assertEqual(a, [1, 2, 3, 4, 5]) + self.assertEqual((b, c), ([10, 20, 30], (4, [1, 2, 3]))) + self.assertEqual(totals, (10, 6, (1, 2, 3))) + self.assertEqual((d, k, g), ([2, 3], ("x",), "__next__")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_iter_unpack_collect.py b/tests/regrtest/test_iter_unpack_collect.py new file mode 100644 index 000000000..448853bf6 --- /dev/null +++ b/tests/regrtest/test_iter_unpack_collect.py @@ -0,0 +1,74 @@ +"""Collecting a `struct.iter_unpack` iterator (`list(it)`, `tuple(it)`, +`sorted(it)`) in hot loops. + +The chunks still to come are read at once while the iterator's class +keeps its own methods; the iterator must be left exhausted, a partly +stepped one must give only the rest, every buffer kind must read the +same, and a `bytearray` must stay unresizable until the iteration ends. +""" + +import struct +import unittest + +BUF = struct.pack("<10I", *range(10)) +ROWS = [(i,) for i in range(10)] + + +class IterUnpackCollect(unittest.TestCase): + def test_loops(self): + for i in range(3000): + self.assertEqual(list(struct.iter_unpack("H", " 2 for x in g(4)), all(x < 2 for x in g(4)), + list(x for x in g(3)), tuple(x for x in g(2)), + ) + self.assertEqual(r, (6, 13, 0, 3, 3, "none", True, False, [0, 1, 2], (0, 1))) + + def test_errors(self): + with self.assertRaises(ValueError): + min(x for x in g(0)) + with self.assertRaises(TypeError): + any((x for x in g(1)), foo=1) + with self.assertRaises(TypeError): + sum(x for x in [1, "a"]) + self.assertEqual(sys.float_info.min, 2.2250738585072014e-308) + self.assertEqual(max([3, 1], key=None), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_iterator_next_method_loads.py b/tests/regrtest/test_iterator_next_method_loads.py new file mode 100644 index 000000000..1431ee973 --- /dev/null +++ b/tests/regrtest/test_iterator_next_method_loads.py @@ -0,0 +1,115 @@ +"""`it.__next__()` and `it.__iter__()` method calls in hot loops. + +Native iterators (`enumerate`, `iter(list)`, `reversed`), the `map`, +`filter` and `zip` adapters, and `itertools` objects must load their +methods as CPython does: the bound form's `__self__` is the iterator, +exhaustion raises StopIteration, errors from the source propagate, and +a subclass's own `__next__` wins. +""" + +import itertools +import unittest + +L = list(range(20)) + + +class Zip2(zip): + def __next__(self): + return ("sub",) + super().__next__() + + +class IteratorNextMethodLoads(unittest.TestCase): + def test_native_iterators(self): + for i in range(3000): + self.assertEqual(enumerate(L).__next__(), (0, 0)) + self.assertEqual(iter(L).__next__(), 0) + self.assertEqual(reversed(L).__next__(), 19) + it = enumerate(L, i) + self.assertIs(it.__iter__(), it) + self.assertEqual(it.__next__(), (i, 0)) + + def test_adapters(self): + for i in range(3000): + self.assertEqual(zip(L, L).__next__(), (0, 0)) + self.assertEqual(map(abs, [-i]).__next__(), i) + self.assertEqual(filter(None, [0, i + 1]).__next__(), i + 1) + m = map(str, L) + self.assertIs(m.__iter__(), m) + + def test_itertools(self): + c = itertools.cycle("ab") + n = itertools.count(5, 2) + for i in range(3000): + self.assertEqual(c.__next__(), "ab"[i % 2]) + self.assertEqual(n.__next__(), 5 + 2 * i) + self.assertEqual(itertools.islice(L, 3, None).__next__(), 3) + self.assertEqual(itertools.chain([i], L).__next__(), i) + + def test_bound_itertools_next(self): + c = itertools.cycle([1, 2, 3]) + nc = c.__next__ + k = itertools.compress("abcdef", [1, 0, 1, 0, 1, 0] * 1000) + nk = k.__next__ + r = itertools.repeat("x", 2500) + nr = r.__next__ + got = [] + for i in range(2500): + self.assertEqual(nc(), i % 3 + 1) + self.assertEqual(nr(), "x") + if i < 3: + got.append(nk()) + self.assertEqual(got, ["a", "c", "e"]) + with self.assertRaises(StopIteration): + nk() + with self.assertRaises(StopIteration): + nr() + a, b = itertools.tee(iter(L)) + na = a.__next__ + self.assertEqual([na() for _ in range(5)], [0, 1, 2, 3, 4]) + self.assertEqual(b.__next__(), 0) + + def test_bound_self(self): + for _ in range(1000): + for it in (enumerate(L), iter(L), zip(L), map(abs, L), + itertools.cycle(L), itertools.count()): + self.assertIs(it.__next__.__self__, it) + self.assertIs(it.__iter__.__self__, it) + + def test_exhaustion_and_errors(self): + def bad(x): + if x == 3: + raise KeyError(x) + return x + + for _ in range(2000): + it = zip([1], [2]) + self.assertEqual(it.__next__(), (1, 2)) + with self.assertRaises(StopIteration): + it.__next__() + e = enumerate([]) + with self.assertRaises(StopIteration): + e.__next__() + m = map(bad, [3]) + with self.assertRaises(KeyError): + m.__next__() + r = itertools.islice(L, 0) + with self.assertRaises(StopIteration): + r.__next__() + + def test_mixed_receivers_at_one_site(self): + its = [zip(L), map(abs, L), itertools.count(), enumerate(L), + iter(L), filter(None, L), itertools.cycle([7])] + want = [(0,), 0, 0, (0, 0), 0, 1, 7] + for _ in range(500): + fresh = [zip(L), map(abs, L), itertools.count(), enumerate(L), + iter(L), filter(None, L), itertools.cycle([7])] + self.assertEqual([it.__next__() for it in fresh], want) + self.assertEqual(len(its), len(want)) + + def test_subclass_override(self): + for _ in range(3000): + self.assertEqual(Zip2(L, L).__next__(), ("sub", 0, 0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_iterator_stores_before_stop.py b/tests/regrtest/test_iterator_stores_before_stop.py new file mode 100644 index 000000000..2f0ff6da2 --- /dev/null +++ b/tests/regrtest/test_iterator_stores_before_stop.py @@ -0,0 +1,110 @@ +"""A Python `__next__` that stores attributes before `raise StopIteration`. + +A frameless iterator step may end at a bare `raise StopIteration` without +building the exception; the stores made ahead of the raise must land once, +for every way the iterator is driven (a `for` loop, `list()`, `sum()`, a +comprehension, `next()` with and without a default). +""" + +import unittest + + +class Counter: + def __init__(self, n): + self.i = 0 + self.n = n + self.calls = 0 + + def __iter__(self): + return self + + def __next__(self): + self.calls += 1 + i = self.i + if i >= self.n: + self.done = True + raise StopIteration + self.i = i + 1 + return i + + +class Bumper: + def __init__(self): + self.i = 0 + + def __iter__(self): + return self + + def __next__(self): + self.i += 1 + if self.i > 3: + raise StopIteration + return self.i + + +class IteratorStoreTests(unittest.TestCase): + ROUNDS = 5000 + + def test_for_loop(self): + for _ in range(self.ROUNDS): + it = Counter(3) + seen = [] + for x in it: + seen.append(x) + self.assertEqual(seen, [0, 1, 2]) + self.assertEqual((it.calls, it.i, it.done), (4, 3, True)) + + def test_list_and_sum(self): + for _ in range(self.ROUNDS): + it = Bumper() + self.assertEqual(list(it), [1, 2, 3]) + self.assertEqual(it.i, 4) + self.assertEqual(list(it), []) + self.assertEqual(it.i, 5) + c = Counter(4) + self.assertEqual(sum(c), 6) + self.assertEqual((c.calls, c.done), (5, True)) + + def test_comprehension(self): + for _ in range(self.ROUNDS): + c = Counter(2) + self.assertEqual([x * 2 for x in c], [0, 2]) + self.assertEqual(c.calls, 3) + + def test_next_without_default(self): + for _ in range(self.ROUNDS): + c = Counter(1) + self.assertEqual(next(c), 0) + with self.assertRaises(StopIteration): + next(c) + self.assertEqual((c.calls, c.done), (2, True)) + with self.assertRaises(StopIteration): + next(c) + self.assertEqual(c.calls, 3) + + def test_next_with_default(self): + for _ in range(self.ROUNDS): + c = Counter(1) + self.assertEqual(next(c, "d"), 0) + self.assertEqual(next(c, "d"), "d") + self.assertEqual((c.calls, c.done), (2, True)) + self.assertEqual(next(c, None), None) + self.assertEqual(c.calls, 3) + + def test_traceback_names_next(self): + c = Counter(0) + for _ in range(self.ROUNDS): + try: + next(c) + except StopIteration as e: + tb = e.__traceback__ + names = [] + while tb is not None: + names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + self.assertIn("__next__", names) + self.assertEqual(c.calls, self.ROUNDS) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_itertools_hot_steps.py b/tests/regrtest/test_itertools_hot_steps.py new file mode 100644 index 000000000..f17bfaac3 --- /dev/null +++ b/tests/regrtest/test_itertools_hot_steps.py @@ -0,0 +1,260 @@ +"""`for` loops, `next()`, `sum()` and `list()` over `islice`, `chain`, +`count`, `cycle`, `zip_longest`, `compress` and `zip(count(), xs)`: the +steps that run no code match the general ones, on plain cursors, nested +adapters, generators, shared iterators and at every end; heap items and +their reference counts survive; a chain that steps itself still works.""" + +import itertools +import sys +import unittest +from itertools import chain, compress, count, cycle, islice, zip_longest + +N = 200 + + +class Box: + def __init__(self, v): + self.v = v + + def __repr__(self): + return f"Box({self.v})" + + +def loop(it): + out = [] + for x in it: + out.append(x) + return out + + +def pairs(it): + out = [] + for a, b in it: + out.append((a, b)) + return out + + +class IsliceTests(unittest.TestCase): + def test_shapes_over_cursors(self): + xs = list(range(30)) + t = tuple(xs) + shapes = [ + (0,), (5,), (40,), (3, 9), (3, 3), (9, 3), (0, None), (7, None), + (0, None, 2), (1, 20, 3), (2, 21, 3), (29, None, 5), (35, None, 2), + (0, 0), (None,), (None, None, 4), + ] + for _ in range(N): + for args in shapes: + sl = slice(*args) + want = xs[sl] + self.assertEqual(loop(islice(xs, *args)), want, args) + self.assertEqual(loop(islice(t, *args)), want, args) + self.assertEqual(loop(islice(range(30), *args)), want, args) + self.assertEqual(list(islice(xs, *args)), want, args) + self.assertEqual(sum(islice(range(30), *args)), sum(want), args) + + def test_consumes_skipped_items_before_the_stop(self): + for _ in range(N): + it = iter(range(10)) + self.assertEqual(loop(islice(it, 3, 3)), []) + self.assertEqual(next(it), 3) + it = iter([0, 1, 2, 3, 4, 5, 6, 7]) + self.assertEqual(loop(islice(it, 1, 6, 2)), [1, 3, 5]) + self.assertEqual(list(it), [6, 7]) + it = iter(range(4)) + self.assertEqual(loop(islice(it, 2, 9)), [2, 3]) + self.assertEqual(list(it), []) + + def test_next_and_shared_cursor(self): + for _ in range(N): + xs = [Box(i) for i in range(8)] + it = iter(xs) + a = islice(it, 2, None) + self.assertIs(next(a), xs[2]) + self.assertIs(next(it), xs[3]) + self.assertIs(next(a), xs[4]) + self.assertEqual(next(islice(xs, 9, None), "end"), "end") + self.assertIs(next(islice(xs, 4, None)), xs[4]) + + def test_over_other_adapters(self): + xs = list(range(6)) + for _ in range(N): + self.assertEqual(loop(islice(chain(xs, xs), 3, 10)), [3, 4, 5, 0, 1, 2, 3]) + self.assertEqual(loop(islice(count(), 5)), [0, 1, 2, 3, 4]) + self.assertEqual(loop(islice(count(10, -3), 1, 4)), [7, 4, 1]) + self.assertEqual(loop(islice(count(2.5), 2)), [2.5, 3.5]) + self.assertEqual(loop(islice(cycle(xs[:3]), 2, 9)), [2, 0, 1, 2, 0, 1, 2]) + self.assertEqual(loop(islice(cycle([]), 3)), []) + self.assertEqual(sum(islice(cycle(xs[:3]), 12)), 12) + self.assertEqual(sum(islice(count(), 100)), 4950) + self.assertEqual(loop(islice(islice(xs, 1, None), 1, 4)), [2, 3, 4]) + self.assertEqual(loop(islice((x * x for x in xs), 1, 4)), [1, 4, 9]) + self.assertEqual(loop(islice(map(str, xs), 2, 4)), ["2", "3"]) + + def test_big_counter_and_overflow(self): + big = sys.maxsize - 2 + self.assertEqual( + loop(islice(count(big), 5)), [big, big + 1, big + 2, big + 3, big + 4] + ) + self.assertEqual( + pairs(zip(count(big), "abcde")), + [(big + i, c) for i, c in enumerate("abcde")], + ) + + def test_heap_items_keep_their_counts(self): + xs = [Box(i) for i in range(12)] + before = [sys.getrefcount(x) for x in xs] + for _ in range(N): + loop(islice(xs, 2, 11, 3)) + loop(chain(xs, xs)) + loop(islice(cycle(xs), 30)) + pairs(zip_longest(xs, xs[:5])) + pairs(zip(count(), xs)) + loop(compress(xs, [1, 0] * 6)) + self.assertEqual([sys.getrefcount(x) for x in xs], before) + + +class ChainCountCycleTests(unittest.TestCase): + def test_chain_loops(self): + xs, t = [1, 2, 3], ("a", "b") + for _ in range(N): + self.assertEqual(loop(chain(xs, t, [], range(2))), [1, 2, 3, "a", "b", 0, 1]) + self.assertEqual(loop(chain()), []) + self.assertEqual(loop(chain([], [])), []) + self.assertEqual(loop(chain.from_iterable([xs, t])), [1, 2, 3, "a", "b"]) + self.assertEqual(loop(chain(xs, (c for c in "xy"))), [1, 2, 3, "x", "y"]) + self.assertEqual(loop(chain("ab", {"k": 1}, {7})), ["a", "b", "k", 7]) + self.assertEqual(sum(chain(xs, xs)), 12) + self.assertEqual(loop(enumerate(chain(xs, t)))[-1], (4, "b")) + + def test_chain_list_grows_while_looping(self): + xs = [0] + out = [] + for x in chain(xs, [99]): + out.append(x) + if x < 5: + xs.append(x + 1) + self.assertEqual(out, [0, 1, 2, 3, 4, 5, 99]) + + def test_chain_that_steps_itself(self): + def sources(): + yield [1, 2] + yield islice(c, 0) + yield [3] + + c = chain.from_iterable(sources()) + self.assertEqual(loop(c), [1, 2, 3]) + + def test_count_and_cycle_next(self): + for _ in range(N): + c = count(5, 2) + self.assertEqual([next(c) for _ in range(4)], [5, 7, 9, 11]) + cy = cycle("ab") + self.assertEqual([next(cy) for _ in range(5)], list("ababa")) + cy = cycle(iter([Box(1)])) + a, b = next(cy), next(cy) + self.assertIs(a, b) + + def test_break_then_resume(self): + it = chain(range(5), range(5)) + for x in it: + if x == 3: + break + self.assertEqual(loop(it), [4, 0, 1, 2, 3, 4]) + it = islice(count(), 2, None, 3) + for x in it: + if x > 6: + break + self.assertEqual(next(it), 11) + + +class PairTests(unittest.TestCase): + def test_zip_longest(self): + xs, ys = [1, 2, 3, 4], ["a", "b"] + for _ in range(N): + self.assertEqual( + pairs(zip_longest(xs, ys)), [(1, "a"), (2, "b"), (3, None), (4, None)] + ) + self.assertEqual( + pairs(zip_longest(ys, xs, fillvalue=0)), + [("a", 1), ("b", 2), (0, 3), (0, 4)], + ) + self.assertEqual(list(zip_longest(xs, xs)), [(x, x) for x in xs]) + self.assertEqual(pairs(zip_longest([], [])), []) + it = iter(xs) + self.assertEqual(pairs(zip_longest(it, it)), [(1, 2), (3, 4)]) + self.assertEqual( + pairs(zip_longest(xs, (y for y in ys))), + [(1, "a"), (2, "b"), (3, None), (4, None)], + ) + rows = list(zip_longest(xs, xs)) + self.assertIsNot(rows[0], rows[1]) + + def test_zip_with_count(self): + xs = ["a", "b", "c"] + for _ in range(N): + self.assertEqual(pairs(zip(count(), xs)), [(0, "a"), (1, "b"), (2, "c")]) + self.assertEqual(pairs(zip(xs, count(1))), [("a", 1), ("b", 2), ("c", 3)]) + self.assertEqual(list(zip(count(3, 3), xs)), [(3, "a"), (6, "b"), (9, "c")]) + self.assertEqual(dict(zip(xs, count())), {"a": 0, "b": 1, "c": 2}) + c = count() + self.assertEqual(pairs(zip(c, xs)), [(0, "a"), (1, "b"), (2, "c")]) + # The counter was stepped once more, finding the list's end. + self.assertEqual(next(c), 4) + c = count() + self.assertEqual(pairs(zip(xs, c)), [("a", 0), ("b", 1), ("c", 2)]) + self.assertEqual(next(c), 3) + self.assertEqual(pairs(zip(count(0.5), xs))[0], (0.5, "a")) + + def test_compress(self): + xs = list("abcdef") + for _ in range(N): + self.assertEqual(loop(compress(xs, [1, 0, 1, 0, 1, 1])), list("acef")) + self.assertEqual(loop(compress(xs, [True, False, None, 0, 2])), ["a", "e"]) + self.assertEqual(loop(compress(xs, (0,) * 6)), []) + self.assertEqual(loop(compress(xs, [[], [0], "", "x"])), ["b", "d"]) + self.assertEqual(list(compress(tuple(xs), [1] * 9)), xs) + self.assertEqual(loop(compress(xs, (i % 2 for i in range(6)))), list("bdf")) + it = iter(xs) + self.assertEqual(loop(compress(it, it)), ["a", "c", "e"]) + + def test_compress_selector_with_bool_method(self): + class Flag: + def __init__(self, v): + self.v = v + + def __bool__(self): + return self.v + + sel = [Flag(True), Flag(False), 1, Flag(True)] + self.assertEqual(loop(compress("wxyz", sel)), ["w", "y", "z"]) + + +class TraceTests(unittest.TestCase): + def test_loops_under_a_trace_hook(self): + lines = [] + + def tracer(frame, event, arg): + if event == "line": + lines.append(frame.f_lineno) + return tracer + + def body(): + total = 0 + for x in islice(chain([1, 2], [3]), 1, None): + total += x + for a, b in zip(count(), "ab"): + total += a + return total + + sys.settrace(tracer) + try: + got = body() + finally: + sys.settrace(None) + self.assertEqual(got, 6) + self.assertGreater(len(lines), 6) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_itertools_native_next.py b/tests/regrtest/test_itertools_native_next.py new file mode 100644 index 000000000..eb8b87f7b --- /dev/null +++ b/tests/regrtest/test_itertools_native_next.py @@ -0,0 +1,105 @@ +"""`__next__` of the native-backed `itertools` classes. + +The classes whose Python `__next__` is `next(self._core)` get a native +`__next__` that steps the adapter in place: bound and unbound calls, +subclasses (with and without their own `__next__`), errors raised while +stepping, and exhaustion behave as before. +""" + +import itertools +import operator +import unittest + + +class NativeNextTests(unittest.TestCase): + def test_bound_calls(self): + c = itertools.count(5) + nx = c.__next__ + self.assertEqual([nx() for _ in range(3)], [5, 6, 7]) + self.assertEqual(next(c), 8) + self.assertEqual(type(c).__next__(c), 9) + + def test_each_class(self): + cases = [ + (itertools.cycle("ab"), ["a", "b", "a"]), + (itertools.repeat(1, 3), [1, 1, 1]), + (itertools.accumulate([1, 2, 3]), [1, 3, 6]), + (itertools.chain([1], [2, 3]), [1, 2, 3]), + (itertools.compress("abc", [1, 0, 1]), ["a", "c"]), + (itertools.dropwhile(lambda x: x < 2, [1, 2, 3]), [2, 3]), + (itertools.takewhile(lambda x: x < 3, [1, 2, 3]), [1, 2]), + (itertools.filterfalse(None, [0, 1, 0, 2]), [0, 0]), + (itertools.starmap(operator.add, [(1, 2), (3, 4)]), [3, 7]), + (itertools.islice(range(10), 2, 8, 3), [2, 5]), + (itertools.pairwise("abc"), [("a", "b"), ("b", "c")]), + (itertools.zip_longest("ab", "x"), [("a", "x"), ("b", None)]), + (itertools.product("ab", repeat=1), [("a",), ("b",)]), + (itertools.permutations("ab"), [("a", "b"), ("b", "a")]), + (itertools.combinations("abc", 2), [("a", "b"), ("a", "c"), ("b", "c")]), + (itertools.combinations_with_replacement("ab", 2), + [("a", "a"), ("a", "b"), ("b", "b")]), + (itertools.batched("abcde", 2), [("a", "b"), ("c", "d"), ("e",)]), + ] + for it, want in cases: + with self.subTest(type(it).__name__): + nx = it.__next__ + got = [nx() for _ in range(len(want))] + self.assertEqual(got, want) + if type(it) is not itertools.cycle: + self.assertRaises(StopIteration, nx) + + def test_tee_and_groupby(self): + a, b = itertools.tee(iter([1, 2, 3])) + self.assertEqual(a.__next__(), 1) + self.assertEqual(list(b), [1, 2, 3]) + self.assertEqual(list(a), [2, 3]) + g = itertools.groupby("aabbb") + k, grp = g.__next__() + self.assertEqual((k, grp.__next__(), list(grp)), ("a", "a", ["a"])) + k, grp = next(g) + self.assertEqual((k, list(grp)), ("b", ["b", "b", "b"])) + self.assertRaises(StopIteration, g.__next__) + + def test_subclasses(self): + class Plain(itertools.count): + pass + + class Doubled(itertools.count): + def __next__(self): + return 2 * super().__next__() + + p = Plain(3) + self.assertEqual([p.__next__(), next(p)], [3, 4]) + d = Doubled(3) + self.assertEqual([d.__next__(), next(d), next(d)], [6, 8, 10]) + self.assertEqual(list(itertools.islice(Doubled(), 3)), [0, 2, 4]) + + def test_errors_while_stepping(self): + def bad(x): + raise KeyError(x) + + it = itertools.takewhile(bad, [7]) + with self.assertRaises(KeyError): + it.__next__() + nx = itertools.starmap(operator.truediv, [(1, 0)]).__next__ + self.assertRaises(ZeroDivisionError, nx) + self.assertRaises(TypeError, itertools.count().__next__, 1) + + def test_source_stop_value(self): + def gen(): + return 42 + yield + + with self.assertRaises(StopIteration) as cm: + itertools.islice(gen(), 1).__next__() + self.assertEqual(cm.exception.value, 42) + + def test_many_steps(self): + nx = itertools.count().__next__ + for _ in range(20000): + v = nx() + self.assertEqual(v, 19999) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_itertools_predicate_steps.py b/tests/regrtest/test_itertools_predicate_steps.py new file mode 100644 index 000000000..77c7f7e67 --- /dev/null +++ b/tests/regrtest/test_itertools_predicate_steps.py @@ -0,0 +1,59 @@ +"""`takewhile`, `dropwhile` and `filterfalse` step in place. + +Over a list or tuple cursor with a predicate that runs as a pure leaf, +each adapter steps without the general path: `takewhile` stops at the +first failing item (consumed, as CPython consumes it), `dropwhile` skips +while the predicate holds, and `filterfalse` keeps the falsy verdicts. +Other predicates and sources keep the general step. +""" + +import itertools +import unittest + +N = 3000 + + +class ItertoolsPredicateStepTests(unittest.TestCase): + def test_takewhile(self): + xs = [1, 2, 3, 4, 1] + for _ in range(N): + a = list(itertools.takewhile(lambda x: x < 3, xs)) + self.assertEqual(a, [1, 2]) + it = iter(xs) + tw = itertools.takewhile(lambda x: x < 3, it) + self.assertEqual(list(tw), [1, 2]) + self.assertEqual(list(it), [4, 1]) + self.assertEqual(list(tw), []) + + def test_dropwhile(self): + xs = (1, 2, 5, 1, 7) + for _ in range(N): + d = list(itertools.dropwhile(lambda x: x < 3, xs)) + self.assertEqual(d, [5, 1, 7]) + self.assertEqual(list(itertools.dropwhile(lambda x: True, xs)), []) + + def test_filterfalse(self): + xs = [0, 1, 2, 0, 3, ""] + for _ in range(N): + f = list(itertools.filterfalse(None, xs)) + g = list(itertools.filterfalse(lambda x: x == 2, [1, 2, 3])) + self.assertEqual(f, [0, 0, ""]) + self.assertEqual(g, [1, 3]) + + def test_side_effects_and_errors(self): + seen = [] + + def pred(x): + seen.append(x) + return x < 2 + + self.assertEqual(list(itertools.takewhile(pred, [1, 2, 3])), [1]) + self.assertEqual(seen, [1, 2]) + with self.assertRaises(ZeroDivisionError): + list(itertools.dropwhile(lambda x: 1 / x, [1, 0])) + with self.assertRaises(TypeError): + list(itertools.filterfalse(lambda x: x < "a", [1])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_itertools_rows_collected.py b/tests/regrtest/test_itertools_rows_collected.py new file mode 100644 index 000000000..8d12322cb --- /dev/null +++ b/tests/regrtest/test_itertools_rows_collected.py @@ -0,0 +1,69 @@ +"""`list()` of `itertools`' combinatoric iterators. + +`list(product(...))`, and the same of `permutations`, `combinations`, +`combinations_with_replacement` and a bounded `repeat`, step the iterator +to its end at once. The rows match a one-at-a-time walk, a partly consumed +iterator gives the rest, and an exhausted one gives nothing more. +""" + +import itertools +import unittest + + +def product_rows(pools, repeat=1): + pools = [tuple(p) for p in pools] * repeat + rows = [()] + for pool in pools: + rows = [r + (x,) for r in rows for x in pool] + return rows + + +class RowsCollectedTests(unittest.TestCase): + def test_product(self): + for _ in range(50): + self.assertEqual(list(itertools.product(range(3), "ab")), product_rows([range(3), "ab"])) + self.assertEqual(list(itertools.product(range(4), repeat=3)), product_rows([range(4)], 3)) + self.assertEqual(list(itertools.product()), [()]) + self.assertEqual(list(itertools.product([], [1])), []) + self.assertEqual(list(itertools.product([1], repeat=0)), [()]) + + def test_others(self): + for _ in range(50): + self.assertEqual(len(list(itertools.permutations(range(5), 2))), 20) + self.assertEqual(list(itertools.permutations("abc")), [tuple(p) for p in ["abc", "acb", "bac", "bca", "cab", "cba"]]) + self.assertEqual(list(itertools.combinations(range(5), 3))[:3], [(0, 1, 2), (0, 1, 3), (0, 1, 4)]) + self.assertEqual(list(itertools.combinations(range(2), 3)), []) + self.assertEqual(list(itertools.combinations_with_replacement("ab", 2)), [("a", "a"), ("a", "b"), ("b", "b")]) + self.assertEqual(list(itertools.repeat("x", 3)), ["x", "x", "x"]) + self.assertEqual(list(itertools.repeat("x", 0)), []) + self.assertEqual(list(itertools.repeat("x", -2)), []) + self.assertEqual(list(itertools.permutations(range(3), 0)), [()]) + + def test_partly_consumed_and_exhausted(self): + it = itertools.product("ab", repeat=2) + self.assertEqual(next(it), ("a", "a")) + self.assertEqual(list(it), [("a", "b"), ("b", "a"), ("b", "b")]) + self.assertEqual(list(it), []) + self.assertIsNone(next(it, None)) + c = itertools.combinations(range(4), 2) + next(c) + next(c) + self.assertEqual(list(c), [(0, 3), (1, 2), (1, 3), (2, 3)]) + r = itertools.repeat(7, 4) + next(r) + self.assertEqual(list(r), [7, 7, 7]) + self.assertEqual(r.__length_hint__(), 0) + + def test_items_shared_not_copied(self): + obj = [1] + rows = list(itertools.product([obj], repeat=2)) + self.assertIs(rows[0][0], obj) + self.assertIs(rows[0][1], obj) + rows = list(itertools.repeat(obj, 2)) + self.assertIs(rows[1], obj) + self.assertEqual(tuple(itertools.product("ab")), (("a",), ("b",))) + self.assertEqual(sorted(itertools.permutations([2, 1])), [(1, 2), (2, 1)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_itertools_rows_hold_items.py b/tests/regrtest/test_itertools_rows_hold_items.py new file mode 100644 index 000000000..5d63c6afb --- /dev/null +++ b/tests/regrtest/test_itertools_rows_hold_items.py @@ -0,0 +1,116 @@ +"""The rows of `itertools`' combinatoric iterators hold their items. + +Rows of `product`, `permutations`, `combinations` and +`combinations_with_replacement` over pools of heap objects (strings built +at run time, lists, instances) match the itertools documentation's recipes, +whether collected at once or taken one at a time. Each row holds a +reference to each item it shows: the items' reference counts rise by the +rows' share and fall back once the rows go, and the items are freed when +nothing else holds them. +""" + +import gc +import itertools +import sys +import unittest +import weakref + + +class Item: + def __init__(self, n): + self.n = n + + def __eq__(self, other): + return isinstance(other, Item) and other.n == self.n + + def __hash__(self): + return self.n + + +def product_rows(*pools, repeat=1): + pools = [tuple(p) for p in pools] * repeat + rows = [()] + for pool in pools: + rows = [r + (x,) for r in rows for x in pool] + return rows + + +def permutation_rows(pool, r=None): + pool = tuple(pool) + n = len(pool) + r = n if r is None else r + return [tuple(pool[i] for i in ix) for ix in product_rows(range(n), repeat=r) + if len(set(ix)) == r] + + +def combination_rows(pool, r): + pool = tuple(pool) + return [tuple(pool[i] for i in ix) for ix in permutation_rows(range(len(pool)), r) + if sorted(ix) == list(ix)] + + +def cwr_rows(pool, r): + pool = tuple(pool) + return [tuple(pool[i] for i in ix) for ix in product_rows(range(len(pool)), repeat=r) + if sorted(ix) == list(ix)] + + +def pools(): + return [ + ["s%d" % i * 3 for i in range(5)], + [[i] for i in range(4)], + [Item(i) for i in range(6)], + ] + + +class RowsHoldItemsTests(unittest.TestCase): + def test_against_recipes(self): + for _ in range(40): + for pool in pools(): + self.assertEqual(list(itertools.combinations(pool, 3)), combination_rows(pool, 3)) + self.assertEqual(list(itertools.combinations_with_replacement(pool, 2)), + cwr_rows(pool, 2)) + self.assertEqual(list(itertools.permutations(pool, 2)), permutation_rows(pool, 2)) + self.assertEqual(list(itertools.product(pool, pool[:2])), + product_rows(pool, pool[:2])) + stepped = [] + it = itertools.combinations(pool, 2) + for row in it: + stepped.append(row) + self.assertEqual(stepped, combination_rows(pool, 2)) + + def test_counts(self): + for make in (lambda p: itertools.combinations(p, 2), + lambda p: itertools.combinations_with_replacement(p, 2), + lambda p: itertools.permutations(p, 2), + lambda p: itertools.product(p, repeat=2)): + for _ in range(30): + pool = [Item(i) for i in range(4)] + before = [sys.getrefcount(x) for x in pool] + rows = list(make(pool)) + shown = [sum(row.count(x) for row in rows) for x in pool] + after = [sys.getrefcount(x) for x in pool] + self.assertEqual([a - b for a, b in zip(after, before)], shown) + del rows + self.assertEqual([sys.getrefcount(x) for x in pool], before) + + def test_items_freed(self): + for _ in range(30): + pool = [Item(i) for i in range(5)] + refs = [weakref.ref(x) for x in pool] + rows = list(itertools.combinations(pool, 3)) + rows += list(itertools.product(pool, repeat=2)) + first = rows[0][0] + del pool + gc.collect() + self.assertTrue(all(r() is not None for r in refs)) + del rows + gc.collect() + self.assertIs(refs[0](), first) + del first + gc.collect() + self.assertTrue(all(r() is None for r in refs)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_json_key_memo.py b/tests/regrtest/test_json_key_memo.py new file mode 100644 index 000000000..fb11565b0 --- /dev/null +++ b/tests/regrtest/test_json_key_memo.py @@ -0,0 +1,47 @@ +"""`json.loads` shares one string per distinct object key in a document. + +The decoder memoizes keys, as CPython's does: equal keys in one document +are the same object, whether written plainly or with escapes, and every +key hashes and compares like any other string. +""" + +import json +import unittest + + +class JsonKeyMemo(unittest.TestCase): + def test_repeated_keys_share_one_string(self): + doc = json.loads('[{"name": 1, "id": 2}, {"name": 3, "id": 4}, {"id": 5}]') + self.assertIs(list(doc[0])[0], list(doc[1])[0]) + self.assertIs(list(doc[0])[1], list(doc[1])[1]) + self.assertIs(list(doc[1])[1], list(doc[2])[0]) + self.assertEqual(doc, [{"name": 1, "id": 2}, {"name": 3, "id": 4}, {"id": 5}]) + + def test_escaped_and_plain_spellings(self): + doc = json.loads('[{"ab": 1}, {"a\\u0062": 2}, {"\\u00e9t\\u00e9": 3}, {"été": 4}]') + self.assertEqual([list(d)[0] for d in doc], ["ab", "ab", "été", "été"]) + self.assertEqual(doc[1]["ab"], 2) + self.assertEqual(doc[3]["été"], 4) + + def test_keys_hash_like_strings(self): + keys = ["k%d" % i for i in range(500)] + ["", "x" * 100, "中文", "\U0001f600"] + text = json.dumps([{k: i} for i, k in enumerate(keys)] + [dict.fromkeys(keys, 0)]) + doc = json.loads(text) + for i, k in enumerate(keys): + self.assertEqual(doc[i], {k: i}) + self.assertEqual(hash(list(doc[i])[0]), hash(k)) + self.assertIn(k, doc[-1]) + self.assertEqual(len(doc[-1]), len(keys)) + self.assertEqual(set(doc[-1]), set(keys)) + + def test_duplicate_keys_keep_the_last_value(self): + self.assertEqual(json.loads('{"a": 1, "b": 2, "a": 3}'), {"a": 3, "b": 2}) + + def test_separate_documents(self): + for i in range(200): + d = json.loads('{"x%d": %d, "y": [%d]}' % (i % 7, i, i)) + self.assertEqual(d, {"x%d" % (i % 7): i, "y": [i]}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_keyword_defaults_in_callbacks.py b/tests/regrtest/test_keyword_defaults_in_callbacks.py new file mode 100644 index 000000000..81e57f95f --- /dev/null +++ b/tests/regrtest/test_keyword_defaults_in_callbacks.py @@ -0,0 +1,313 @@ +"""Callbacks with keyword-only defaults, and partials with keywords. + +`map`, `filter`, `sorted`, `max` and the other native loops evaluate a +small callback in place. A function with keyword-only parameters takes +their defaults there, and a `functools.partial` binds its stored +keywords by name. These tests pin what the full call does for every +shape the in-place one has to decline or get right: a required +keyword-only parameter, a keyword that collides with a positional, one +that names nothing, a positional-only parameter named by keyword, +replaced defaults, stored keywords changed between calls, subclasses, +and tracing. +""" + +import bisect +import functools +import heapq +import itertools +import sys +import traceback +import unittest + +ROUNDS = 300 +R = list(range(8)) + + +def shift(v, *, off=1): + return v + off + + +def scaled(v, scale=2, *, off=1, neg=False): + return -(v * scale + off) if neg else v * scale + off + + +def required(v, *, off): + return v + off + + +def posonly(v, /, scale=2, *, off=0): + return v * scale + off + + +def joined(a, b, *, sep="-"): + return "%s%s%s" % (a, sep, b) + + +def collecting(v, *, off=1, **kw): + return v + off + len(kw) + + +def looping(v, *, off=1): + t = 0 + for _ in range(3): + t += v + off + return t + + +class K: + def m(self, v, *, off=10): + return v + off + + @staticmethod + def s(v, *, off=20): + return v + off + + @classmethod + def c(cls, v, *, off=30): + return v + off + + +def raised(f): + try: + f() + except Exception as e: + names = [x.name for x in traceback.extract_tb(e.__traceback__)] + return type(e).__name__, str(e), names[1:] + return None + + +class KeywordOnlyDefaults(unittest.TestCase): + def test_native_loops_fill_the_defaults(self): + k = K() + for _ in range(ROUNDS): + self.assertEqual(list(map(shift, R)), [1, 2, 3, 4, 5, 6, 7, 8]) + self.assertEqual(list(map(scaled, R)), [1, 3, 5, 7, 9, 11, 13, 15]) + self.assertEqual(list(map(posonly, R)), [0, 2, 4, 6, 8, 10, 12, 14]) + self.assertEqual(list(map(joined, R[:2], R[:2])), ["0-0", "1-1"]) + self.assertEqual(list(map(collecting, R[:3])), [1, 2, 3]) + self.assertEqual(list(map(looping, R[:3])), [3, 6, 9]) + self.assertEqual(list(map(k.m, R[:3])), [10, 11, 12]) + self.assertEqual(list(map(K.s, R[:3])), [20, 21, 22]) + self.assertEqual(list(map(K.c, R[:3])), [30, 31, 32]) + self.assertEqual(sorted(R, key=scaled), R) + self.assertEqual(max(R, key=shift), 7) + self.assertEqual(list(filter(shift, [-1, 0, 1])), [0, 1]) + self.assertEqual(functools.reduce(joined, "abcd"), "a-b-c-d") + self.assertEqual( + list(itertools.starmap(joined, [(1, 2), (3, 4)])), ["1-2", "3-4"] + ) + self.assertEqual(bisect.bisect_left(R, 4, key=shift), 3) + self.assertEqual(heapq.nlargest(2, R, key=scaled), [7, 6]) + + def test_a_required_keyword_only_parameter(self): + for _ in range(ROUNDS): + self.assertEqual( + raised(lambda: list(map(required, R))), + ( + "TypeError", + "required() missing 1 required keyword-only argument: 'off'", + [""], + ), + ) + + def test_a_surplus_positional_never_binds_one(self): + for _ in range(ROUNDS): + self.assertEqual( + raised(lambda: list(map(shift, R, R))), + ( + "TypeError", + "shift() takes 1 positional argument but 2 were given", + [""], + ), + ) + + def test_replaced_defaults(self): + def f(v, scale=2, *, off=1): + return v * scale + off + + for _ in range(ROUNDS): + self.assertEqual(list(map(f, R[:3])), [1, 3, 5]) + f.__kwdefaults__ = {"off": 7} + for _ in range(ROUNDS): + self.assertEqual(list(map(f, R[:3])), [7, 9, 11]) + f.__defaults__ = (5,) + for _ in range(ROUNDS): + self.assertEqual(list(map(f, R[:3])), [7, 12, 17]) + f.__kwdefaults__ = {"other": 1} + kind, message, _ = raised(lambda: list(map(f, R))) + self.assertEqual(kind, "TypeError") + self.assertTrue( + message.endswith(".f() missing 1 required keyword-only argument: 'off'") + ) + f.__kwdefaults__ = None + self.assertEqual(raised(lambda: list(map(f, R)))[0], "TypeError") + f.__kwdefaults__ = {"off": 0} + f.__defaults__ = None + kind, message, _ = raised(lambda: sorted(R, key=functools.partial(f, off=3))) + self.assertEqual(kind, "TypeError") + self.assertTrue( + message.endswith(".f() missing 1 required positional argument: 'scale'") + ) + + +class PartialsWithKeywords(unittest.TestCase): + def test_stored_keywords_bind_by_name(self): + k = K() + p1 = functools.partial(scaled, scale=3) + p2 = functools.partial(scaled, off=5, neg=True) + p3 = functools.partial(scaled, 7) + p4 = functools.partial(required, off=2) + p5 = functools.partial(joined, sep="+") + p6 = functools.partial(joined, "L", sep="/") + p7 = functools.partial(collecting, extra=1) + p8 = functools.partial(looping, off=2) + p9 = functools.partial(functools.partial(scaled, off=9), scale=4) + p10 = functools.partial(k.m, off=1) + for _ in range(ROUNDS): + self.assertEqual(list(map(p1, R[:4])), [1, 4, 7, 10]) + self.assertEqual(sorted(R[:4], key=p2), [3, 2, 1, 0]) + self.assertEqual(max(R, key=p2), 0) + self.assertEqual(list(map(p3, R[:3])), [1, 8, 15]) + self.assertEqual(list(map(p4, R[:3])), [2, 3, 4]) + self.assertEqual(list(map(p5, R[:2], R[:2])), ["0+0", "1+1"]) + self.assertEqual(functools.reduce(p5, "abc"), "a+b+c") + self.assertEqual(list(map(p6, R[:2])), ["L/0", "L/1"]) + self.assertEqual(list(map(p7, R[:3])), [2, 3, 4]) + self.assertEqual(list(map(p8, R[:3])), [6, 9, 12]) + self.assertEqual(list(map(p9, R[:3])), [9, 13, 17]) + self.assertEqual(list(map(p10, R[:3])), [1, 2, 3]) + self.assertEqual( + list(filter(functools.partial(scaled, scale=0, off=0), R)), [] + ) + self.assertEqual( + [(key, len(list(g))) for key, g in itertools.groupby(R, key=p2)][:2], + [(-5, 1), (-7, 1)], + ) + + def test_keywords_the_call_cannot_bind(self): + collides = functools.partial(scaled, v=7) + unknown = functools.partial(scaled, nope=1) + named_posonly = functools.partial(posonly, v=3) + surplus = functools.partial(scaled, 1, 2) + for _ in range(ROUNDS): + for loop in ( + lambda p: list(map(p, R)), + lambda p: sorted(R, key=p), + lambda p: max(R, key=p), + lambda p: p(3), + ): + self.assertEqual( + raised(lambda: loop(collides))[:2], + ("TypeError", "scaled() got multiple values for argument 'v'"), + ) + self.assertEqual( + raised(lambda: loop(unknown))[:2], + ("TypeError", "scaled() got an unexpected keyword argument 'nope'"), + ) + self.assertEqual( + raised(lambda: loop(named_posonly))[:2], + ( + "TypeError", + "posonly() got some positional-only arguments passed as " + "keyword arguments: 'v'", + ), + ) + self.assertEqual( + raised(lambda: loop(surplus))[:2], + ( + "TypeError", + "scaled() takes from 1 to 2 positional arguments but 3 " + "were given", + ), + ) + + def test_stored_keywords_changed_between_calls(self): + q = functools.partial(scaled, scale=3) + for _ in range(ROUNDS): + self.assertEqual(list(map(q, R[:3])), [1, 4, 7]) + q.keywords["scale"] = 10 + for _ in range(ROUNDS): + self.assertEqual(list(map(q, R[:3])), [1, 11, 21]) + q.keywords["off"] = 100 + self.assertEqual(sorted(R[:3], key=q), [0, 1, 2]) + self.assertEqual(list(map(q, R[:3])), [100, 110, 120]) + del q.keywords["scale"] + self.assertEqual(list(map(q, R[:3])), [100, 102, 104]) + q.keywords["nope"] = 1 + self.assertEqual(raised(lambda: list(map(q, R)))[0], "TypeError") + + def test_subclasses(self): + class P(functools.partial): + pass + + class Q(functools.partial): + def __call__(self, *a, **k): + return "mine" + + sp = P(scaled, scale=6) + sp.tag = "t" + for _ in range(ROUNDS): + self.assertEqual(list(map(sp, R[:3])), [1, 7, 13]) + self.assertEqual(sorted(R[:3], key=sp), [0, 1, 2]) + self.assertEqual(list(map(Q(scaled, scale=6), R[:2])), ["mine", "mine"]) + self.assertEqual(sp.tag, "t") + + +class Observed(unittest.TestCase): + def test_tracing_sees_every_call(self): + p = functools.partial(scaled, scale=3) + for _ in range(ROUNDS): + list(map(shift, R)) + list(map(p, R)) + sorted(R, key=p) + events = [] + + def tracer(frame, event, arg): + if event == "call": + events.append(frame.f_code.co_name) + + sys.settrace(tracer) + try: + list(map(shift, R[:3])) + list(map(p, R[:3])) + sorted(R[:3], key=functools.partial(scaled, off=2)) + finally: + sys.settrace(None) + self.assertEqual(events, ["shift"] * 3 + ["scaled"] * 6) + + def test_profiling_sees_every_call(self): + p = functools.partial(scaled, off=2) + for _ in range(ROUNDS): + max(R, key=p) + events = [] + + def profiler(frame, event, arg): + if event == "call": + events.append(frame.f_code.co_name) + + sys.setprofile(profiler) + try: + list(map(shift, R[:2])) + max(R[:2], key=p) + finally: + sys.setprofile(None) + self.assertEqual( + [e for e in events if e in ("shift", "scaled")], ["shift"] * 2 + ["scaled"] * 2 + ) + + def test_recursion_through_a_partial(self): + def deep(n, *, acc=0): + if n <= 0: + return acc + return max([n - 1], key=functools.partial(deep, acc=acc + 1)) + + def runaway(v, *, k=1): + return list(map(runaway, [v])) + + for _ in range(20): + self.assertEqual(deep(5), 4) + self.assertRaises(RecursionError, runaway, 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_kwargs_read_only_uses.py b/tests/regrtest/test_kwargs_read_only_uses.py new file mode 100644 index 000000000..48e7c46ac --- /dev/null +++ b/tests/regrtest/test_kwargs_read_only_uses.py @@ -0,0 +1,64 @@ +"""A `**kwargs` dict that's only read (a truth test, `in`, a loop over its +keys, `len`, `get` and `pop`) isn't registered with the collector; one that +escapes into a cycle still is, and is collected.""" + +import gc +import unittest + + +def reads(a, **kw): + n = len(kw) + if kw: + n += 100 + if "x" in kw: + n += kw.get("x", 0) + for k in kw: + n += len(k) + n += kw.pop("y", 0) + return n + + +def escapes(**kw): + kw["box"].append(kw) + return kw["box"] + + +def view_escapes(**kw): + return kw.items() + + +class Box(list): + pass + + +class KwargsReads(unittest.TestCase): + def test_reads(self): + for _ in range(500): + self.assertEqual(reads(1), 0) + self.assertEqual(reads(1, x=5), 1 + 100 + 5 + 1) + self.assertEqual(reads(1, x=5, y=7), 2 + 100 + 5 + 2 + 7) + self.assertEqual(reads(1, zz=1), 1 + 100 + 2) + + def test_escaping_dict_collected(self): + gc.collect() + for _ in range(300): + escapes(box=Box()) + gc.collect() + self.assertFalse([o for o in gc.get_objects() if type(o) is Box]) + + def test_view_keeps_dict(self): + for _ in range(200): + v = view_escapes(a=1, b=2) + self.assertEqual(sorted(v), [("a", 1), ("b", 2)]) + + def test_fresh_dict_each_call(self): + def keep(**kw): + return kw + a = keep(x=1) + b = keep(y=2) + self.assertIsNot(a, b) + self.assertEqual((a, b), ({"x": 1}, {"y": 2})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_kwargs_unique_append.py b/tests/regrtest/test_kwargs_unique_append.py new file mode 100644 index 000000000..2523bad50 --- /dev/null +++ b/tests/regrtest/test_kwargs_unique_append.py @@ -0,0 +1,81 @@ +"""Keyword calls of `**kwargs` functions append each collected keyword +without probing for a repeat; the dictionaries (keys in call order, +values, length), many keywords, keywords that also bind named +parameters, a dictionary the callee returns or stores, one it changes, +and the duplicate-keyword and unexpected-keyword errors match the +general call.""" + +import unittest + + +def count(**k): + return len(k) + + +def keys(**k): + return tuple(k) + + +def give(**k): + return k + + +def mixed(a, b=2, **k): + return (a, b, sorted(k.items())) + + +kept = [] + + +def keep(**k): + kept.append(k) + return len(kept) + + +def change(**k): + k["z"] = 0 + return sorted(k) + + +class KwargsUniqueAppend(unittest.TestCase): + def test_leaf_calls(self): + n = 0 + for i in range(3000): + n += count(a=i, b=2) + self.assertEqual(keys(b=1, a=2, c=3), ("b", "a", "c")) + self.assertEqual(n, 6000) + + def test_many_keywords(self): + for i in range(500): + d = give(k0=0, k1=1, k2=2, k3=3, k4=4, k5=5, k6=6, k7=7, k8=8, + k9=9, k10=10, k11=11, k12=12, k13=13, k14=i) + self.assertEqual(list(d), ["k%d" % j for j in range(15)]) + self.assertEqual(d["k14"], i) + self.assertEqual(d.get("k3"), 3) + self.assertNotIn("k15", d) + + def test_escaping_dicts(self): + out = [give(a=i, b=-i) for i in range(1000)] + self.assertEqual(out[7], {"a": 7, "b": -7}) + self.assertEqual(len({id(d) for d in out}), 1000) + kept.clear() + for i in range(500): + keep(x=i) + self.assertEqual([d["x"] for d in kept], list(range(500))) + for i in range(500): + self.assertEqual(change(y=i, a=1), ["a", "y", "z"]) + + def test_named_and_errors(self): + for i in range(1000): + self.assertEqual(mixed(1, c=3, b=i, d=4), (1, i, [("c", 3), ("d", 4)])) + self.assertEqual(mixed(a=5, e=1), (5, 2, [("e", 1)])) + with self.assertRaises(TypeError): + mixed(1, a=2) + with self.assertRaises(TypeError): + give(**{"a": 1}, a=2) + with self.assertRaises(SyntaxError): + compile("give(a=1, a=2)", "", "eval") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_kwonly_default_calls.py b/tests/regrtest/test_kwonly_default_calls.py new file mode 100644 index 000000000..ca0a98505 --- /dev/null +++ b/tests/regrtest/test_kwonly_default_calls.py @@ -0,0 +1,94 @@ +"""Calls of functions with keyword-only parameters in compiled loops. + +A positional call of a pure leaf with keyword-only defaults caches its +site's shape, so the framed call binds it and compiled code lowers it in +line; changed `__defaults__` and `__kwdefaults__`, a required keyword-only +parameter, methods, and a site that sees another function all behave as +in CPython. Run it past the compile threshold. +""" + + +def fkw(a, b=2, *, c=3): + return a + b + c + + +def freq(a, *, c): + return a + c + + +def fother(a, b=20, *, c=30): + return a * 100 + b + c + + +class K: + def m(self, a, *, s=5): + return a + s + + +def run(n, g): + t = 0 + for i in range(n): + t += g(i) + return t + + +def loop(n): + t = 0 + for i in range(n): + t += fkw(i) + return t + + +def loop_kw(n): + t = 0 + for i in range(n): + t += fkw(i, c=4) + fkw(i, b=1) + return t + + +def loop_method(n, k): + t = 0 + for i in range(n): + t += k.m(i) + return t + + +N = 3000 +base = sum(range(N)) +assert loop(N) == base + 5 * N +assert loop_kw(N) == 2 * base + 6 * N + 4 * N +assert loop_method(N, K()) == base + 5 * N +assert run(N, fkw) == base + 5 * N +assert run(N, fother) == 100 * base + 50 * N + +# Changed defaults take effect at once. +fkw.__kwdefaults__ = {"c": 10} +assert loop(10) == sum(range(10)) + 12 * 10 +fkw.__defaults__ = (0,) +assert loop(10) == sum(range(10)) + 10 * 10 +fkw.__kwdefaults__ = None +try: + loop(1) +except TypeError as e: + assert "c" in str(e) +else: + raise AssertionError("missing keyword-only argument") +fkw.__kwdefaults__ = {"c": 3} +fkw.__defaults__ = (2,) +assert loop(10) == sum(range(10)) + 5 * 10 + +# A required keyword-only parameter still raises. +try: + run(1, freq) +except TypeError: + pass +else: + raise AssertionError("missing required keyword-only argument") + +# The global rebound to another function at the cached site. +saved = fkw +fkw = fother +assert loop(10) == 100 * sum(range(10)) + 50 * 10 +fkw = saved +assert loop(N) == base + 5 * N +print("ok") diff --git a/tests/regrtest/test_kwonly_tier2_loops.py b/tests/regrtest/test_kwonly_tier2_loops.py new file mode 100644 index 000000000..23fcbfe54 --- /dev/null +++ b/tests/regrtest/test_kwonly_tier2_loops.py @@ -0,0 +1,115 @@ +"""Hot loops in functions with keyword-only parameters. + +Tier 2 compiles frames whose signatures carry keyword-only parameters; +the parameters are locals the caller's binding fills before the body +runs. These loops cover defaults, explicit values, rebinding, deletion, +and values of several types. +""" + +import unittest + + +def scaled(n, *, scale=2, off=1): + t = 0 + for i in range(n): + t += i * scale + off + return t + + +def floats(xs, *, key=3): + t = 0.0 + for x in xs: + t += x * 1.5 + key + return t + + +def rebinds(n, *, step=1): + t = 0 + for i in range(n): + t += step + if i % 7 == 0: + step = step + 1 + return t, step + + +def deletes(n, *, tag="a"): + out = 0 + for i in range(n): + out += len(tag) + del tag + try: + tag # noqa: B018 + except UnboundLocalError: + return out, "unbound" + return out, "bound" + + +def mixed(n, a, /, b, *, c, d=None): + t = 0 + for i in range(n): + t += a + b + c + (0 if d is None else d) + return t + + +class Acc: + def run(self, n, *, by=1): + t = 0 + for i in range(n): + t += by + return t + + +class KwonlyLoopTests(unittest.TestCase): + N = 30000 + + def test_defaults_and_explicit(self): + n = self.N + for _ in range(3): + self.assertEqual(scaled(n), sum(i * 2 + 1 for i in range(n))) + self.assertEqual(scaled(n, scale=3, off=0), sum(i * 3 for i in range(n))) + + def test_float_and_int_key(self): + xs = [float(i) for i in range(self.N)] + expect = sum(x * 1.5 + 2 for x in xs) + for _ in range(3): + self.assertEqual(floats(xs, key=2), expect) + self.assertEqual(floats(xs, key=2.5), sum(x * 1.5 + 2.5 for x in xs)) + + def test_type_change_between_calls(self): + for _ in range(3): + self.assertEqual(scaled(1000, scale=2.0), float(scaled(1000))) + self.assertEqual(scaled(1000, scale=1 << 70, off=0), + sum(i * (1 << 70) for i in range(1000))) + + def test_rebinding(self): + n = self.N + t, step = 0, 1 + for i in range(n): + t += step + if i % 7 == 0: + step += 1 + for _ in range(3): + self.assertEqual(rebinds(n), (t, step)) + + def test_deletion(self): + for _ in range(3): + self.assertEqual(deletes(self.N, tag="xyz"), (3 * self.N, "unbound")) + + def test_mixed_signature(self): + for _ in range(3): + self.assertEqual(mixed(self.N, 1, 2, c=3), 6 * self.N) + self.assertEqual(mixed(self.N, 1, b=2, c=3, d=4), 10 * self.N) + + def test_method(self): + a = Acc() + for _ in range(3): + self.assertEqual(a.run(self.N), self.N) + self.assertEqual(a.run(self.N, by=5), 5 * self.N) + + def test_missing_kwonly_still_raises(self): + with self.assertRaises(TypeError): + mixed(10, 1, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_lambda_part_callbacks.py b/tests/regrtest/test_lambda_part_callbacks.py new file mode 100644 index 000000000..5629b36de --- /dev/null +++ b/tests/regrtest/test_lambda_part_callbacks.py @@ -0,0 +1,87 @@ +"""Native adapters (`map`, `filter`, `itertools.groupby`, `min`/`max` +keys) calling a lambda that reads one part of its argument +(`lambda w: w[0]`, `lambda r: r["k"]`, `lambda p: p.x`): the part read +directly matches the call, on strings (ASCII and not), tuples, lists, +dicts and instances; misses and other types take the full call and raise +what it raises; a trace hook still sees every call.""" + +import itertools +import sys +import unittest + +N = 300 + + +class P: + def __init__(self, x): + self.x = x + + @property + def doubled(self): + return self.x * 2 + + +class LambdaPartCallbackTests(unittest.TestCase): + def test_groupby_first_letter(self): + words = sorted("apple avocado banana blueberry cherry cranberry date".split()) + want = [("a", 2), ("b", 2), ("c", 2), ("d", 1)] + for _ in range(N): + got = [(k, len(list(g))) for k, g in itertools.groupby(words, key=lambda w: w[0])] + self.assertEqual(got, want) + self.assertEqual( + [k for k, _ in itertools.groupby(words, key=lambda w: w[-1])], + [w[-1] for w in words if True][:1] + + [ + b[-1] + for a, b in zip(words, words[1:]) + if a[-1] != b[-1] + ], + ) + + def test_map_shapes(self): + rows = [{"k": i, "v": -i} for i in range(10)] + pairs = [(i, str(i)) for i in range(10)] + ps = [P(i) for i in range(10)] + for _ in range(N): + self.assertEqual(list(map(lambda r: r["k"], rows)), list(range(10))) + self.assertEqual(list(map(lambda t: t[1], pairs)), [str(i) for i in range(10)]) + self.assertEqual(list(map(lambda t: t[-2], pairs)), list(range(10))) + self.assertEqual(list(map(lambda p: p.x, ps)), list(range(10))) + self.assertEqual(list(map(lambda p: p.doubled, ps)), [2 * i for i in range(10)]) + self.assertEqual(list(map(lambda s: s[1], ["ab", "éü", "日本"])), ["b", "ü", "本"]) + + def test_filter_and_minmax(self): + rows = [{"ok": i % 3 == 0, "n": i} for i in range(12)] + for _ in range(N): + self.assertEqual([r["n"] for r in filter(lambda r: r["ok"], rows)], [0, 3, 6, 9]) + self.assertEqual(max(rows, key=lambda r: r["n"])["n"], 11) + self.assertEqual(min(["bb", "a", "ccc"], key=lambda s: s[0]), "a") + + def test_misses_raise(self): + with self.assertRaises(KeyError): + list(map(lambda r: r["k"], [{"k": 1}, {}])) + with self.assertRaises(IndexError): + list(map(lambda s: s[3], ["abcd", "ab"])) + with self.assertRaises(AttributeError): + list(map(lambda p: p.x, [P(1), object()])) + with self.assertRaises(TypeError): + list(map(lambda t: t[0], [(1,), 5])) + + def test_trace_sees_calls(self): + calls = [] + + def tracer(frame, event, arg): + if event == "call" and frame.f_code.co_name == "": + calls.append(1) + return None + + sys.settrace(tracer) + try: + list(map(lambda t: t[0], [(1,), (2,), (3,)])) + finally: + sys.settrace(None) + self.assertEqual(len(calls), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_large_block_reuse.py b/tests/regrtest/test_large_block_reuse.py new file mode 100644 index 000000000..66fc954b2 --- /dev/null +++ b/tests/regrtest/test_large_block_reuse.py @@ -0,0 +1,51 @@ +"""Large buffers freed and allocated again, and repetition of sequences. + +A freed block too large for the allocator's arenas is kept a while for an +allocation of about its size, so it must come back whole: a zeroed +allocation (`bytearray(n)`, `bytes(n)`) after a filled one of the same +size reads all zeros, and nothing written to a kept block shows through. +`[x] * n` and `(x,) * n` copy values without a reference count bitwise +and alias anything else, as CPython does. Run it past the compile +threshold, with sizes on both sides of the in-line limits. +""" + +N = 3 * 1024 * 1024 + + +def large_rounds(): + for i in range(6): + filled = bytes([i + 1]) * N + assert filled.count(i + 1) == N + del filled + z = bytearray(N) + assert z.count(0) == N and len(z) == N + z[::4096] = b"\x07" * len(z[::4096]) + del z + assert bytes(N).count(0) == N + lst = [i] * (N // 8) + assert lst[-1] == i and len(lst) == N // 8 + del lst + assert [None] * (N // 8) == [None] * (N // 8) + + +def repeats(n): + for i in range(n): + k = i % 7 + assert [0, 1.5, True, None] * k == [0, 1.5, True, None] * k + assert len([i] * 5000) == 5000 and ([i] * 5000)[4999] == i + t = (i, -2.0) * k + assert len(t) == 2 * k and (k == 0 or t[-2:] == (i, -2.0)) + shared = [[]] * 3 + shared[0].append(i) + assert shared[2] == [i] + s = ["ab", i] * 3 + assert s == ["ab", i, "ab", i, "ab", i] and s[0] is s[4] + big = 10**30 + assert ([big] * 2)[1] is big + assert [1] * -3 == [] and (1,) * 0 == () + + +large_rounds() +repeats(3000) +large_rounds() +print("ok") diff --git a/tests/regrtest/test_leaf_class_read.py b/tests/regrtest/test_leaf_class_read.py new file mode 100644 index 000000000..c7d383fa6 --- /dev/null +++ b/tests/regrtest/test_leaf_class_read.py @@ -0,0 +1,63 @@ +"""`obj.__class__` read inside an in-place evaluated method. + +A dataclass's `__eq__` compares `other.__class__ is self.__class__`; the +read answers the instance's class where `object`'s descriptor does, and a +class that defines its own `__class__`, or an instance whose class was +reassigned, still reads as Python reads it. +""" + +import dataclasses +import unittest + +N = 30000 + + +@dataclasses.dataclass +class P: + a: int + b: int + + +class Q(P): + pass + + +class Fake: + @property + def __class__(self): + return P + + +def same_class(x, y): + return x.__class__ is y.__class__ + + +class LeafClassReadTests(unittest.TestCase): + def test_dataclass_eq(self): + p1, p2, q = P(1, 2), P(1, 2), Q(1, 2) + for _ in range(N): + a = p1 == p2 + b = p1 == q + c = p1 == P(1, 3) + self.assertEqual((a, b, c), (True, False, False)) + + def test_overridden_and_reassigned(self): + class A: + pass + + class B: + pass + + x, y = A(), A() + f = Fake() + out = [] + for i in range(N): + if i == N // 2: + y.__class__ = B + out.append((same_class(x, y), same_class(f, P(0, 0)))) + self.assertEqual(out[0], (True, True)) + self.assertEqual(out[-1], (False, True)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_constructor_calls.py b/tests/regrtest/test_leaf_constructor_calls.py new file mode 100644 index 000000000..1487e08b3 --- /dev/null +++ b/tests/regrtest/test_leaf_constructor_calls.py @@ -0,0 +1,112 @@ +"""Builtin type constructors called from small functions and getters. + +A function or property getter whose body only reads and calls +(`return list(self.items)`, `return str(self.n)`) is evaluated in place, +and keeps being once its plan is compiled, a builtin type's constructor +included. Results are fresh objects where CPython's are, arguments the +constructor can't take fall back to the ordinary call, and reads from a +generator's steps (`sum(x.prop for x in xs)`) agree. +""" + +import unittest + +N = 30000 + + +class Box: + def __init__(self, items): + self.items = items + self.n = len(items) + + @property + def copy(self): + return list(self.items) + + @property + def text(self): + return str(self.n) + + @property + def frozen(self): + return tuple(self.items) + + def as_int(self, s): + return int(s) + + def fresh(self): + return dict() + + +class LeafConstructorTests(unittest.TestCase): + def test_results_are_fresh_copies(self): + b = Box([1, 2]) + seen = [] + for i in range(N): + c = b.copy + if i % 5000 == 0: + seen.append(c) + self.assertEqual(c, [1, 2]) + self.assertIsNot(c, b.items) + c.append(3) + self.assertEqual(b.items, [1, 2]) + self.assertEqual(len({id(x) for x in seen}), len(seen)) + + def test_other_constructors(self): + b = Box([1, 2, 3]) + for _ in range(N): + t, f, k, d = b.text, b.frozen, b.as_int("42"), b.fresh() + self.assertEqual((t, f, k, d), ("3", (1, 2, 3), 42, {})) + d["x"] = 1 + self.assertEqual(b.fresh(), {}) + + def test_arguments_the_constructor_declines(self): + b = Box([1]) + out = [] + for i in range(N): + s = "12" if i % 2 else "0x1" + try: + out.append(b.as_int(s)) + except ValueError: + out.append(None) + self.assertEqual(out[:2], [None, 12]) + b.items = (x for x in range(3)) + self.assertEqual(b.copy, [0, 1, 2]) + + def test_generator_steps(self): + boxes = [Box([i]) for i in range(4)] + for _ in range(N // 4): + r = sum((x.copy for x in boxes), []) + s = "".join(x.text for x in boxes) + self.assertEqual(r, [0, 1, 2, 3]) + self.assertEqual(s, "1111") + + def test_generator_steps_with_activation_getters(self): + def helper(x): + return [x, x] + + class Node: + def __init__(self, v): + self.v = v + + @property + def pair(self): + return helper(self.v) + + nodes = [Node(i) for i in range(3)] + for _ in range(N // 3): + r = sum((n.pair for n in nodes), []) + self.assertEqual(r, [0, 0, 1, 1, 2, 2]) + + def test_subclass_items(self): + class L(list): + pass + + b = Box(L([5])) + for _ in range(N): + c = b.copy + self.assertIs(type(c), list) + self.assertEqual(c, [5]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_convert_unpack.py b/tests/regrtest/test_leaf_convert_unpack.py new file mode 100644 index 000000000..717c45836 --- /dev/null +++ b/tests/regrtest/test_leaf_convert_unpack.py @@ -0,0 +1,62 @@ +"""Frameless leaf evaluations of an f-string's `!r` and `!s` conversions +and of `a, b = seq` unpacking: the reprs of strings (with quotes and +escapes), ints, floats, bools and `None`; `!r` of an instance (its +`__repr__` runs); unpacking tuples and lists, a nested unpack, a wrong +length's ValueError, a non-sequence's TypeError, and swaps through +unpacking, all as the general call gives them.""" + +import unittest + + +class R: + def __init__(self, a, b): + self.a, self.b = a, b + + def __repr__(self): + return f"R({self.a!r}, {self.b!s})" + + +class Inner: + def __repr__(self): + return "" + + +def first_last(pair): + a, b = pair + return f"{b!r}:{a!r}" + + +def nested(t): + a, (b, c) = t + return a + b * c + + +def swap(t): + x, y, z = t + z, x = x, z + return (x, y, z) + + +class LeafConvertUnpack(unittest.TestCase): + def test_reprs(self): + out = [] + for i in range(3000): + out.append((repr(R("it's", 2.5)), repr(R('say "hi"\n', None)), repr(R(True, i)), "%r" % (R(Inner(), "s"),))) + self.assertEqual(out[9], ("R(\"it's\", 2.5)", "R('say \"hi\"\\n', None)", "R(True, 9)", "R(, s)")) + + def test_unpack(self): + out = [] + for i in range(3000): + out.append((first_last((i, "x")), first_last(["y", 1.5]), nested((1, [i, 2])), swap((1, 2, 3)))) + self.assertEqual(out[4], ("'x':4", "1.5:'y'", 9, (3, 2, 1))) + for i in range(500): + with self.assertRaises(ValueError) as cm: + first_last((1, 2, 3)) + with self.assertRaises(TypeError): + first_last(5) + self.assertEqual(str(cm.exception), "too many values to unpack (expected 2, got 3)") + self.assertEqual(first_last("ab"), "'b':'a'") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_defaults.py b/tests/regrtest/test_leaf_defaults.py new file mode 100644 index 000000000..ca808eefb --- /dev/null +++ b/tests/regrtest/test_leaf_defaults.py @@ -0,0 +1,64 @@ +"""A pure-leaf function called without its trailing defaulted parameters +from native callers (`map`, `sorted(key=...)`, `max(key=...)`, a bound +method's callback): the defaults bind, `__defaults__` replaced later +binds the new ones, a mutable default is the same object each call, +keyword-only parameters and `**kwargs` still bind, and every result +matches the general call.""" + +import unittest + + +def scale(x, factor=2): + return x * factor + + +def pick(x, i=0, j=None): + return (x, i, j) + + +def kwo(x, *, k=3): + return x + k + + +def kws(x, **kw): + return (x, len(kw)) + + +def same(x, acc=[]): + return acc + + +class C: + def __init__(self): + self.d = {"a": 1} + + def get(self, k, default=-1): + return self.d.get(k, default) + + +class LeafDefaults(unittest.TestCase): + def test_native_callers(self): + xs = list(range(10)) + c = C() + for i in range(2000): + r = (list(map(scale, xs)), sorted(xs, key=scale), max(xs, key=pick), + list(map(c.get, ["a", "b"])), list(map(kwo, xs[:2])), list(map(kws, xs[:2]))) + self.assertEqual(r, ([2 * x for x in xs], xs, 9, [1, -1], [3, 4], [(0, 0), (1, 0)])) + accs = set(map(id, map(same, xs))) + self.assertEqual(len(accs), 1) + + def test_replaced_defaults(self): + def f(x, y=1): + return x + y + + out = [] + for i in range(2000): + out.extend(map(f, [0])) + f.__defaults__ = (10,) + for i in range(2000): + out.extend(map(f, [0])) + self.assertEqual((out.count(1), out.count(10)), (2000, 2000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_floored_divmod.py b/tests/regrtest/test_leaf_floored_divmod.py new file mode 100644 index 000000000..51465101a --- /dev/null +++ b/tests/regrtest/test_leaf_floored_divmod.py @@ -0,0 +1,68 @@ +"""Floor division and modulo of machine ints in hot pure functions. + +Sort keys and small pure helpers run in compiled leaf plans and the +interpreter's leaf int path. Both must floor toward negative infinity +for every sign combination, raise ZeroDivisionError for a zero divisor, +and promote -2**63 // -1 to a big int. +""" + +import unittest + +MIN = -(2**63) +PAIRS = [ + (7, 3), (-7, 3), (7, -3), (-7, -3), + (6, 3), (-6, 3), (6, -3), (-6, -3), + (0, 5), (0, -5), (1, 2**62), (-1, 2**62), + (MIN, 1), (MIN, -2), (MIN, 3), (2**63 - 1, -7), +] + + +def fdiv(a, b): + return a // b + + +def fmod(a, b): + return a % b + + +def neg_mod3(x): + return -x % 3 + + +class LeafFlooredDivMod(unittest.TestCase): + def test_sign_combinations(self): + want = [(a // b, a % b) for a, b in PAIRS] + for _ in range(3000): + got = [(fdiv(a, b), fmod(a, b)) for a, b in PAIRS] + self.assertEqual(got, want) + for (a, b), (q, r) in zip(PAIRS, want): + self.assertEqual(q * b + r, a) + if r: + self.assertEqual(r < 0, b < 0) + + def test_min_over_minus_one(self): + for _ in range(3000): + self.assertEqual(fdiv(MIN, -1), 2**63) + self.assertEqual(fmod(MIN, -1), 0) + + def test_zero_divisor(self): + for _ in range(3000): + self.assertEqual(fdiv(9, 4), 2) + with self.assertRaises(ZeroDivisionError): + fdiv(9, 0) + with self.assertRaises(ZeroDivisionError): + fmod(-9, 0) + + def test_sort_keys(self): + data = list(range(-50, 50)) + want_pair = sorted(data, key=lambda x: (x % 3 if x >= 0 else -((-x) % 3) % 3, x)) + for _ in range(300): + self.assertEqual(sorted(data, key=lambda x: (-x % 3, x)), + sorted(data, key=lambda x: ((3 - x % 3) % 3, x))) + self.assertEqual(sorted(data, key=lambda x: (x % 3, x)), want_pair) + self.assertEqual(sorted(data, key=neg_mod3)[:5], [-48, -45, -42, -39, -36]) + self.assertEqual(sorted(data, key=lambda x: (x // -4, x))[:3], [49, 45, 46]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_fstring.py b/tests/regrtest/test_leaf_fstring.py new file mode 100644 index 000000000..7eeebeb89 --- /dev/null +++ b/tests/regrtest/test_leaf_fstring.py @@ -0,0 +1,89 @@ +"""A `__str__`, `__repr__` or small function whose f-string formats strings, +ints, floats, bools and `None` evaluates frameless: the text of each kind +(float reprs too), many pieces, a piece that is an instance (its `__str__` +runs) or a `str` subclass, a string reused after another f-string extends +it, and fields changed later match the general call, through `str()`, +`repr()`, `"%s" % obj`, `"{}".format(obj)` and `map(str, ...)`.""" + +import unittest + + +class P: + def __init__(self, x, y, label="p", flag=True, extra=None): + self.x, self.y, self.label, self.flag, self.extra = x, y, label, flag, extra + + def __str__(self): + return f"P({self.x}, {self.y})" + + def __repr__(self): + return f"P(x={self.x}, y={self.y}, label={self.label}, flag={self.flag}, extra={self.extra})" + + +class Inner: + def __str__(self): + return "inner" + + +class MyStr(str): + def __str__(self): + return "mystr" + + +def pair(a, b): + s = f"{a}" + t = f"{s}-{b}" + return (s, t) + + +def single(a): + return f"{a}" + + +def wide(a, b, c): + return f"{a}.{b}.{c}.{a}.{b}.{c}.{a}.{b}.{c}" + + +def wider(a, b, c): + return f"{a}.{b}.{c}.{a}.{b}.{c}.{a}.{b}.{c}.{a}" + + +class LeafFString(unittest.TestCase): + def test_text(self): + p = P(3, 2.5, "lbl", False, None) + out = [] + for i in range(3000): + out.append((str(p), repr(p), "%s" % p, "{}".format(p), str(P(i, -i)))) + self.assertEqual(out[4][:4], ("P(3, 2.5)", "P(x=3, y=2.5, label=lbl, flag=False, extra=None)", + "P(3, 2.5)", "P(3, 2.5)")) + self.assertEqual(out[9][4], "P(9, -9)") + self.assertEqual(", ".join(map(str, [P(1, 2), P(0.1, 1e20)])), "P(1, 2), P(0.1, 1e+20)") + nan = float("nan") + self.assertEqual(str(P(nan, float("-inf"))), "P(nan, -inf)") + + def test_pieces_that_decline(self): + out = [] + for i in range(2000): + out.append((str(P(Inner(), MyStr("m"))), str(P(i, (1, 2))))) + self.assertEqual(out[0], ("P(inner, mystr)", "P(0, (1, 2))")) + + def test_reuse_and_changes(self): + out = [] + for i in range(3000): + out.append(pair(i, "z")) + out.append(single("abc")) + self.assertEqual(out[10], ("5", "5-z")) + self.assertEqual(out[11], "abc") + joined = [(wide(i, "b", 2.5), wider(i, None, True)) for i in range(2000)] + self.assertEqual(joined[7], ("7.b.2.5.7.b.2.5.7.b.2.5", "7.None.True.7.None.True.7.None.True.7")) + p = P(0, 0) + seen = [] + for i in range(2000): + p.x = i + seen.append(str(p)) + p.y = "why" + seen.append(str(p)) + self.assertEqual(seen[-2:], ["P(1999, 0)", "P(1999, why)"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_hash_single.py b/tests/regrtest/test_leaf_hash_single.py new file mode 100644 index 000000000..ad0ec79a0 --- /dev/null +++ b/tests/regrtest/test_leaf_hash_single.py @@ -0,0 +1,57 @@ +"""`return hash(self.a)` in a frameless `__hash__` hashes the attribute +directly when it hashes natively; every value and every fallback matches +the builtin.""" + +import unittest + + +class One: + def __init__(self, a): + self.a = a + + def __eq__(self, o): + return isinstance(o, One) and self.a == o.a + + def __hash__(self): + return hash(self.a) + + +class Plain: + pass + + +class LeafHashSingle(unittest.TestCase): + def test_values(self): + p = Plain() + vals = [0, -1, 7, 2**61 - 1, 2**62, True, None, 1.5, -0.0, "s", "", b"b", + (1, "x"), p, One(3), frozenset({1})] + for _ in range(200): + for v in vals: + self.assertEqual(hash(One(v)), hash(v)) + self.assertEqual(len({One(i % 7) for i in range(200)}), 7) + + def test_nan_and_unhashable(self): + nan = float("nan") + for _ in range(200): + self.assertEqual(hash(One(nan)), hash(nan)) + with self.assertRaises(TypeError): + hash(One([1])) + + def test_shadowed_hash(self): + ns = {} + exec( + "class S:\n" + " def __init__(self, a): self.a = a\n" + " def __hash__(self): return hash(self.a)\n", + ns, + ) + S = ns["S"] + for _ in range(200): + self.assertEqual(hash(S(5)), hash(5)) + ns["hash"] = lambda x: 4242 + for _ in range(200): + self.assertEqual(hash(S(5)), 4242) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_instance_compare_nested.py b/tests/regrtest/test_leaf_instance_compare_nested.py new file mode 100644 index 000000000..6ca2c30ea --- /dev/null +++ b/tests/regrtest/test_leaf_instance_compare_nested.py @@ -0,0 +1,189 @@ +"""Comparisons of two instances inside pure methods (leaf evaluations), +run as nested calls of the instances' own comparison methods: +`total_ordering`'s derived methods, an `__eq__` comparing instance +fields, `NotImplemented` and non-bool answers, a raising method, a +self-recursive `__eq__`, nesting deeper than the nested-call limit, and a +comparison next to a store.""" + +import functools +import unittest + +N = 3000 + + +@functools.total_ordering +class V: + def __init__(self, v): + self.v = v + + def __eq__(self, o): + return self.v == o.v + + def __lt__(self, o): + return self.v < o.v + + +class P: + def __init__(self, x, y): + self.x = x + self.y = y + + def __eq__(self, o): + return self.x == o.x and self.y == o.y + + +class Box: + def __init__(self, p): + self.p = p + + def __eq__(self, o): + return self.p == o.p + + +class Outer: + def __init__(self, b): + self.b = b + + def __eq__(self, o): + return self.b == o.b + + +class Top: + def __init__(self, o): + self.o = o + + def __eq__(self, other): + return self.o == other.o + + +class NI: + def __eq__(self, o): + return NotImplemented + + +class HoldsNI: + def __init__(self): + self.n = NI() + + def __eq__(self, o): + return self.n == o.n + + +class Num: + def __init__(self, v): + self.v = v + + def __eq__(self, o): + return self.v - o.v + + +class HoldsNum: + def __init__(self, v): + self.n = Num(v) + + def __eq__(self, o): + return self.n == o.n + + +class Bad: + def __eq__(self, o): + raise KeyError("bad") + + +class HoldsBad: + def __init__(self): + self.b = Bad() + + def __eq__(self, o): + return self.b == o.b + + +class Rec: + def __init__(self, nxt): + self.nxt = nxt + + def __eq__(self, o): + return self.nxt == o.nxt + + +class Tracker: + def __init__(self, p): + self.p = p + self.seen = 0 + + def same(self, o): + self.seen = self.seen + 1 + return self.p == o.p + + +class NestedCompareTests(unittest.TestCase): + def test_total_ordering(self): + vs = [V(i % 7) for i in range(10)] + for _ in range(N // 10): + self.assertEqual(max(vs).v, 6) + self.assertEqual(min(vs).v, 0) + a, b = V(1), V(2) + for _ in range(N): + self.assertTrue(b > a) + self.assertFalse(a > b) + self.assertFalse(a > a) + self.assertTrue(a >= a) + self.assertTrue(a <= b) + + def test_field_equality(self): + for _ in range(N): + self.assertTrue(Box(P(1, 2)) == Box(P(1, 2))) + self.assertFalse(Box(P(1, 2)) == Box(P(1, 3))) + self.assertTrue(Box(P(1, 2)) != Box(P(2, 2))) + boxes = [Box(P(i, i)) for i in range(10)] + for _ in range(N // 10): + self.assertEqual(boxes.index(Box(P(7, 7))), 7) + self.assertIn(Box(P(3, 3)), boxes) + + def test_deep_nesting(self): + a = Top(Outer(Box(P(1, 2)))) + b = Top(Outer(Box(P(1, 2)))) + c = Top(Outer(Box(P(1, 9)))) + for _ in range(N): + self.assertTrue(a == b) + self.assertFalse(a == c) + + def test_not_implemented_and_non_bool(self): + for _ in range(N // 10): + # Both sides answer NotImplemented: identity decides. + self.assertFalse(HoldsNI() == HoldsNI()) + h = HoldsNI() + self.assertTrue(h == h) + self.assertEqual(HoldsNum(5) == HoldsNum(2), 3) + self.assertEqual(HoldsNum(5) == HoldsNum(5), 0) + + def test_raising(self): + for _ in range(N // 100): + with self.assertRaises(KeyError): + HoldsBad() == HoldsBad() + + def test_recursion(self): + def chain(n, base): + r = base + for _ in range(n): + r = Rec(r) + return r + + a, b = chain(50, 1), chain(50, 1) + for _ in range(N // 100): + self.assertTrue(a == b) + self.assertFalse(a == chain(50, 2)) + x, y = Rec(None), Rec(None) + x.nxt, y.nxt = x, y + with self.assertRaises(RecursionError): + x == y + + def test_with_store(self): + t, u = Tracker(P(1, 1)), Tracker(P(1, 1)) + for _ in range(N): + self.assertTrue(t.same(u)) + self.assertEqual(t.seen, N) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_membership_and_protocols.py b/tests/regrtest/test_leaf_membership_and_protocols.py new file mode 100644 index 000000000..4dcbf6648 --- /dev/null +++ b/tests/regrtest/test_leaf_membership_and_protocols.py @@ -0,0 +1,164 @@ +"""Membership, truth and attribute fallbacks evaluated in place. + +Frameless evaluation now runs `x in container` (and `not in`) over native +containers, `bool(obj)` takes the truth test's path, and a pure +`__getattr__` answers a missing attribute without an activation. These +loops check results against containers whose members compare in Python, +recursive `__contains__`, error cases and the `__bool__ = None` block. +""" + +import unittest + +N = 3000 + + +class Loose: + def __init__(self, v): + self.v = v + + def __eq__(self, other): + return getattr(other, "v", other) == self.v + + def __hash__(self): + return hash(self.v) + + +class Box: + def __init__(self, items): + self.items = items + + def __contains__(self, x): + return x in self.items + + +class NotBox: + def __init__(self, items): + self.items = items + + def has_not(self, x): + return x not in self.items + + +class Nested: + def __init__(self, inner): + self.inner = inner + + def __contains__(self, x): + return x in self.inner + + +def key_in(x, allowed=frozenset({1, 3})): + return x in allowed + + +class MembershipTests(unittest.TestCase): + def test_native_containers(self): + boxes = [Box([1, 2, 3]), Box((1, 2)), Box({1: 0}), Box({2, 3}), + Box(frozenset({1}))] + text = Box("abc") + for i in range(N): + r = [(2 in b, "b" in b, 1 in b) for b in boxes] + r.append(("b" in text, "z" in text)) + self.assertEqual(r, [(True, False, True), (True, False, True), + (False, False, True), (True, False, False), + (False, False, True), (True, False)]) + nb = NotBox([1, 2]) + for i in range(N): + r2 = (nb.has_not(1), nb.has_not(5)) + self.assertEqual(r2, (False, True)) + + def test_python_equality_and_nesting(self): + b = Box([Loose(1), Loose(2)]) + nested = Nested(Box([7])) + for i in range(N): + r = (1 in b, 5 in b, Loose(2) in b, 7 in nested, 8 in nested) + self.assertEqual(r, (True, False, True, True, False)) + + def test_errors(self): + b = Box(5) + for i in range(N): + try: + 1 in b + except TypeError as e: + msg = str(e) + self.assertEqual(msg, "argument of type 'int' is not a container or iterable") + s = Box("abc") + with self.assertRaises(TypeError): + for i in range(N): + 1 in s + + def test_sorted_with_membership_key(self): + for i in range(N): + r = sorted([3, 2, 1, 4], key=key_in) + self.assertEqual(r, [2, 4, 3, 1]) + + +class TruthTests(unittest.TestCase): + def test_bool_call(self): + class Empty: + def __len__(self): + return 0 + + class Both: + def __bool__(self): + return False + + def __len__(self): + return 5 + + class Plain: + pass + + for i in range(N): + r = (bool(Empty()), bool(Both()), bool(Plain()), bool([0])) + self.assertEqual(r, (False, False, True, True)) + + def test_bool_errors(self): + class Neg: + def __len__(self): + return -1 + + class Int: + def __bool__(self): + return 1 + + class Blocked: + __bool__ = None + + for cls, exc, msg in ((Neg, ValueError, "__len__() should return >= 0"), + (Int, TypeError, "__bool__ should return bool, returned int"), + (Blocked, TypeError, "'Blocked' cannot be interpreted as a boolean")): + for i in range(N // 10): + with self.assertRaises(exc) as cm: + bool(cls()) + self.assertEqual(str(cm.exception), msg) + with self.assertRaises(TypeError): + if Blocked(): + pass + + +class GetattrFallbackTests(unittest.TestCase): + def test_fallback(self): + class GA: + def __init__(self): + self.real = 1 + + def __getattr__(self, name): + return name + + class GE: + def __getattr__(self, name): + if name.startswith("x"): + return 1 + raise AttributeError(name) + + g, ge = GA(), GE() + for i in range(N): + r = (g.real, g.missing, ge.xa, getattr(ge, "nope", 5), hasattr(ge, "nope")) + self.assertEqual(r, (1, "missing", 1, 5, False)) + with self.assertRaises(AttributeError): + ge.nope + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_number_methods.py b/tests/regrtest/test_leaf_number_methods.py new file mode 100644 index 000000000..d791d4ff0 --- /dev/null +++ b/tests/regrtest/test_leaf_number_methods.py @@ -0,0 +1,46 @@ +"""Frameless callbacks call int and float methods that read their receiver +(as_integer_ratio, conjugate, is_integer, bit_count, hex); results, errors, +and the try/except functions that use them match CPython.""" + +import fractions +import statistics +import unittest + + +def exact_ratio(x): + try: + return x.as_integer_ratio() + except AttributeError: + pass + return (x, None) + + +class LeafNumberMethods(unittest.TestCase): + def test_methods(self): + xs = list(range(-5, 30)) + [2 ** 70] + for _ in range(200): + self.assertEqual(list(map(exact_ratio, [3, 0.5, -2.25, "s"])), + [(3, 1), (1, 2), (-9, 4), ("s", None)]) + self.assertEqual(max(xs, key=lambda x: x.bit_count()), 15) + self.assertEqual(list(map(lambda x: x.as_integer_ratio()[0], xs))[-1], 2 ** 70) + self.assertEqual(list(map(lambda f: f.hex(), [1.0, 0.5])), ["0x1.0000000000000p+0", "0x1.0000000000000p-1"]) + self.assertEqual(list(map(lambda f: f.is_integer(), [1.0, 1.5])), [True, False]) + self.assertEqual(list(map(lambda i: i.conjugate() + i.is_integer(), [4])), [5]) + + def test_errors(self): + for _ in range(100): + with self.assertRaises(OverflowError): + list(map(lambda f: f.as_integer_ratio(), [float("inf")])) + with self.assertRaises(ValueError): + list(map(lambda f: f.as_integer_ratio(), [float("nan")])) + + def test_statistics(self): + data = list(range(20)) + for _ in range(100): + self.assertEqual(statistics.mean(data), 9.5) + self.assertEqual(statistics.mean([1, 2.5]), 1.75) + self.assertEqual(statistics.mean([fractions.Fraction(1, 3), 1]), fractions.Fraction(2, 3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_opaque_str_methods.py b/tests/regrtest/test_leaf_opaque_str_methods.py new file mode 100644 index 000000000..20a7438df --- /dev/null +++ b/tests/regrtest/test_leaf_opaque_str_methods.py @@ -0,0 +1,48 @@ +"""Frameless callbacks call str methods registered as opaque (count, +zfill, title, rjust, partition, index, isupper, ...); results and errors +match the full calls, and other receivers still take them.""" + +import unittest + + +class S(str): + def count(self, x, *a): + return 99 + + +class LeafOpaqueStrMethods(unittest.TestCase): + def test_methods(self): + ws = ["alpha", "Beta", "gamma", "delta", "banana"] + for _ in range(200): + self.assertEqual(list(map(lambda s: s.zfill(7), ws)), + ["00alpha", "000Beta", "00gamma", "00delta", "0banana"]) + self.assertEqual(sorted(ws, key=lambda w: (w.count("a"), w)), + ["Beta", "delta", "alpha", "gamma", "banana"]) + self.assertEqual(list(map(lambda s: s.title(), ["ab cd"])), ["Ab Cd"]) + self.assertEqual(list(map(lambda s: s.rjust(4, "."), ["ab"])), ["..ab"]) + self.assertEqual(list(map(lambda s: s.partition("-"), ["a-b"])), [("a", "-", "b")]) + self.assertEqual(list(map(lambda s: s.isupper(), ["AB", "Ab"])), [True, False]) + self.assertEqual(list(map(lambda s: s.rfind("a"), ws)), [4, 3, 4, 4, 5]) + + def test_bytes_methods(self): + bs = [b"alpha", b"Beta", b"banana"] + for _ in range(200): + self.assertEqual(sorted(bs, key=lambda b: b.count(b"a")), [b"Beta", b"alpha", b"banana"]) + self.assertEqual(list(map(lambda b: b.upper().hex(), [b"ab"])), ["4142"]) + self.assertEqual(list(map(lambda b: b.partition(b"n"), [b"banana"])), [(b"ba", b"n", b"ana")]) + with self.assertRaises(ValueError): + list(map(lambda b: b.index(b"z"), [b"abc"])) + ba = bytearray(b"xy") + self.assertEqual(list(map(lambda b: b.upper(), [ba])), [bytearray(b"XY")]) + + def test_errors_and_subclasses(self): + for _ in range(100): + with self.assertRaises(ValueError): + list(map(lambda s: s.index("z"), ["abc"])) + with self.assertRaises(TypeError): + list(map(lambda s: s.zfill("x"), ["abc"])) + self.assertEqual(list(map(lambda s: s.count("a"), [S("aaa")])), [99]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_plan_global_callees.py b/tests/regrtest/test_leaf_plan_global_callees.py new file mode 100644 index 000000000..7a3834143 --- /dev/null +++ b/tests/regrtest/test_leaf_plan_global_callees.py @@ -0,0 +1,282 @@ +"""Small functions that call other small functions, run as callbacks. + +A function that only computes from its arguments is evaluated without a +frame when a builtin calls it (`map`, `sorted`'s key, `filter`), and once +warm its evaluation is compiled. The compiled form reads a global in line +for any function over the same namespaces (a lambda is a new function +each time its expression runs), and compiles a helper it calls in line +behind a check that the name still holds that helper. These tests pin +what must keep working around those shortcuts: rebinding the helper, +functions sharing code over different namespaces, replaced code objects, +helpers that raise, and the comparisons of plain instances beside those +of value subclasses. +""" + +import enum +import functools +import heapq +import itertools +import types +import unittest +from collections import namedtuple + +ROUNDS = 40 +XS = [(i * 7919) % 101 for i in range(800)] +SCALE = 3 + + +def helper(v): + return v * 2 + 1 + + +def other_helper(v): + return v - 1000 + + +def looping_helper(v): + total = 0 + for k in range(3): + total += v + k + return total + + +def defaulted_helper(v, bump=5): + return v + bump + + +def two_deep(v): + return helper(v) + 1 + + +def three_deep(v): + return two_deep(v) * 2 + + +def divide(v): + return 1000 // (v - 50) + + +def twice(v): + return helper(v) - helper(v + 1) + + +def scaled(v): + return v * SCALE + + +def run(f): + return [f(x) for x in XS] + + +class GlobalCallees(unittest.TestCase): + def tearDown(self): + globals()["helper"] = HELPER + globals()["SCALE"] = 3 + + def test_fresh_lambdas_share_the_compiled_form(self): + want = [x * 2 + 1 + x for x in XS] + for _ in range(ROUNDS): + self.assertEqual(list(map(lambda v: helper(v) + v, XS)), want) + self.assertEqual(sorted(XS, key=lambda v: helper(v))[:3], sorted(XS)[:3]) + self.assertEqual(list(filter(lambda v: helper(v) % 3 == 0, XS)), [x for x in XS if (2 * x + 1) % 3 == 0]) + self.assertEqual(functools.reduce(lambda a, b: a + helper(b), XS, 0), sum(2 * x + 1 for x in XS)) + + def test_rebinding_the_helper(self): + f = lambda v: helper(v) + 1 # noqa: E731 + for _ in range(ROUNDS): + self.assertEqual(list(map(f, XS)), [2 * x + 2 for x in XS]) + g = globals() + for replacement, expect in ( + (other_helper, lambda x: x - 999), + (abs, lambda x: x + 1), + (looping_helper, lambda x: 3 * x + 4), + (defaulted_helper, lambda x: x + 6), + (lambda v: v, lambda x: x + 1), + (HELPER, lambda x: 2 * x + 2), + ): + g["helper"] = replacement + for _ in range(3): + self.assertEqual(list(map(f, XS)), [expect(x) for x in XS]) + g["helper"] = HELPER + for _ in range(ROUNDS): + self.assertEqual(list(map(f, XS)), [2 * x + 2 for x in XS]) + + def test_changing_a_global_value_between_calls(self): + g = globals() + for round_ in range(ROUNDS): + g["SCALE"] = round_ % 5 + self.assertEqual(list(map(scaled, XS)), [x * (round_ % 5) for x in XS]) + self.assertEqual(list(map(lambda v: v * SCALE + 1, XS)), [x * (round_ % 5) + 1 for x in XS]) + g["unrelated_%d" % round_] = round_ + for round_ in range(ROUNDS): + del g["unrelated_%d" % round_] + + def test_one_code_object_over_two_namespaces(self): + source = "def helper(v):\n return v + OFFSET\ndef use(v):\n return helper(v) * 2\n" + code = compile(source, "", "exec") + first, second = {"OFFSET": 1}, {"OFFSET": 100} + exec(code, first) + exec(code, second) + self.assertIs(first["use"].__code__, second["use"].__code__) + for _ in range(ROUNDS): + self.assertEqual(list(map(first["use"], XS)), [(x + 1) * 2 for x in XS]) + self.assertEqual(list(map(second["use"], XS)), [(x + 100) * 2 for x in XS]) + moved = types.FunctionType(first["use"].__code__, {"helper": lambda v: -v}) + for _ in range(3): + self.assertEqual(list(map(moved, XS)), [-x * 2 for x in XS]) + self.assertEqual(list(map(first["use"], XS)), [(x + 1) * 2 for x in XS]) + second["OFFSET"] = 7 + self.assertEqual(list(map(second["use"], XS)), [(x + 7) * 2 for x in XS]) + + def test_own_builtins(self): + namespace = {"__builtins__": {"abs": lambda v: v + 0.5}} + exec("def use(v):\n return abs(v - 50)\n", namespace) + plain = {} + exec("def use(v):\n return abs(v - 50)\n", plain) + for _ in range(ROUNDS): + self.assertEqual(list(map(plain["use"], XS)), [abs(x - 50) for x in XS]) + self.assertEqual(list(map(namespace["use"], XS)), [x - 50 + 0.5 for x in XS]) + + def test_deeper_and_repeated_calls(self): + for _ in range(ROUNDS): + self.assertEqual(run(three_deep), [(2 * x + 2) * 2 for x in XS]) + self.assertEqual(list(map(twice, XS)), [-2 for _ in XS]) + self.assertEqual(list(map(lambda v: two_deep(v) - helper(v), XS)), [1 for _ in XS]) + + def test_replacing_a_helpers_code(self): + def local_helper(v): + return v + 1 + + def replacement(v): + return v * 10 + + namespace = {"local_helper": local_helper} + exec("def use(v):\n return local_helper(v) + 2\n", namespace) + use = namespace["use"] + for _ in range(ROUNDS): + self.assertEqual(list(map(use, XS)), [x + 3 for x in XS]) + local_helper.__code__ = replacement.__code__ + for _ in range(3): + self.assertEqual(list(map(use, XS)), [x * 10 + 2 for x in XS]) + + def test_a_helper_that_raises(self): + f = lambda v: divide(v) + 1 # noqa: E731 + safe = [x for x in XS if x != 50] + for _ in range(ROUNDS): + self.assertEqual(list(map(f, safe)), [1000 // (x - 50) + 1 for x in safe]) + frames = [] + try: + list(map(f, XS)) + except ZeroDivisionError as exc: + tb = exc.__traceback__ + while tb is not None: + frames.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + self.assertEqual(frames[-2:], ["", "divide"]) + + def test_other_callers(self): + Item = namedtuple("Item", "x") + items = [Item(x) for x in XS] + for _ in range(ROUNDS // 4): + self.assertEqual(max(items, key=lambda o: helper(o.x)).x, max(XS)) + self.assertEqual(min(XS, key=two_deep), min(XS)) + self.assertEqual( + list(itertools.accumulate(XS[:50], lambda a, b: helper(a) % 97 + b))[-1], + functools.reduce(lambda a, b: (2 * a + 1) % 97 + b, XS[:50]), + ) + self.assertEqual( + [k for k, _ in itertools.groupby(sorted(XS), key=lambda v: helper(v) // 50)], + sorted({(2 * x + 1) // 50 for x in XS}), + ) + self.assertEqual(any(helper(v) > 500 for v in XS), False) + self.assertEqual(sum(helper(v) for v in XS), sum(2 * x + 1 for x in XS)) + + +HELPER = helper + + +class Plain: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x = x + self.y = y + + def __lt__(self, other): + return self.x < other.x + + def __eq__(self, other): + return self.x == other.x and self.y == other.y + + def __hash__(self): + return hash((self.x, self.y)) + + +class Shy: + def __init__(self, x): + self.x = x + + def __lt__(self, other): + if not isinstance(other, Shy): + return NotImplemented + return self.x < other.x + + def __gt__(self, other): + if not isinstance(other, Shy): + return NotImplemented + return self.x > other.x + + +class Level(enum.IntEnum): + LOW = 1 + MID = 5 + HIGH = 9 + + +Pair = namedtuple("Pair", "a b") + + +class Comparisons(unittest.TestCase): + def test_plain_instances_in_native_containers(self): + items = [Plain((i * 7919) % 101, i) for i in range(60)] + for _ in range(60): + heap = [] + for item in items: + heapq.heappush(heap, item) + drained = [heapq.heappop(heap).x for _ in range(len(heap))] + self.assertEqual(drained, sorted(i.x for i in items)) + self.assertEqual(items.index(items[40]), 40) + self.assertEqual(items.count(items[5]), 1) + self.assertIn(Plain(items[7].x, 7), items) + self.assertEqual(max(items).x, max(i.x for i in items)) + self.assertEqual([i.x for i in sorted(items)], sorted(i.x for i in items)) + + def test_value_subclasses_beside_plain_instances(self): + pairs = [Pair((i * 31) % 17, i) for i in range(40)] + levels = [Level.MID, Level.LOW, Level.HIGH] * 10 + for _ in range(60): + self.assertEqual(sorted(pairs), sorted(tuple(p) for p in pairs)) + self.assertTrue(pairs[3] < (99, 0) and (0, -1) < pairs[3]) + self.assertEqual(max(levels), 9) + self.assertEqual(sorted(levels)[:10], [Level.LOW] * 10) + self.assertTrue(Level.LOW < 3 < Level.MID) + self.assertEqual(min(pairs + [(0, -5)]), (0, -5)) + self.assertIn((pairs[4].a, 4), pairs) + self.assertEqual(levels.index(Level.HIGH), 2) + + def test_mixed_operands_keep_the_protocol(self): + shy = [Shy(3), Shy(1), Shy(2)] + for _ in range(200): + self.assertEqual([s.x for s in sorted(shy)], [1, 2, 3]) + with self.assertRaises(TypeError): + sorted([Shy(1), 2]) + with self.assertRaises(TypeError): + Shy(1) < Level.LOW + with self.assertRaises(TypeError): + Pair(1, 2) < Shy(1) + self.assertNotEqual(Shy(1), Pair(1, 2)) + self.assertNotEqual(Level.LOW, Shy(1)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_pure_builtins_concat.py b/tests/regrtest/test_leaf_pure_builtins_concat.py new file mode 100644 index 000000000..e6cedb734 --- /dev/null +++ b/tests/regrtest/test_leaf_pure_builtins_concat.py @@ -0,0 +1,41 @@ +"""Frameless callbacks call round, pow, repr, hex, oct and bin on native +numbers, and add strings; results and errors match the full calls.""" + +import unittest + + +class LeafPureBuiltinsConcat(unittest.TestCase): + def test_numeric_builtins(self): + xs = [i * 0.37 for i in range(40)] + [2.5, 3.5, -0.5] + ints = list(range(-5, 40)) + for _ in range(200): + self.assertEqual(list(map(lambda x: round(x, 1), xs[:5])), [0.0, 0.4, 0.7, 1.1, 1.5]) + self.assertEqual(sorted(xs, key=lambda x: round(x, 1))[:2], [-0.5, 0.0]) + self.assertEqual(list(map(lambda x: round(x), [2.5, 3.5, -0.5])), [2, 4, 0]) + self.assertEqual(min(ints, key=lambda x: pow(x - 25, 2)), 25) + self.assertEqual(list(map(lambda x: pow(x, -1), [2, 4])), [0.5, 0.25]) + self.assertEqual(list(map(lambda x: hex(x), [255, -1, 0])), ["0xff", "-0x1", "0x0"]) + self.assertEqual(list(map(lambda x: oct(x) + bin(x), [8])), ["0o100b1000"]) + self.assertEqual(list(map(lambda x: repr(x), [1, 1.5, "a'b", None, True])), + ["1", "1.5", '"a\'b"', "None", "True"]) + + def test_concat(self): + words = ["b", "a", "c"] + for _ in range(200): + self.assertEqual(list(map(lambda s: s + "!", words)), ["b!", "a!", "c!"]) + self.assertEqual(sorted(words, key=lambda s: "z" + s), ["a", "b", "c"]) + self.assertEqual(list(map(lambda s: repr(len(s)) + s, words)), ["1b", "1a", "1c"]) + self.assertEqual(list(map(lambda s: s + "é" + s, ["x"])), ["xéx"]) + + def test_errors(self): + for _ in range(100): + with self.assertRaises(TypeError): + list(map(lambda s: s + 1, ["a"])) + with self.assertRaises(TypeError): + list(map(lambda x: hex(x), [1.5])) + with self.assertRaises(ZeroDivisionError): + list(map(lambda x: pow(x, -1), [0])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_reads_of_materialized_dicts.py b/tests/regrtest/test_leaf_reads_of_materialized_dicts.py new file mode 100644 index 000000000..01a6d268e --- /dev/null +++ b/tests/regrtest/test_leaf_reads_of_materialized_dicts.py @@ -0,0 +1,108 @@ +"""Frameless getters reading instances whose `__dict__` was materialized. + +`cached_property`, `obj.__dict__[...] = v`, `vars(obj).update(...)` and +unpickling leave an instance with a published dictionary. Compiled leaf +reads cache a field's position in it and check the name there on every +read; the value must follow every change to the dictionary and to the +class. +""" + +import copy +import functools +import pickle +import unittest + + +class Rec: + label = "class-label" + + def __init__(self, x): + self.x = x + self.y = x + 1 + + @functools.cached_property + def doubled(self): + return self.x * 2 + + def get_x(self): + return self.x + + def get_label(self): + return self.label + + def __hash__(self): + return hash(self.x) + + +class MaterializedReadTests(unittest.TestCase): + ROUNDS = 4000 + + def test_reads_follow_dict_writes(self): + r = Rec(1) + r.doubled + for i in range(self.ROUNDS): + r.__dict__["x"] = i + self.assertEqual(r.get_x(), i) + self.assertEqual(hash(r), hash(i)) + + def test_delete_and_reinsert(self): + r = Rec(1) + vars(r).update(z=0) + for i in range(self.ROUNDS): + self.assertEqual(r.get_x(), 1 if i % 2 == 0 else "again") + if i % 2 == 0: + del r.__dict__["x"] + r.__dict__["x"] = "again" + else: + del r.__dict__["x"] + r.__dict__["x"] = 1 + del r.__dict__["x"] + with self.assertRaises(AttributeError): + r.get_x() + + def test_instance_shadow_comes_and_goes(self): + r = Rec(1) + r.doubled + for i in range(self.ROUNDS): + self.assertEqual(r.get_label(), "class-label") + r.__dict__["label"] = i + self.assertEqual(r.get_label(), i) + del r.__dict__["label"] + Rec.label = "changed" + try: + self.assertEqual(r.get_label(), "changed") + finally: + Rec.label = "class-label" + + def test_mixed_layouts_share_sites(self): + plain = [Rec(i) for i in range(20)] + mat = [Rec(i) for i in range(20)] + for m in mat: + m.doubled + for _ in range(200): + self.assertEqual(sum(r.get_x() for r in plain), 190) + self.assertEqual(sum(r.get_x() for r in mat), 190) + self.assertEqual( + [r.get_x() for pair in zip(plain, mat) for r in pair][:4], [0, 0, 1, 1] + ) + + def test_copies_and_unpickled(self): + base = Rec(5) + items = [copy.copy(base), copy.deepcopy(base), pickle.loads(pickle.dumps(base))] + for _ in range(self.ROUNDS): + self.assertEqual([r.get_x() for r in items], [5, 5, 5]) + items[1].x = 9 + self.assertEqual([r.get_x() for r in items], [5, 9, 5]) + + def test_cached_property_value(self): + for i in range(self.ROUNDS): + r = Rec(i) + self.assertEqual(r.doubled, i * 2) + self.assertEqual(r.doubled, i * 2) + del r.doubled + r.x = 0 + self.assertEqual(r.doubled, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_same_class_test.py b/tests/regrtest/test_leaf_same_class_test.py new file mode 100644 index 000000000..1273d6074 --- /dev/null +++ b/tests/regrtest/test_leaf_same_class_test.py @@ -0,0 +1,92 @@ +"""`other.__class__ is self.__class__` in compiled `__eq__` bodies. + +A leaf body's two `__class__` reads and the `is` between them run as one +test of the instances' classes. It must agree with the reads it replaces: +a dataclass's `__eq__` against an equal, an unequal, a subclass's and a +foreign operand; a class whose `__class__` is a property; `is not`; an +instance whose `__class__` was reassigned; and non-instance operands. +""" + +import dataclasses +import unittest + + +@dataclasses.dataclass(frozen=True) +class D: + x: int + y: int + + +@dataclasses.dataclass(frozen=True) +class E(D): + pass + + +class Masked: + @property + def __class__(self): + return int + + def __init__(self, v): + self.v = v + + def __eq__(self, other): + return other.__class__ is self.__class__ + + __hash__ = object.__hash__ + + +class Pair: + def __init__(self, v): + self.v = v + + def __eq__(self, other): + if other.__class__ is not self.__class__: + return NotImplemented + return self.v == other.v + + __hash__ = object.__hash__ + + +class Other: + def __init__(self, v): + self.v = v + + +class SameClassTests(unittest.TestCase): + def test_dataclass_eq(self): + a, b, c, e = D(1, 2), D(1, 2), D(1, 3), E(1, 2) + d = {a: "a"} + for _ in range(300): + self.assertEqual(d[b], "a") + self.assertTrue(a == b) + self.assertFalse(a == c) + self.assertFalse(a == e) + self.assertFalse(a == (1, 2)) + self.assertFalse(a == 5) + self.assertNotIn(e, d) + + def test_property_class(self): + m = Masked(1) + for _ in range(300): + self.assertTrue(m == 5) + self.assertTrue(m == Masked(2)) + self.assertFalse(m == "x") + + def test_is_not_and_reassigned(self): + p, q = Pair(1), Pair(1) + for _ in range(300): + self.assertTrue(p == q) + self.assertFalse(p == Other(1)) + self.assertFalse(p == 1) + r = Pair(1) + r.__class__ = Other + for _ in range(300): + self.assertFalse(p == r) + r.__class__ = Pair + for _ in range(300): + self.assertTrue(p == r) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_seq_literal.py b/tests/regrtest/test_leaf_seq_literal.py new file mode 100644 index 000000000..0b7a9436b --- /dev/null +++ b/tests/regrtest/test_leaf_seq_literal.py @@ -0,0 +1,48 @@ +"""Frameless leaf evaluations of list literals and of tuples past three +items: their items (scalars, strings, other objects, the arguments +themselves), a fresh list each call (not shared between calls), nesting, +and the results' use as keys and sort keys, as the general call gives +them.""" + +import unittest + + +def pair_list(a, b): + return [a, b] + + +def quad(a, b, c, d): + return (a, b, c, d) + + +def wide(a, b): + return (a, b, a, b, a, b, a, b) + + +def nested(a): + return [a, [a, a], (a, a, a, a)] + + +class LeafSeqLiteral(unittest.TestCase): + def test_values(self): + out = [] + for i in range(3000): + out.append((pair_list(i, "s"), quad(1, 2.5, None, "x"), wide(i, True), nested(i))) + self.assertEqual(out[6], ([6, "s"], (1, 2.5, None, "x"), (6, True) * 4, [6, [6, 6], (6, 6, 6, 6)])) + a, b = pair_list(1, 2), pair_list(1, 2) + a.append(3) + self.assertEqual(b, [1, 2]) + obj = object() + self.assertIs(pair_list(obj, 0)[0], obj) + + def test_as_keys(self): + words = ["bb", "a", "ccc", "dd"] + for i in range(2000): + r = sorted(words, key=lambda w: (len(w), w[0], w, -len(w))) + self.assertEqual(r, ["a", "bb", "dd", "ccc"]) + d = {quad(1, 2, 3, 4): "q"} + self.assertEqual(d[quad(1, 2, 3, 4)], "q") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_slice_dict_literal.py b/tests/regrtest/test_leaf_slice_dict_literal.py new file mode 100644 index 000000000..579e2d50c --- /dev/null +++ b/tests/regrtest/test_leaf_slice_dict_literal.py @@ -0,0 +1,74 @@ +"""Frameless leaf evaluations of `seq[a:b]` with computed bounds and of +dict literals: slices of strings, lists, tuples and bytes with negative, +missing and out-of-range bounds; a non-int bound's TypeError; dict +literals of string, int, float, bool, None and tuple keys, a duplicate key +(the first key kept, the last value), values that are fresh objects, an +unhashable key's TypeError, and an instance key (its `__hash__` runs), as +the general call gives them.""" + +import unittest + + +def mid(s, a, b): + return s[a:b] + + +def head(s, n): + return s[:n] + + +def point(x, y): + return {"x": x, "y": y, 1: [x], (1, 2): None, 2.5: True} + + +def dup(v): + return {1: "a", 1.0: v, True: "c"} + + +def keyed(k, v): + return {k: v} + + +class K: + def __init__(self, n): + self.n = n + + def __hash__(self): + return self.n + + def __eq__(self, o): + return isinstance(o, K) and o.n == self.n + + +class LeafSliceDictLiteral(unittest.TestCase): + def test_slices(self): + out = [] + for i in range(3000): + out.append((mid("abcdef", 1, -1), mid([1, 2, 3, 4], -3, 99), mid((1, 2, 3), 2, 1), + mid(b"xyz", 0, i % 4), head("hello", i % 7))) + self.assertEqual(out[5], ("bcde", [2, 3, 4], (), b"x", "hello")) + self.assertEqual(out[3][4], "hel") + for i in range(500): + with self.assertRaises(TypeError): + mid("abc", "x", 2) + self.assertEqual(mid("abc", None, 2), "ab") + + def test_dict_literals(self): + out = [] + for i in range(3000): + out.append((point(i, "y"), dup(i), keyed("k", [i]))) + p = out[7][0] + self.assertEqual(p, {"x": 7, "y": "y", 1: [7], (1, 2): None, 2.5: True}) + self.assertIsNot(out[7][0][1], out[8][0][1]) + d = out[9][1] + self.assertEqual(d, {1: "c"}) + self.assertIs(type(list(d)[0]), int) + self.assertEqual(out[2][2], {"k": [2]}) + for i in range(500): + with self.assertRaises(TypeError): + keyed([1], 2) + self.assertEqual(keyed(K(i), i)[K(i)], i) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_slots_tuple_compare.py b/tests/regrtest/test_leaf_slots_tuple_compare.py new file mode 100644 index 000000000..e125d91b3 --- /dev/null +++ b/tests/regrtest/test_leaf_slots_tuple_compare.py @@ -0,0 +1,91 @@ +"""Frameless evaluations read `__slots__` members and compare tuples of +scalars and strings, as rich comparisons from sort and min call them; +results and every declined case match the full call.""" + +import unittest + + +class S: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x, self.y = x, y + + def __lt__(self, o): + return self.x < o.x or (self.x == o.x and self.y < o.y) + + def __repr__(self): + return f"S({self.x}, {self.y})" + + +class T: + def __init__(self, *k): + self.k = k + + def __lt__(self, o): + return self.k < o.k + + def __eq__(self, o): + return self.k == o.k + + def __le__(self, o): + return self.k <= o.k + + +class Partial: + __slots__ = ("x", "y") + + def __init__(self, x): + self.x = x + + def __lt__(self, o): + return self.y < o.y + + +class LeafSlotsTupleCompare(unittest.TestCase): + def test_slot_sort(self): + xs = [S(i * 7 % 13, i) for i in range(40)] + want = sorted(xs, key=lambda s: (s.x, s.y)) + for _ in range(100): + got = sorted(xs) + self.assertEqual([(s.x, s.y) for s in got], [(s.x, s.y) for s in want]) + self.assertEqual(min(xs).x, 0) + + def test_tuple_compare(self): + cases = [ + ((1, 2), (1, 3)), ((1, 2), (1, 2)), ((1,), (1, 0)), ((), ()), + (("a", 1), ("a", 0)), ((1.5, "b"), (1.5, "a")), ((True, 1), (1, 0)), + ((None, 1), (None, 2)), ((2, "x"), (1, "y")), + ] + for _ in range(100): + for a, b in cases: + ta, tb = T(*a), T(*b) + self.assertEqual(ta < tb, a < b) + self.assertEqual(ta == tb, a == b) + self.assertEqual(ta <= tb, a <= b) + + def test_declined_cases(self): + nan = float("nan") + for _ in range(100): + self.assertEqual(T(nan, 1) < T(nan, 2), (nan, 1) < (nan, 2)) + self.assertEqual(T(nan) == T(nan), (nan,) == (nan,)) + n = (nan,) + self.assertTrue(T(*n) == T(*n)) + self.assertEqual(T((1, 2), 3) < T((1, 3), 0), True) + with self.assertRaises(TypeError): + T(1, "a") < T(1, 2) + with self.assertRaises(TypeError): + T(None, 1) < T(None, 2) if False else (T(None) < T(1)) + self.assertEqual(T([1]) < T([2]), True) + + def test_unset_slot_raises(self): + a, b = Partial(1), Partial(2) + for _ in range(100): + with self.assertRaises(AttributeError): + a < b + a.y, b.y = 5, 3 + self.assertFalse(a < b) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_spread_methods_and_defaults.py b/tests/regrtest/test_leaf_spread_methods_and_defaults.py new file mode 100644 index 000000000..8a2f754ef --- /dev/null +++ b/tests/regrtest/test_leaf_spread_methods_and_defaults.py @@ -0,0 +1,102 @@ +"""`f(*args)` and `obj.m(*args)` of small functions, with defaults filled in. + +The frameless `CALL_FUNCTION_EX` path binds a bound method's receiver +first and fills trailing parameters from the function's positional +defaults; a rebound `__defaults__`, a descriptor-dispatched method or a +wrong arity must behave as the full call does. +""" + +import unittest + + +class Box: + def __init__(self, v): + self.v = v + + def get(self, a, b=10): + return (self.v, a, b) + + def pair(self, a, b): + return (self.v, a, b) + + def bump(self, k=1): + self.v += k + return self.v + + +def add(a, b=2, c=3): + return a + b * 10 + c * 100 + + +class LeafSpreadTests(unittest.TestCase): + ROUNDS = 5000 + + def test_method_spread(self): + b = Box(1) + one, two, none = (5,), (5, 6), () + for _ in range(self.ROUNDS): + self.assertEqual(b.get(*one), (1, 5, 10)) + self.assertEqual(b.get(*two), (1, 5, 6)) + self.assertEqual(b.pair(*two), (1, 5, 6)) + self.assertEqual(Box(2).get(*one), (2, 5, 10)) + b.v = 0 + for _ in range(100): + b.bump(*none) + self.assertEqual(b.v, 100) + b.bump(*(5,)) + self.assertEqual(b.v, 105) + + def test_function_defaults(self): + for _ in range(self.ROUNDS): + self.assertEqual(add(*(1,)), 321) + self.assertEqual(add(*(1, 0)), 301) + self.assertEqual(add(*(1, 0, 0)), 1) + self.assertEqual(add(*(1,), **{}), 321) + + def test_arity_errors(self): + b = Box(1) + for _ in range(3): + with self.assertRaises(TypeError): + b.pair(*(1,)) + with self.assertRaises(TypeError): + b.get(*(1, 2, 3)) + with self.assertRaises(TypeError): + add(*()) + + def test_defaults_rebound(self): + def f(a, b=1): + return (a, b) + + for _ in range(self.ROUNDS): + self.assertEqual(f(*(0,)), (0, 1)) + f.__defaults__ = (9,) + self.assertEqual(f(*(0,)), (0, 9)) + f.__defaults__ = None + with self.assertRaises(TypeError): + f(*(0,)) + + def test_receiver_kept_alive(self): + def make(): + return Box(7).get + + for _ in range(self.ROUNDS): + self.assertEqual(make()(*(1,)), (7, 1, 10)) + + def test_static_and_class_methods(self): + class C: + @staticmethod + def s(a, b=2): + return (a, b) + + @classmethod + def c(cls, a, b=3): + return (cls.__name__, a, b) + + for _ in range(self.ROUNDS): + self.assertEqual(C.s(*(1,)), (1, 2)) + self.assertEqual(C().c(*(1,)), ("C", 1, 3)) + self.assertEqual(C.c(*(1, 4)), ("C", 1, 4)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_store_item.py b/tests/regrtest/test_leaf_store_item.py new file mode 100644 index 000000000..f699e71ba --- /dev/null +++ b/tests/regrtest/test_leaf_store_item.py @@ -0,0 +1,128 @@ +"""Effect leaves that store into a dict or list (`self._d[k] = v` in a +`__setitem__`, a memo's `self.cache[k] = v`): the stores land with every +kind of key and value; a list's negative index; an index out of range +(IndexError) and an unhashable key (TypeError) raise as the general call +does; a key with a Python `__hash__`, a store followed by an attribute +store, a store before something that can still fail, and a displaced +value with a finalizer all store exactly once; and calls from compiled +loops, `map()` and `sum()`-style native callers agree.""" + +import unittest + + +class D: + def __init__(self): + self._d = {} + + def __setitem__(self, k, v): + self._d[k] = v + + +class L: + def __init__(self, n): + self.xs = [0] * n + + def __setitem__(self, i, v): + self.xs[i] = v + + +class Memo: + def __init__(self): + self.cache = {} + self.misses = 0 + + def put(self, k, v): + self.cache[k] = v + return v + + def put_count(self, k, v): + self.cache[k] = v + self.misses = self.misses + 1 + + def put_then_index(self, k, v, seq): + self.cache[k] = v + return seq[k] + + +class Chain: + """`xml.dom.pulldom`'s event list: `emit` reads an item out of the + node it then unlinks, the store displacing that node's last reference.""" + + def __init__(self): + self.first = [None, None] + self.last = self.first + + def push(self, x): + self.last[1] = [x, None] + self.last = self.last[1] + + def emit(self): + rc = self.first[1][0] + self.first[1] = self.first[1][1] + return rc + + +class K: + def __init__(self, n): + self.n = n + + def __hash__(self): + return self.n + + def __eq__(self, o): + return isinstance(o, K) and o.n == self.n + + +class Fin: + dels = 0 + + def __del__(self): + Fin.dels += 1 + + +class LeafStoreItem(unittest.TestCase): + def test_dict_and_list(self): + d, l = D(), L(4) + for i in range(3000): + d[i % 7] = i + d["s%d" % (i % 3)] = [i] + d[(i % 2, "t")] = None + l[i % 4] = i + l[-1] = "last" + self.assertEqual(d._d[6], 2999 - (2999 - 6) % 7) + self.assertEqual(d._d["s2"], [2999]) + self.assertEqual(l.xs, [2996, 2997, 2998, "last"]) + self.assertEqual(list(map(Memo().put, range(5), "abcde")), list("abcde")) + + def test_read_from_displaced(self): + c, got = Chain(), [] + for i in range(3000): + c.push(("ev", [i], "x%d" % i)) + for i in range(3000): + got.append(c.emit()) + self.assertEqual(got[4], ("ev", [4], "x4")) + self.assertEqual(got[-1], ("ev", [2999], "x2999")) + + def test_errors_and_declines(self): + l, d, m = L(2), D(), Memo() + for i in range(500): + with self.assertRaises(IndexError): + l[5] = 1 + with self.assertRaises(TypeError): + d[[1]] = 1 + d[K(i % 3)] = i + m.put_count(i % 5, i) + with self.assertRaises(IndexError): + m.put_then_index(i, i, []) + self.assertEqual(len(d._d), 3) + self.assertEqual(m.misses, 500) + self.assertEqual(m.cache[499], 499) + f = D() + for i in range(300): + f[0] = Fin() + f[0] = 0 + self.assertEqual(Fin.dels, 300) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_str_percent.py b/tests/regrtest/test_leaf_str_percent.py new file mode 100644 index 000000000..bf0894685 --- /dev/null +++ b/tests/regrtest/test_leaf_str_percent.py @@ -0,0 +1,92 @@ +"""A `__str__` or `__repr__` that formats its fields with `%` (or repeats a +string with `*`) evaluates frameless: the text of every conversion, a +tuple of arguments, a field that is itself an instance (its `__str__` +runs), a bad conversion's TypeError, a missing argument, and a field +changed later match the general call, through `str()`, `"%s" % obj`, +`"{}".format(obj)`, `f"{obj}"` and `map(str, ...)`.""" + +import unittest + + +class Q: + def __init__(self, n, name="q", x=1.5): + self.n = n + self.name = name + self.x = x + + def __str__(self): + return "Q%d" % self.n + + def __repr__(self): + return "Q(%r, %s, %5.2f, %x)" % (self.name, self.n, self.x, self.n) + + +class Bar: + def __init__(self, k): + self.k = k + + def __str__(self): + return "-" * self.k + + +class Outer: + def __init__(self, inner): + self.inner = inner + + def __str__(self): + return "<%s>" % self.inner + + +class Bad: + def __init__(self, v): + self.v = v + + def __str__(self): + return "%d" % self.v + + +class Short: + def __str__(self): + return "%s %s" % ("a",) + + +class LeafStrPercent(unittest.TestCase): + def test_text(self): + q = Q(26, "zz", 2.25) + out = [] + for i in range(3000): + out.append((str(q), repr(q), "%s" % q, "{}".format(q), f"{q}", str(Bar(i % 4)))) + self.assertEqual(out[5], ("Q26", "Q('zz', 26, 2.25, 1a)", "Q26", "Q26", "Q26", "-")) + self.assertEqual(out[7][5], "---") + self.assertEqual(", ".join(map(str, [Q(1), Q(2)])), "Q1, Q2") + + def test_nested_and_changed(self): + o = Outer(Q(3)) + out = [] + for i in range(2000): + out.append(str(o)) + o.inner = Outer(Q(4)) + for i in range(2000): + out.append(str(o)) + self.assertEqual((out[0], out[-1]), ("", "<>")) + q = Q(1) + seen = [] + for i in range(2000): + q.n = i + seen.append(str(q)) + self.assertEqual(seen[-1], "Q1999") + + def test_errors(self): + for i in range(1000): + self.assertEqual(str(Bad(i)), str(i)) + for i in range(500): + with self.assertRaises(TypeError) as cm: + str(Bad("x")) + with self.assertRaises(TypeError) as sm: + str(Short()) + self.assertEqual(str(cm.exception), "%d format: a real number is required, not str") + self.assertEqual(str(sm.exception), "not enough arguments for format string") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_str_repr_len_in_place.py b/tests/regrtest/test_leaf_str_repr_len_in_place.py new file mode 100644 index 000000000..d6e0362b5 --- /dev/null +++ b/tests/regrtest/test_leaf_str_repr_len_in_place.py @@ -0,0 +1,104 @@ +"""Compiled `str(obj)`, `repr(obj)` and `len(obj)` of an instance whose +class's Python `__str__`, `__repr__` or `__len__` is a warm pure leaf +evaluate it in place; the results, attribute reads in the body, a +repr-only class's `str()`, temporaries as arguments, results of the +wrong type (the protocols' errors, worded as CPython words them), a +negative or `bool` length, a body that raises, and a method replaced +later match the general call.""" + +import unittest + + +class P: + def __init__(self, name, n): + self.name = name + self.n = n + + def __str__(self): + return self.name + + def __repr__(self): + return "P(" + self.name + ")" + + def __len__(self): + return self.n + + +class OnlyRepr: + def __repr__(self): + return "only" + + +class BadStr: + def __str__(self): + return 3 + + def __repr__(self): + return None + + def __len__(self): + return "x" + + +class Neg: + def __len__(self): + return -1 + + +class Flag: + def __len__(self): + return True + + +class Raises: + def __str__(self): + return self.missing + + +class LeafStrReprLenInPlace(unittest.TestCase): + def test_results(self): + p = P("a", 4) + o = OnlyRepr() + out = [] + for i in range(3000): + out.append((str(p), repr(p), len(p), str(o), len(Flag()))) + self.assertEqual(set(out), {("a", "P(a)", 4, "only", 1)}) + temps = [str(P("t%d" % i, i)) for i in range(2000)] + self.assertEqual(temps[7], "t7") + lens = [len(P("x", i)) for i in range(2000)] + self.assertEqual(lens[9], 9) + + def test_errors(self): + b = BadStr() + for i in range(1000): + with self.assertRaises(TypeError) as cm: + str(b) + self.assertEqual(str(cm.exception), "__str__ returned non-string (type int)") + with self.assertRaises(TypeError) as cm: + repr(b) + self.assertEqual(str(cm.exception), "__repr__ returned non-string (type NoneType)") + with self.assertRaises(TypeError): + len(b) + with self.assertRaises(ValueError) as cm: + len(Neg()) + self.assertEqual(str(cm.exception), "__len__() should return >= 0") + with self.assertRaises(AttributeError): + str(Raises()) + + def test_replaced(self): + class K: + def __str__(self): + return "one" + + k = K() + out = [] + for i in range(2000): + out.append(str(k)) + K.__str__ = lambda self: "two" + for i in range(2000): + out.append(str(k)) + self.assertEqual((out.count("one"), out.count("two")), (2000, 2000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_subscript_owned_result.py b/tests/regrtest/test_leaf_subscript_owned_result.py new file mode 100644 index 000000000..3be833683 --- /dev/null +++ b/tests/regrtest/test_leaf_subscript_owned_result.py @@ -0,0 +1,55 @@ +"""A frameless evaluation that subscripts a container it built itself +(`return s.split(".")[0]`) returns an item that outlives the container: +the result stays correct once the call runs frameless, through functions, +properties, callbacks, and chained subscripts.""" + +import gc +import unittest + + +def head(s): + return s.split(".")[0] + + +def last_pair(s): + return s.rpartition(".")[2] + + +def nested(s): + return (s.split("."), 1)[0][1] + + +def dget(k): + return {"a": [k], "b": 2}["a"][0] + + +class P: + def __init__(self, s): + self.s = s + + @property + def head(self): + return self.s.split(".")[0] + + +class OwnedSubscript(unittest.TestCase): + def test_functions(self): + for i in range(3000): + s = "x%d.y.z" % (i % 50) + self.assertEqual(head(s), "x%d" % (i % 50)) + self.assertEqual(last_pair(s), "z") + self.assertEqual(nested(s), "y") + self.assertEqual(dget(i), i) + if i % 500 == 0: + gc.collect() + + def test_property_and_callbacks(self): + ps = [P("a%d.b" % i) for i in range(50)] + for _ in range(100): + self.assertEqual([p.head for p in ps], ["a%d" % i for i in range(50)]) + self.assertEqual(list(map(head, [p.s for p in ps]))[-1], "a49") + self.assertEqual(sorted(ps, key=lambda p: p.s.split(".")[0])[0].s, "a0.b") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_tuple_compare_fused.py b/tests/regrtest/test_leaf_tuple_compare_fused.py new file mode 100644 index 000000000..48311479f --- /dev/null +++ b/tests/regrtest/test_leaf_tuple_compare_fused.py @@ -0,0 +1,265 @@ +"""Comparison methods that compare two tuples they build on the spot. + +`return (self.x, self.y) < (o.x, o.y)` (and the one- and three-item +forms, as `dataclass(order=True)` writes them, and the same with two +list literals) compares the items without building either sequence once +the method is hot. Every operator, +mixed numbers, strings, items that can't be ordered, expressions and +walrus stores inside the tuples, and the sorts and searches that call +these methods must all keep CPython's results. +""" + +import dataclasses +import unittest + + +class P: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x = x + self.y = y + + def __lt__(self, o): + return (self.x, self.y) < (o.x, o.y) + + def __le__(self, o): + return (self.x, self.y) <= (o.x, o.y) + + def __eq__(self, o): + return (self.x, self.y) == (o.x, o.y) + + def __ne__(self, o): + return (self.x, self.y) != (o.x, o.y) + + def __gt__(self, o): + return (self.x, self.y) > (o.x, o.y) + + def __ge__(self, o): + return (self.x, self.y) >= (o.x, o.y) + + __hash__ = None + + +class Neg: + def __init__(self, x, y): + self.x = x + self.y = y + + def __lt__(self, o): + return (self.x, -self.y) < (o.x, -o.y) + + +class Locals: + def __init__(self, x, y): + self.x = x + self.y = y + + def __lt__(self, o): + x, y = self.x, self.y + return (x, y) < (o.x, o.y) + + +class Walrus: + def __init__(self, x, y): + self.x = x + self.y = y + + def __lt__(self, o): + return (self.x, (z := o.y)) < (o.x, z - self.y) + + +class One: + def __init__(self, x): + self.x = x + + def __lt__(self, o): + return (self.x,) < (o.x,) + + +class Three: + def __init__(self, x, y, z): + self.x = x + self.y = y + self.z = z + + def __lt__(self, o): + return (self.x, self.y, self.z) < (o.x, o.y, o.z) + + def __eq__(self, o): + return (self.x, self.y, self.z) == (o.x, o.y, o.z) + + __hash__ = None + + +class Lists: + def __init__(self, p, q): + self.p = p + self.q = q + + def __lt__(self, o): + return [self.p, self.q] < [o.p, o.q] + + def __le__(self, o): + return [self.p] <= [o.p] + + def __eq__(self, o): + return [self.p, self.q, 0] == [o.p, o.q, 0] + + __hash__ = None + + +class Mixed: + def __init__(self, p, q): + self.p = p + self.q = q + + def __lt__(self, o): + return [self.p, self.q] < (o.p, o.q) + + +@dataclasses.dataclass(order=True) +class DC3: + x: int + y: object + z: float + + +OPS = ("__lt__", "__le__", "__eq__", "__ne__", "__gt__", "__ge__") +VALUES = [1, 2, 2.0, 1.5, -1, 2**70, True, False, None, "a", "b", "ab"] + + +def table(): + out = [] + for a in VALUES: + for b in VALUES[:5]: + for c in VALUES: + for d in VALUES[:5]: + p, q = P(a, b), P(c, d) + for op in OPS: + try: + out.append(getattr(p, op)(q)) + except TypeError: + out.append("TypeError") + return out + + +def expected(): + out = [] + for a in VALUES: + for b in VALUES[:5]: + for c in VALUES: + for d in VALUES[:5]: + s, t = (a, b), (c, d) + for op in ( + lambda: s < t, + lambda: s <= t, + lambda: s == t, + lambda: s != t, + lambda: s > t, + lambda: s >= t, + ): + try: + out.append(op()) + except TypeError: + out.append("TypeError") + return out + + +class PairCompareTests(unittest.TestCase): + def test_operator_table(self): + want = expected() + for _ in range(3): + self.assertEqual(table(), want) + + def test_sorts(self): + data = [(i * 7 % 11, i * 5 % 3) for i in range(300)] + for cls in (P, Neg, Locals): + objs = [cls(x, y) for x, y in data] + for _ in range(20): + got = [(o.x, o.y) for o in sorted(objs)] + key = (lambda p: (p[0], -p[1])) if cls is Neg else None + self.assertEqual(got, sorted(data, key=key)) + m = min(objs) + self.assertEqual((m.x, m.y), min(data, key=key)) + + def test_one_and_three_items(self): + data = [(i * 7 % 11, i * 5 % 3, i % 2 * 0.5) for i in range(300)] + threes = [Three(*t) for t in data] + ones = [One(t[0]) for t in data] + dcs = [DC3(*t) for t in data] + for _ in range(20): + got = [(o.x, o.y, o.z) for o in sorted(threes)] + got1 = [o.x for o in sorted(ones)] + got2 = [dataclasses.astuple(o) for o in sorted(dcs)] + self.assertEqual(got, sorted(data)) + self.assertEqual(got1, sorted(t[0] for t in data)) + self.assertEqual(got2, sorted(data)) + a, b = Three(1, 2, 3), Three(1, 2, 3.0) + c, d = DC3(1, "a", 2.0), DC3(1, 2, 2.0) + for _ in range(500): + self.assertTrue(a == b) + self.assertFalse(a < b) + self.assertTrue(Three(1, 2, 3) < Three(1, 2, 4)) + self.assertFalse(c == d) + self.assertTrue(DC3(1, "a", 2.0) <= c) + with self.assertRaises(TypeError): + c < d + + def test_list_literals(self): + data = [(i * 7 % 11, i * 5 % 3) for i in range(300)] + objs = [Lists(*t) for t in data] + for _ in range(20): + got = [(o.p, o.q) for o in sorted(objs)] + self.assertEqual(got, sorted(data)) + a, b = Lists(1, "x"), Lists(1, 2) + for _ in range(500): + self.assertTrue(Lists(1, 2) <= Lists(1, 0)) + self.assertTrue(Lists(1, 2.0) == Lists(1, 2)) + self.assertFalse(a == b) + with self.assertRaises(TypeError): + a < b + with self.assertRaises(TypeError): + Mixed(1, 2) < Mixed(1, 3) + + def test_walrus_store_between(self): + objs = [Walrus(i % 4, i % 3) for i in range(200)] + for _ in range(50): + got = [objs[i] < objs[i + 1] for i in range(199)] + want = [ + (a.x, b.y) < (b.x, b.y - a.y) for a, b in zip(objs, objs[1:]) + ] + self.assertEqual(got, want) + + def test_strings_and_same_objects(self): + s = "x" * 3 + a, b = P(s, 1), P("xxx", 2) + for _ in range(500): + self.assertTrue(a < b) + self.assertFalse(a == b) + self.assertTrue(a == P(s, 1)) + + def test_unorderable_items(self): + a, b = P(1, "a"), P(1, 2) + for _ in range(500): + self.assertFalse(a == b) + with self.assertRaises(TypeError): + a < b + o = object() + c, d = P(o, 1), P(o, 2) + e = P(object(), 1) + for _ in range(500): + self.assertTrue(c < d) + with self.assertRaises(TypeError): + c < e + + def test_nested_instances(self): + inner = [P(i % 3, i % 2) for i in range(50)] + outer = [P(inner[i], i) for i in range(50)] + for _ in range(20): + got = [(o.x.x, o.x.y, o.y) for o in sorted(outer)] + self.assertEqual(got, sorted((i % 3, i % 2, i) for i in range(50))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_leaf_user_format.py b/tests/regrtest/test_leaf_user_format.py new file mode 100644 index 000000000..32b07e022 --- /dev/null +++ b/tests/regrtest/test_leaf_user_format.py @@ -0,0 +1,67 @@ +"""A class's pure `__format__` runs frameless for f-strings and format(); +results, errors, and every case the frameless call declines match the full +call.""" + +import unittest + + +class P: + def __init__(self, v): + self.v = v + + def __format__(self, spec): + return format(self.v, spec) + + +class Bad: + def __format__(self, spec): + return 5 + + +class Raises: + def __format__(self, spec): + if spec == "boom": + raise ValueError(spec) + return "ok:" + spec + + +class Sub(P): + pass + + +class LeafUserFormat(unittest.TestCase): + def test_values(self): + p, q = P(5), P(2.5) + for _ in range(300): + self.assertEqual(f"{p:>4}", " 5") + self.assertEqual(f"{p}", "5") + self.assertEqual(format(p, "03d"), "005") + self.assertEqual(f"{q:.2f}", "2.50") + self.assertEqual("{:x}".format(P(255)), "ff") + self.assertEqual(f"{Sub('ab'):>3}", " ab") + + def test_errors(self): + for _ in range(200): + with self.assertRaises(TypeError): + f"{Bad()}" + with self.assertRaises(ValueError): + format(P(5), "q") + with self.assertRaises(ValueError): + f"{Raises():boom}" + self.assertEqual(f"{Raises():x}", "ok:x") + + def test_patched(self): + class T: + def __format__(self, spec): + return "a" + t = T() + for _ in range(300): + self.assertEqual(f"{t}", "a") + T.__format__ = lambda self, spec: "b" + self.assertEqual(f"{t}", "b") + del T.__format__ + self.assertEqual(format(t, ""), str(t)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_len_and_getitem_dunder_sites.py b/tests/regrtest/test_len_and_getitem_dunder_sites.py new file mode 100644 index 000000000..c2e4e1b20 --- /dev/null +++ b/tests/regrtest/test_len_and_getitem_dunder_sites.py @@ -0,0 +1,63 @@ +"""`len(obj)` and `obj[i]` through a Python `__len__` / `__getitem__`. + +Compiled `len()` sites evaluate a frameless `__len__` in place, and +compiled subscripts enter a warm `__getitem__`'s compiled plan; results, +errors and the checks on `__len__`'s result behave as before. +""" + +import unittest + +N = 30000 + + +class Seq: + def __init__(self, d): + self.d = d + + def __len__(self): + return len(self.d) + + def __getitem__(self, i): + return self.d[i] + + +class Neg: + def __len__(self): + return -1 + + +class Bad: + def __len__(self): + raise KeyError("len") + + +class Big: + def __len__(self): + return 2 ** 70 + + +class DunderSiteTests(unittest.TestCase): + def test_values(self): + s = Seq([1, 2, 3]) + total = 0 + for i in range(N): + total += len(s) + s[i % 3] + self.assertEqual(total, N * 3 + (N // 3) * 6) + s.d = [9] + self.assertEqual((len(s), s[0], s[-1]), (1, 9, 9)) + + def test_errors(self): + s = Seq([1]) + for _ in range(N // 100): + with self.assertRaises(IndexError): + s[5] + with self.assertRaises(ValueError): + len(Neg()) + with self.assertRaises(KeyError): + len(Bad()) + with self.assertRaises(OverflowError): + len(Big()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_len_dunder_direct.py b/tests/regrtest/test_len_dunder_direct.py new file mode 100644 index 000000000..1e2995650 --- /dev/null +++ b/tests/regrtest/test_len_dunder_direct.py @@ -0,0 +1,125 @@ +"""Compiled `len(obj)` calls a class's Python `__len__` directly; the +lengths, the errors for a bad result, raises (caught in the frame or +past it), `len` shadowed or replaced, and a method replaced later match +the general call.""" + +import builtins +import unittest + + +class Sized: + def __init__(self, n): + self.n = n + self.calls = 0 + + def __len__(self): + self.calls += 1 + return self.n + + +class Bad: + def __init__(self, r): + self.r = r + + def __len__(self): + self.seen = True + return self.r + + +class Raiser: + def __len__(self): + raise KeyError("no length") + + +class IntSub(int): + pass + + +class LenDunderDirect(unittest.TestCase): + def test_lengths(self): + s = Sized(7) + total = 0 + for i in range(3000): + total += len(s) + self.assertEqual(total, 21000) + self.assertEqual(s.calls, 3000) + + def test_result_kinds(self): + for i in range(500): + self.assertEqual(len(Bad(True)), 1) + self.assertEqual(len(Bad(IntSub(5))), 5) + self.assertIs(type(len(Bad(IntSub(5)))), int) + with self.assertRaises(ValueError) as cm: + len(Bad(-1)) + self.assertEqual(str(cm.exception), "__len__() should return >= 0") + with self.assertRaises(TypeError) as cm: + len(Bad(1.5)) + self.assertEqual(str(cm.exception), "'float' object cannot be interpreted as an integer") + with self.assertRaises(OverflowError): + len(Bad(2**70)) + + def test_raises(self): + r = Raiser() + n = 0 + for i in range(1000): + try: + n += len(r) + except KeyError: + n += 1 + self.assertEqual(n, 1000) + + def size(o): + return len(o) + 1 + + for i in range(1000): + with self.assertRaises(KeyError): + size(r) + self.assertEqual(size(Sized(2)), 3) + + def test_mixed_receivers(self): + s = Sized(3) + items = [s, [1, 2], "abcd", {1: 2}, s] + for _ in range(600): + self.assertEqual([len(x) for x in items], [3, 2, 4, 1, 3]) + + def test_len_shadowed(self): + s = Sized(4) + real = builtins.len + try: + for i in range(500): + self.assertEqual(len(s), 4) + builtins.len = lambda o: -1 + self.assertEqual(len(s), -1) + finally: + builtins.len = real + self.assertEqual(len(s), 4) + + def test_method_replaced(self): + class C: + def __len__(self): + return 1 + + c = C() + n = 0 + for i in range(1000): + n += len(c) + C.__len__ = lambda self: 10 + for i in range(1000): + n += len(c) + del C.__len__ + with self.assertRaises(TypeError): + len(c) + self.assertEqual(n, 11000) + + def test_generator_caller(self): + s = Sized(2) + + def g(): + for i in range(500): + yield len(s) + + self.assertEqual(sum(g()), 1000) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_length_hint_probe_and_csv_state.py b/tests/regrtest/test_length_hint_probe_and_csv_state.py new file mode 100644 index 000000000..f38b9afe6 --- /dev/null +++ b/tests/regrtest/test_length_hint_probe_and_csv_state.py @@ -0,0 +1,106 @@ +"""list() of instances probes __len__ and __length_hint__ (whose absence +is now remembered per class version), and csv readers read their state +by position: a class that gains __len__ or __length_hint__ after +list() warmed up has it called (its errors raised, a TypeError ignored), +and readers read rows, count lines and end the same through next(), +list() and a for loop, with an attribute set on one, each matching +CPython.""" + +import csv +import unittest + + +class It: + def __init__(self, n): + self.i, self.n = 0, n + + def __iter__(self): + return self + + def __next__(self): + if self.i >= self.n: + raise StopIteration + self.i += 1 + return self.i + + +calls = [] + + +def collect(n, make): + out = None + for i in range(n): + out = list(make()) + return out + + +class LengthHintTests(unittest.TestCase): + def test_hooks_added_later(self): + self.assertEqual(collect(400, lambda: It(3)), [1, 2, 3]) + + def hint(self): + calls.append("hint") + return 3 + + It.__length_hint__ = hint + try: + del calls[:] + self.assertEqual(collect(5, lambda: It(2)), [1, 2]) + self.assertEqual(calls, ["hint"] * 5) + finally: + del It.__length_hint__ + + def bad_len(self): + raise RuntimeError("len") + + It.__len__ = bad_len + try: + with self.assertRaises(RuntimeError): + collect(1, lambda: It(2)) + finally: + del It.__len__ + + def type_len(self): + raise TypeError("ignored") + + It.__len__ = type_len + try: + self.assertEqual(collect(3, lambda: It(2)), [1, 2]) + finally: + del It.__len__ + del calls[:] + self.assertEqual(collect(400, lambda: It(1)), [1]) + self.assertEqual(calls, []) + + +class CsvStateTests(unittest.TestCase): + lines = ["a,b", "1,2", '"x,y",z'] + + def test_next_list_and_loop(self): + want = [["a", "b"], ["1", "2"], ["x,y", "z"]] + for n in (1, 300): + for i in range(n): + r = csv.reader(self.lines) + got = [next(r), next(r), next(r)] + with self.assertRaises(StopIteration): + next(r) + self.assertEqual(got, want) + self.assertEqual(r.line_num, 3) + for i in range(n): + rows = list(csv.reader(self.lines)) + self.assertEqual(rows, want) + for i in range(n): + r = csv.reader(self.lines) + rows = [row for row in r] + self.assertEqual((rows, r.line_num), (want, 3)) + + def test_dialect_read_between_rows(self): + r = csv.reader(self.lines) + self.assertEqual(next(r), ["a", "b"]) + self.assertEqual(r.dialect.delimiter, ",") + self.assertEqual(list(r), [["1", "2"], ["x,y", "z"]]) + self.assertEqual(r.line_num, 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_linked_walk_loops.py b/tests/regrtest/test_linked_walk_loops.py new file mode 100644 index 000000000..0f0fb8ca4 --- /dev/null +++ b/tests/regrtest/test_linked_walk_loops.py @@ -0,0 +1,171 @@ +"""Loops that walk a linked structure (`n = n.next`): the same results +whichever tier runs them, with slotted and dict-backed nodes, with typed +work and calls in the body, across `None` ends, cycles cut by a counter, +and nodes replaced while walking.""" + +import unittest + + +class SNode: + __slots__ = ("v", "nxt") + + def __init__(self, v, nxt): + self.v = v + self.nxt = nxt + + +class DNode: + def __init__(self, v, nxt): + self.v = v + self.nxt = nxt + + def weight(self): + return self.v * 2 + 1 + + +class Tree: + __slots__ = ("key", "left", "right") + + def __init__(self, key): + self.key = key + self.left = None + self.right = None + + +def build(cls, n): + head = None + for i in range(n): + head = cls(i, head) + return head + + +def total(head): + t = 0 + n = head + while n is not None: + t += n.v + n = n.nxt + return t + + +def length(head): + c = 0 + while head is not None: + c += 1 + head = head.nxt + return c + + +def last(head): + while head.nxt is not None: + head = head.nxt + return head + + +def weighted(head): + t = 0.0 + n = head + while n is not None: + t += n.weight() * 0.5 + t -= n.v % 3 + t += (n.v * n.v) % 7 + n = n.nxt + return t + + +def insert(root, key): + if root is None: + return Tree(key) + n = root + while True: + if key < n.key: + if n.left is None: + n.left = Tree(key) + return root + n = n.left + else: + if n.right is None: + n.right = Tree(key) + return root + n = n.right + + +def depth_of(root, key): + d = 0 + n = root + while n is not None and n.key != key: + n = n.left if key < n.key else n.right + d += 1 + return d if n is not None else -1 + + +class LinkedWalkTests(unittest.TestCase): + def test_sums_and_lengths(self): + for cls in (SNode, DNode): + head = build(cls, 200) + for _ in range(400): + self.assertEqual(total(head), 199 * 200 // 2) + self.assertEqual(length(head), 200) + self.assertEqual(last(head).v, 0) + self.assertEqual(total(None), 0) + self.assertEqual(length(None), 0) + + def test_typed_work_and_calls(self): + head = build(DNode, 150) + want = sum((2 * v + 1) * 0.5 - v % 3 + (v * v) % 7 for v in range(150)) + for _ in range(300): + self.assertEqual(weighted(head), want) + + def test_mixed_node_kinds(self): + head = None + for i in range(100): + head = (SNode if i % 2 else DNode)(i, head) + for _ in range(400): + self.assertEqual(total(head), 4950) + + def test_field_that_stops_being_a_node(self): + head = build(SNode, 50) + for _ in range(300): + self.assertEqual(total(head), 1225) + head.nxt.nxt.nxt = 5 + with self.assertRaises(AttributeError): + total(head) + head.nxt.nxt.nxt = None + self.assertEqual(total(head), 49 + 48 + 47) + + def test_cycle_cut_by_counter(self): + a = SNode(1, None) + b = SNode(2, a) + a.nxt = b + for _ in range(50): + n, t, steps = a, 0, 0 + while n is not None and steps < 1001: + t += n.v + n = n.nxt + steps += 1 + self.assertEqual(t, 1 * 501 + 2 * 500) + + def test_relink_while_walking(self): + for _ in range(200): + head = build(SNode, 20) + n, seen = head, [] + while n is not None: + seen.append(n.v) + if n.v == 10: + n.nxt = n.nxt.nxt + n = n.nxt + self.assertEqual(seen, [v for v in range(19, -1, -1) if v != 9]) + + def test_tree_descent(self): + root = None + keys = [(i * 37) % 101 for i in range(101)] + for k in keys: + root = insert(root, k) + for _ in range(100): + self.assertEqual(depth_of(root, keys[0]), 0) + self.assertEqual(depth_of(root, 1000), -1) + self.assertTrue(all(depth_of(root, k) >= 0 for k in keys)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_list_constant_slice_store.py b/tests/regrtest/test_list_constant_slice_store.py new file mode 100644 index 000000000..cdcd0e069 --- /dev/null +++ b/tests/regrtest/test_list_constant_slice_store.py @@ -0,0 +1,90 @@ +"""`xs[a:b] = ys` with literal bounds, which compile to one slice constant. + +Every shape must splice as the general slice assignment does: negative and +omitted bounds, bounds past either end, a value that is the target list +itself, and values or targets the fast path leaves to the full handler. +""" + +import unittest + + +class ListConstantSliceStore(unittest.TestCase): + def test_bounds(self): + for _ in range(100): + a = list(range(8)) + a[2:5] = [0] + self.assertEqual(a, [0, 1, 0, 5, 6, 7]) + a = list(range(8)) + a[-3:] = (9, 9) + self.assertEqual(a, [0, 1, 2, 3, 4, 9, 9]) + a = list(range(8)) + a[:2] = [] + self.assertEqual(a, [2, 3, 4, 5, 6, 7]) + a = list(range(8)) + a[6:2] = ["x"] + self.assertEqual(a, [0, 1, 2, 3, 4, 5, "x", 6, 7]) + a = list(range(4)) + a[10:20] = [1, 2] + self.assertEqual(a, [0, 1, 2, 3, 1, 2]) + a = list(range(4)) + a[-10:1] = [7] + self.assertEqual(a, [7, 1, 2, 3]) + a = list(range(4)) + a[:] = [5] + self.assertEqual(a, [5]) + + def test_value_is_target(self): + for _ in range(100): + a = [1, 2, 3] + a[1:2] = a + self.assertEqual(a, [1, 1, 2, 3, 3]) + + def test_other_values_and_steps(self): + for _ in range(100): + a = list(range(6)) + a[1:3] = (x * 10 for x in range(3)) + self.assertEqual(a, [0, 0, 10, 20, 3, 4, 5]) + a = list(range(6)) + a[::2] = "abc" + self.assertEqual(a, ["a", 1, "b", 3, "c", 5]) + a = list(range(6)) + a[1:3] = "xy" + self.assertEqual(a, [0, "x", "y", 3, 4, 5]) + a = list(range(6)) + with self.assertRaises(TypeError): + a[1:3] = 5 + self.assertEqual(a, list(range(6))) + + def test_removed_items_are_released(self): + import gc + import weakref + + class O: + pass + + for _ in range(20): + o = O() + r = weakref.ref(o) + a = [1, o, 2] + del o + a[1:2] = [3] + gc.collect() + self.assertIsNone(r()) + self.assertEqual(a, [1, 3, 2]) + + def test_list_subclass_target(self): + log = [] + + class L(list): + def __setitem__(self, k, v): + log.append(k) + super().__setitem__(k, v) + + a = L([1, 2, 3]) + a[0:1] = [9] + self.assertEqual(a, [9, 2, 3]) + self.assertEqual(log, [slice(0, 1, None)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_list_count_index_native.py b/tests/regrtest/test_list_count_index_native.py new file mode 100644 index 000000000..a016ee74e --- /dev/null +++ b/tests/regrtest/test_list_count_index_native.py @@ -0,0 +1,48 @@ +"""`list.count(x)`, `list.index(x)` and the tuple's when no comparison runs code. + +Mixed numbers compare across `int`, `float` and `bool`; `nan` matches +itself by identity; strings, bytes, `None` and tuples of those compare +natively; an item with its own `__eq__`, bounds, and a missing value +take the full path; a missing value's error reads as CPython's. Run it +past the compile threshold. +""" + + +class Eq: + calls = 0 + + def __eq__(self, other): + Eq.calls += 1 + return other == "eq" + + +nan = float("nan") + + +def run(n): + for i in range(n): + xs = [1, 2.0, True, "a", b"b", None, (1, "a"), 2, nan] + assert xs.count(1) == 2 and xs.count(2) == 2 and xs.count(True) == 2 + assert xs.count("a") == 1 and xs.count(b"b") == 1 and xs.count(None) == 1 + assert xs.count((1, "a")) == 1 and xs.count(nan) == 1 and xs.count(3) == 0 + assert xs.index(2) == 1 and xs.index("a") == 3 and xs.index(nan) == 8 + assert xs.index((1, "a")) == 6 and xs.index(1.0) == 0 + try: + xs.index("zz") + except ValueError as e: + assert str(e) == "list.index(x): x not in list" + else: + raise AssertionError("found a missing value") + assert xs.index(2, 2) == 7 and xs.index(True, 1, 3) == 2 + ys = [Eq(), "eq", 1] + before = Eq.calls + assert ys.count("eq") == 2 and Eq.calls == before + 1 + assert ys.index(1) == 2 + t = tuple(xs) + assert t.count(1) == 2 and t.count(nan) == 1 and t.index(2) == 1 + assert t.index("a") == 3 and t.index(2, 2) == 7 + assert (Eq(), "eq").count("eq") == 2 + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_list_index_bounds_native.py b/tests/regrtest/test_list_index_bounds_native.py new file mode 100644 index 000000000..b640244e4 --- /dev/null +++ b/tests/regrtest/test_list_index_bounds_native.py @@ -0,0 +1,59 @@ +"""list.index(x, start[, stop]) with int bounds scanned natively: found +and missing values, negative and out-of-range bounds, an empty range, +bools and big ints as bounds (the full path), instances whose __eq__ +runs Python (the full path), and argument errors, each matching +CPython.""" + +import unittest + + +class Eq: + def __init__(self, v): + self.v = v + + def __eq__(self, other): + return isinstance(other, Eq) and self.v == other.v + + +XS = [5, "a", 7, 5, 9, 5] + + +def find(n, *args): + out = None + for i in range(n): + try: + out = XS.index(*args) + except ValueError as e: + out = str(e) + return out + + +class ListIndexTests(unittest.TestCase): + def test_bounds(self): + for n in (1, 300): + self.assertEqual(find(n, 5), 0) + self.assertEqual(find(n, 5, 1), 3) + self.assertEqual(find(n, 5, 4), 5) + self.assertEqual(find(n, 5, 1, 3), "list.index(x): x not in list") + self.assertEqual(find(n, 5, -2), 5) + self.assertEqual(find(n, 9, -100, 100), 4) + self.assertEqual(find(n, "a", 2), "list.index(x): x not in list") + self.assertEqual(find(n, 7, 3, 1), "list.index(x): x not in list") + self.assertEqual(find(n, 5, True), 3) + self.assertEqual(find(n, 5, 2**70), "list.index(x): x not in list") + + def test_python_eq_and_errors(self): + ys = [Eq(1), Eq(2), Eq(1)] + for i in range(300): + r = ys.index(Eq(1), 1) + self.assertEqual(r, 2) + with self.assertRaises(TypeError): + XS.index(5, "a") + with self.assertRaises(TypeError): + XS.index(5, 0, 1, 2) + with self.assertRaises(TypeError): + XS.index() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_list_iterator_detach_shared.py b/tests/regrtest/test_list_iterator_detach_shared.py new file mode 100644 index 000000000..84aef131a --- /dev/null +++ b/tests/regrtest/test_list_iterator_detach_shared.py @@ -0,0 +1,95 @@ +"""Exhausted list and reverse iterators detach from their lists through a +shared empty store; loops over small lists and tuples retire their cursors +in place.""" + +import gc +import pickle +import unittest + + +class Tracked: + deleted = 0 + + def __del__(self): + Tracked.deleted += 1 + + +class DetachTests(unittest.TestCase): + def test_exhausted_iterators_stay_empty(self): + a = [1, 2] + b = [3] + ia, ib = iter(a), iter(b) + self.assertEqual(list(ia), [1, 2]) + self.assertEqual(list(ib), [3]) + a.append(9) + b.append(9) + self.assertEqual(list(ia), []) + self.assertEqual(list(ib), []) + # A fresh iterator over a list still sees everything. + self.assertEqual(list(iter(a)), [1, 2, 9]) + r = reversed([1, 2]) + self.assertEqual(list(r), [2, 1]) + self.assertEqual(list(r), []) + + def test_reduce_after_exhaustion(self): + it = iter([1, 2, 3]) + list(it) + f, args = it.__reduce__()[:2] + self.assertEqual(args, ([],)) + args[0].append(5) + it2 = iter([4]) + list(it2) + self.assertEqual(it2.__reduce__()[1], ([],)) + self.assertEqual(list(pickle.loads(pickle.dumps(it))), []) + r = reversed([1]) + list(r) + self.assertEqual(r.__reduce__()[1], ([],)) + + def test_shared_generator_cursor_detaches(self): + xs = [1, 2] + g = (x for x in xs) + self.assertEqual(list(g), [1, 2]) + xs.append(3) + self.assertEqual(list(g), []) + + def test_small_loops(self): + g = {0: [1, 2], 1: [3], 2: []} + total = 0 + for i in range(3000): + for w in g[i % 3]: + total += w + self.assertEqual(total, 6000) + t = (1, 2) + empty = [] + n = 0 + for i in range(3000): + for w in t: + n += w + for w in empty: + n += 100 + self.assertEqual(n, 9000) + + def test_temporary_list_frees_items_at_loop_end(self): + Tracked.deleted = 0 + for i in range(500): + for x in [Tracked(), Tracked()]: + pass + del x + gc.collect() + self.assertEqual(Tracked.deleted, 1000) + + def test_iterators_collected(self): + Tracked.deleted = 0 + its = [] + for i in range(200): + it = iter([Tracked()]) + list(it) + its.append(it) + gc.collect() + self.assertEqual(Tracked.deleted, 200) + del its + gc.collect() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_list_of_user_iterables.py b/tests/regrtest/test_list_of_user_iterables.py new file mode 100644 index 000000000..8a61169e1 --- /dev/null +++ b/tests/regrtest/test_list_of_user_iterables.py @@ -0,0 +1,67 @@ +"""list() and tuple() of instances whose __iter__ returns a native +iterator, drained without stepping it through the general loop: ranges +(negative steps, empty, big), lists, tuples, strs, reversed lists, dict +and set iterators (including one changed while drained), a partly +consumed iterator returned from __iter__, and a list that grows while +drained, each matching CPython.""" + +import unittest + + +class It: + def __init__(self, make): + self.make = make + + def __iter__(self): + return self.make() + + +def drain(n, obj): + out = None + for i in range(n): + out = list(obj) + return out + + +class UserIterableTests(unittest.TestCase): + def test_native_iterators(self): + for n in (1, 300): + self.assertEqual(drain(n, It(lambda: iter(range(5)))), [0, 1, 2, 3, 4]) + self.assertEqual(drain(n, It(lambda: iter(range(10, 0, -3)))), [10, 7, 4, 1]) + self.assertEqual(drain(n, It(lambda: iter(range(0)))), []) + self.assertEqual(drain(n, It(lambda: iter([1, "a", None]))), [1, "a", None]) + self.assertEqual(drain(n, It(lambda: iter((1, 2)))), [1, 2]) + self.assertEqual(drain(n, It(lambda: iter("hé"))), ["h", "é"]) + self.assertEqual(drain(n, It(lambda: reversed([1, 2, 3]))), [3, 2, 1]) + self.assertEqual(drain(n, It(lambda: iter({"a": 1, "b": 2}))), ["a", "b"]) + self.assertEqual(sorted(drain(n, It(lambda: iter({3, 1, 2})))), [1, 2, 3]) + big = It(lambda: iter(range(2**62, 2**62 + 3))) + self.assertEqual(drain(300, big), [2**62, 2**62 + 1, 2**62 + 2]) + self.assertEqual(tuple(It(lambda: iter([4, 5]))), (4, 5)) + + def test_partly_consumed_and_shared(self): + src = iter([1, 2, 3, 4]) + next(src) + self.assertEqual(list(It(lambda: src)), [2, 3, 4]) + self.assertEqual(list(src), []) + xs = [1, 2] + it = iter(xs) + self.assertEqual(list(It(lambda: it)), [1, 2]) + xs.append(3) + self.assertEqual(list(it), []) + + def test_changed_dict(self): + d = {1: 1, 2: 2} + + class Grow: + def __iter__(self): + g = iter(d) + d[3] = 3 + return g + + with self.assertRaises(RuntimeError): + list(Grow()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_list_slice_store.py b/tests/regrtest/test_list_slice_store.py new file mode 100644 index 000000000..ac5e72d57 --- /dev/null +++ b/tests/regrtest/test_list_slice_store.py @@ -0,0 +1,54 @@ +"""Slice assignment to a list in compiled code. + +A unit-step slice of an exact list assigned a list's or a tuple's items +splices in place; bounds clamp as Python's do, a reversed slice inserts, +a list assigned to itself copies first, and an extended slice takes the +full path. A displaced item's finalizer runs before the next statement. +Run it past the compile threshold. +""" + + +class D: + log = [] + + def __init__(self, n): + self.n = n + + def __del__(self): + D.log.append(self.n) + + +def run(n): + for _ in range(n): + xs = [1, 2, 3, 4, 5] + xs[:] = xs[2:] + assert xs == [3, 4, 5] + xs[1:2] = (7, 8, 9) + assert xs == [3, 7, 8, 9, 5] + xs[3:1] = [0] + assert xs == [3, 7, 8, 0, 9, 5] + xs[-2:] = [] + assert xs == [3, 7, 8, 0] + xs[10:] = [1] + assert xs == [3, 7, 8, 0, 1] + xs[:] = xs + assert xs == [3, 7, 8, 0, 1] + xs[::2] = [0, 0, 0] + assert xs == [0, 7, 0, 0, 0] + try: + xs[::2] = [1] + except ValueError: + pass + else: + raise AssertionError("extended slice of the wrong length") + ys = [D(1), D(2)] + ys[:1] = [3] + assert D.log == [1], D.log + D.log.clear() + del ys + assert D.log == [2] + D.log.clear() + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_local_callee_loops.py b/tests/regrtest/test_local_callee_loops.py new file mode 100644 index 000000000..e99317823 --- /dev/null +++ b/tests/regrtest/test_local_callee_loops.py @@ -0,0 +1,133 @@ +"""Loops that call a small Python function tier 2 calls generically. + +A callee held in a local, or a global one tier 2 doesn't compile (one +with keyword-only parameters or `*args`), goes through tier 2's generic +call helper; a loop doing little else runs in the frame JIT, which checks +and enters the callee directly, while a loop calling a long function +stays in tier 2. Results, a callee that changes partway, a bound method, keyword +arguments, a callee that raises, and a loop heavy with arithmetic (which +tier 2 keeps) all behave as before. Run it past the compile threshold. +""" + + +def f3(a, b, c): + return a + b * c + + +def g3(a, b, c): + return a - b - c + + +class Acc: + def __init__(self): + self.n = 0 + + def add(self, k, *, by=1): + self.n += k * by + return self.n + + +def calls(n, f): + total = 0 + for i in range(n): + total += f(i, 2, 3) + return total + + +def swaps(n): + total = 0 + f = f3 + for i in range(n): + if i == n // 2: + f = g3 + total += f(i, 1, 1) + return total + + +def bound(n): + acc = Acc() + add = acc.add + for i in range(n): + add(i, by=2) + return acc.n + + +def raises(n): + def boom(i): + if i == n - 1: + raise ValueError(i) + return i + + caught = 0 + for i in range(n): + try: + boom(i) + except ValueError as e: + caught = e.args[0] + return caught + + +def heavy(n, f): + total = 0.0 + for i in range(n): + x = i * 0.5 + y = x * x + x * 3.0 - i / 7 + (i % 5) * 2.0 - (i % 3) * 1.5 + z = y * y - x * y + 0.25 * x - y / 9 + x * 0.125 - (y - x) * 0.5 + total += z + y + x + f(i, 1, 1) * 1.0 + return total + + +def kwonly(a, b=2, *, c=3): + return a + b + c + + +def star(*args): + return len(args) + + +def long_body(xs, k): + t = 0 + for x in xs: + t += x * k + t -= x + t += x // 3 + return t + + +def globals_loop(n): + total = 0 + xs = [1, 2, 3] + for i in range(n): + total += kwonly(i, c=4) + star(i, i) + total += long_body(xs, i) + return total + + +def globals_expected(n): + total = 0 + for i in range(n): + total += i + 2 + 4 + 2 + total += sum(x * i - x + x // 3 for x in (1, 2, 3)) + return total + + +n = 4000 +assert globals_loop(n) == globals_expected(n) +assert calls(n, f3) == sum(i + 6 for i in range(n)) +assert swaps(n) == sum(i + 1 for i in range(n // 2)) + sum(i - 2 for i in range(n // 2, n)) +assert bound(n) == 2 * sum(range(n)) +assert raises(n) == n - 1 + + +def heavy_expected(n): + total = 0.0 + for i in range(n): + x = i * 0.5 + y = x * x + x * 3.0 - i / 7 + (i % 5) * 2.0 - (i % 3) * 1.5 + z = y * y - x * y + 0.25 * x - y / 9 + x * 0.125 - (y - x) * 0.5 + total += z + y + x + (i + 1) * 1.0 + return total + + +assert heavy(n, f3) == heavy_expected(n) +print("ok") diff --git a/tests/regrtest/test_lock_handoff.py b/tests/regrtest/test_lock_handoff.py new file mode 100644 index 000000000..3c555d228 --- /dev/null +++ b/tests/regrtest/test_lock_handoff.py @@ -0,0 +1,46 @@ +"""A contended lock's waiter gets its turn. + +A waiter for a `threading.Lock` (or `RLock`) waits for the lock to come +free with the GIL released and takes it once the GIL is back, so the +running thread can retake a lock it released instead of switching +threads at every acquire. A holder that has the lock nearly all the time +when it yields the GIL must still not starve the waiter: past a few +milliseconds the waiter takes the lock as soon as it comes free. +""" + +import threading +import time + + +def check(lock): + stop = False + rounds = [0] + + def hog(): + while not stop: + with lock: + total = 0 + for i in range(2000): + total += i + rounds[0] += 1 + + t = threading.Thread(target=hog) + t.start() + try: + start = time.monotonic() + got = 0 + while time.monotonic() - start < 0.3: + with lock: + got += 1 + elapsed = time.monotonic() - start + finally: + stop = True + t.join() + assert got >= 3, (type(lock).__name__, got) + assert rounds[0] >= 3, rounds[0] + # Each acquire waits a few milliseconds at most. + assert elapsed < 3.0, elapsed + + +check(threading.Lock()) +check(threading.RLock()) diff --git a/tests/regrtest/test_logging_disabled_levels.py b/tests/regrtest/test_logging_disabled_levels.py new file mode 100644 index 000000000..100f3863c --- /dev/null +++ b/tests/regrtest/test_logging_disabled_levels.py @@ -0,0 +1,101 @@ +"""Logger level methods on a disabled level return at once. + +`logger.debug(...)` and its kin, for a level the logger is disabled for as +its class's `isEnabledFor` decides it, return `None` without the Python +method; everything else (an enabled level, keywords, a subclass's own +`isEnabledFor`, `logging.disable`, a changed level) behaves as before, +records and their caller information included. +""" + +import logging +import unittest + + +class ListHandler(logging.Handler): + def __init__(self): + super().__init__() + self.records = [] + + def emit(self, record): + self.records.append(record) + + +class LoggingDisabledTests(unittest.TestCase): + def setUp(self): + self.logger = logging.getLogger("weave.test.disabled") + self.logger.propagate = False + self.handler = ListHandler() + self.logger.addHandler(self.handler) + self.logger.setLevel(logging.WARNING) + + def tearDown(self): + self.logger.removeHandler(self.handler) + self.logger.disabled = False + logging.disable(logging.NOTSET) + + def test_disabled_levels_drop(self): + for i in range(500): + self.assertIsNone(self.logger.debug("x %s", i)) + self.assertIsNone(self.logger.info("y")) + self.assertEqual(self.handler.records, []) + self.logger.warning("w %d", 1) + self.assertEqual([r.getMessage() for r in self.handler.records], ["w 1"]) + + def test_level_changes(self): + for i in range(100): + self.logger.debug("drop") + self.logger.setLevel(logging.DEBUG) + self.logger.debug("keep %s", "me") + self.assertEqual([r.getMessage() for r in self.handler.records], ["keep me"]) + rec = self.handler.records[0] + self.assertEqual(rec.funcName, "test_level_changes") + self.assertTrue(rec.pathname.endswith("test_logging_disabled_levels.py")) + self.logger.disabled = True + for i in range(100): + self.logger.error("drop") + self.logger.disabled = False + logging.disable(logging.ERROR) + for i in range(100): + self.logger.error("drop") + logging.disable(logging.NOTSET) + self.logger.critical("c") + self.assertEqual([r.getMessage() for r in self.handler.records], ["keep me", "c"]) + + def test_keywords_and_stacklevel(self): + self.logger.setLevel(logging.INFO) + + def helper(): + self.logger.info("from helper", stacklevel=2) + + helper() + self.assertEqual(self.handler.records[-1].funcName, "test_keywords_and_stacklevel") + for i in range(50): + self.logger.debug("drop", exc_info=True) + self.assertEqual(len(self.handler.records), 1) + try: + raise ValueError("boom") + except ValueError: + self.logger.error("caught", exc_info=True) + self.assertIsNotNone(self.handler.records[-1].exc_info) + + def test_subclass_and_adapter(self): + class Loud(logging.Logger): + def isEnabledFor(self, level): + return True + + loud = Loud("weave.loud") + h = ListHandler() + loud.addHandler(h) + loud.setLevel(logging.CRITICAL) + for i in range(50): + loud.debug("always %d", i) + self.assertEqual(len(h.records), 50) + adapter = logging.LoggerAdapter(self.logger, {"k": 1}) + for i in range(50): + adapter.debug("drop") + adapter.warning("kept") + self.assertEqual(self.handler.records[-1].getMessage(), "kept") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_long_fstrings_and_filter_slice_stores.py b/tests/regrtest/test_long_fstrings_and_filter_slice_stores.py new file mode 100644 index 000000000..ccc247be4 --- /dev/null +++ b/tests/regrtest/test_long_fstrings_and_filter_slice_stores.py @@ -0,0 +1,79 @@ +"""Compiled f-strings of up to sixteen parts, and slice stores from `filter`. + +`f"{a}-{b}-{c}-{d}-{e}"` (nine parts, `UUID.__str__`'s shape) joins in +compiled code; past sixteen parts, or with a non-`str` part, the full +path joins. `xs[a:b] = filter(None, ys)` (`urljoin`'s) drains the filter +in place when the items' truth runs no code, and takes the full path +otherwise (an instance's `__bool__`, a `filter` with a Python function), +including when the filter reads the list being assigned. +""" + +import unittest + + +def nine(a, b, c, d, e): + return f"{a}-{b}-{c}-{d}-{e}" + + +def seventeen(*p): + return f"{p[0]}{p[1]}{p[2]}{p[3]}{p[4]}{p[5]}{p[6]}{p[7]}{p[8]}|{p[9]}|{p[10]}|{p[11]}|{p[12]}|{p[13]}|{p[14]}|{p[15]}|{p[16]}" + + +class Truthy: + def __init__(self, v): + self.v = v + + def __bool__(self): + return self.v > 0 + + +def slice_filter(xs, ys): + xs[1:-1] = filter(None, ys) + return xs + + +class LongFStringTests(unittest.TestCase): + def test_nine_parts(self): + for i in range(300): + self.assertEqual(nine("ab", i, 1.5, None, "€"), f"ab-{i}-1.5-None-€") + self.assertEqual(nine("x\udcac", "", "", "", ""), "x\udcac----") + + def test_past_the_limit(self): + parts = [str(i) for i in range(17)] + want = "".join(parts[:9]) + "|" + "|".join(parts[9:]) + for _ in range(300): + self.assertEqual(seventeen(*parts), want) + + +class FilterSliceStoreTests(unittest.TestCase): + def test_strings(self): + for _ in range(300): + self.assertEqual(slice_filter(["a", "b", "c", "d"], ["", "x", "", "y"]), ["a", "x", "y", "d"]) + self.assertEqual(slice_filter([1, 2], [0, 0]), [1, 2]) + self.assertEqual(slice_filter([1, 2, 3], []), [1, 3]) + + def test_full_path_cases(self): + objs = [Truthy(1), Truthy(0), Truthy(2)] + for _ in range(100): + got = slice_filter(["a", "b", "c"], objs) + self.assertEqual([getattr(o, "v", o) for o in got], ["a", 1, 2, "c"]) + xs = ["", "p", "", "q"] + for _ in range(100): + ys = list(xs) + ys[1:-1] = filter(lambda s: s, ys) + self.assertEqual(ys, ["", "p", "q", "q"]) + + def test_filter_over_target(self): + for _ in range(100): + xs = ["a", "", "b", "", "c"] + xs[:] = filter(None, xs) + self.assertEqual(xs, ["a", "b", "c"]) + ys = ["", "z"] + it = filter(None, ys) + ys[0:0] = it + self.assertEqual(ys, ["z", "", "z"]) + self.assertEqual(list(it), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_lookup_misses_caught_unseen.py b/tests/regrtest/test_lookup_misses_caught_unseen.py new file mode 100644 index 000000000..af3d2e5d2 --- /dev/null +++ b/tests/regrtest/test_lookup_misses_caught_unseen.py @@ -0,0 +1,350 @@ +"""A lookup miss that its caller catches without looking at it. + +`m[key]` of a class whose `__getitem__` is `return self.items[key]` is +read with no call. When the key is missing and the caller's own handler +is `except KeyError:` with no name bound and nothing run before the +exception is dropped (`Mapping.get`, `Mapping.__contains__`), the error +is raised with no `__getitem__` frame behind it, since nothing can see +the difference. These tests pin every handler shape that could: a bound +name, `sys.exc_info()`, a re-raise, a chained raise, a handler for +another class, and a module that rebinds the handler's name. +""" + +import collections.abc as abc +import sys +import traceback +import unittest + +ROUNDS = 400 + + +class Wraps(abc.MutableMapping): + def __init__(self, d=None): + self._d = dict(d or {}) + + def __getitem__(self, k): + return self._d[k] + + def __setitem__(self, k, v): + self._d[k] = v + + def __delitem__(self, k): + del self._d[k] + + def __iter__(self): + return iter(self._d) + + def __len__(self): + return len(self._d) + + +class Items: + def __init__(self, xs): + self.xs = xs + + def __getitem__(self, i): + return self.xs[i] + + +def frames(e): + return [f.name for f in traceback.extract_tb(e.__traceback__)] + + +def unseen(m, k): + try: + return m[k] + except KeyError: + return "default" + + +def unseen_pass(m, k): + r = "none" + try: + r = m[k] + except KeyError: + pass + return r + + +def bound(m, k): + try: + return m[k] + except KeyError as e: + return e.args, frames(e), e.__context__ + + +def lookup(m, k): + try: + return m[k] + except LookupError: + return "lookup" + + +def anything(m, k): + try: + return m[k] + except Exception: + return "exception" + + +def bare(m, k): + try: + return m[k] + except: # noqa: E722 + return "bare" + + +def another_class(m, k): + try: + return m[k] + except IndexError: + return "index" + + +def inspecting(m, k): + try: + return m[k] + except KeyError: + return sys.exc_info()[0].__name__, frames(sys.exc_info()[1]) + + +def reraising(m, k): + try: + return m[k] + except KeyError: + raise + + +def chaining(m, k): + try: + return m[k] + except KeyError: + raise ValueError("v") + + +def either(m, k): + try: + return m[k] + except (KeyError, IndexError): + return "tuple" + + +def with_finally(m, k, log): + try: + return m[k] + except KeyError: + return "caught" + finally: + log.append("finally") + + +def nested(m, k): + try: + try: + return m[k] + except IndexError: + return "inner" + except KeyError: + return "outer" + + +def index(s, i): + try: + return s[i] + except IndexError: + return "index" + + +def index_bound(s, i): + try: + return s[i] + except IndexError as e: + return str(e), frames(e) + + +def shadowed(m, k, KeyError=ValueError): + try: + return m[k] + except KeyError: + return "shadowed" + + +def raised(f): + try: + f() + except Exception as e: + return type(e).__name__, str(e), frames(e)[1:], type(e.__context__).__name__ + return None + + +class HandlerShapes(unittest.TestCase): + def setUp(self): + self.m = Wraps({"a": 1, "b": 2}) + + def test_handlers_that_never_look(self): + m = self.m + for _ in range(ROUNDS): + self.assertEqual((unseen(m, "a"), unseen(m, "z")), (1, "default")) + self.assertEqual((unseen_pass(m, "b"), unseen_pass(m, "z")), (2, "none")) + self.assertEqual(lookup(m, "z"), "lookup") + self.assertEqual(anything(m, "z"), "exception") + self.assertEqual(bare(m, "z"), "bare") + self.assertEqual(either(m, "z"), "tuple") + self.assertEqual(nested(m, "z"), "outer") + log = [] + self.assertEqual((with_finally(m, "z", log), log), ("caught", ["finally"])) + # Keys the dict hashes itself, and one it can't hash. + self.assertEqual(unseen(m, 1), "default") + self.assertEqual(unseen(m, (1, 2)), "default") + self.assertEqual(unseen(m, 1.5), "default") + self.assertEqual(unseen(m, None), "default") + self.assertEqual(raised(lambda: unseen(m, [1]))[0], "TypeError") + + def test_handlers_that_look(self): + m = self.m + for _ in range(ROUNDS): + self.assertEqual(bound(m, "a"), 1) + self.assertEqual(bound(m, "z"), (("z",), ["bound", "__getitem__"], None)) + self.assertEqual( + inspecting(m, "z"), ("KeyError", ["inspecting", "__getitem__"]) + ) + self.assertEqual( + raised(lambda: reraising(m, "z")), + ("KeyError", "'z'", ["", "reraising", "__getitem__"], "NoneType"), + ) + self.assertEqual( + raised(lambda: chaining(m, "z")), + ("ValueError", "v", ["", "chaining"], "KeyError"), + ) + + def test_a_miss_nothing_here_catches(self): + m = self.m + for _ in range(ROUNDS): + self.assertEqual( + raised(lambda: another_class(m, "z")), + ("KeyError", "'z'", ["", "another_class", "__getitem__"], "NoneType"), + ) + self.assertEqual( + raised(lambda: shadowed(m, "z")), + ("KeyError", "'z'", ["", "shadowed", "__getitem__"], "NoneType"), + ) + self.assertEqual( + raised(lambda: m["z"]), + ("KeyError", "'z'", ["", "__getitem__"], "NoneType"), + ) + + def test_an_index_past_a_list_or_tuple(self): + s, t = Items([1, 2, 3]), Items((1, 2)) + for _ in range(ROUNDS): + self.assertEqual((index(s, 1), index(s, 9), index(s, -9)), (2, "index", "index")) + self.assertEqual(index(t, 5), "index") + self.assertEqual( + index_bound(s, 9), + ("list index out of range", ["index_bound", "__getitem__"]), + ) + self.assertEqual( + index_bound(t, 9), + ("tuple index out of range", ["index_bound", "__getitem__"]), + ) + + +class MixinMethods(unittest.TestCase): + def test_get_contains_pop_and_setdefault(self): + for _ in range(ROUNDS): + m = Wraps({"a": 1, "b": 2}) + self.assertEqual((m.get("a"), m.get("z"), m.get("z", 5)), (1, None, 5)) + self.assertEqual(("a" in m, "z" in m), (True, False)) + self.assertEqual(m.pop("zz", "p"), "p") + self.assertEqual(raised(lambda: m.pop("zz"))[:2], ("KeyError", "'zz'")) + self.assertEqual((m.setdefault("a", 9), m.setdefault("n", 3)), (1, 3)) + self.assertEqual(m.pop("n"), 3) + self.assertEqual(sorted(m.popitem() for _ in range(2)), [("a", 1), ("b", 2)]) + self.assertEqual(raised(m.popitem)[0], "KeyError") + self.assertEqual(dict(m), {}) + + +class NothingLeftBehind(unittest.TestCase): + def test_no_exception_is_current_afterwards(self): + m = Wraps({"a": 1}) + + def after(): + try: + m["z"] + except KeyError: + pass + current = sys.exception() + try: + raise ValueError("next") + except ValueError as e: + return current, e.__context__ + + for _ in range(ROUNDS): + self.assertEqual(after(), (None, None)) + + def test_a_module_that_rebinds_the_handlers_name(self): + ns = {"__name__": "rebinds"} + exec( + "def f(m, k):\n" + " try:\n" + " return m[k]\n" + " except KeyError:\n" + " return 'caught'\n", + ns, + ) + f, m = ns["f"], Wraps({"a": 1}) + for _ in range(ROUNDS): + self.assertEqual((f(m, "a"), f(m, "z")), (1, "caught")) + ns["KeyError"] = IndexError + for _ in range(ROUNDS): + self.assertEqual(f(m, "a"), 1) + self.assertEqual( + raised(lambda: f(m, "z")), + ("KeyError", "'z'", ["", "f", "__getitem__"], "NoneType"), + ) + + +class PolymorphicSites(unittest.TestCase): + """One read site over several classes, and a class changed under it.""" + + def test_a_property_added_to_one_of_the_classes(self): + class A: + def __init__(self): + self.x = 1 + self.n = None + + class B(A): + def __init__(self): + super().__init__() + self.y = 2 + + class C(A): + def __init__(self): + self.z = 0 + super().__init__() + + class D(A): + pass + + def read(objs): + return [(o.x, o.n) for o in objs] + + objs = [A(), B(), C(), D()] * 3 + for _ in range(ROUNDS): + self.assertEqual(read(objs), [(1, None)] * 12) + B.x = property(lambda self: "prop") + C.n = "class attribute, shadowed" + for _ in range(ROUNDS): + self.assertEqual( + read(objs), [(1, None), ("prop", None), (1, None), (1, None)] * 3 + ) + del B.x + # (The list repeats its four objects: the first is also the fifth.) + objs[0].x = 7 + for _ in range(ROUNDS): + self.assertEqual( + read(objs)[:5], [(7, None), (1, None), (1, None), (1, None), (7, None)] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_lru_identity_keys.py b/tests/regrtest/test_lru_identity_keys.py new file mode 100644 index 000000000..456fab360 --- /dev/null +++ b/tests/regrtest/test_lru_identity_keys.py @@ -0,0 +1,54 @@ +"""`functools.lru_cache` keys of objects that hash by identity. + +`typing`'s `_tp_cache` calls its cache as `f(*args, **kwds)` with keys +such as `(alias, (str, Any))`. Compiled code probes such keys natively: +objects that hash and compare by identity, classes, and tuples of them. +An object whose class defines `__eq__` or `__hash__` must still go through +Python, and a miss must still run the function. Run it past the compile +threshold. +""" + +import functools +import typing + + +class Plain: + pass + + +class Eq: + def __init__(self, v): + self.v = v + + def __eq__(self, other): + return isinstance(other, Eq) and self.v == other.v + + def __hash__(self): + return hash(self.v) + + +calls = [] + + +@functools.lru_cache(maxsize=None) +def cached(*args): + calls.append(args) + return len(calls) + + +def forward(*args, **kwds): + return cached(*args, **kwds) + + +a, b = Plain(), Plain() +for _ in range(3000): + first = forward(a, (str, int)) + assert forward(a, (str, int)) == first + assert forward(b, (str, int)) != first + assert forward(a, (int, str)) != first + assert forward(Eq(1)) == forward(Eq(1)) + assert typing.List[int] is typing.List[int] + assert typing.Dict[str, typing.Any] == typing.Dict[str, typing.Any] + assert typing.Optional[str] == typing.Union[str, None] + +assert len(calls) == 4, calls diff --git a/tests/regrtest/test_lru_typed_probe.py b/tests/regrtest/test_lru_typed_probe.py new file mode 100644 index 000000000..3ef62c943 --- /dev/null +++ b/tests/regrtest/test_lru_typed_probe.py @@ -0,0 +1,102 @@ +"""Calls of a `typed=True` `functools.lru_cache` wrapper in hot loops, as +`fnmatch` makes them. + +Hits and misses must count as CPython counts them; `1`, `1.0`, `True` +and a `str` subclass's equal value must each keep their own entry; calls +with more arguments than the native probe takes, keyword calls, and +arguments it can't key must still find their entries. +""" + +import fnmatch +import functools +import unittest + + +class Sub(str): + pass + + +class Eq: + """Compares equal to 7 (an argument the native probe can't key).""" + + def __hash__(self): + return hash(7) + + def __eq__(self, other): + return other == 7 + + +class LruTypedProbe(unittest.TestCase): + def test_sole_argument(self): + calls = [] + + @functools.lru_cache(maxsize=64, typed=True) + def f(x): + calls.append(x) + return (type(x).__name__, x) + + for i in range(3000): + self.assertEqual(f("p%d" % (i % 10)), ("str", "p%d" % (i % 10))) + self.assertEqual(f(i % 5), ("int", i % 5)) + self.assertEqual(len(calls), 15) + info = f.cache_info() + self.assertEqual((info.hits, info.misses, info.currsize), (6000 - 15, 15, 15)) + self.assertEqual(f(1.0), ("float", 1.0)) + self.assertEqual(f(True), ("bool", True)) + self.assertEqual(f(1), ("int", 1)) + self.assertEqual(f(Sub("p1")), ("Sub", "p1")) + self.assertEqual(f("p1"), ("str", "p1")) + self.assertEqual(f.cache_info().currsize, 18) + + def test_several_arguments(self): + @functools.lru_cache(maxsize=None, typed=True) + def g(*args, **kw): + return len(args), tuple(map(type, args)), tuple(sorted(kw)) + + for i in range(2000): + k = i % 4 + self.assertEqual(g(k, "a"), (2, (int, str), ())) + self.assertEqual(g(k, "a", b"b", (1, 2)), (4, (int, str, bytes, tuple), ())) + self.assertEqual(g(k, 1, 2, 3, 4), (5, (int,) * 5, ())) + self.assertEqual(g(k, x=1), (1, (int,), ("x",))) + info = g.cache_info() + self.assertEqual((info.misses, info.currsize), (16, 16)) + self.assertEqual(info.hits, 8000 - 16) + + def test_bounded_recency(self): + @functools.lru_cache(maxsize=2, typed=True) + def h(x): + return x * 2 + + for _ in range(500): + self.assertEqual(h("a"), "aa") + self.assertEqual(h("b"), "bb") + h("c") + h("b") + h("a") + info = h.cache_info() + self.assertEqual((info.hits, info.misses, info.currsize), (999, 4, 2)) + + def test_mixed_keys(self): + @functools.lru_cache(maxsize=None, typed=True) + def k(x): + return "v%r" % (type(x).__name__,) + + e = Eq() + k(e) + for _ in range(300): + self.assertEqual(k(7), "v'int'") + self.assertEqual(k(e), "v'Eq'") + self.assertEqual(k(7.0), "v'float'") + info = k.cache_info() + self.assertEqual((info.hits, info.misses, info.currsize), (898, 3, 3)) + + def test_fnmatch_loop(self): + for i in range(3000): + self.assertTrue(fnmatch.fnmatchcase("module_%d.py" % i, "mod*.py")) + self.assertFalse(fnmatch.fnmatchcase("x.txt", "mod*.py")) + self.assertTrue(fnmatch.fnmatchcase(b"a.c", b"*.c")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_managed_dict_verdict.py b/tests/regrtest/test_managed_dict_verdict.py new file mode 100644 index 000000000..fefb462ea --- /dev/null +++ b/tests/regrtest/test_managed_dict_verdict.py @@ -0,0 +1,92 @@ +"""`obj.__dict__` follows later changes to the class and its bases. + +The interpreter remembers, per class version, that a class's instances +read `__dict__` as their own dict. Giving the class (or a base) a +`__getattribute__` must be seen at the next read, and a subclass with a +`__dict__` of its own reads that. +""" + +import unittest + + +class FakeDict: + def __get__(self, obj, owner=None): + return {"fake": True} + + +class ManagedDictVerdict(unittest.TestCase): + def read_all(self, objs): + return [o.__dict__ for o in objs] + + def test_plain_reads(self): + class P: + pass + + o = P() + o.a = 1 + for _ in range(50): + self.assertEqual(o.__dict__, {"a": 1}) + self.assertIs(o.__dict__, o.__dict__) + + def test_subclass_with_dict_descriptor(self): + class P: + pass + + class Q(P): + __dict__ = FakeDict() + + p, q = P(), Q() + p.a = 1 + for _ in range(20): + self.assertEqual(p.__dict__, {"a": 1}) + self.assertEqual(q.__dict__, {"fake": True}) + + def test_base_gains_getattribute(self): + class B: + pass + + class C(B): + pass + + o = C() + o.x = 2 + for _ in range(20): + self.assertEqual(o.__dict__, {"x": 2}) + + def ga(self, name): + if name == "__dict__": + return "intercepted" + return object.__getattribute__(self, name) + + B.__getattribute__ = ga + for _ in range(20): + self.assertEqual(o.__dict__, "intercepted") + del B.__getattribute__ + for _ in range(20): + self.assertEqual(o.__dict__, {"x": 2}) + + def test_getattr_does_not_hide_dict(self): + class G: + def __getattr__(self, name): + return "missing:" + name + + o = G() + o.y = 3 + for _ in range(20): + self.assertEqual(o.__dict__, {"y": 3}) + self.assertEqual(o.zz, "missing:zz") + + def test_dict_get_idiom(self): + class P: + pass + + o = P() + o.k = 5 + total = 0 + for i in range(300): + total += o.__dict__.get("k", 0) + o.__dict__.get("zz", 0) + self.assertEqual(total, 1500) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_map_builtin_over_sequence_cursor.py b/tests/regrtest/test_map_builtin_over_sequence_cursor.py new file mode 100644 index 000000000..019c0ae56 --- /dev/null +++ b/tests/regrtest/test_map_builtin_over_sequence_cursor.py @@ -0,0 +1,81 @@ +"""`list(map(f, xs))` of a builtin over a list's, tuple's or range's cursor. + +Each item steps off the cursor in place; an item the builtin's leaf half +declines takes the full call, which may run code that changes the list, +and the cursor must end, raise and resume as stepping it one by one does. +""" + +import unittest + + +class Sized: + def __init__(self, n, log=None, grow=None): + self.n = n + self.log = log + self.grow = grow + + def __len__(self): + if self.log is not None: + self.log.append(self.n) + if self.grow is not None: + self.grow.append("more") + return self.n + + +class MapCursorTests(unittest.TestCase): + def test_plain(self): + words = "the quick brown fox jumps over the lazy dog".split() + for _ in range(300): + self.assertEqual(list(map(len, words)), [3, 5, 5, 3, 5, 4, 3, 4, 3]) + self.assertEqual(list(map(abs, (-1, 2, -3))), [1, 2, 3]) + self.assertEqual(list(map(str.upper, ["a", "b"])), ["A", "B"]) + self.assertEqual(list(map(abs, range(-2, 2))), [2, 1, 0, 1]) + self.assertEqual(sorted(map(len, words)), [3, 3, 3, 3, 4, 4, 5, 5, 5]) + + def test_declined_items_run_code(self): + log = [] + xs = ["ab", Sized(7, log), "c", Sized(2, log)] + self.assertEqual(list(map(len, xs)), [2, 7, 1, 2]) + self.assertEqual(log, [7, 2]) + + def test_list_grows_during_the_drain(self): + xs = ["a"] + xs.append(Sized(3, grow=xs)) + out = [] + for n in map(len, xs): + out.append(n) + if len(out) > 5: + break + self.assertEqual(out[:3], [1, 3, 4]) + xs = ["a", Sized(3, grow=None), "bb"] + self.assertEqual(list(map(len, xs)), [1, 3, 2]) + + def test_raise_and_resume(self): + it = iter(["ab", 5, "cde"]) + m = map(len, it) + with self.assertRaises(TypeError): + list(m) + self.assertEqual(list(m), [3]) + self.assertEqual(list(m), []) + self.assertEqual(list(it), []) + + def test_partly_consumed_cursor(self): + xs = ["a", "bb", "ccc", "dddd"] + it = iter(xs) + next(it) + self.assertEqual(list(map(len, it)), [2, 3, 4]) + self.assertEqual(list(it), []) + m = map(len, iter(xs)) + self.assertEqual(next(m), 1) + self.assertEqual(list(m), [2, 3, 4]) + + def test_exhausted_list_stays_ended(self): + xs = ["a"] + it = iter(xs) + self.assertEqual(list(map(len, it)), [1]) + xs.append("bb") + self.assertEqual(list(map(len, it)), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_map_leaf_builtin_callbacks.py b/tests/regrtest/test_map_leaf_builtin_callbacks.py new file mode 100644 index 000000000..6307a17ed --- /dev/null +++ b/tests/regrtest/test_map_leaf_builtin_callbacks.py @@ -0,0 +1,57 @@ +"""list(map(f, xs)) where f is a builtin with a leaf body, from compiled +loops: unbound str methods, abs and ord over lists and tuples, an item +the body rejects (the full call raises CPython's error), a receiver of +the wrong type for an unbound method, a str subclass item, and a list +that grows while mapped, each matching CPython.""" + +import unittest + +WORDS = ["hello", "World", "fOO"] + + +class S(str): + pass + + +def run(n, f, src): + out = None + for i in range(n): + out = list(map(f, src)) + return out + + +class MapLeafTests(unittest.TestCase): + def test_methods(self): + for n in (1, 300): + self.assertEqual(run(n, str.upper, WORDS), ["HELLO", "WORLD", "FOO"]) + self.assertEqual(run(n, str.capitalize, tuple(WORDS)), ["Hello", "World", "Foo"]) + self.assertEqual(run(n, str.lower, [S("AbC")]), ["abc"]) + self.assertEqual(run(n, abs, [-1, 2.5, -3]), [1, 2.5, 3]) + self.assertEqual(run(n, ord, "ab"), [97, 98]) + self.assertEqual(run(n, len, [[1], "ab", ()]), [1, 2, 0]) + + def test_errors(self): + with self.assertRaises(TypeError) as cm: + run(300, str.upper, ["a", 1]) + self.assertIn("descriptor 'upper'", str(cm.exception)) + with self.assertRaises(TypeError): + run(300, ord, ["a", "bc"]) + with self.assertRaises(TypeError): + run(300, abs, [1, "x"]) + + def test_growing_source(self): + def grow(n): + out = None + for i in range(n): + xs = ["a", "b"] + m = map(str.upper, xs) + first = next(m) + xs.append("c") + out = [first] + list(m) + return out + + self.assertEqual(grow(300), ["A", "B", "C"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_map_native_call_and_zip_longest_rows.py b/tests/regrtest/test_map_native_call_and_zip_longest_rows.py new file mode 100644 index 000000000..fe44f6fe4 --- /dev/null +++ b/tests/regrtest/test_map_native_call_and_zip_longest_rows.py @@ -0,0 +1,62 @@ +"""list(map(f, xs)) where f is an instance with a native __call__ +(itemgetter, attrgetter, methodcaller, partial) runs its fast half per +item, and zip_longest builds narrow rows in place: results, a getter +that raises partway (KeyError, IndexError, AttributeError), multi-key +getters, a partial over a Python function, and zip_longest over one to +five sources of unequal lengths with fill values, each matching +CPython.""" + +import functools +import itertools +import operator +import unittest + + +class P: + def __init__(self, x): + self.x = x + + +class NativeCallMapTests(unittest.TestCase): + def test_getters(self): + pairs = [(1, "a"), (2, "b"), (3, "c")] + for i in range(300): + r = list(map(operator.itemgetter(0), pairs)) + s = list(map(operator.itemgetter(1, 0), pairs)) + t = list(map(operator.attrgetter("x"), [P(1), P(2)])) + u = list(map(operator.methodcaller("upper"), ["a", "b"])) + v = list(map(functools.partial(operator.add, 10), [1, 2])) + w = list(map(functools.partial(lambda a, b: a * b, 3), [1, 2])) + self.assertEqual(r, [1, 2, 3]) + self.assertEqual(s, [("a", 1), ("b", 2), ("c", 3)]) + self.assertEqual((t, u, v, w), ([1, 2], ["A", "B"], [11, 12], [3, 6])) + + def test_errors(self): + for i in range(300): + with self.assertRaises(KeyError): + list(map(operator.itemgetter("k"), [{"k": 1}, {}])) + with self.assertRaises(IndexError): + list(map(operator.itemgetter(2), [(1, 2, 3), (1,)])) + with self.assertRaises(AttributeError): + list(map(operator.attrgetter("x"), [P(1), object()])) + + +class ZipLongestRowTests(unittest.TestCase): + def test_widths(self): + for i in range(300): + a = list(itertools.zip_longest([1, 2, 3], "ab")) + b = list(itertools.zip_longest([1], [], (2, 3), fillvalue=0)) + c = list(itertools.zip_longest([1, 2])) + d = list(itertools.zip_longest([1], [2], [3], [4, 5])) + e = list(itertools.zip_longest([1], [2], [3], [4], [5, 6], fillvalue="-")) + self.assertEqual(a, [(1, "a"), (2, "b"), (3, None)]) + self.assertEqual(b, [(1, 0, 2), (0, 0, 3)]) + self.assertEqual(c, [(1,), (2,)]) + self.assertEqual(d, [(1, 2, 3, 4), (None, None, None, 5)]) + self.assertEqual(e, [(1, 2, 3, 4, 5), ("-", "-", "-", "-", 6)]) + it = iter([1, 2]) + self.assertEqual(list(itertools.zip_longest(it, it)), [(1, 2)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_map_over_getters.py b/tests/regrtest/test_map_over_getters.py new file mode 100644 index 000000000..9ba58347e --- /dev/null +++ b/tests/regrtest/test_map_over_getters.py @@ -0,0 +1,281 @@ +"""`map` over the `operator` getters and callers, and lambdas like them. + +`list(map(itemgetter(1), pairs))`, `map(attrgetter("x"), objs)` and +`map(methodcaller("area"), shapes)` read each item's part (or call each +item's method) without going through the getter's own call: the shape is +read once for the whole `map`, an attribute's place is remembered for a +run of one class's instances, and a method is looked up once per class. +These tests pin what those shortcuts must not change: every kind of item +a getter can meet, items that raise, attributes that move, and classes +that change while the `map` runs. +""" + +import unittest +from collections import namedtuple +from operator import attrgetter, itemgetter, methodcaller + +N = 400 + + +class Point: + def __init__(self, x, y): + self.x = x + self.y = y + + def norm(self): + return self.x * 2 + + def add(self, v, w=0): + return self.x + v + w + + def loop(self): + total = 0 + for k in range(3): + total += self.x + k + return total + + +class Other: + x = "class value" + + def norm(self): + return "other" + + +class Slotted: + __slots__ = ("x", "y") + + def __init__(self, x): + self.x = x + + def norm(self): + return -self.x + + +class Computed: + def __init__(self, x): + self._x = x + + @property + def x(self): + return self._x + 1000 + + def norm(self): + return self._x + + +class Fallback: + def __getattr__(self, name): + return "fallback " + name + + +class Getitem: + def __getitem__(self, key): + return ("got", key) + + +Pair = namedtuple("Pair", "x y") + + +def collect(f, items): + out = [] + try: + for value in map(f, items): + out.append(value) + except Exception as exc: # noqa: BLE001 + out.append(type(exc).__name__) + return out + + +class ItemGetters(unittest.TestCase): + def test_sequences(self): + pairs = [(i, i * 2, str(i)) for i in range(N)] + for getter in (itemgetter(1), lambda t: t[1]): + self.assertEqual(list(map(getter, pairs)), [i * 2 for i in range(N)]) + for getter in (itemgetter(-1), lambda t: t[-1]): + self.assertEqual(list(map(getter, pairs)), [str(i) for i in range(N)]) + lists = [[i, i + 1] for i in range(N)] + self.assertEqual(list(map(itemgetter(0), lists)), list(range(N))) + self.assertEqual(list(map(itemgetter(1), ["ab", "cd", "xy"] * 50)), ["b", "d", "y"] * 50) + self.assertEqual(list(map(itemgetter(0), [Pair(i, 0) for i in range(N)])), list(range(N))) + + def test_mixed_items(self): + items = [(1, 2), [3, 4], "56", {1: "one"}, Getitem(), Pair(7, 8), b"xy", range(5, 9)] + want = [2, 4, "6", "one", ("got", 1), 8, ord("y"), 6] + for _ in range(60): + self.assertEqual(list(map(itemgetter(1), items)), want) + self.assertEqual(list(map(lambda t: t[1], items)), want) + + def test_misses_raise(self): + self.assertEqual(collect(itemgetter(2), [(1, 2, 3), (4, 5)]), [3, "IndexError"]) + self.assertEqual(collect(itemgetter(1), [(1, 2), {}, (3, 4)]), [2, "KeyError"]) + self.assertEqual(collect(itemgetter(0), [(1,), 5]), [1, "TypeError"]) + self.assertEqual(collect(itemgetter("k"), [{"k": 1}, {"j": 2}]), [1, "KeyError"]) + self.assertEqual(collect(itemgetter("k"), [{"k": 1}, (1, 2)]), [1, "TypeError"]) + + def test_string_keys(self): + class Counted(dict): + def __missing__(self, key): + return "missing " + key + + class Loud(dict): + def __getitem__(self, key): + return "loud " + key + + rows = [{"k": i, "j": -i} for i in range(N)] + for getter in (itemgetter("k"), lambda d: d["k"]): + self.assertEqual(list(map(getter, rows)), list(range(N))) + mixed = [{"k": 1}, Counted(), Counted(k=2), Loud(k=3), Getitem()] + for _ in range(60): + self.assertEqual( + list(map(itemgetter("k"), mixed)), + [1, "missing k", 2, "loud k", ("got", "k")], + ) + + def test_several_items_and_no_shortcut_shapes(self): + pairs = [(i, i + 1, i + 2) for i in range(N)] + self.assertEqual(list(map(itemgetter(0, 2), pairs)), [(i, i + 2) for i in range(N)]) + self.assertEqual(list(map(itemgetter(slice(0, 2)), pairs)), [(i, i + 1) for i in range(N)]) + self.assertEqual(list(map(itemgetter(True), pairs)), [i + 1 for i in range(N)]) + + +class AttrGetters(unittest.TestCase): + def test_one_class(self): + points = [Point(i, -i) for i in range(N)] + for getter in (attrgetter("x"), lambda p: p.x): + self.assertEqual(list(map(getter, points)), list(range(N))) + self.assertEqual(list(map(attrgetter("y"), points)), [-i for i in range(N)]) + self.assertEqual(list(map(attrgetter("x", "y"), points)), [(i, -i) for i in range(N)]) + + def test_mixed_classes(self): + items = [Point(1, 2), Other(), Slotted(3), Computed(4), Fallback(), Pair(5, 6), Point(7, 8)] + want = [1, "class value", 3, 1004, "fallback x", 5, 7] + for _ in range(60): + self.assertEqual(list(map(attrgetter("x"), items)), want) + self.assertEqual(list(map(lambda o: o.x, items)), want) + + def test_instances_laid_out_differently(self): + plain = [Point(i, 0) for i in range(8)] + reordered = Point.__new__(Point) + reordered.y = "y first" + reordered.x = "x second" + seen = Point(1, 2) + vars(seen)["x"] = "through vars" + replaced = Point(1, 2) + replaced.__dict__ = {"x": "new dict"} + extra = Point(1, 2) + extra.z = 5 + del extra.y + shadow = Other() + shadow.x = "instance value" + missing = Point(1, 2) + del missing.x + items = plain + [reordered, seen, replaced, extra, shadow] + plain + want = list(range(8)) + ["x second", "through vars", "new dict", 1, "instance value"] + list(range(8)) + for _ in range(60): + self.assertEqual(list(map(attrgetter("x"), items)), want) + self.assertEqual(collect(attrgetter("x"), plain + [missing] + plain), list(range(8)) + ["AttributeError"]) + self.assertEqual(collect(attrgetter("y"), [Slotted(1)]), ["AttributeError"]) + + def test_class_changes_while_the_map_runs(self): + class Shifty: + def __init__(self, x): + self.x = x + + items = [Shifty(i) for i in range(12)] + + def source(): + for i, item in enumerate(items): + if i == 4: + Shifty.x = property(lambda self: "from property") + if i == 8: + del Shifty.x + yield item + + self.assertEqual( + list(map(attrgetter("x"), source())), + [0, 1, 2, 3] + ["from property"] * 4 + [8, 9, 10, 11], + ) + + def swapping(): + for i, item in enumerate(items): + if i == 6: + item.__class__ = Other + yield item + + self.assertEqual(list(map(attrgetter("x"), swapping())), list(range(12))) + + def test_dotted_names(self): + outer = [Point(Point(i, 0), 0) for i in range(N)] + self.assertEqual(list(map(attrgetter("x.x"), outer)), list(range(N))) + + +class MethodCallers(unittest.TestCase): + def test_one_class(self): + points = [Point(i, 0) for i in range(N)] + self.assertEqual(list(map(methodcaller("norm"), points)), [2 * i for i in range(N)]) + self.assertEqual(list(map(methodcaller("add", 5), points)), [i + 5 for i in range(N)]) + self.assertEqual(list(map(methodcaller("add", 5, 2), points)), [i + 7 for i in range(N)]) + self.assertEqual(list(map(methodcaller("add", 1, w=4), points)), [i + 5 for i in range(N)]) + self.assertEqual(list(map(methodcaller("loop"), points)), [3 * i + 3 for i in range(N)]) + + def test_mixed_receivers(self): + shadowed = Point(9, 0) + shadowed.norm = lambda: "instance callable" + items = [Point(1, 0), Other(), Slotted(3), Computed(4), shadowed, Point(5, 0)] + want = [2, "other", -3, 4, "instance callable", 10] + for _ in range(60): + self.assertEqual(list(map(methodcaller("norm"), items)), want) + words = ["ab", "Cd", "eF"] * 40 + self.assertEqual(list(map(methodcaller("upper"), words)), [w.upper() for w in words]) + self.assertEqual(list(map(methodcaller("split", "b"), ["abc", "xby"])), [["a", "c"], ["x", "y"]]) + + def test_errors(self): + self.assertEqual(collect(methodcaller("norm"), [Point(1, 0), 5]), [2, "AttributeError"]) + self.assertEqual(collect(methodcaller("add"), [Point(1, 0)]), ["TypeError"]) + self.assertEqual(collect(methodcaller("add", 1, 2, 3), [Point(1, 0)]), ["TypeError"]) + + class Bad: + def norm(self): + raise KeyError("inside") + + self.assertEqual(collect(methodcaller("norm"), [Point(1, 0), Bad(), Point(2, 0)]), [2, "KeyError"]) + + def test_class_changes_while_the_map_runs(self): + class Shifty: + def __init__(self, x): + self.x = x + + def norm(self): + return self.x + + items = [Shifty(i) for i in range(12)] + + def source(): + for i, item in enumerate(items): + if i == 4: + Shifty.norm = lambda self: self.x * 100 + if i == 8: + item.norm = lambda: "own" + yield item + + self.assertEqual( + list(map(methodcaller("norm"), source())), + [0, 1, 2, 3, 400, 500, 600, 700, "own", 900, 1000, 1100], + ) + + def test_other_consumers(self): + points = [Point((i * 7) % 11, i) for i in range(60)] + caller = methodcaller("norm") + for _ in range(40): + self.assertEqual([v for v in map(caller, points)], [p.x * 2 for p in points]) + self.assertEqual(max(points, key=caller).x, 10) + self.assertEqual(sorted(points, key=caller)[0].x, 0) + self.assertEqual(sum(map(attrgetter("x"), points)), sum(p.x for p in points)) + self.assertEqual(min(map(itemgetter(0), [(p.x, p.y) for p in points])), 0) + self.assertEqual([caller(p) for p in points[:5]], [p.x * 2 for p in points[:5]]) + self.assertEqual(dict(zip(map(attrgetter("y"), points), map(caller, points)))[3], points[3].x * 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_mapping_mixins_through_builtins.py b/tests/regrtest/test_mapping_mixins_through_builtins.py new file mode 100644 index 000000000..3590da278 --- /dev/null +++ b/tests/regrtest/test_mapping_mixins_through_builtins.py @@ -0,0 +1,549 @@ +"""`collections.abc.Mapping` subclasses handed to `dict`, `**` and their views. + +`dict(m)`, `{**m}`, `f(**m)` and `d.update(m)` read a mapping through +`m.keys()` and `m[key]`. For a class that takes `keys` from `Mapping` +unchanged, the keys are `iter(m)`'s and no view or bound method is made; +`list`, `sorted`, `set` and the like over `m.keys()`, `m.values()` and +`m.items()` take what the view's generator would yield without making +it. These tests pin the results, the order of the calls a mapping sees, +which errors come out of `**`, and that a class or a view changed by +hand goes back to the long way round. +""" + +import collections.abc as abc +import traceback +import unittest +from collections import ChainMap, OrderedDict, UserDict + +ROUNDS = 300 + + +class Wraps(abc.MutableMapping): + def __init__(self, d=None): + self._d = dict(d or {}) + + def __getitem__(self, k): + return self._d[k] + + def __setitem__(self, k, v): + self._d[k] = v + + def __delitem__(self, k): + del self._d[k] + + def __iter__(self): + return iter(self._d) + + def __len__(self): + return len(self._d) + + +class Logged(abc.Mapping): + def __init__(self, d): + self._d = d + self.log = [] + + def __getitem__(self, k): + self.log.append("get") + return self._d[k] + + def __iter__(self): + self.log.append("iter") + return iter(self._d) + + def __len__(self): + self.log.append("len") + return len(self._d) + + +class Sorted(abc.Mapping): + """Keys from a generator, values computed.""" + + def __init__(self, d): + self._d = d + + def __getitem__(self, k): + return self._d[k] * 2 + + def __iter__(self): + for k in sorted(self._d, reverse=True): + yield k + + def __len__(self): + return len(self._d) + + +class OwnKeys(abc.Mapping): + def __init__(self, d): + self._d = d + + def __getitem__(self, k): + return self._d[k] + + def __iter__(self): + return iter(self._d) + + def __len__(self): + return len(self._d) + + def keys(self): + return ["b", "a"] + + +class Fails(abc.Mapping): + def __init__(self, exc): + self.exc = exc + + def __getitem__(self, k): + if k == "b": + raise self.exc + return 1 + + def __iter__(self): + return iter(["a", "b", "c"]) + + def __len__(self): + return 3 + + +class Folded(abc.MutableMapping): + """A case-insensitive mapping, as HTTP header classes are written.""" + + def __init__(self, data=None): + self._store = {} + if data: + self.update(data) + + def __setitem__(self, key, value): + self._store[key.lower()] = (key, value) + + def __getitem__(self, key): + return self._store[key.lower()][1] + + def __delitem__(self, key): + del self._store[key.lower()] + + def __iter__(self): + return (cased for cased, _ in self._store.values()) + + def __len__(self): + return len(self._store) + + +def kw(**k): + return sorted(k.items()) + + +def outcome(f): + try: + return f() + except Exception as e: + return type(e).__name__, str(e), type(e.__cause__).__name__ + + +BASE = {"k%d" % i: i for i in range(7)} + + +class Results(unittest.TestCase): + def check(self, make, pairs): + keys = [k for k, _ in pairs] + values = [v for _, v in pairs] + want = dict(pairs) + for _ in range(ROUNDS): + m = make() + self.assertEqual(dict(m), want) + self.assertEqual(list(dict(m)), keys) + self.assertEqual({**m}, want) + self.assertEqual(kw(**m), sorted(pairs)) + d = {"zz": 0} + d.update(m) + self.assertEqual(d, {"zz": 0, **want}) + self.assertEqual(list(m.keys()), keys) + self.assertEqual(list(m.values()), values) + self.assertEqual(list(m.items()), pairs) + self.assertEqual(sorted(m.items()), sorted(pairs)) + self.assertEqual(tuple(m.keys()), tuple(keys)) + self.assertEqual(sorted(set(m.values())), sorted(set(values))) + self.assertEqual([k for k in m.keys()], keys) + self.assertEqual([v for v in m.values()], values) + self.assertEqual([(k, v) for k, v in m.items()], pairs) + self.assertEqual(",".join(m.keys()), ",".join(keys)) + self.assertEqual(len(m.keys()), len(keys)) + self.assertEqual(dict(m.items()), want) + self.assertEqual(list(zip(m.keys(), m.values())), pairs) + self.assertTrue(m == want) + + def test_a_wrapped_dict(self): + self.check(lambda: Wraps(BASE), list(BASE.items())) + self.check(Wraps, []) + + def test_keys_from_a_generator(self): + self.check( + lambda: Sorted(BASE), [(k, BASE[k] * 2) for k in sorted(BASE, reverse=True)] + ) + + def test_a_user_dict_and_a_chain_map(self): + self.check(lambda: UserDict(BASE), list(BASE.items())) + both = ChainMap({"a": 1}, BASE) + self.check(lambda: both, [(k, both[k]) for k in both]) + + def test_folded_keys(self): + self.check(lambda: Folded({"Aa": 1, "bB": 2}), [("Aa", 1), ("bB", 2)]) + + def test_a_class_with_its_own_keys(self): + for _ in range(ROUNDS): + m = OwnKeys({"a": 1, "b": 2, "c": 3}) + self.assertEqual(list(dict(m).items()), [("b", 2), ("a", 1)]) + self.assertEqual(list({**m}.items()), [("b", 2), ("a", 1)]) + self.assertEqual(kw(**m), [("a", 1), ("b", 2)]) + + def test_an_instance_with_its_own_keys(self): + for _ in range(ROUNDS): + m = Wraps(BASE) + m.keys = lambda: ["k1"] + self.assertEqual((dict(m), {**m}), ({"k1": 1}, {"k1": 1})) + + def test_a_class_that_gains_and_loses_keys(self): + class Plain(abc.Mapping): + def __init__(self): + self._d = {"a": 1, "b": 2} + + def __getitem__(self, k): + return self._d[k] + + def __iter__(self): + return iter(self._d) + + def __len__(self): + return 2 + + for _ in range(ROUNDS): + p = Plain() + self.assertEqual(dict(p), {"a": 1, "b": 2}) + Plain.keys = lambda self: ["b"] + self.assertEqual(dict(p), {"b": 2}) + del Plain.keys + self.assertEqual(dict(p), {"a": 1, "b": 2}) + + +class Calls(unittest.TestCase): + def test_what_each_consumer_asks_of_the_mapping(self): + seven = ["get"] * 7 + for _ in range(ROUNDS): + m = Logged(dict(BASE)) + + def asked(f): + del m.log[:] + f() + return list(m.log) + + # Nothing but the keys and each value: no length is asked. + self.assertEqual(asked(lambda: dict(m)), ["iter"] + seven) + self.assertEqual(asked(lambda: {**m}), ["iter"] + seven) + self.assertEqual(asked(lambda: kw(**m)), ["iter"] + seven) + self.assertEqual(asked(lambda: {}.update(m)), ["iter"] + seven) + # `list` and `sorted` ask a view its length first. + self.assertEqual(asked(lambda: list(m.keys())), ["len", "iter"]) + self.assertEqual(asked(lambda: list(m.values())), ["len", "iter"] + seven) + self.assertEqual(asked(lambda: sorted(m.items())), ["len", "iter"] + seven) + self.assertEqual(asked(lambda: [v for v in m.values()]), ["iter"] + seven) + + def test_values_are_read_as_the_keys_come(self): + order = [] + + class Interleaved(abc.Mapping): + def __getitem__(self, k): + order.append(("get", k)) + return k + + def __iter__(self): + for k in "ab": + order.append(("key", k)) + yield k + + def __len__(self): + return 2 + + # A view's generator reads each value as its key comes. + want = [("key", "a"), ("get", "a"), ("key", "b"), ("get", "b")] + # `dict` and `**` list the keys first. + listed = [("key", "a"), ("key", "b"), ("get", "a"), ("get", "b")] + for _ in range(ROUNDS): + for consume, order_wanted in ( + (lambda m: list(m.values()), want), + (lambda m: list(m.items()), want), + (lambda m: [v for v in m.values()], want), + (lambda m: dict(m), listed), + (lambda m: {**m}, listed), + (lambda m: kw(**m), listed), + (lambda m: {}.update(m), listed), + ): + del order[:] + consume(Interleaved()) + self.assertEqual(order, order_wanted) + + +class Errors(unittest.TestCase): + def test_an_error_from_getitem(self): + for _ in range(ROUNDS): + for exc in (ValueError("v"), IndexError("i")): + name = type(exc).__name__ + shown = (name, str(exc), "NoneType") + b = Fails(exc) + for f in ( + lambda: dict(b), + lambda: {**b}, + lambda: kw(**b), + lambda: list(b.values()), + lambda: list(b.items()), + lambda: [v for v in b.values()], + lambda: sorted(b.items()), + ): + self.assertEqual(outcome(f), shown) + self.assertEqual(list(b.keys()), ["a", "b", "c"]) + + def test_a_key_error_under_a_keyword_splat_reads_as_a_repeat(self): + for _ in range(ROUNDS): + b = Fails(KeyError("b")) + self.assertEqual(outcome(lambda: dict(b)), ("KeyError", "'b'", "NoneType")) + self.assertEqual(outcome(lambda: {**b}), ("KeyError", "'b'", "NoneType")) + name, message, _ = outcome(lambda: kw(**b)) + self.assertEqual(name, "TypeError") + self.assertTrue( + message.endswith("got multiple values for keyword argument 'b'"), message + ) + + def test_a_stop_iteration_inside_a_view(self): + for _ in range(ROUNDS): + b = Fails(StopIteration("s")) + for f in (lambda: dict(b), lambda: {**b}, lambda: kw(**b)): + self.assertEqual(outcome(f), ("StopIteration", "s", "NoneType")) + # The views' iterators are generators: PEP 479 applies. + wrapped = ("RuntimeError", "generator raised StopIteration", "StopIteration") + for f in ( + lambda: list(b.values()), + lambda: list(b.items()), + lambda: [v for v in b.values()], + lambda: sorted(b.items()), + ): + self.assertEqual(outcome(f), wrapped) + + +class ChangedByHand(unittest.TestCase): + def test_a_patched_view_is_used_as_patched(self): + m = Wraps({"a": 1, "b": 2}) + for _ in range(ROUNDS): + before = (list(m.keys()), dict(m)) + original = abc.KeysView.__iter__ + + def shouting(self): + for k in self._mapping: + yield k.upper() + + abc.KeysView.__iter__ = shouting + try: + self.assertEqual(list(m.keys()), ["A", "B"]) + self.assertEqual(sorted(m.keys()), ["A", "B"]) + self.assertEqual(outcome(lambda: dict(m)), ("KeyError", "'A'", "NoneType")) + self.assertEqual(outcome(lambda: {**m}), ("KeyError", "'A'", "NoneType")) + finally: + abc.KeysView.__iter__ = original + self.assertEqual((list(m.keys()), dict(m)), before) + self.assertEqual(before, (["a", "b"], {"a": 1, "b": 2})) + + def test_the_dict_changes_under_a_view(self): + for _ in range(ROUNDS): + m = Wraps(BASE) + + def grow(): + for _ in m.keys(): + m["new"] = 1 + + name, message, _ = outcome(grow) + self.assertEqual( + (name, message), ("RuntimeError", "dictionary changed size during iteration") + ) + + +def frames(e): + return [f.name for f in traceback.extract_tb(e.__traceback__)] + + +def raised(f): + try: + f() + except Exception as e: + return type(e).__name__, str(e), frames(e)[1:] + return None + + +class TwoDicts(Wraps): + """Iterates one dict and reads another.""" + + def __init__(self, d): + super().__init__(d) + self._other = {k: v * 10 for k, v in d.items()} + + def __getitem__(self, k): + return self._other[k] + + +class MissesOne(Wraps): + def __init__(self, d): + super().__init__(d) + self._other = dict(d) + del self._other["k3"] + + def __getitem__(self, k): + return self._other[k] + + +class Backwards(Wraps): + def __iter__(self): + return reversed(self._d) + + +class RaisesAtOne(Wraps): + def __getitem__(self, k): + if k == "k3": + raise ValueError("three") + return self._d[k] + + +class BrokenIter(Wraps): + def __iter__(self): + raise ValueError("iter") + + +class Doubling(UserDict): + def __getitem__(self, k): + return super().__getitem__(k) * 2 + + +class WithMissing(UserDict): + def __missing__(self, k): + return "missing" + + +class SortedKeys(UserDict): + def __iter__(self): + return iter(sorted(self.data, reverse=True)) + + +class NotJustAWrapper(unittest.TestCase): + """Mappings that do more than wrap one dict keep the whole protocol.""" + + def test_another_dict_behind_getitem(self): + want = {k: v * 10 for k, v in BASE.items()} + for _ in range(ROUNDS): + m = TwoDicts(BASE) + self.assertEqual((dict(m), {**m}), (want, want)) + self.assertEqual(list(m.values()), list(want.values())) + self.assertEqual(list(m.items()), list(want.items())) + b = Backwards(BASE) + self.assertEqual(list(dict(b)), list(BASE)[::-1]) + self.assertEqual(list(b.keys()), list(BASE)[::-1]) + self.assertEqual(list(b.values()), list(BASE.values())[::-1]) + + def test_an_error_keeps_every_frame(self): + for _ in range(ROUNDS): + m = MissesOne(BASE) + self.assertEqual( + raised(lambda: dict(m)), ("KeyError", "'k3'", ["", "__getitem__"]) + ) + self.assertEqual( + raised(lambda: {**m}), ("KeyError", "'k3'", ["", "__getitem__"]) + ) + # A view's read happens inside the view's own generator. + self.assertEqual( + raised(lambda: list(m.values())), + ("KeyError", "'k3'", ["", "__iter__", "__getitem__"]), + ) + r = RaisesAtOne(BASE) + self.assertEqual( + raised(lambda: sorted(r.items())), + ("ValueError", "three", ["", "__iter__", "__getitem__"]), + ) + b = BrokenIter(BASE) + self.assertEqual( + raised(lambda: dict(b)), ("ValueError", "iter", ["", "__iter__", "__iter__"]) + ) + self.assertEqual( + raised(lambda: list(b.values())), + ("ValueError", "iter", ["", "__iter__", "__iter__"]), + ) + + def test_user_dict_subclasses(self): + for _ in range(ROUNDS): + self.assertEqual(dict(Doubling(BASE)), {k: v * 2 for k, v in BASE.items()}) + self.assertEqual(list(Doubling(BASE).values()), [v * 2 for v in BASE.values()]) + self.assertEqual(dict(WithMissing(BASE)), BASE) + self.assertEqual(WithMissing(BASE)["nope"], "missing") + s = SortedKeys(BASE) + self.assertEqual(list(dict(s)), sorted(BASE, reverse=True)) + self.assertEqual(list(s.items()), sorted(BASE.items(), reverse=True)) + + def test_the_wrapped_dict_is_read_as_it_is_now(self): + for _ in range(ROUNDS): + m = Wraps(BASE) + first = dict(m) + m["z"] = 26 + del m["k0"] + self.assertEqual(first, BASE) + self.assertEqual(dict(m), {**{k: v for k, v in BASE.items() if k != "k0"}, "z": 26}) + self.assertEqual(list(m.keys())[-1], "z") + m._d = {"swapped": 1} + self.assertEqual((dict(m), list(m.items())), ({"swapped": 1}, [("swapped", 1)])) + # The copy is its own dict. + copy = dict(m) + copy["only in the copy"] = 1 + self.assertFalse("only in the copy" in m) + u = UserDict(BASE) + u.data = {"new": 1} + self.assertEqual((dict(u), list(u.values())), ({"new": 1}, [1])) + + +class YieldFromADict(unittest.TestCase): + def test_keys_views_and_ends(self): + def deleg(d): + yield from d + + def then(d): + x = yield from d + yield ("done", x) + + for _ in range(ROUNDS): + d = dict(BASE) + self.assertEqual(list(deleg(d)), list(d)) + self.assertEqual(list(deleg({})), []) + self.assertEqual(list(then({"q": 1})), ["q", ("done", None)]) + self.assertEqual(list(deleg(d.items())), list(d.items())) + self.assertEqual(list(deleg(d.values())), list(d.values())) + self.assertEqual(list(deleg(reversed(d))), list(d)[::-1]) + self.assertEqual(list(deleg(OrderedDict(d))), list(d)) + g = deleg(d) + first = next(g) + d["k0"] = 99 + self.assertEqual([first, next(g)], ["k0", "k1"]) + self.assertEqual(g.send(None), "k2") + g.close() + self.assertEqual(list(g), []) + + def test_a_dict_that_grows_under_it(self): + def deleg(d): + yield from d + + for _ in range(ROUNDS): + d = dict(BASE) + g = deleg(d) + next(g) + d["zzz"] = 1 + with self.assertRaises(RuntimeError) as caught: + next(g) + self.assertEqual( + str(caught.exception), "dictionary changed size during iteration" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_mappingproxy_str.py b/tests/regrtest/test_mappingproxy_str.py new file mode 100644 index 000000000..0be100822 --- /dev/null +++ b/tests/regrtest/test_mappingproxy_str.py @@ -0,0 +1,35 @@ +"""`str()` and `format()` of a `mappingproxy`. + +As CPython's `mappingproxy_str`, a proxy's `str()` is its mapping's (a +class's `__dict__` prints as a dict), and `format()` with an empty spec +is that `str()`, as is `%s`; `repr()` keeps the `mappingproxy(...)` wrapper, and a +non-empty spec raises `TypeError`. +""" + +import types +import unittest + + +class MappingProxyStrTests(unittest.TestCase): + def test_str_and_format(self): + m = types.MappingProxyType({"a": 1}) + self.assertEqual(str(m), "{'a': 1}") + self.assertEqual(f"{m}", "{'a': 1}") + self.assertEqual(format(m), "{'a': 1}") + self.assertEqual(repr(m), "mappingproxy({'a': 1})") + self.assertEqual(f"{m!r}", "mappingproxy({'a': 1})") + with self.assertRaises(TypeError): + format(m, "x") + self.assertEqual("%s" % m, "{'a': 1}") + self.assertEqual("%s|%r" % (m, m), "{'a': 1}|mappingproxy({'a': 1})") + + def test_class_dict(self): + class C: + x = 1 + + self.assertTrue(str(C.__dict__).startswith("{")) + self.assertTrue(repr(C.__dict__).startswith("mappingproxy({")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_match_statements_in_compiled_code.py b/tests/regrtest/test_match_statements_in_compiled_code.py new file mode 100644 index 000000000..9ae856bdb --- /dev/null +++ b/tests/regrtest/test_match_statements_in_compiled_code.py @@ -0,0 +1,454 @@ +"""`match` statements keep to compiled code. + +The pattern-matching instructions (`MATCH_SEQUENCE`, `MATCH_MAPPING`, +`GET_LEN`, `MATCH_KEYS`, `MATCH_CLASS`) used to leave compiled code at +every pattern. Their plain cases now run there. These tests run each kind +of pattern in loops hot enough to be compiled and pin the results, +including every case that still has to take the full handler: user +sequence and mapping classes, properties, `__getattr__`, slots, metaclass +instance checks, and the errors a class pattern raises. +""" + +import collections +import collections.abc +import dataclasses +import typing +import unittest + +N = 400 + + +@dataclasses.dataclass +class Point: + x: int + y: int = 0 + + +class Shape: + __match_args__ = ("kind", "size") + + def __init__(self, kind, size): + self.kind = kind + self.size = size + + +class Slotted: + __slots__ = ("a", "b") + __match_args__ = ("a", "b") + + def __init__(self, a, b): + self.a = a + self.b = b + + +class Computed: + __match_args__ = ("double",) + + def __init__(self, v): + self.v = v + + @property + def double(self): + return self.v * 2 + + +class Lazy: + def __getattr__(self, name): + if name == "ghost": + return "boo" + raise AttributeError(name) + + +class MyInt(int): + pass + + +class Seq(collections.abc.Sequence): + def __init__(self, items): + self.items = list(items) + self.len_calls = 0 + + def __len__(self): + self.len_calls += 1 + return len(self.items) + + def __getitem__(self, i): + return self.items[i] + + +class Map(collections.abc.Mapping): + def __init__(self, d): + self.d = dict(d) + + def __getitem__(self, k): + return self.d[k] + + def __iter__(self): + return iter(self.d) + + def __len__(self): + return len(self.d) + + +def classify_value(v): + match v: + case 0: + return "zero" + case 1 | 2: + return "small" + case "a": + return "letter" + case None: + return "none" + case True: + return "true" + case _: + return "other" + + +def classify_seq(s): + match s: + case []: + return "empty" + case [x]: + return ("one", x) + case [x, y]: + return ("two", x, y) + case [x, *rest, z]: + return ("many", x, len(rest), z) + case _: + return "not a sequence" + + +def classify_map(m): + match m: + case {"kind": "a", "value": v}: + return ("a", v) + case {"kind": k, **rest}: + return ("kind", k, sorted(rest)) + case {1: one}: + return ("int key", one) + case {}: + return "mapping" + case _: + return "not a mapping" + + +def classify_obj(o): + match o: + case Point(x=0, y=0): + return "origin" + case Point(x=0, y=y): + return ("on y", y) + case Point(x, y) if x == y: + return ("diagonal", x) + case Point(): + return "point" + case Shape("sq", size): + return ("square", size) + case Shape(kind=k) if k.startswith("c"): + return ("round", k) + case Slotted(a, b): + return ("slotted", a, b) + case Computed(d): + return ("computed", d) + case Lazy(ghost=g): + return ("lazy", g) + case _: + return "unknown" + + +def classify_builtin(v): + match v: + case bool(b): + return ("bool", b) + case MyInt(n): + return ("myint", int(n)) + case int(n) if n > 5: + return ("big", n) + case int(): + return "int" + case str() as s: + return ("str", len(s)) + case float(f): + return ("float", f) + case bytes(b): + return ("bytes", b) + case list(xs) | tuple(xs): + return ("seq", len(xs)) + case dict(d): + return ("dict", len(d)) + case _: + return "other" + + +class Patterns(unittest.TestCase): + def repeat(self, fn, inputs, expected): + for _ in range(N): + got = [fn(v) for v in inputs] + self.assertEqual(got, expected) + + def test_literals(self): + self.repeat( + classify_value, + [0, 1, 2, "a", None, True, False, 3.5, "b", 0.0], + ["zero", "small", "small", "letter", "none", "small", "zero", "other", "other", "zero"], + ) + + def test_sequences(self): + seq = Seq([7, 8, 9]) + self.repeat( + classify_seq, + [[], (), [1], (1, 2), [1, 2, 3, 4], "ab", b"ab", {1, 2}, range(2), seq, iter([1])], + [ + "empty", + "empty", + ("one", 1), + ("two", 1, 2), + ("many", 1, 2, 4), + "not a sequence", + "not a sequence", + "not a sequence", + ("two", 0, 1), + ("many", 7, 1, 9), + "not a sequence", + ], + ) + self.assertGreater(seq.len_calls, 0) + + def test_mappings(self): + counted = collections.defaultdict(list, kind="b") + self.repeat( + classify_map, + [ + {"kind": "a", "value": 3}, + {"kind": "b", "extra": 1, "more": 2}, + {1: "one"}, + {}, + [], + Map({"kind": "a", "value": 9}), + collections.OrderedDict(kind="z"), + counted, + {"value": 1}, + ], + [ + ("a", 3), + ("kind", "b", ["extra", "more"]), + ("int key", "one"), + "mapping", + "not a mapping", + ("a", 9), + ("kind", "z", []), + ("kind", "b", []), + "mapping", + ], + ) + self.assertEqual(dict(counted), {"kind": "b"}) + + def test_classes(self): + self.repeat( + classify_obj, + [ + Point(0), + Point(0, 5), + Point(3, 3), + Point(1, 2), + Shape("sq", 4), + Shape("circle", 1), + Shape("tri", 3), + Slotted(1, 2), + Computed(21), + Lazy(), + object(), + 5, + ], + [ + "origin", + ("on y", 5), + ("diagonal", 3), + "point", + ("square", 4), + ("round", "circle"), + "unknown", + ("slotted", 1, 2), + ("computed", 42), + ("lazy", "boo"), + "unknown", + "unknown", + ], + ) + + def test_builtin_classes(self): + self.repeat( + classify_builtin, + [True, MyInt(3), 9, 2, "abc", 1.5, b"x", [1, 2], (1,), {"k": 1}, None, {1}], + [ + ("bool", True), + ("myint", 3), + ("big", 9), + "int", + ("str", 3), + ("float", 1.5), + ("bytes", b"x"), + ("seq", 2), + ("seq", 1), + ("dict", 1), + "other", + "other", + ], + ) + + def test_missing_and_deleted_attributes(self): + def read(o): + match o: + case Shape(kind=k, size=s): + return (k, s) + case Shape(): + return "partial" + return None + + whole, partial = Shape("a", 1), Shape("b", 2) + del partial.size + for _ in range(N): + got = (read(whole), read(partial)) + self.assertEqual(got, (("a", 1), "partial")) + whole.size = 10 + self.assertEqual(read(whole), ("a", 10)) + Shape.size = "class default" + try: + self.assertEqual(read(partial), ("b", "class default")) + finally: + del Shape.size + + def test_instance_checks_through_metaclasses(self): + class Sized(collections.abc.Sized): + def __len__(self): + return 3 + + @typing.runtime_checkable + class Named(typing.Protocol): + name: str + + class WithName: + name = "n" + + def probe(o): + match o: + case collections.abc.Sized(): + return "sized" + case Named(): + return "named" + return "neither" + + for _ in range(N // 4): + got = [probe(v) for v in ([1], Sized(), WithName(), 5)] + self.assertEqual(got, ["sized", "sized", "named", "neither"]) + + def test_class_pattern_errors(self): + class NoArgs: + pass + + class BadArgs: + __match_args__ = ["a"] + + def positional(o): + match o: + case NoArgs(x): + return x + + def bad(o): + match o: + case BadArgs(x): + return x + + def twice(o): + match o: + case Shape(k, kind=again): + return k, again + + def too_many(o): + match o: + case Shape(a, b, c): + return a + + def not_a_class(o, target): + match o: + case target(): + return True + + for _ in range(3): + with self.assertRaises(TypeError): + positional(NoArgs()) + with self.assertRaises(TypeError): + bad(BadArgs()) + with self.assertRaises(TypeError): + twice(Shape("a", 1)) + with self.assertRaises(TypeError): + too_many(Shape("a", 1)) + with self.assertRaises(TypeError): + not_a_class(1, 5) + self.assertIsNone(positional(5)) + + def test_duplicate_value_keys(self): + class K: + A = "k" + B = "k" + + def probe(m): + match m: + case {K.A: a, K.B: b}: + return a, b + + # (A subject with fewer keys than the pattern fails its length + # check before the keys are looked at.) + self.assertIsNone(probe({"k": 1})) + for _ in range(3): + with self.assertRaises(ValueError): + probe({"k": 1, "j": 2}) + + def test_nested_patterns_and_captures(self): + def walk(node): + match node: + case {"op": "add", "args": [left, right]}: + return walk(left) + walk(right) + case {"op": "neg", "args": [inner]}: + return -walk(inner) + case {"value": int(v) | float(v)}: + return v + case [Point(x=x), Point(x=x2)] as pair: + return x + x2 + len(pair) + case _: + raise ValueError(node) + + tree = { + "op": "add", + "args": [ + {"op": "neg", "args": [{"value": 2}]}, + {"op": "add", "args": [{"value": 1.5}, {"value": 4}]}, + ], + } + for _ in range(N): + got = (walk(tree), walk([Point(1), Point(2)])) + self.assertEqual(got, (3.5, 5)) + + def test_subject_changes_between_iterations(self): + def kind(v): + match v: + case [a, b]: + return "pair" + case {"a": _}: + return "map" + case Point(x=0): + return "point0" + case str(): + return "str" + return "none" + + items = [[1, 2], {"a": 1}, Point(0), "s", 3, (1, 2), {"b": 1}, Point(1)] + for _ in range(N): + got = [kind(v) for v in items] + self.assertEqual(got, ["pair", "map", "point0", "str", "none", "pair", "none", "none"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_math_gcd_lcm_words.py b/tests/regrtest/test_math_gcd_lcm_words.py new file mode 100644 index 000000000..9de65d02c --- /dev/null +++ b/tests/regrtest/test_math_gcd_lcm_words.py @@ -0,0 +1,82 @@ +"""`math.gcd` and `math.lcm` of machine-word arguments, in hot loops. + +Word arguments take a word-sized path; results past 63 bits, big +arguments, bools, zeros, negatives, and bad types must answer as the +general path does. +""" + +import math +import unittest + + +def ref_gcd(*xs): + g = 0 + for x in xs: + a, b = abs(g), abs(x) + while b: + a, b = b, a % b + g = a + return g + + +def ref_lcm(*xs): + if not xs: + return 1 + acc = abs(xs[0]) + for x in xs[1:]: + if acc == 0 or x == 0: + acc = 0 + else: + acc = acc * abs(x) // ref_gcd(acc, x) + return acc + + +class GcdLcmWords(unittest.TestCase): + def test_loops(self): + for i in range(-3000, 3000): + self.assertEqual(math.gcd(i, 360), ref_gcd(i, 360)) + self.assertEqual(math.lcm(i, 6), ref_lcm(i, 6)) + self.assertEqual(math.lcm(4, 6, i), ref_lcm(4, 6, i)) + + def test_edges(self): + big = 2**63 + cases = [ + (), + (0,), + (-7,), + (0, 0), + (True, 4), + (False, 4), + (-(2**63), 0), + (-(2**63), -(2**63)), + (2**62, 3), + (2**40, 2**40 + 1), + (big, 6), + (big * 3, 2**70), + (12, 18, 30), + (7, 0, 5), + ] + for args in cases: + with self.subTest(args=args): + self.assertEqual(math.gcd(*args), ref_gcd(*args)) + self.assertEqual(math.lcm(*args), ref_lcm(*args)) + self.assertIs(type(math.gcd(*args)), int) + self.assertIs(type(math.lcm(*args)), int) + + def test_lcm_past_a_word(self): + self.assertEqual(math.lcm(2**40, 3**20), 2**40 * 3**20) + self.assertEqual(math.lcm(2**62, 3), 3 * 2**62) + self.assertEqual(math.lcm(-(2**63), 1), 2**63) + + def test_bad_types(self): + for _ in range(200): + with self.assertRaises(TypeError): + math.gcd(4, 2.0) + with self.assertRaises(TypeError): + math.lcm(4, "2") + with self.assertRaises(TypeError): + math.lcm(0, 2.5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_math_isclose_plain_numbers.py b/tests/regrtest/test_math_isclose_plain_numbers.py new file mode 100644 index 000000000..79742dd62 --- /dev/null +++ b/tests/regrtest/test_math_isclose_plain_numbers.py @@ -0,0 +1,71 @@ +"""`math.isclose` of two plain numbers at the default tolerances. + +Two floats or ints with no keywords compare at once; infinities, NaNs, +ints too large for a float, other number types and keyword tolerances +must answer as the general path does. +""" + +import math +import unittest +from decimal import Decimal +from fractions import Fraction + + +class IscloseTests(unittest.TestCase): + def test_plain_pairs(self): + cases = [ + (1.0, 1.0, True), + (1.0, 1.0 + 1e-10, True), + (1.0, 1.0 + 1e-8, False), + (0.0, 1e-300, False), + (0.0, 0.0, True), + (-0.0, 0.0, True), + (3, 3, True), + (3, 3.0000000001, True), + (3, 4, False), + (10**15, 10**15 + 1, True), + (2**53, 2**53 + 1, True), + (-5, 5, False), + ] + for _ in range(200): + for a, b, want in cases: + self.assertIs(math.isclose(a, b), want, (a, b)) + self.assertIs(math.isclose(b, a), want, (b, a)) + + def test_specials(self): + inf, nan = math.inf, math.nan + self.assertIs(math.isclose(inf, inf), True) + self.assertIs(math.isclose(-inf, -inf), True) + self.assertIs(math.isclose(inf, -inf), False) + self.assertIs(math.isclose(inf, 1e308), False) + self.assertIs(math.isclose(nan, nan), False) + self.assertIs(math.isclose(nan, 1.0), False) + self.assertIs(math.isclose(1, nan), False) + + def test_big_and_other_numbers(self): + self.assertIs(math.isclose(10**30, 10**30 + 1), True) + self.assertIs(math.isclose(10**30, 2 * 10**30), False) + with self.assertRaises(OverflowError): + math.isclose(10**400, 1.0) + self.assertIs(math.isclose(True, 1.0), True) + self.assertIs(math.isclose(Fraction(1, 3), 1 / 3), True) + self.assertIs(math.isclose(Decimal("2.5"), 2.5), True) + + def test_keywords_and_errors(self): + self.assertIs(math.isclose(1.0, 1.1, rel_tol=0.2), True) + self.assertIs(math.isclose(0.0, 1e-10, abs_tol=1e-9), True) + self.assertIs(math.isclose(1.0, 1.1, rel_tol=0.01), False) + with self.assertRaises(ValueError): + math.isclose(1.0, 1.0, rel_tol=-1) + with self.assertRaises(TypeError): + math.isclose(1.0) + with self.assertRaises(TypeError): + math.isclose(1.0, 2.0, 3.0) + with self.assertRaises(TypeError): + math.isclose("1", 1.0) + with self.assertRaises(TypeError): + math.isclose(1.0, 1.0, tol=1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_membership_leaf_eq_scan.py b/tests/regrtest/test_membership_leaf_eq_scan.py new file mode 100644 index 000000000..80d454f35 --- /dev/null +++ b/tests/regrtest/test_membership_leaf_eq_scan.py @@ -0,0 +1,103 @@ +"""`x in seq` of an instance whose `__eq__` is a short pure method. + +A list or tuple scan resolves the item's `__eq__` once and calls it on +each member of the item's own class. Members of other classes, answers +that aren't bools, methods with effects, and lists that change while +scanned must all keep CPython's results. +""" + +import unittest + + +class Pt: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x = x + self.y = y + + def __eq__(self, o): + if not isinstance(o, Pt): + return NotImplemented + return (self.x, self.y) == (o.x, o.y) + + __hash__ = None + + +class SubPt(Pt): + __slots__ = () + + +class Odd: + def __init__(self, v): + self.v = v + + def __eq__(self, o): + return self.v if isinstance(o, Odd) else NotImplemented + + +class Logged: + log = [] + + def __init__(self, v): + self.v = v + + def __eq__(self, o): + Logged.log.append(self.v) + return isinstance(o, Logged) and self.v == o.v + + +class Shrinker: + def __init__(self, v, seq): + self.v = v + self.seq = seq + + def __eq__(self, o): + if self.seq: + self.seq.pop() + return False + + +class MembershipTests(unittest.TestCase): + def test_hits_and_misses(self): + pts = [Pt(i % 5, i % 3) for i in range(12)] + tup = tuple(pts) + for _ in range(300): + self.assertIn(Pt(2, 2), pts) + self.assertNotIn(Pt(9, 9), pts) + self.assertIn(pts[7], tup) + self.assertIn(Pt(4, 1), tup) + self.assertNotIn(Pt(1, 9), tup) + self.assertEqual(pts.count(Pt(0, 0)), 1) + self.assertEqual(pts.index(Pt(1, 1)), 1) + + def test_other_classes_and_values(self): + pts = [1, "a", None, SubPt(1, 1), Pt(2, 2)] + for _ in range(300): + self.assertIn(Pt(1, 1), pts) + self.assertIn(Pt(2, 2), pts) + self.assertNotIn(Pt(3, 3), pts) + self.assertIn(SubPt(2, 2), pts) + + def test_non_bool_answers(self): + items = [Odd(0), Odd(""), Odd([1])] + for _ in range(300): + self.assertIn(Odd(None), items) + self.assertNotIn(Odd(None), items[:2]) + + def test_member_methods_run_in_order(self): + items = [Logged(i) for i in range(5)] + for _ in range(100): + Logged.log.clear() + self.assertIn(Logged(3), items) + self.assertEqual(Logged.log, [0, 1, 2, 3]) + + def test_list_shrinking_during_scan(self): + seq = [1, 2, 3, 4, 5, 6] + probe = Shrinker(0, seq) + self.assertNotIn(probe, seq) + self.assertLess(len(seq), 6) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_memory_stream_construct.py b/tests/regrtest/test_memory_stream_construct.py new file mode 100644 index 000000000..c206aac58 --- /dev/null +++ b/tests/regrtest/test_memory_stream_construct.py @@ -0,0 +1,56 @@ +"""`io.BytesIO()` and `io.StringIO()` built without the generic constructor. + +The exact types, empty or given plain `bytes` or `str`, are their +`__new__`'s stream: positioned at the start, writable, and of the right +type; other arguments, keywords and subclasses take the full +constructor. Run it past the compile threshold. +""" + +import io + + +class B(io.BytesIO): + pass + + +class S(io.StringIO): + def extra(self): + return "x" + + +def run(n): + for i in range(n): + b = io.BytesIO() + assert type(b) is io.BytesIO and b.tell() == 0 and b.getvalue() == b"" + b.write(b"ab") + assert b.getvalue() == b"ab" + b2 = io.BytesIO(b"xyz") + assert b2.tell() == 0 and b2.read(2) == b"xy" and b2.getvalue() == b"xyz" + s = io.StringIO() + assert type(s) is io.StringIO and s.getvalue() == "" + s.write("a\nb") + assert s.getvalue() == "a\nb" + s2 = io.StringIO("l1\r\nl2") + assert s2.read() == "l1\r\nl2" and s2.tell() == 6 + assert io.StringIO("q", newline=None).getvalue() == "q" + assert io.StringIO("a\r\nb", None).getvalue() == "a\nb" + assert io.BytesIO(bytearray(b"ba")).getvalue() == b"ba" + assert io.BytesIO(initial_bytes=b"k").getvalue() == b"k" + assert type(B()) is B and B(b"z").getvalue() == b"z" + assert S("w").extra() == "x" and S("w").getvalue() == "w" + try: + io.StringIO(5) + except TypeError: + pass + else: + raise AssertionError("int initial value") + try: + io.BytesIO("s") + except TypeError: + pass + else: + raise AssertionError("str initial bytes") + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_memory_stream_pure_paths.py b/tests/regrtest/test_memory_stream_pure_paths.py new file mode 100644 index 000000000..c10ec7b6f --- /dev/null +++ b/tests/regrtest/test_memory_stream_pure_paths.py @@ -0,0 +1,83 @@ +"""`BytesIO.write` at the stream's end and `getvalue()` run in place. + +The in-place halves append the bytes and copy the contents as the full +methods do; a write anywhere else, into an exported buffer, or on a +closed stream keeps the full method and its errors. +""" + +import io +import unittest + +N = 3000 + + +class MemoryStreamPurePathTests(unittest.TestCase): + def test_appends_and_values(self): + for _ in range(N): + b = io.BytesIO() + n = b.write(b"abc") + b.write(b"de") + v = b.getvalue() + self.assertEqual((n, v, b.tell()), (3, b"abcde", 5)) + + def test_overwrite_after_seek(self): + for _ in range(N): + b = io.BytesIO(b"hello") + b.seek(1) + b.write(b"EY") + b.seek(0, 2) + b.write(b"!") + self.assertEqual(b.getvalue(), b"hEYlo!") + + def test_overseek_fills_gap(self): + b = io.BytesIO(b"ab") + b.seek(4) + for _ in range(N): + pass + b.write(b"z") + self.assertEqual(b.getvalue(), b"ab\x00\x00z") + + def test_export_refuses_write(self): + b = io.BytesIO(b"ab") + b.seek(0, 2) + view = b.getbuffer() + for _ in range(100): + with self.assertRaises(BufferError): + b.write(b"x") + view.release() + b.write(b"x") + self.assertEqual(b.getvalue(), b"abx") + + def test_closed_streams_raise(self): + b = io.BytesIO() + s = io.StringIO("q") + b.close() + s.close() + for _ in range(100): + with self.assertRaises(ValueError): + b.write(b"x") + with self.assertRaises(ValueError): + b.getvalue() + with self.assertRaises(ValueError): + s.getvalue() + + def test_string_io_value(self): + for _ in range(N): + s = io.StringIO() + s.write("ab") + v = s.getvalue() + self.assertEqual(v, "ab") + + def test_subclass_write_override(self): + class B(io.BytesIO): + def write(self, data): + return super().write(data.upper()) + + for _ in range(N): + b = B() + b.write(b"ab") + self.assertEqual(b.getvalue(), b"AB") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_memoryview_iteration_as_bytes.py b/tests/regrtest/test_memoryview_iteration_as_bytes.py new file mode 100644 index 000000000..2f6404998 --- /dev/null +++ b/tests/regrtest/test_memoryview_iteration_as_bytes.py @@ -0,0 +1,53 @@ +"""Iterating a plain byte memoryview. + +A one-dimensional `'B'` view of a `bytes` object steps as the bytes do (no +element objects made first); one over a whole `bytearray` steps the +bytearray live, seeing a store made mid-loop, as CPython's `memoryiter` +does. Other formats, strides and windows keep the element path, and a +released view raises CPython's error. +""" + +import unittest + + +class MemoryviewIterationTests(unittest.TestCase): + def test_bytes_views(self): + data = bytes(range(256)) * 4 + for _ in range(20): + self.assertEqual(sum(memoryview(data)), sum(data)) + self.assertEqual(list(memoryview(data)[10:20]), list(range(10, 20))) + self.assertEqual(list(memoryview(data)[::3])[:4], [0, 3, 6, 9]) + self.assertEqual(list(memoryview(b"")), []) + + def test_other_formats(self): + data = bytes(range(256)) + self.assertEqual(sum(memoryview(data).cast("b")), -128) + self.assertEqual(list(memoryview(b"\x01\x00\x02\x00").cast("H")), [1, 2]) + self.assertEqual(list(memoryview(b"\x00" * 8).cast("d")), [0.0]) + + def test_live_bytearray(self): + ba = bytearray(b"abc") + it = iter(memoryview(ba)) + self.assertEqual(next(it), 97) + ba[1] = 0x7A + self.assertEqual(list(it), [0x7A, 99]) + window = memoryview(bytearray(b"abcdef"))[1:4] + self.assertEqual(list(window), [98, 99, 100]) + + def test_released(self): + m = memoryview(b"x") + m.release() + for f in (iter, lambda v: v.tobytes(), lambda v: v.tolist()): + with self.assertRaisesRegex(ValueError, "operation forbidden on released memoryview object"): + f(m) + + def test_loop_counts(self): + data = bytes(range(256)) * 100 + total = 0 + for b in memoryview(data): + total += b + self.assertEqual(total, sum(data)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_memoryview_plain_subviews.py b/tests/regrtest/test_memoryview_plain_subviews.py new file mode 100644 index 000000000..e7207ab15 --- /dev/null +++ b/tests/regrtest/test_memoryview_plain_subviews.py @@ -0,0 +1,198 @@ +"""Slicing a memoryview gives a view of the same buffer. + +`view[i:j]` of a one-dimensional view is a view of the same bytes: it +reads and writes through to the buffer, slices again, keeps its format +and item size, and counts as an export of a bytearray until it's +released. The same holds whether the slice runs once or in a loop long +enough to be compiled, and for a view only the expression holds. +""" + +import array +import struct +import unittest + + +def window(view, lo, hi): + return view[lo:hi] + + +def windows(view, width, count): + out = [] + for i in range(count): + out.append(bytes(view[i:i + width])) + return out + + +def window_sum(view, width, count): + total = 0 + for i in range(count): + part = view[i:i + width] + total += part[0] + part[-1] + len(part) + return total + + +class SubviewTests(unittest.TestCase): + def test_a_subview_reads_the_same_bytes(self): + data = bytes(range(200)) + view = memoryview(data) + for lo, hi in [(0, 200), (10, 20), (190, 300), (-5, None), (None, -195), (50, 10), (7, 7)]: + with self.subTest(lo=lo, hi=hi): + sub = view[lo:hi] + self.assertEqual(bytes(sub), data[lo:hi]) + self.assertEqual(len(sub), len(data[lo:hi])) + self.assertEqual(sub.nbytes, len(data[lo:hi])) + self.assertEqual(sub.format, "B") + self.assertEqual(sub.itemsize, 1) + self.assertEqual(sub.shape, (len(data[lo:hi]),)) + self.assertEqual(sub.strides, (1,)) + self.assertEqual(sub.ndim, 1) + self.assertTrue(sub.readonly) + self.assertTrue(sub.c_contiguous) + self.assertTrue(sub.contiguous) + self.assertIs(sub.obj, data) + + def test_subviews_of_subviews(self): + data = bytes(range(256)) + view = memoryview(data) + a = view[10:200] + b = a[5:100] + c = b[-10:] + self.assertEqual(bytes(c), data[100:110]) + self.assertEqual(c[0], 100) + self.assertEqual(c[-1], 109) + self.assertEqual(bytes(c[::-1]), data[100:110][::-1]) + self.assertEqual(bytes(b[::3][1:4]), data[15:110][::3][1:4]) + self.assertEqual(bytes(view[::2][10:20]), data[::2][10:20]) + self.assertEqual(bytes(view[::-1][10:20]), data[::-1][10:20]) + + def test_wider_items(self): + values = array.array("i", range(100)) + view = memoryview(values) + sub = view[10:20] + self.assertEqual(sub.tolist(), list(range(10, 20))) + self.assertEqual(sub.itemsize, values.itemsize) + self.assertEqual(sub.format, "i") + self.assertEqual(sub.nbytes, 10 * values.itemsize) + self.assertEqual(sub.shape, (10,)) + self.assertEqual(sub.strides, (values.itemsize,)) + self.assertEqual(sub[3:5].tolist(), [13, 14]) + self.assertEqual(sub[-1], 19) + sub[0] = -7 + self.assertEqual(values[10], -7) + self.assertEqual(view[5:15][::2].tolist(), [5, 7, 9, 11, 13]) + cast = memoryview(struct.pack("8H", *range(8))).cast("H") + self.assertEqual(cast[2:6].tolist(), [2, 3, 4, 5]) + self.assertEqual(cast[2:6][1:3].tolist(), [3, 4]) + + def test_a_cast_shape_keeps_its_trailing_dimensions(self): + view = memoryview(bytes(range(24))).cast("B", (4, 6)) + sub = view[1:3] + self.assertEqual(sub.shape, (2, 6)) + self.assertEqual(sub.tolist(), [list(range(6, 12)), list(range(12, 18))]) + + def test_writes_go_through(self): + buf = bytearray(b"0123456789") + view = memoryview(buf) + sub = view[2:6] + self.assertFalse(sub.readonly) + sub[0] = ord("a") + sub[1:3] = b"bc" + self.assertEqual(buf, b"01abc56789") + sub[:] = b"WXYZ" + self.assertEqual(buf, b"01WXYZ6789") + self.assertEqual(bytes(view[1:7]), b"1WXYZ6") + ro = view.toreadonly()[2:6] + self.assertTrue(ro.readonly) + with self.assertRaises(TypeError): + ro[0] = 1 + + def test_a_subview_is_an_export(self): + buf = bytearray(b"0123456789") + view = memoryview(buf) + sub = view[2:6] + view.release() + with self.assertRaises(BufferError): + buf.append(1) + with self.assertRaises(BufferError): + del buf[:1] + self.assertEqual(bytes(sub), b"2345") + sub.release() + buf.append(65) + self.assertEqual(buf, b"0123456789A") + with self.assertRaises(ValueError): + sub[0:1] + with self.assertRaises(ValueError): + view[0:1] + + def test_temporary_views(self): + buf = bytearray(b"0123456789") + for _ in range(200): + self.assertEqual(bytes(memoryview(buf)[3:5]), b"34") + self.assertEqual(memoryview(buf)[3:5][1], ord("4")) + # Every temporary is gone: the buffer resizes again. + buf.extend(b"ab") + self.assertEqual(len(buf), 12) + + def test_hash_and_equality(self): + data = b"abcdefabcdef" + view = memoryview(data) + self.assertEqual(view[0:6], view[6:12]) + self.assertEqual(hash(view[0:6]), hash(b"abcdef")) + self.assertEqual(view[0:6], b"abcdef") + self.assertNotEqual(view[0:6], view[1:7]) + self.assertEqual({view[0:3]: 1}[b"abc"], 1) + + def test_zero_dimensional_views_refuse_slices(self): + scalar = memoryview(b"\x01\x00\x00\x00").cast("i", ()) + with self.assertRaises(TypeError): + scalar[0:1] + + +class HotLoopTests(unittest.TestCase): + def test_slices_in_a_long_loop(self): + data = bytes(i & 0xFF for i in range(5000)) + view = memoryview(data) + got = windows(view, 16, 4000) + self.assertEqual(got[0], data[0:16]) + self.assertEqual(got[3999], data[3999:4015]) + self.assertTrue(all(got[i] == data[i:i + 16] for i in range(0, 4000, 97))) + want = sum(data[i] + data[i + 15] + 16 for i in range(4000)) + for _ in range(4): + self.assertEqual(window_sum(view, 16, 4000), want) + + def test_bounds_from_variables(self): + data = bytes(range(100)) + view = memoryview(data) + total = 0 + for i in range(3000): + lo = i % 90 + total += len(window(view, lo, lo + 10)) + window(view, lo, None)[0] + self.assertEqual(total, sum(10 + (i % 90) for i in range(3000))) + + def test_a_loop_over_a_bytearray_view_releases_every_subview(self): + buf = bytearray(range(256)) * 4 + view = memoryview(buf) + total = 0 + for i in range(3000): + part = view[i % 1000:i % 1000 + 8] + total += part[0] + part.release() + self.assertEqual(total, sum((i % 1000) % 256 for i in range(3000))) + del part + view.release() + buf.append(0) + self.assertEqual(len(buf), 1025) + + def test_unreleased_subviews_die_with_their_names(self): + buf = bytearray(64) + view = memoryview(buf) + for i in range(3000): + part = view[i % 32:i % 32 + 8] + del part + view.release() + buf.append(0) + self.assertEqual(len(buf), 65) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_memoryview_typed_items.py b/tests/regrtest/test_memoryview_typed_items.py new file mode 100644 index 000000000..5d0931db8 --- /dev/null +++ b/tests/regrtest/test_memoryview_typed_items.py @@ -0,0 +1,86 @@ +"""`view[i]` of typed 1-D memoryviews (`cast("I")`, `cast("d")`), in hot +loops, including views the subscript holds alone. + +Every simple format must read as CPython unpacks it; negative and +out-of-range indexes, released views, multi-dimensional and 0-dim views, +and views over an exporter whose buffer release runs code must answer +as the general subscript does. +""" + +import array +import struct +import unittest + +BUF = struct.pack("<8I", *range(100, 108)) + + +class Exporter: + def __init__(self): + self.data = bytearray(BUF) + self.released = 0 + + def __buffer__(self, flags): + return memoryview(self.data) + + def __release_buffer__(self, view): + self.released += 1 + + +class MemoryviewTypedItems(unittest.TestCase): + def test_temporary_views(self): + for i in range(4000): + self.assertEqual(memoryview(BUF).cast("I")[3], 103) + self.assertEqual(memoryview(BUF).cast("I")[-1], 107) + k = i % 16 + want = 100 + k // 2 if k % 2 == 0 else 0 + self.assertEqual(memoryview(bytearray(BUF)).cast("H")[k], want) + + def test_formats(self): + for fmt in "bBhHiIlLqQnNfd?": + size = struct.calcsize(fmt) + raw = bytes(range(1, 8 * size + 1)) + m = memoryview(raw).cast(fmt) + want = [struct.unpack_from(fmt, raw, k * size)[0] for k in range(8)] + for _ in range(300): + for k in range(-8, 8): + self.assertEqual(m[k], want[k]) + self.assertIs(type(m[k]), type(want[k])) + + def test_errors(self): + m = memoryview(BUF).cast("I") + for _ in range(500): + with self.assertRaises(IndexError): + m[8] + with self.assertRaises(IndexError): + m[-9] + m2 = memoryview(BUF).cast("B", shape=[4, 8]) + with self.assertRaises(NotImplementedError): + m2[0] + self.assertEqual(m2[1, 2], BUF[10]) + z = memoryview(BUF[:4]).cast("I", shape=[]) + with self.assertRaises(TypeError): + z[0] + m.release() + with self.assertRaises(ValueError): + m[0] + + def test_exporter_release_runs(self): + e = Exporter() + for i in range(500): + self.assertEqual(memoryview(e).cast("I")[i % 8], 100 + i % 8) + m = memoryview(e) + self.assertEqual(m.cast("I")[1], 101) + m.release() + self.assertGreaterEqual(e.released, 500) + + def test_array_views(self): + a = array.array("d", [0.5, 1.5, 2.5]) + for _ in range(2000): + self.assertEqual(memoryview(a)[1], 1.5) + b = array.array("i", [-1, 2, -3]) + for _ in range(2000): + self.assertEqual(memoryview(b)[2], -3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_metaclass_contains.py b/tests/regrtest/test_metaclass_contains.py new file mode 100644 index 000000000..b038795dd --- /dev/null +++ b/tests/regrtest/test_metaclass_contains.py @@ -0,0 +1,88 @@ +"""`x in cls` for a class whose metaclass defines `__contains__`. + +The metaclass's plain function is called with the class (`EnumType`'s +membership test, a user metaclass's), with no bound method made; its +result's truth is the answer, and its errors propagate. +""" + +import enum +import unittest + +N = 3000 + + +class Color(enum.Enum): + RED = 1 + GREEN = 2 + + +class Perm(enum.Flag): + R = 4 + W = 2 + + +class Meta(type): + def __contains__(cls, item): + if item == "boom": + raise ValueError("boom") + return item in cls.items + + +class Bag(metaclass=Meta): + items = (1, 2) + + +class SubMeta(Meta): + pass + + +class Sub(metaclass=SubMeta): + items = ("a",) + + +class Truthy: + def __bool__(self): + return True + + +class OddMeta(type): + def __contains__(cls, item): + return Truthy() + + +class Odd(metaclass=OddMeta): + pass + + +class MetaclassContainsTests(unittest.TestCase): + def test_enum(self): + for _ in range(N): + a = Color.RED in Color + b = 1 in Color + c = 3 in Color + d = Perm.R | Perm.W in Perm + self.assertEqual((a, b, c, d), (True, True, False, True)) + self.assertNotIn("x", Color) + + def test_user_metaclass(self): + for _ in range(N): + r = (1 in Bag, 3 in Bag, "a" in Sub, 2 not in Bag) + self.assertEqual(r, (True, False, True, False)) + with self.assertRaises(ValueError): + "boom" in Bag + + def test_result_truth(self): + for _ in range(N): + r = 0 in Odd + self.assertIs(r, True) + + def test_plain_class_has_no_membership(self): + class P: + pass + + with self.assertRaises(TypeError): + 1 in P + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_method_reads_through_instances.py b/tests/regrtest/test_method_reads_through_instances.py new file mode 100644 index 000000000..8258c9d15 --- /dev/null +++ b/tests/regrtest/test_method_reads_through_instances.py @@ -0,0 +1,96 @@ +"""Methods, staticmethods and classmethods read as values through +instances from compiled loops (the class entry memoized per class +version, bound or unwrapped on each read): identity and binding of the +results, a site that sees several classes with different kinds of entry, +an instance attribute that shadows later, the class entry replaced, +subclasses, and calls of the values, each matching CPython.""" + +import unittest + + +class A: + def m(self): + return ("m", type(self).__name__) + + @staticmethod + def s(x=0): + return ("s", x) + + @classmethod + def c(cls): + return ("c", cls.__name__) + + +class B(A): + pass + + +class C(A): + m = staticmethod(lambda: ("sm",)) + s = classmethod(lambda cls: ("cs", cls.__name__)) + + def c(self): + return ("cm", type(self).__name__) + + +def read(n, o, name): + out = None + for i in range(n): + out = getattr(o, "__class__") and (o.m, o.s, o.c) + return out + + +def site(n, objs): + seen = [] + for i in range(n): + for o in objs: + m = o.m + s = o.s + c = o.c + seen = (m(), s(), c()) + return seen + + +class MethodReadTests(unittest.TestCase): + def test_binding(self): + a, b = A(), B() + for i in range(300): + m, s, c = a.m, a.s, a.c + self.assertEqual(m.__self__, a) + self.assertIs(m.__func__, A.__dict__["m"]) + self.assertIs(s, A.__dict__["s"].__func__) + self.assertIs(c.__self__, A) + self.assertEqual((m(), s(3), c()), (("m", "A"), ("s", 3), ("c", "A"))) + for i in range(300): + bc = b.c + bm = b.m + self.assertIs(bc.__self__, B) + self.assertEqual(bm(), ("m", "B")) + self.assertIsNot(a.m, a.m) + self.assertEqual(a.m, a.m) + + def test_polymorphic_site(self): + r = site(300, [A(), B(), C()]) + self.assertEqual(r, (("sm",), ("cs", "C"), ("cm", "C"))) + + def test_shadow_and_replace(self): + a = A() + for i in range(300): + m = a.m + a.m = lambda: "inst" + self.assertEqual(a.m(), "inst") + del a.m + self.assertEqual(a.m(), ("m", "A")) + old = A.__dict__["s"] + A.s = staticmethod(lambda x=0: ("s2", x)) + try: + self.assertEqual(a.s(1), ("s2", 1)) + finally: + A.s = old + for i in range(300): + v = a.s + self.assertEqual(v(4), ("s", 4)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_method_site_published_dict.py b/tests/regrtest/test_method_site_published_dict.py new file mode 100644 index 000000000..9805647fe --- /dev/null +++ b/tests/regrtest/test_method_site_published_dict.py @@ -0,0 +1,108 @@ +"""Method calls and native-method reads at compiled sites. + +`self.fn()` of a callable an instance holds in its own dict answers from +where the site last found it, also for an instance whose dict was +materialized (its names assigned out of the class's order, as a +`threading.Condition` over a lock with `_release_save` does): a replaced, +deleted or class-shadowed value, and a class changed mid-loop, behave as +in CPython. Reading a native method off a built-in subclass's instance +(`lock.__exit__`, to call with `*args`) binds it each time, unless the +instance or its class shadows it; a lock's `__exit__` returns `None` and +raises for an unheld lock. Run it past the compile threshold. +""" + +import threading + + +class Holder: + def __init__(self, order): + for name in order: + setattr(self, name, (lambda n: lambda: n)(name)) + + def call(self, n): + t = [] + for _ in range(n): + t.append(self.b()) + return t + + +first = Holder("ab") +late = Holder("ba") +N = 3000 +assert first.call(N) == ["b"] * N +assert late.call(N) == ["b"] * N +late.b = lambda: "new" +assert late.call(3) == ["new"] * 3 +late.__dict__["b"] = lambda: "dict" +assert late.call(3) == ["dict"] * 3 +del late.b +Holder.b = lambda self: "class" +assert late.call(3) == ["class"] * 3 +del Holder.b + + +class Desc: + def __get__(self, obj, owner=None): + return lambda: "descr" + + def __set__(self, obj, v): + raise AttributeError + + +other = Holder("ba") +assert other.call(N) == ["b"] * N +Holder.b = Desc() +assert other.call(3) == ["descr"] * 3 +del Holder.b + + +def notify_many(c, n): + with c: + for _ in range(n): + c.notify() + + +notify_many(threading.Condition(threading.Lock()), N) +notify_many(threading.Condition(threading.RLock()), N) +notify_many(threading.Condition(), N) + + +def exits(lk, n): + args = (None, None, None) + out = [] + for _ in range(n): + lk.__enter__() + out.append(lk.__exit__(*args)) + return out + + +class SubDict(dict): + pass + + +def reads(d, n): + got = [] + for _ in range(n): + f = d.get + got.append(f("k", 0)) + return got + + +assert exits(threading.Lock(), N) == [None] * N +assert exits(threading.RLock(), N) == [None] * N +for lock in (threading.Lock(), threading.RLock()): + try: + lock.__exit__(None, None, None) + except RuntimeError: + pass + else: + raise AssertionError("exit of an unheld lock") +d = SubDict(k=1) +assert reads(d, N) == [1] * N +d.get = lambda k, default=None: "own" +assert reads(d, 3) == ["own"] * 3 +e = SubDict(k=2) +assert reads(e, 3) == [2] * 3 +SubDict.get = lambda self, k, default=None: "class" +assert reads(e, 3) == ["class"] * 3 +print("ok") diff --git a/tests/regrtest/test_methodcaller_direct.py b/tests/regrtest/test_methodcaller_direct.py new file mode 100644 index 000000000..2d6b4f292 --- /dev/null +++ b/tests/regrtest/test_methodcaller_direct.py @@ -0,0 +1,108 @@ +"""Compiled `mc(obj)` of an `operator.methodcaller` whose method is a +Python function of `obj`'s plain class calls the method directly; the +results with no, one and two stored arguments, defaults, raises (caught in +the frame or past it), stored keywords, `*args` methods, an instance +attribute shadowing the method, native receivers, and a method replaced +later match the general call.""" + +import operator +import unittest + + +class C: + def __init__(self, v): + self.v = v + self.calls = 0 + + def get(self): + self.calls += 1 + return self.v + + def add(self, a): + return self.v + a + + def mix(self, a, b): + return (self.v, a, b) + + def dflt(self, a, b=10): + return a + b + + def star(self, *a): + return len(a) + + def kw(self, *, k=0): + return k + + def boom(self, a): + if a == 3: + raise KeyError(a) + return a + + +class MethodcallerDirect(unittest.TestCase): + def test_results(self): + c = C(5) + get = operator.methodcaller("get") + add = operator.methodcaller("add", 2) + mix = operator.methodcaller("mix", "a", "b") + for i in range(2000): + self.assertEqual(get(c), 5) + self.assertEqual(add(c), 7) + self.assertEqual(mix(c), (5, "a", "b")) + self.assertEqual(c.calls, 2000) + + def test_other_shapes(self): + c = C(1) + d1 = operator.methodcaller("dflt", 1) + d2 = operator.methodcaller("dflt", 1, 2) + st = operator.methodcaller("star", 1, 2, 3) + kw = operator.methodcaller("kw", k=4) + up = operator.methodcaller("upper") + for i in range(1000): + self.assertEqual(d1(c), 11) + self.assertEqual(d2(c), 3) + self.assertEqual(st(c), 3) + self.assertEqual(kw(c), 4) + self.assertEqual(up("ab"), "AB") + self.assertEqual(list(map(operator.methodcaller("add", i), [C(1), C(2)])), [1 + i, 2 + i]) + + def test_raises(self): + c = C(0) + n = 0 + for i in range(1000): + try: + operator.methodcaller("boom", i % 5)(c) + except KeyError: + n += 1 + self.assertEqual(n, 200) + + def call(mc, o): + return mc(o) + + bad = operator.methodcaller("boom", 3) + for i in range(500): + with self.assertRaises(KeyError): + call(bad, c) + with self.assertRaises(AttributeError): + operator.methodcaller("missing")(c) + + def test_shadowed_and_replaced(self): + c = C(2) + get = operator.methodcaller("get") + out = [] + for i in range(1000): + out.append(get(c)) + c.get = lambda: "instance" + for i in range(1000): + out.append(get(c)) + del c.get + C.get = lambda self: "class" + for i in range(1000): + out.append(get(c)) + self.assertEqual( + (out.count(2), out.count("instance"), out.count("class")), (1000, 1000, 1000) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_methodcaller_native_receivers.py b/tests/regrtest/test_methodcaller_native_receivers.py new file mode 100644 index 000000000..fbefe0103 --- /dev/null +++ b/tests/regrtest/test_methodcaller_native_receivers.py @@ -0,0 +1,82 @@ +"""`operator.methodcaller` called on native values. + +A `methodcaller` with positional arguments only, called on a `str`, +`bytes`, `list`, `dict`, `set` or `int` whose method is a leaf builtin, +runs that method in place; anything else (an instance, a subclass, stored +keywords, a missing method, arguments the method refuses) takes the full +call, with CPython's result or error. +""" + +import operator +import unittest + + +class MethodcallerTests(unittest.TestCase): + def test_native_receivers(self): + cases = [ + (operator.methodcaller("lower"), "AbC", "abc"), + (operator.methodcaller("upper"), "abc", "ABC"), + (operator.methodcaller("strip"), " x ", "x"), + (operator.methodcaller("split", ","), "a,b", ["a", "b"]), + (operator.methodcaller("split"), "a b", ["a", "b"]), + (operator.methodcaller("startswith", "ab"), "abc", True), + (operator.methodcaller("replace", "a", "b", 1), "aaa", "baa"), + (operator.methodcaller("get", "k", 0), {"k": 1}, 1), + (operator.methodcaller("get", "z", 0), {"k": 1}, 0), + (operator.methodcaller("get", "z"), {"k": 1}, None), + (operator.methodcaller("bit_length"), 255, 8), + (operator.methodcaller("count", 1), [1, 2, 1], 2), + (operator.methodcaller("index", 2), (1, 2), 1), + (operator.methodcaller("hex"), b"\x01\xff", "01ff"), + (operator.methodcaller("issubset", {1, 2}), {1}, True), + ] + for _ in range(300): + for m, obj, want in cases: + self.assertEqual(m(obj), want) + + def test_mutating_methods(self): + append = operator.methodcaller("append", 7) + pop = operator.methodcaller("pop") + add = operator.methodcaller("add", 3) + xs, s = [], set() + for _ in range(200): + append(xs) + add(s) + self.assertEqual(len(xs), 200) + self.assertEqual(s, {3}) + for _ in range(200): + self.assertEqual(pop(xs), 7) + self.assertEqual(xs, []) + + def test_errors_and_other_receivers(self): + with self.assertRaises(IndexError): + operator.methodcaller("pop")([]) + with self.assertRaises(AttributeError): + operator.methodcaller("nope")("x") + with self.assertRaises(TypeError): + operator.methodcaller("split", 5)("a b") + with self.assertRaises(KeyError): + operator.methodcaller("pop", "z")({}) + + class S(str): + def lower(self): + return "own" + + class C: + def f(self, x): + return x * 2 + + lower = operator.methodcaller("lower") + f = operator.methodcaller("f", 21) + for _ in range(200): + self.assertEqual(lower(S("ABC")), "own") + self.assertEqual(f(C()), 42) + kw = operator.methodcaller("split", sep=",") + self.assertEqual(kw("a,b"), ["a", "b"]) + self.assertEqual(operator.methodcaller("fromkeys", "ab")(dict), {"a": None, "b": None}) + self.assertEqual(sorted(["b", "A", "c"], key=operator.methodcaller("lower")), ["A", "b", "c"]) + self.assertEqual(list(map(operator.methodcaller("strip"), [" a", "b "])), ["a", "b"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_min_max_builtin_key.py b/tests/regrtest/test_min_max_builtin_key.py new file mode 100644 index 000000000..2dabe1cf1 --- /dev/null +++ b/tests/regrtest/test_min_max_builtin_key.py @@ -0,0 +1,49 @@ +"""`min`, `max`, `sorted` and `list.sort` with a builtin key (`key=abs`, `key=len`). + +The key's body runs directly for each item; ties keep the first item, a +key that raises propagates its error, `default` applies to an empty +iterable, and Python and `None` keys behave as before. Run it past the +compile threshold. +""" + + +class Sized: + def __init__(self, n): + self.n = n + + def __len__(self): + return self.n + + +def run(n): + for _ in range(n): + xs = [3, -7, 2, 7, -1] + assert min(xs, key=abs) == -1 and max(xs, key=abs) == -7 + assert max(["bb", "a", "cc"], key=len) == "bb" + assert min([2.5, -0.5, True], key=abs) == -0.5 + assert min([], key=abs, default="d") == "d" + assert max((1, 2), key=None) == 2 + assert min([3, 1], key=lambda v: -v) == 3 + assert sorted([3, -1, 2, -3], key=abs) == [-1, 2, 3, -3] + assert sorted(["bb", "a", "cc", "d"], key=len, reverse=True) == ["bb", "cc", "a", "d"] + mixed = [[1, 2], "abc", Sized(0), (1,)] + assert [len(v) for v in sorted(mixed, key=len)] == [0, 1, 2, 3] + ws = ["pear", "fig", "kiwi"] + ws.sort(key=len) + assert ws == ["fig", "pear", "kiwi"] + try: + sorted([1, "x"], key=abs) + except TypeError: + pass + else: + raise AssertionError("abs of a str in sorted") + try: + min([1, "x"], key=abs) + except TypeError: + pass + else: + raise AssertionError("abs of a str") + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_min_max_key_native.py b/tests/regrtest/test_min_max_key_native.py new file mode 100644 index 000000000..b06990870 --- /dev/null +++ b/tests/regrtest/test_min_max_key_native.py @@ -0,0 +1,83 @@ +"""`min` and `max` with Python key functions whose keys compare natively +(tuples of lengths and strings, floats with NaN, mixed ints and floats) +or through user comparisons, and compiled key bodies that call `len` on +the common containers, a subclass with its own `__len__`, and an object +without a length: every result matches the full comparison, and ties keep +the first extremum.""" + +import unittest + +N = 2000 + + +class Rev: + def __init__(self, v): + self.v = v + + def __lt__(self, other): + return self.v > other.v + + def __gt__(self, other): + return self.v < other.v + + +class LongStr(str): + def __len__(self): + return 100 + + +class MinMaxKeyNativeTests(unittest.TestCase): + def test_tuple_keys(self): + words = "the quick brown fox jumps over the lazy dog".split() + key = lambda w: (len(w), w) + for _ in range(N): + self.assertEqual(max(words, key=key), "quick") + self.assertEqual(min(words, key=key), "dog") + + def test_ties_keep_first(self): + words = ["bb", "aa", "cc", "dd"] + key = lambda w: len(w) + for _ in range(N): + self.assertEqual(max(words, key=key), "bb") + self.assertEqual(min(words, key=key), "bb") + + def test_float_and_nan_keys(self): + nan = float("nan") + xs = [1.5, nan, 3.0, 2] + key = lambda x: x + for _ in range(N): + self.assertEqual(max(xs, key=key), 3.0) + self.assertEqual(min(xs, key=key), 1.5) + self.assertIs(max([nan, 1.0], key=key), nan) + + def test_mixed_and_user_keys(self): + for _ in range(N): + self.assertEqual(max([1, 2.5, 2], key=lambda x: x), 2.5) + self.assertEqual(max([3, 1, 2], key=lambda x: Rev(x)), 1) + self.assertEqual(max([3, 1, 2], key=lambda x: (Rev(x),)), 1) + + def test_uncomparable_keys_raise(self): + with self.assertRaises(TypeError): + max([1, "a"], key=lambda x: x) + with self.assertRaises(TypeError): + max([1, 2], key=lambda x: (x, None) if x == 1 else (1, "a")) + + def test_len_in_key_bodies(self): + key = lambda x: len(x) + items = ["abc", [1, 2], (1, 2, 3, 4), {"a": 1}, b"xy", {1, 2, 3, 4, 5}] + for _ in range(N): + self.assertEqual(max(items, key=key), {1, 2, 3, 4, 5}) + self.assertEqual(min(items, key=key), {"a": 1}) + self.assertEqual(max(["ab", LongStr("x")], key=key), "x") + self.assertEqual(len(LongStr("x")), 100) + with self.assertRaises(TypeError): + max([1, 2], key=key) + + def test_len_of_non_ascii(self): + key = lambda s: len(s) + for _ in range(N): + self.assertEqual(max(["héllo", "naïve!", "日本語"], key=key), "naïve!") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_missing_globals_gate_clears.py b/tests/regrtest/test_missing_globals_gate_clears.py new file mode 100644 index 000000000..784fdeb5c --- /dev/null +++ b/tests/regrtest/test_missing_globals_gate_clears.py @@ -0,0 +1,56 @@ +"""Builtin lookups after annotationlib evaluated a class's annotations +with a dict subclass's __missing__ as globals (a typing.NamedTuple, a +dataclass with a forward reference): compiled loops that only read +builtins still see them, a live exec namespace whose __missing__ serves +names (builtins' too, as in CPython) keeps serving them, and once it is gone the builtins answer again, +each matching CPython.""" + +import dataclasses +import typing +import unittest + + +class TD(typing.NamedTuple): + a: int + b: "Later" = None + + +@dataclasses.dataclass +class DC: + x: "Later" + + +class Later: + pass + + +class Fallback(dict): + def __missing__(self, key): + return "missing:" + key + + +def loop(n): + t = 0 + xs = [1, 2] + for i in range(n): + t += len(xs) + abs(-1) + hash(1) + return t + + +class GateTests(unittest.TestCase): + def test_builtins_after_annotations(self): + self.assertEqual(TD(1), (1, None)) + self.assertEqual(loop(5000), 5000 * 4) + + def test_live_missing_namespace(self): + ns = Fallback(__builtins__=__builtins__) + exec("def f(n):\n out = None\n while n:\n out = (len, undefined_name)\n n -= 1\n return out", ns) + self.assertEqual(ns["f"](3000), ("missing:len", "missing:undefined_name")) + self.assertEqual(loop(3000), 3000 * 4) + self.assertEqual(ns["f"](10), ("missing:len", "missing:undefined_name")) + del ns + self.assertEqual(loop(3000), 3000 * 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_module_attr_rebinding_and_inplace_natives.py b/tests/regrtest/test_module_attr_rebinding_and_inplace_natives.py new file mode 100644 index 000000000..b924a238a --- /dev/null +++ b/tests/regrtest/test_module_attr_rebinding_and_inplace_natives.py @@ -0,0 +1,583 @@ +"""A store to a module attribute from outside the module rebinds an +existing name in place: the module's own functions (compiled or not) +see the new value at once, a displaced value dies at once, and new +names, dunders and module subclasses behave as before. Native functions +that never look at the calling frame (`sys.getsizeof`, `abc`'s checks, +`int.from_bytes`, `time.mktime`, the `warnings` and `datetime` helpers) +run in place from compiled code with the same results.""" + +import abc +import sys +import time +import types +import typing +import unittest +import warnings +import weakref +from datetime import date, datetime, timedelta + +N = 300 + +SOURCE = """ +scale = 1 +label = "a" + +def helper(x): + return x + 1 + +def read(): + return scale + +def total(n): + s = 0 + for i in range(n): + s += scale + return s + +def apply(n): + s = 0 + for i in range(n): + s += helper(i) + return s + +def tag(): + return label + "!" + +def rebind(v): + global scale + scale = v +""" + + +def fresh_module(name="rebinding_target"): + m = types.ModuleType(name) + exec(SOURCE, m.__dict__) + return m + + +class Probe: + def __init__(self, log, name): + self.log, self.name = log, name + + def __del__(self): + self.log.append(self.name) + + +class Rebinding(unittest.TestCase): + def test_reads_follow_outside_stores(self): + m = fresh_module() + for i in range(N): + m.scale = i + self.assertEqual(m.read(), i) + self.assertEqual(m.scale, i) + m.label = "b" + self.assertEqual(m.tag(), "b!") + + def test_hot_loops_see_the_new_value(self): + m = fresh_module() + for _ in range(8): + self.assertEqual(m.total(20000), 20000) + m.scale = 3 + self.assertEqual(m.total(20000), 60000) + m.scale = 2.5 + self.assertEqual(m.total(4), 10.0) + m.rebind(7) + self.assertEqual((m.scale, m.total(10)), (7, 70)) + + def test_rebound_callee(self): + m = fresh_module() + for _ in range(8): + self.assertEqual(m.apply(20000), sum(range(1, 20001))) + m.helper = lambda x: x * 2 + self.assertEqual(m.apply(10), 90) + m.helper = abs + self.assertEqual(m.apply(10), 45) + + def test_store_in_a_loop_between_calls(self): + m = fresh_module() + got = 0 + for i in range(N): + m.scale = i & 3 + got += m.total(5) + self.assertEqual(got, 5 * sum(i & 3 for i in range(N))) + + def test_displaced_value_dies_at_once(self): + m = fresh_module() + log = [] + for i in range(50): + m.scale = Probe(log, i) + self.assertEqual(log, list(range(49))) + m.scale = None + self.assertEqual(log, list(range(50))) + + def test_shared_displaced_value_lives(self): + m = fresh_module() + keep = [Probe([], i) for i in range(5)] + refs = [weakref.ref(k) for k in keep] + for i in range(N): + m.scale = keep[i % 5] + self.assertIs(m.scale, keep[(N - 1) % 5]) + self.assertTrue(all(r() is not None for r in refs)) + self.assertEqual([k.log for k in keep], [[]] * 5) + + def test_new_names_and_deletes(self): + m = fresh_module() + for i in range(N): + setattr(m, "extra%d" % (i % 7), i) + m.fresh = i + self.assertEqual(m.fresh, i) + del m.fresh + self.assertFalse(hasattr(m, "fresh")) + self.assertEqual(m.extra0, 294) + self.assertEqual(m.read(), 1) + with self.assertRaises(AttributeError): + del m.never_set + + def test_dunders_and_dict_view(self): + m = fresh_module() + m.__doc__ = "doc" + m.__custom__ = 5 + self.assertEqual((m.__doc__, m.__custom__), ("doc", 5)) + d = m.__dict__ + for i in range(N): + m.scale = i + self.assertEqual(d["scale"], i) + d["scale"] = -i + self.assertEqual(m.read(), -i) + + def test_module_subclass_setattr(self): + class Watching(types.ModuleType): + def __setattr__(self, name, value): + seen.append(name) + super().__setattr__(name, value) + + seen = [] + m = Watching("watching") + exec(SOURCE, m.__dict__) + for i in range(20): + m.scale = i + self.assertEqual(seen, ["scale"] * 20) + self.assertEqual(m.read(), 19) + + def test_imported_names_follow(self): + m = fresh_module("rebinding_importer") + sys.modules[m.__name__] = m + try: + ns = {} + exec("import rebinding_importer as r\ndef f():\n return r.scale\n", ns) + for i in range(N): + m.scale = i + self.assertEqual(ns["f"](), i) + finally: + del sys.modules[m.__name__] + + +class Sized: + def __sizeof__(self): + return 1000 + + +class Shape(abc.ABC): + @abc.abstractmethod + def area(self): ... + + +class Square(Shape): + def area(self): + return 1 + + +class Hooked(abc.ABC): + calls = 0 + + @classmethod + def __subclasshook__(cls, other): + Hooked.calls += 1 + return hasattr(other, "quack") or NotImplemented + + +class Duck: + def quack(self): + return "quack" + + +@typing.runtime_checkable +class Quacks(typing.Protocol): + def quack(self): ... + + +class InPlaceNatives(unittest.TestCase): + def test_getsizeof(self): + base = sys.getsizeof(Sized()) - 1000 + for _ in range(N): + got = (sys.getsizeof(1), sys.getsizeof("abc"), sys.getsizeof(Sized()), sys.getsizeof([])) + self.assertEqual(got[2], 1000 + base) + self.assertEqual(got, (sys.getsizeof(1), sys.getsizeof("abc"), 1000 + base, sys.getsizeof([]))) + self.assertTrue(all(isinstance(n, int) and n > 0 for n in got)) + + class Broken: + def __sizeof__(self): + raise ValueError("no size") + + for _ in range(5): + with self.assertRaises(ValueError): + sys.getsizeof(Broken()) + with self.assertRaises(ValueError): + sys.getsizeof(Broken(), 7) + + def test_abc_checks(self): + sq, d = Square(), Duck() + hits = 0 + for _ in range(N): + hits += isinstance(sq, Shape) + hits += issubclass(Square, Shape) + hits += not isinstance(d, Shape) + hits += isinstance(d, Hooked) + hits += not isinstance(1, Hooked) + hits += isinstance(d, Quacks) + hits += not isinstance(sq, Quacks) + self.assertEqual(hits, 7 * N) + self.assertGreater(Hooked.calls, 0) + + class Late: + pass + + self.assertFalse(isinstance(Late(), Shape)) + Shape.register(Late) + for _ in range(N): + self.assertTrue(isinstance(Late(), Shape)) + + def test_abc_errors(self): + for _ in range(5): + with self.assertRaises(TypeError): + issubclass(1, Shape) + with self.assertRaises(TypeError): + Shape() + + def test_from_bytes(self): + for i in range(N): + a = int.from_bytes(b"\x01\x02", "big") + b = int.from_bytes(map(int, ("1", "2")), "big") + c = int.from_bytes([255, i & 255], byteorder="little", signed=True) + d = int.from_bytes(bytes([i & 255])) + e = int.from_bytes((x for x in (1, 0)), "little") + self.assertEqual((a, b, d, e), (258, 258, (N - 1) & 255, 1)) + self.assertEqual(c, int.from_bytes(bytes([255, (N - 1) & 255]), "little", signed=True)) + for _ in range(5): + with self.assertRaises(ValueError): + int.from_bytes(b"\x01", "middle") + with self.assertRaises((TypeError, ValueError)): + int.from_bytes([256], "big") + + class I(int): + pass + + self.assertIs(type(I.from_bytes(b"\x01", "big")), I) + + def test_mktime(self): + st = time.localtime(1700000000) + for _ in range(N): + t = time.mktime(st) + self.assertEqual(t, 1700000000.0) + with self.assertRaises(TypeError): + time.mktime(1) + + def test_catch_warnings(self): + before = (warnings.filters[:], warnings.showwarning) + for i in range(N): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + warnings.warn("quiet") + with warnings.catch_warnings(record=True) as log: + warnings.simplefilter("always") + warnings.warn("loud %d" % i) + self.assertEqual(len(log), 1) + self.assertEqual(str(log[0].message), "loud %d" % i) + self.assertEqual((warnings.filters, warnings.showwarning), before) + + def test_nested_catch_warnings(self): + for _ in range(N // 10): + with warnings.catch_warnings(): + warnings.simplefilter("error") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + warnings.warn("inner") + with self.assertRaises(UserWarning): + warnings.warn("outer") + + +class Day(date): + pass + + +class Stamp(datetime): + pass + + +class DateHelpers(unittest.TestCase): + def test_subclass_paths(self): + for i in range(N): + d = Day(2024, 1 + i % 12, 1 + i % 28) + s = Stamp(2024, 5, 17, i % 24, i % 60) + got = (d.toordinal(), d.weekday(), d.isocalendar()[1], s.timetuple()[3], s.isoformat()) + last = N - 1 + want_d = date(2024, 1 + last % 12, 1 + last % 28) + want_s = datetime(2024, 5, 17, last % 24, last % 60) + self.assertEqual( + got, + ( + want_d.toordinal(), + want_d.weekday(), + want_d.isocalendar()[1], + want_s.timetuple()[3], + want_s.isoformat(), + ), + ) + self.assertIs(type(d + timedelta(days=1)), Day) + + def test_calendar_methods(self): + d0 = date(2024, 5, 17) + for i in range(N): + d = d0 + timedelta(days=i) + iso = d.isocalendar() + tt = d.timetuple() + self.assertEqual(tuple(iso), (d.isocalendar().year, d.isocalendar().week, d.isocalendar().weekday)) + self.assertEqual(date.fromisocalendar(*iso), d) + self.assertEqual((tt.tm_year, tt.tm_mon, tt.tm_mday), (d.year, d.month, d.day)) + self.assertEqual(tt.tm_yday, d.toordinal() - date(d.year, 1, 1).toordinal() + 1) + + +R_UP = range(0, 100, 3) +R_DOWN = range(50, -50, -7) + + +class RangeLanes(unittest.TestCase): + def test_membership_matches_a_list(self): + for r in (R_UP, R_DOWN, range(5), range(0), range(10, 0), range(-3, 3), range(7, 8)): + items = list(r) + for _ in range(3): + for v in range(-60, 110): + self.assertEqual(v in r, v in items, (r, v)) + + def test_membership_in_a_hot_loop(self): + hits = 0 + for i in range(N * 10): + hits += i in R_UP + hits += -i in R_DOWN + self.assertEqual(hits, sum(i in list(R_UP) for i in range(N * 10)) + sum(-i in list(R_DOWN) for i in range(N * 10))) + + def test_other_operands(self): + class Three: + def __eq__(self, other): + return other == 3 + + def __hash__(self): + return 3 + + for _ in range(N): + got = ( + True in R_UP, + 3.0 in R_UP, + 3.5 in R_UP, + "3" in R_UP, + None in R_UP, + Three() in R_UP, + 2**70 in R_UP, + 2**70 in range(0, 2**80, 2**10), + (2**70 + 1) in range(0, 2**80, 2**10), + ) + self.assertEqual(got, (False, True, False, False, False, True, False, True, False)) + self.assertIn(False, R_UP) + + def test_slices_match_a_list(self): + for r in (R_UP, R_DOWN, range(5), range(0)): + items = list(r) + for sl in ( + slice(2, 8), + slice(None, 3), + slice(-3, None), + slice(None, None, 2), + slice(None, None, -1), + slice(8, 2, -2), + slice(100, 200), + slice(-100, 2), + slice(5, 5), + ): + for _ in range(20): + got = r[sl] + self.assertIs(type(got), range) + self.assertEqual(list(got), items[sl], (r, sl)) + + def test_slices_in_a_hot_loop(self): + total = 0 + for i in range(N * 10): + total += len(R_UP[2:8]) + R_UP[1:][0] + R_DOWN[::-1][i & 3] + want = sum(6 + 3 + list(R_DOWN)[::-1][i & 3] for i in range(N * 10)) + self.assertEqual(total, want) + with self.assertRaises(ValueError): + R_UP[::0] + with self.assertRaises(TypeError): + R_UP["a":] + + +class BytearrayRuns(unittest.TestCase): + def test_deleted_runs_match_a_list(self): + for sl in ( + slice(None, 3), + slice(-2, None), + slice(2, 5), + slice(5, 2), + slice(0, 0), + slice(None, None), + slice(100, 200), + slice(-100, 2), + slice(None, None, 2), + slice(None, None, -1), + slice(1, None, 3), + ): + for _ in range(20): + buf = bytearray(range(10)) + ref = list(range(10)) + del buf[sl] + del ref[sl] + self.assertEqual(list(buf), ref, sl) + + def test_consumed_prefix_loop(self): + buf = bytearray() + taken = [] + for i in range(N): + buf.extend(bytes([i & 255, 1, 2])) + taken.append(buf[0]) + del buf[:2] + del buf[-1:] + self.assertEqual(taken, [i & 255 for i in range(N)]) + self.assertEqual(buf, bytearray()) + + def test_exported_buffer_refuses(self): + buf = bytearray(b"abcdef") + with memoryview(buf): + for _ in range(5): + with self.assertRaises(BufferError): + del buf[:2] + del buf[2:2] + del buf[:2] + self.assertEqual(buf, b"cdef") + + def test_other_keys_and_subclasses(self): + class Buf(bytearray): + pass + + class Idx: + def __index__(self): + return 1 + + for _ in range(N // 10): + b = Buf(b"abcdef") + del b[:2] + del b[Idx() :] + c = bytearray(b"abcdef") + del c[Idx() : 3] + self.assertEqual((b, type(b), c), (b"c", Buf, b"adef")) + with self.assertRaises(TypeError): + del c["a":] + with self.assertRaises(ValueError): + del c[::0] + + +class Meta(type): + def __bool__(cls): + return cls.flag + + +class Flagged(metaclass=Meta): + flag = False + + +class LenMeta(type): + def __len__(cls): + return cls.size + + +class Counted(metaclass=LenMeta): + size = 0 + + +T_VALUES = [ + (ValueError, True), + (unittest.TestCase, True), + (types.MappingProxyType({}), False), + (types.MappingProxyType({1: 2}), True), + (types.SimpleNamespace(), True), + (slice(0), True), + (range(0), False), + (range(3), True), + (range(5, 0), False), + (range(5, 0, -1), True), + (memoryview(b""), False), + (memoryview(b"a"), True), + (0j, False), + (1j, True), + (complex(0.0, -0.0), False), + (property(), True), + (staticmethod(len), True), + ({}.keys(), False), + ({1: 2}.items(), True), + (b"", False), + (bytearray(b"a"), True), + (frozenset(), False), + (2**80, True), + (len, True), + (sys, True), +] + + +class NativeTruth(unittest.TestCase): + def test_or_and_forms(self): + for value, want in T_VALUES: + picked = taken = 0 + for i in range(N): + x = value or "other" + y = value and "kept" + picked += x is value + taken += y == "kept" + if value and i >= 0: + taken += 1 + if not value: + picked -= 1 + self.assertEqual((picked, taken), (N, 2 * N) if want else (-N, 0), value) + self.assertIs(bool(value), want) + + def test_metaclass_decides(self): + hits = 0 + for i in range(N): + Flagged.flag = bool(i & 1) + Counted.size = i & 1 + hits += (Flagged or 0) is Flagged + hits += (Counted and 1) == 1 + self.assertEqual(hits, 2 * (N // 2)) + Flagged.flag, Counted.size = False, 0 + for _ in range(N): + self.assertEqual((Flagged or "f", Counted or "c"), ("f", "c")) + + def test_changing_containers(self): + d = {} + keys, proxy = d.keys(), types.MappingProxyType(d) + seen = [] + for i in range(N): + if i & 1: + d[1] = 2 + else: + d.clear() + seen.append((bool(keys or 0), bool(proxy or 0))) + self.assertEqual(seen, [(bool(i & 1), bool(i & 1)) for i in range(N)]) + + def test_released_memoryview(self): + mv = memoryview(b"ab") + mv.release() + for _ in range(5): + with self.assertRaises(ValueError): + bool(mv) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_mro_lookup_through_bases.py b/tests/regrtest/test_mro_lookup_through_bases.py new file mode 100644 index 000000000..7ce6a095e --- /dev/null +++ b/tests/regrtest/test_mro_lookup_through_bases.py @@ -0,0 +1,131 @@ +"""Class attribute lookups on classes made over shared bases (as `email` +makes a header class per header), answered from the bases' own lookups: +diamonds, bases that disagree, names that move on a base after a subclass +looked them up, `__bases__` reassignment, and a metaclass `mro()`.""" + +import unittest + + +class SharedBases(unittest.TestCase): + def test_fresh_classes_over_two_bases(self): + class Base: + kind = "base" + + def describe(self): + return "base" + + class Mixin: + flavor = "mixin" + + def describe(self): + return "mixin" + + for i in range(500): + cls = type("_H%d" % i, (Mixin, Base), {}) + self.assertEqual(cls.kind, "base") + self.assertEqual(cls.flavor, "mixin") + self.assertEqual(cls().describe(), "mixin") + self.assertFalse(hasattr(cls, "missing")) + self.assertIs(cls.__repr__, object.__repr__) + cls2 = type("_G%d" % i, (Base, Mixin), {}) + self.assertEqual(cls2().describe(), "base") + + def test_diamond_takes_the_merge_order(self): + class A: + def f(self): + return "A" + + class B(A): + pass + + class C(A): + def f(self): + return "C" + + for _ in range(300): + D = type("D", (B, C), {}) + # B finds A.f, C finds C.f: the merge puts C before A. + self.assertEqual(D().f(), "C") + self.assertEqual([k.__name__ for k in D.__mro__], ["D", "B", "C", "A", "object"]) + E = type("E", (B,), {}) + self.assertEqual(E().f(), "A") + + def test_shared_owner_through_both_bases(self): + class Root: + x = 1 + + class L(Root): + pass + + class R(Root): + pass + + for _ in range(300): + K = type("K", (L, R), {}) + self.assertEqual(K.x, 1) + + def test_base_changes_after_lookup(self): + class Base: + pass + + class Other: + pass + + made = [type("_S%d" % i, (Base, Other), {}) for i in range(50)] + for cls in made: + self.assertFalse(hasattr(cls, "late")) + Other.late = "other" + for cls in made: + self.assertEqual(cls.late, "other") + Base.late = "base" + for cls in made: + self.assertEqual(cls.late, "base") + del Base.late + for cls in made: + self.assertEqual(cls.late, "other") + del Other.late + for cls in made: + self.assertFalse(hasattr(cls, "late")) + + def test_bases_reassigned(self): + class A: + v = "A" + + class B: + v = "B" + + class C: + w = "C" + + X = type("X", (A, C), {}) + self.assertEqual((X.v, X.w), ("A", "C")) + X.__bases__ = (B, C) + self.assertEqual((X.v, X.w), ("B", "C")) + Y = type("Y", (X,), {}) + self.assertEqual(Y.v, "B") + X.__bases__ = (A, C) + self.assertEqual((X.v, Y.v), ("A", "A")) + + def test_custom_mro(self): + class A: + v = "A" + + class B: + v = "B" + + class Reverse(type): + def mro(cls): + head, *rest = super().mro() + return [head] + list(reversed(rest[:-1])) + [rest[-1]] + + Z = Reverse("Z", (A, B), {}) + self.assertEqual([k.__name__ for k in Z.__mro__], ["Z", "B", "A", "object"]) + self.assertEqual(Z.v, "B") + # (A subclass gets the metaclass, so its MRO is reversed too.) + W = type("W", (Z,), {}) + self.assertEqual([k.__name__ for k in W.__mro__], ["W", "A", "B", "Z", "object"]) + self.assertEqual(W.v, "A") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_named_tuple_defaults_and_keywords.py b/tests/regrtest/test_named_tuple_defaults_and_keywords.py new file mode 100644 index 000000000..4def32c04 --- /dev/null +++ b/tests/regrtest/test_named_tuple_defaults_and_keywords.py @@ -0,0 +1,101 @@ +"""Named tuples built with defaults filled in or with keyword arguments. + +The construction lanes build the tuple directly from the positionals, the +keywords placed by field name, and the generated `__new__`'s defaults as +they stand; every call that binds otherwise must still raise as CPython's. +""" + +import collections +import typing +import unittest + + +P = collections.namedtuple("P", "x y z", defaults=(10, [20])) + + +class T(typing.NamedTuple): + a: int + b: str = "b" + c: tuple = () + + +class Sub(P): + __slots__ = () + + def total(self): + return self.x + self.y + + +class NamedTupleConstructionTests(unittest.TestCase): + ROUNDS = 4000 + + def test_defaults(self): + for _ in range(self.ROUNDS): + self.assertEqual(P(1), (1, 10, [20])) + self.assertEqual(P(1, 2), (1, 2, [20])) + self.assertEqual(T(1), (1, "b", ())) + self.assertEqual(T(1, "x"), (1, "x", ())) + self.assertIs(P(1).z, P(2).z) + self.assertIs(type(P(1)), P) + self.assertIs(type(Sub(1)), Sub) + self.assertEqual(Sub(1).total(), 11) + + def test_keywords(self): + for _ in range(self.ROUNDS): + self.assertEqual(P(x=1, y=2, z=3), (1, 2, 3)) + self.assertEqual(P(1, z=3), (1, 10, 3)) + self.assertEqual(P(z=3, x=1), (1, 10, 3)) + self.assertEqual(T(c=(1,), a=0), (0, "b", (1,))) + self.assertEqual(Sub(y=5, x=1).total(), 6) + + def test_binding_errors(self): + for _ in range(3): + with self.assertRaises(TypeError): + P() + with self.assertRaises(TypeError): + P(y=1) + with self.assertRaises(TypeError): + P(1, x=2) + with self.assertRaises(TypeError): + P(1, w=2) + with self.assertRaises(TypeError): + P(1, 2, 3, 4) + with self.assertRaises(TypeError): + T() + with self.assertRaises(TypeError): + P(1, **{"y": 1, "q": 2}) + + def test_defaults_rebound(self): + Q = collections.namedtuple("Q", "a b", defaults=(1,)) + for _ in range(self.ROUNDS): + self.assertEqual(Q(0), (0, 1)) + Q.__new__.__defaults__ = (7, 8) + self.assertEqual(Q(), (7, 8)) + self.assertEqual(Q(0), (0, 8)) + Q.__new__.__defaults__ = None + with self.assertRaises(TypeError): + Q(0) + self.assertEqual(Q(0, b=2), (0, 2)) + + def test_new_replaced(self): + R = collections.namedtuple("R", "a b", defaults=(1,)) + for _ in range(self.ROUNDS): + self.assertEqual(R(a=0), (0, 1)) + + def new(cls, a, b=5): + return tuple.__new__(cls, (a * 2, b)) + + R.__new__ = new + self.assertEqual(R(1), (2, 5)) + self.assertEqual(R(a=1, b=0), (2, 0)) + + def test_star_calls(self): + args = (1,) + kw = {"z": 3} + for _ in range(self.ROUNDS): + self.assertEqual(P(*args, **kw), (1, 10, 3)) + self.assertEqual(P(**{"x": 1}), (1, 10, [20])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_namedtuple_field_first.py b/tests/regrtest/test_namedtuple_field_first.py new file mode 100644 index 000000000..cb50229d3 --- /dev/null +++ b/tests/regrtest/test_namedtuple_field_first.py @@ -0,0 +1,157 @@ +"""Named tuple field reads that compiled code takes ahead of other lanes. + +A field read of a named tuple instance answers from its site's stamp +before the lanes for properties, `__slots__` members, and hooks. Each +case runs hot at a site that also sees other kinds of receivers with an +attribute of the same name, through a local and through a stack +receiver, and must agree with CPython, including after the class +changes. +""" + +import threading +import unittest +from collections import namedtuple + +N = 3000 + +P = namedtuple("P", "x y") + + +class Slotted: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x = x + self.y = y + + +class Propped: + @property + def x(self): + return "prop-x" + + y = "class-y" + + +class Plain: + def __init__(self): + self.x = "plain-x" + self.y = "plain-y" + + +class Loc(threading.local): + def __init__(self): + self.x = "local-x" + self.y = "local-y" + + +class SlotSub(P): + __slots__ = () + + @property + def total(self): + return self.x + self.y + + +def read_local(objs): + out = [] + for _ in range(N // len(objs)): + out = [] + for o in objs: + out.append((o.x, o.y)) + return out + + +holder = {} + + +def read_stack(): + out = None + for _ in range(N): + out = (holder["p"].x, holder["p"].y) + return out + + +class NamedTupleFieldFirstTests(unittest.TestCase): + def test_mixed_site(self): + p = P("tx", "ty") + objs = [p, Slotted("sx", "sy"), Propped(), Plain(), Loc(), p] + self.assertEqual( + read_local(objs), + [ + ("tx", "ty"), + ("sx", "sy"), + ("prop-x", "class-y"), + ("plain-x", "plain-y"), + ("local-x", "local-y"), + ("tx", "ty"), + ], + ) + + def test_stack_receiver(self): + holder["p"] = P(1, [2]) + self.assertEqual(read_stack(), (1, [2])) + holder["p"] = Slotted("a", "b") + self.assertEqual(read_stack(), ("a", "b")) + + def test_subclass_property_and_fields(self): + s = SlotSub(3, 4) + + def run(): + out = None + for _ in range(N): + out = (s.x, s.y, s.total) + return out + + self.assertEqual(run(), (3, 4, 7)) + with self.assertRaises(AttributeError): + s.z = 1 + + def test_field_overridden_later(self): + class Q(P): + pass + + q = Q("a", "b") + + def run(): + out = None + for _ in range(N): + out = (q.x, q.y) + return out + + self.assertEqual(run(), ("a", "b")) + Q.x = property(lambda self: "over") + self.assertEqual(run(), ("over", "b")) + del Q.x + self.assertEqual(run(), ("a", "b")) + + def test_getattribute_added_later(self): + class R(P): + pass + + r = R(5, 6) + + def run(): + out = None + for _ in range(N): + out = (r.x, r.y) + return out + + self.assertEqual(run(), (5, 6)) + R.__getattribute__ = lambda self, name: "hooked " + name + self.assertEqual(run(), ("hooked x", "hooked y")) + del R.__getattribute__ + self.assertEqual(run(), (5, 6)) + + def test_fresh_instances(self): + def run(): + total = 0 + for i in range(N): + total += P(i, 1).x + P(1, i).y + return total + + self.assertEqual(run(), 2 * sum(range(N))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_namedtuple_field_site.py b/tests/regrtest/test_namedtuple_field_site.py new file mode 100644 index 000000000..ba2f2e1bd --- /dev/null +++ b/tests/regrtest/test_namedtuple_field_site.py @@ -0,0 +1,58 @@ +"""Named tuple field reads in compiled code. + +A field read answers from its site's stamp while the class's version +holds; a subclass with an instance `__dict__` (the field descriptor still +wins), a subclass that overrides a field with a property, a class changed +mid-loop, and a site that sees several named tuple classes behave as in +CPython. Run it past the compile threshold. +""" + +from collections import namedtuple + +P = namedtuple("P", "x y label") + + +class Sub(P): + pass + + +class Prop(P): + @property + def x(self): + return -1 + + +def total(n, p): + t = 0 + for _ in range(n): + t += p.x + p.y + return t + + +def labels(n, ps): + out = [] + for i in range(n): + out.append(ps[i % len(ps)].label) + return out + + +N = 3000 +assert total(N, P(1, 2, "a")) == 3 * N +s = Sub(3, 4, "s") +s.x_shadow = 9 +s.__dict__["x"] = 100 +assert total(N, s) == 7 * N +assert total(N, Prop(5, 6, "p")) == 5 * N +assert labels(N, [P(0, 0, "a"), Sub(0, 0, "b"), Prop(0, 0, "c")])[:3] == ["a", "b", "c"] +q = P(7, 8, "q") +assert total(N, q) == 15 * N +P.y = property(lambda self: 1000) +assert total(10, q) == 1007 * 10 +del P.y +try: + total(1, q) +except AttributeError: + pass +else: + raise AssertionError("deleted field") +print("ok") diff --git a/tests/regrtest/test_namedtuple_keys_truth_range_slices.py b/tests/regrtest/test_namedtuple_keys_truth_range_slices.py new file mode 100644 index 000000000..bbe04f19b --- /dev/null +++ b/tests/regrtest/test_namedtuple_keys_truth_range_slices.py @@ -0,0 +1,296 @@ +"""Named tuples as dict keys and set members, truth tests of several +classes in one loop, range slices and `len()` of a `mappingproxy` or a +`memoryview`: the native lanes match the general paths, overrides of +`__hash__`, `__eq__`, `__bool__` and `__len__` stay in charge, and a +class changed under a loop is asked again.""" + +import itertools +import sys +import types +import unittest +from collections import deque, namedtuple + +N = 300 + +Point = namedtuple("Point", "x y") +Name = namedtuple("Name", "first last") +Deep = namedtuple("Deep", "p tag") + + +class Hashy(namedtuple("Hashy", "a b")): + __slots__ = () + + def __hash__(self): + return 7 + + +class Eqy(namedtuple("Eqy", "a b")): + __slots__ = () + + def __eq__(self, other): + return isinstance(other, Eqy) and self.a == other.a + + def __hash__(self): + return hash(self.a) + + +class T(tuple): + pass + + +class KeyTests(unittest.TestCase): + def test_dict_keys(self): + for _ in range(N): + d = {} + for i in range(8): + d[Point(i % 4, "k")] = i + self.assertEqual(len(d), 4) + self.assertEqual(d[Point(3, "k")], 7) + self.assertEqual(d[(3, "k")], 7) + self.assertEqual(d.get(Point(9, "k")), None) + self.assertIn(Point(0, "k"), d) + self.assertNotIn(Point(0, "z"), d) + d[(1, "k")] = "tuple" + self.assertEqual(d[Point(1, "k")], "tuple") + self.assertIs(type(next(iter(d))), Point) + self.assertEqual(d[Name(2, "k")], 6) + self.assertEqual(d[T((2, "k"))], 6) + del d[Point(2, "k")] + with self.assertRaises(KeyError): + d[Point(2, "k")] + + def test_set_members(self): + for _ in range(N): + s = {Point(1, 2), Point(1, 2), Name("a", "b"), (5, 6)} + self.assertEqual(len(s), 3) + self.assertIn(Point(1, 2), s) + self.assertIn((1, 2), s) + self.assertIn(Point(5, 6), s) + self.assertIn(Name("a", "b"), s) + self.assertNotIn(Point(2, 1), s) + s.add(Point(9, 9)) + s.discard((9, 9)) + self.assertNotIn(Point(9, 9), s) + self.assertEqual({Point(1, 2)} & {(1, 2)}, {(1, 2)}) + fs = frozenset([Point(1, "a")]) + self.assertIn(Point(1, "a"), fs) + + def test_hash_matches_tuple(self): + for _ in range(N): + self.assertEqual(hash(Point(1, "a")), hash((1, "a"))) + self.assertEqual(hash(Deep(Point(1, 2), "t")), hash(((1, 2), "t"))) + self.assertEqual(hash(T((1, 2, 3))), hash((1, 2, 3))) + self.assertEqual(hash(Point(1.5, None)), hash((1.5, None))) + self.assertEqual(hash(Point(10**30, True)), hash((10**30, True))) + with self.assertRaises(TypeError): + hash(Point([1], 2)) + with self.assertRaises(TypeError): + {Point([1], 2): 1} + with self.assertRaises(TypeError): + Point({}, 2) in {Point(1, 2)} + + def test_other_item_kinds(self): + for _ in range(N): + d = {Point(1.5, None): "f", Point(True, b"x"): "b", Deep(Point(1, 2), "t"): "deep"} + self.assertEqual(d[Point(1.5, None)], "f") + self.assertEqual(d[(1, b"x")], "b") + self.assertEqual(d[Deep(Point(1, 2), "t")], "deep") + self.assertEqual(d[((1, 2), "t")], "deep") + self.assertIn(Point(1.0, b"x"), d) + obj = object() + e = {Point(obj, 1): "o"} + self.assertEqual(e[Point(obj, 1)], "o") + self.assertNotIn(Point(object(), 1), e) + + def test_overrides(self): + for _ in range(N): + d = {Hashy(1, 2): "h"} + self.assertEqual(d[Hashy(1, 2)], "h") + self.assertNotIn((1, 2), d) + self.assertEqual(hash(Hashy(1, 2)), 7) + e = {Eqy(1, "x"): "e"} + self.assertEqual(e[Eqy(1, "other")], "e") + self.assertNotIn(Eqy(2, "x"), e) + self.assertIn(Eqy(1, 0), {Eqy(1, 5)}) + + def test_reference_counts(self): + marker = object() + before = sys.getrefcount(marker) + d = {} + for _ in range(N): + d[Point(marker, 1)] = 1 + d[Point(marker, 1)] + Point(marker, 1) in d + hash(Point(marker, 2)) + self.assertEqual(sys.getrefcount(marker), before + 1) + d.clear() + self.assertEqual(sys.getrefcount(marker), before) + + +class Plain: + pass + + +class WithBool: + def __init__(self, v): + self.v = v + + def __bool__(self): + return self.v + + +class WithLen: + def __init__(self, n): + self.n = n + + def __len__(self): + return self.n + + +class L(list): + pass + + +class TruthTests(unittest.TestCase): + def test_several_classes_in_one_loop(self): + things = [ + (Plain(), True), (WithBool(True), True), (WithBool(False), False), + (WithLen(0), False), (WithLen(3), True), (L(), False), (L([0]), True), + (Point(0, 0), True), (T(()), False), (deque(), False), (deque([0]), True), + ] + for _ in range(N): + for obj, want in things: + if obj: + got = True + else: + got = False + self.assertIs(got, want, obj) + self.assertIs(not obj, not want) + self.assertIs(bool(obj), want) + + def test_unrolled_tests(self): + a, b, c, d, e = Plain(), L([1]), Point(1, 2), deque([1]), WithLen(0) + hits = 0 + for _ in range(N * 20): + if a: + hits += 1 + if b: + hits += 1 + if c: + hits += 1 + if d: + hits += 1 + if e: + hits += 100 + self.assertEqual(hits, N * 20 * 4) + + def test_class_changed_under_the_loop(self): + class Flip: + pass + + class Other: + pass + + f, o = Flip(), Other() + seen = [] + for i in range(400): + if i == 200: + Flip.__bool__ = lambda self: False + if i == 300: + del Flip.__bool__ + Flip.__len__ = lambda self: 0 + seen.append((bool(f), bool(o))) + if f: + pass + if o: + pass + self.assertEqual(seen[:200], [(True, True)] * 200) + self.assertEqual(seen[200:], [(False, True)] * 200) + + def test_bool_that_raises(self): + class Bad: + def __bool__(self): + raise ValueError("no truth") + + b, p = Bad(), Plain() + for _ in range(50): + self.assertTrue(p) + with self.assertRaises(ValueError): + if b: + pass + + +class RangeSliceTests(unittest.TestCase): + def test_against_lists(self): + ranges = [range(0), range(7), range(3, 30, 4), range(20, -5, -3), range(-10, 10), range(5, 5), range(1, 2)] + bounds = [None, 0, 1, 2, 5, -1, -2, -7, 100, -100] + steps = [None, 1, 2, 3, -1, -2, -5, 100, -100] + for r in ranges: + xs = list(r) + for a, b, c in itertools.product(bounds, bounds, steps): + got = r[a:b:c] + self.assertIs(type(got), range) + self.assertEqual(list(got), xs[a:b:c], (r, a, b, c)) + self.assertEqual(len(got), len(xs[a:b:c])) + + def test_shapes_of_results(self): + for _ in range(N): + r = range(0, 100, 3) + self.assertEqual(r[2:8], range(6, 24, 3)) + self.assertEqual(r[::-1], range(99, -3, -3)) + self.assertEqual(r[:0], range(0, 0, 3)) + self.assertEqual(r[5:], range(15, 102, 3)) + self.assertEqual(repr(range(10)[2:5]), "range(2, 5)") + self.assertEqual(range(10)[::2][1:3], range(2, 6, 2)) + + def test_wide_values_and_errors(self): + big = range(0, 2**70, 2**65) + self.assertEqual(list(big[1:3]), [2**65, 2**66]) + edge = range(sys.maxsize - 10, sys.maxsize) + self.assertEqual(list(edge[-2:]), [sys.maxsize - 2, sys.maxsize - 1]) + self.assertEqual(list(edge[::-4]), [sys.maxsize - 1, sys.maxsize - 5, sys.maxsize - 9]) + self.assertEqual(len(range(10)[: 2**80]), 10) + self.assertEqual(len(range(10)[-(2**80) :]), 10) + with self.assertRaises(ValueError): + range(10)[::0] + with self.assertRaises(TypeError): + range(10)["a":] + + class Idx: + def __index__(self): + return 3 + + self.assertEqual(range(10)[Idx() :], range(3, 10)) + self.assertEqual(range(10)[: Idx() : Idx()], range(0, 3, 3)) + + +class LenTests(unittest.TestCase): + def test_mappingproxy(self): + d = {"a": 1} + mp = types.MappingProxyType(d) + for i in range(N): + self.assertEqual(len(mp), len(d)) + if i == 100: + d["b"] = 2 + self.assertEqual(len(mp), 2) + self.assertEqual(len(types.MappingProxyType({})), 0) + self.assertEqual(len(type("C", (), {"x": 1}).__dict__) > 1, True) + + def test_memoryview(self): + mv = memoryview(bytes(range(12))) + shaped = mv.cast("B", (3, 4)) + words = memoryview(bytearray(16)).cast("I") + for _ in range(N): + self.assertEqual(len(mv), 12) + self.assertEqual(len(shaped), 3) + self.assertEqual(len(words), 4) + self.assertEqual(len(mv[2:5]), 3) + self.assertEqual(len(memoryview(b"")), 0) + gone = memoryview(b"abc") + gone.release() + with self.assertRaises(ValueError): + len(gone) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_namespace_and_update_keywords.py b/tests/regrtest/test_namespace_and_update_keywords.py new file mode 100644 index 000000000..1ea37863b --- /dev/null +++ b/tests/regrtest/test_namespace_and_update_keywords.py @@ -0,0 +1,97 @@ +"""types.SimpleNamespace(k=v) and d.update(k=v) from compiled loops: the +namespace's attributes, repr, equality, vars() and cycles through it; a +subclass of SimpleNamespace; update over existing keys (order kept, values +replaced), over a dict with non-string keys, through a bound method held +in a local, on a dict subclass, and with a key whose hash collides with an +instance key whose __eq__ runs Python code.""" + +import gc +import types +import unittest + + +class NS(types.SimpleNamespace): + pass + + +class EqLog: + """A key equal to the string 'a', hashing as it does, that logs its + comparisons.""" + + log = [] + + def __hash__(self): + return hash("a") + + def __eq__(self, other): + EqLog.log.append(other) + return other == "a" + + +def namespaces(n): + out = None + for i in range(n): + ns = types.SimpleNamespace(a=i, b="x") + sub = NS(a=1) + out = (ns.a, ns.b, repr(types.SimpleNamespace(z=1, y=2)), vars(ns) == {"a": i, "b": "x"}, + ns == types.SimpleNamespace(a=i, b="x"), type(sub).__name__, sub.a) + ns.self = ns + return out + + +def updates(n): + out = None + for i in range(n): + d = {"b": 0, "a": 0} + d.update(a=i, c=2) + e = {1: "one"} + e.update(x=1) + up = d.update + up(b=5) + out = (list(d.items()), e) + return out + + +class Sub(dict): + def __setitem__(self, k, v): + super().__setitem__(k, v * 2) + + +def subclass_update(n): + s = None + for i in range(n): + s = Sub() + s.update(a=1) + return dict(s) + + +def colliding(n): + out = None + for i in range(n): + d = {EqLog(): 1} + d.update(a=2) + out = len(d) + return out + + +class Tests(unittest.TestCase): + def test_namespaces(self): + got = namespaces(3000) + self.assertEqual(got, (2999, "x", "namespace(z=1, y=2)", True, True, "NS", 1)) + gc.collect() + + def test_updates(self): + self.assertEqual(updates(3000), ([("b", 5), ("a", 2999), ("c", 2)], {1: "one", "x": 1})) + + def test_subclass(self): + # (dict.update doesn't call a subclass's __setitem__.) + self.assertEqual(subclass_update(2000), {"a": 1}) + + def test_colliding_key(self): + EqLog.log.clear() + self.assertEqual(colliding(1000), 1) + self.assertEqual(len(EqLog.log), 1000) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_namespace_attr_compiled.py b/tests/regrtest/test_namespace_attr_compiled.py new file mode 100644 index 000000000..118037a06 --- /dev/null +++ b/tests/regrtest/test_namespace_attr_compiled.py @@ -0,0 +1,49 @@ +"""Attribute reads of namespace-backed objects in compiled code. + +`typing.get_type_hints` reads `t.__args__` of a union, which WeavePy keeps +in a namespace, as `types.SimpleNamespace` keeps its fields. Compiled code +reads an entry the namespace holds in place; a missing one still raises +`AttributeError`, and the union's computed attributes still answer. Items +are heap objects. Run it past the compile threshold. +""" + +import types +import typing + + +class Item: + pass + + +def args_of(t): + return t.__args__ + + +def field(ns): + return ns.a + + +def missing(ns): + try: + return ns.zz + except AttributeError: + return "missing" + + +item = Item() + + +def f(a: int, b: typing.Optional[str] = None) -> typing.Optional[int]: + return None + + +for _ in range(3000): + assert args_of(typing.Optional[int]) == (int, type(None)) + assert args_of(int | str) == (int, str) + ns = types.SimpleNamespace(a=item) + assert field(ns) is item and missing(ns) == "missing" + ns.a = 5 + assert field(ns) == 5 + assert typing.get_origin(int | None) is typing.Union + hints = typing.get_type_hints(f) + assert hints["b"] == typing.Optional[str] and hints["return"] == int | None diff --git a/tests/regrtest/test_native_call_callbacks.py b/tests/regrtest/test_native_call_callbacks.py new file mode 100644 index 000000000..d81aeac89 --- /dev/null +++ b/tests/regrtest/test_native_call_callbacks.py @@ -0,0 +1,57 @@ +"""Callbacks that call an instance with a native `__call__`. + +`map(itemgetter(1), xs)`, `sorted(xs, key=attrgetter("n"))` and their kin +find the class's native `__call__` and its leaf half once per class +version: a subclass with its own `__call__`, or a class whose `__call__` +changes, is called as Python calls it. +""" + +import operator +import unittest + + +class P: + def __init__(self, n): + self.n = n + + +class NativeCallCallbackTests(unittest.TestCase): + def test_map_and_keys(self): + pairs = [(i, -i) for i in range(50)] + ps = [P(3), P(1), P(2)] + for _ in range(100): + self.assertEqual(list(map(operator.itemgetter(1), pairs))[:3], [0, -1, -2]) + self.assertEqual([p.n for p in sorted(ps, key=operator.attrgetter("n"))], [1, 2, 3]) + self.assertEqual(max(pairs, key=operator.itemgetter(1)), (0, 0)) + self.assertEqual(min(ps, key=operator.attrgetter("n")).n, 1) + + def test_subclass_and_changed_call(self): + try: + class G(operator.itemgetter): + def __call__(self, obj): + return ("own", obj[0]) + except TypeError: + self.skipTest("an immutable C type") + g = G(0) + for _ in range(100): + self.assertEqual(list(map(g, [(1,), (2,)])), [("own", 1), ("own", 2)]) + + class H(operator.itemgetter): + pass + + h = H(0) + self.assertEqual(list(map(h, [(5,)] * 50)), [5] * 50) + H.__call__ = lambda self, obj: "patched" + self.assertEqual(list(map(h, [(5,)] * 3)), ["patched"] * 3) + del H.__call__ + self.assertEqual(list(map(h, [(6,)])), [6]) + + def test_errors(self): + with self.assertRaises(IndexError): + list(map(operator.itemgetter(5), [(1,)])) + with self.assertRaises(AttributeError): + sorted([P(1), object()], key=operator.attrgetter("n")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_native_callback_reentry.py b/tests/regrtest/test_native_callback_reentry.py new file mode 100644 index 000000000..017c99577 --- /dev/null +++ b/tests/regrtest/test_native_callback_reentry.py @@ -0,0 +1,64 @@ +"""Python callbacks that native functions call (`bisect`'s `key`). + +A native function calling back into Python from a running frame reuses +the frame's interpreter state instead of publishing it again: results, +errors, tracebacks, `sys._getframe` from inside the callback, and +callbacks that reenter the native function behave as before. +""" + +import bisect +import sys +import unittest + +N = 3000 + + +class NativeCallbackTests(unittest.TestCase): + def test_bisect_key(self): + xs = list(range(0, 300, 3)) + for i in range(N): + r = (bisect.bisect_left(xs, i % 300, key=lambda x: x), + bisect.bisect_right(xs, 30, key=lambda x: x)) + self.assertEqual(r, (bisect.bisect_left(xs, (N - 1) % 300), 11)) + + def test_raising_key(self): + def bad(x): + raise KeyError(x) + + for _ in range(300): + try: + bisect.bisect_left([1, 2, 3], 2, key=bad) + except KeyError as e: + caught = e + tb = caught.__traceback__ + names = [] + while tb is not None: + names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + self.assertEqual(names[0], "test_raising_key") + self.assertEqual(names[-1], "bad") + + def test_frames_inside_key(self): + seen = [] + + def key(x): + seen.append(sys._getframe(1).f_code.co_name) + return x + + for _ in range(300): + bisect.bisect_left([1, 2, 3, 4], 3, key=key) + self.assertEqual(set(seen), {"test_frames_inside_key"}) + + def test_reentrant_key(self): + inner = list(range(10)) + + def key(x): + return bisect.bisect_left(inner, x, key=lambda y: y) + + for _ in range(N // 10): + r = bisect.bisect_left(list(range(10)), 5, key=key) + self.assertEqual(r, 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_native_class_descriptors.py b/tests/regrtest/test_native_class_descriptors.py new file mode 100644 index 000000000..9a8be4e7f --- /dev/null +++ b/tests/regrtest/test_native_class_descriptors.py @@ -0,0 +1,107 @@ +"""Native class and static methods read through a class. + +`itertools.chain.from_iterable`, `dict.fromkeys`, and `str.maketrans` bind +(or don't) as `classmethod.__get__` and `staticmethod.__get__` do, from a +site's memo once it's warm, while Python class methods keep their own +lane. `dict.fromkeys` of a string, a mapping, or a set builds in place. +""" + +import itertools +import unittest + +N = 3000 + + +class Plain: + @classmethod + def cm(cls, x): + return (cls, x) + + @staticmethod + def sm(x): + return x + + +class Sub(Plain): + pass + + +class D(dict): + pass + + +class NativeClassDescriptorTests(unittest.TestCase): + def test_chain_from_iterable_binds_each_read(self): + out = [] + for _ in range(N): + f = itertools.chain.from_iterable + out.append(f) + self.assertTrue(all(f.__self__ is itertools.chain for f in out)) + self.assertIsNot(out[0], out[1]) + self.assertEqual(list(out[-1]([[1, 2], [3]])), [1, 2, 3]) + + def test_fromkeys_through_classes(self): + for _ in range(N): + f = dict.fromkeys + self.assertIs(f.__self__, dict) + for _ in range(N): + g = D.fromkeys + self.assertIs(g.__self__, D) + self.assertIs(type(g("ab")), D) + + def test_maketrans_is_unbound(self): + for _ in range(N): + m = str.maketrans + self.assertFalse(hasattr(m, "__self__") and m.__self__ is str) + self.assertEqual("abc".translate(m("ab", "xy")), "xyc") + for _ in range(N): + b = bytes.maketrans + self.assertEqual(b"abc".translate(b(b"a", b"z")), b"zbc") + + def test_python_class_methods_unchanged(self): + for i in range(N): + r = Plain.cm(i) + self.assertEqual(r, (Plain, N - 1)) + for i in range(N): + r = Sub.cm(i) + self.assertEqual(r, (Sub, N - 1)) + for i in range(N): + r = Plain.sm(i) + self.assertEqual(r, N - 1) + + def test_reassigned_class_attribute(self): + class K: + @classmethod + def f(cls): + return 1 + + got = [] + for i in range(N): + if i == N // 2: + K.f = staticmethod(len) + got.append(K.f) + self.assertEqual(got[0](), 1) + self.assertIs(got[-1], len) + + def test_fromkeys_sources(self): + for _ in range(N): + a = dict.fromkeys("abca") + b = dict.fromkeys({"x": 1, "y": 2}, 0) + c = dict.fromkeys(frozenset([3]), "v") + d = dict.fromkeys("hé", []) + self.assertEqual(list(a.items()), [("a", None), ("b", None), ("c", None)]) + self.assertEqual(b, {"x": 0, "y": 0}) + self.assertEqual(c, {3: "v"}) + self.assertEqual(list(d), ["h", "é"]) + self.assertIs(d["h"], d["é"]) + s = {1, 2, 3} + self.assertEqual(list(dict.fromkeys(s)), list(s)) + e = {} + self.assertEqual(dict.fromkeys(e), {}) + self.assertEqual(dict.fromkeys(""), {}) + with self.assertRaises(TypeError): + dict.fromkeys([[1]]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_native_classmethod_calls.py b/tests/regrtest/test_native_classmethod_calls.py new file mode 100644 index 000000000..eb62505ae --- /dev/null +++ b/tests/regrtest/test_native_classmethod_calls.py @@ -0,0 +1,100 @@ +"""Native classmethods (chain.from_iterable, dict.fromkeys, bytes.fromhex, +float.fromhex, int.from_bytes) called through their class or a subclass +from compiled loops: each call gives the general call's value, a subclass +gets an instance of itself, Python code the call runs (an iterable's +__iter__, a subclass's __setitem__) runs at the call, and errors raise at +the call.""" + +import itertools +import unittest + + +class Chain(itertools.chain): + pass + + +class D(dict): + def __setitem__(self, k, v): + super().__setitem__(k, v * 2 if isinstance(v, int) else v) + + +class It: + def __init__(self): + self.seen = 0 + + def __iter__(self): + self.seen += 1 + return iter([[self.seen], [0]]) + + +class Bad: + def __iter__(self): + raise RuntimeError("no") + + +def chains(n, it): + out = None + xs = [[1], [2, 3]] + for i in range(n): + out = ( + list(itertools.chain.from_iterable(xs)), + list(itertools.chain.from_iterable(it)), + type(Chain.from_iterable(xs)).__name__, + list(Chain.from_iterable(x for x in xs)), + ) + return out + + +def others(n): + out = None + for i in range(n): + out = ( + dict.fromkeys("ab", 0), + D.fromkeys("ab", 1), + type(D.fromkeys("a")).__name__, + bytes.fromhex("01ff"), + float.fromhex("0x1.8p1"), + int.from_bytes(b"\x01\x00", "little"), + ) + return out + + +class NativeClassmethodTests(unittest.TestCase): + def test_chain(self): + for n in (1, 400): + it = It() + got = chains(n, it) + self.assertEqual(got[0], [1, 2, 3]) + self.assertEqual(got[1], [n, 0]) + self.assertEqual(got[2], "Chain") + self.assertEqual(got[3], [1, 2, 3]) + self.assertEqual(it.seen, n) + + def test_others(self): + want = ({"a": 0, "b": 0}, {"a": 2, "b": 2}, "D", b"\x01\xff", 3.0, 1) + for n in (1, 400): + self.assertEqual(others(n), want) + + def test_errors(self): + def bad(n): + caught = 0 + for i in range(n): + try: + itertools.chain.from_iterable(Bad()) + except RuntimeError: + caught += 1 + try: + bytes.fromhex("zz") + except ValueError: + caught += 1 + try: + itertools.chain.from_iterable(5) + except TypeError: + caught += 1 + return caught + + self.assertEqual(bad(300), 900) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_native_kw_in_place.py b/tests/regrtest/test_native_kw_in_place.py new file mode 100644 index 000000000..62f6e992f --- /dev/null +++ b/tests/regrtest/test_native_kw_in_place.py @@ -0,0 +1,218 @@ +"""Keyword calls of native methods and functions from compiled loops, +which read their operands where they sit on the stack: the results, the +order in which the operands are released, keyword values that are heap +objects the call drops last, callbacks that raise, bound classmethods, +and a receiver that only the bound method holds.""" + +import gc +import unittest + + +class Noisy: + """Records its finalization in a shared log.""" + + def __init__(self, log, tag, value=0): + self.log = log + self.tag = tag + self.value = value + + def __del__(self): + self.log.append(self.tag) + + def __lt__(self, other): + return self.value < other.value + + +def to_from_bytes(n): + acc = 0 + for i in range(n): + x = 258 + i + b = x.to_bytes(2, byteorder="big") + acc += int.from_bytes(b, byteorder="big") + acc += int.from_bytes(b, byteorder="little", signed=False) + acc += len(x.to_bytes(length=4, byteorder="little")) + return acc + + +def str_kw(n): + out = [] + for i in range(n): + s = "a.b.c\nd" + out.append(( + s.rsplit(".", maxsplit=1), + s.splitlines(keepends=True), + s.split(sep=".", maxsplit=i % 3), + s.expandtabs(tabsize=4), + )) + return out + + +def sort_with_key(n): + out = None + for i in range(n): + out = sorted([3, -1, 2, -i], key=abs, reverse=True) + return out + + +def raising_key(n): + caught = 0 + for i in range(n): + try: + sorted([1, 2, 3], key=lambda v: 1 // (v - 2)) + except ZeroDivisionError: + caught += 1 + return caught + + +def wrong_keyword(n): + caught = 0 + for i in range(n): + try: + (258).to_bytes(2, byteorder="big", bogus=1) + except TypeError as e: + caught += "bogus" in str(e) + return caught + + +def release_order(log, n): + for i in range(n): + items = [Noisy(log, "item-a", 2), Noisy(log, "item-b", 1)] + key = Noisy(log, "key") + # The list and the key function's holder die with the call. + result = sorted(items, key=lambda v, k=key: v.value, reverse=False) + del items, key + log.append("call") + del result + log.append("after") + + +class MyInt(int): + pass + + +def subclass_from_bytes(n): + out = None + for i in range(n): + out = MyInt.from_bytes(b"\x01\x02", byteorder="big") + return out + + +def keyword_halves(n): + out = [] + for i in range(n): + v = -(i % 300) - 1 + out.append(( + v.to_bytes(2, byteorder="little", signed=True), + (i % 256).to_bytes(byteorder="big"), + True.to_bytes(length=2, byteorder="big"), + (2**70 + i).to_bytes(length=9, byteorder="big"), + "a\r\nb\nc".splitlines(keepends=i % 2), + "a b c".rsplit(maxsplit=1), + "a-b-c".rsplit(sep="-"), + int.from_bytes(bytearray(b"\xff\x01"), byteorder="little", signed=True), + int.from_bytes(b"\x01\x02", byteorder="big"), + )) + return out + + +def keyword_half_errors(n): + caught = [] + for i in range(n): + for f in ( + lambda: (300).to_bytes(1, byteorder="big"), + lambda: (1).to_bytes(-1, byteorder="big"), + lambda: (1).to_bytes(2, byteorder="middle"), + lambda: (-1).to_bytes(2, byteorder="big"), + lambda: (1).to_bytes(2, "big", True), + lambda: "a".rsplit(maxsplit="1"), + lambda: int.from_bytes(b"\x01", "big", True), + lambda: int.from_bytes(b"\x01", byteorder="big", bogus=1), + lambda: int.from_bytes(b"\x01", byteorder="middle"), + ): + try: + f() + except (OverflowError, ValueError, TypeError) as e: + caught.append(type(e).__name__) + return caught + + +def bound_receiver(n): + acc = 0 + for i in range(n): + split = "x y z".split + acc += len(split(maxsplit=1)) + acc += len(bytes.fromhex("0102").hex(sep=":")) + return acc + + +class Tests(unittest.TestCase): + def test_to_from_bytes(self): + n = 3000 + want = sum( + (258 + i) + int.from_bytes((258 + i).to_bytes(2, "big"), "little") + 4 + for i in range(n) + ) + self.assertEqual(to_from_bytes(n), want) + + def test_str_methods(self): + out = str_kw(2000) + self.assertEqual(out[0], (["a.b", "c\nd"], ["a.b.c\n", "d"], ["a.b.c\nd"], "a.b.c\nd")) + self.assertEqual(out[1][2], ["a", "b.c\nd"]) + self.assertEqual(out[2][2], ["a", "b", "c\nd"]) + + def test_sort_key(self): + self.assertEqual(sort_with_key(2000), [-1999, 3, 2, -1]) + + def test_raising_callback(self): + self.assertEqual(raising_key(2000), 2000) + + def test_wrong_keyword(self): + self.assertEqual(wrong_keyword(2000), 2000) + + def test_release_order(self): + log = [] + release_order(log, 1500) + gc.collect() + # Each round: the key's holder dies when the lambda (an operand) + # goes, as the call returns; the sorted copy keeps the items alive + # until it goes, and releases its last item first. + self.assertEqual(log[:10], ["key", "call", "item-a", "item-b", "after"] * 2) + self.assertEqual(log[-5:], ["key", "call", "item-a", "item-b", "after"]) + self.assertEqual(log.count("call"), 1500) + self.assertEqual(log.count("key"), 1500) + self.assertEqual(log.count("item-a"), 1500) + + def test_keyword_halves(self): + out = keyword_halves(1000) + for i, row in enumerate(out): + v = -(i % 300) - 1 + self.assertEqual(row[0], v.to_bytes(2, "little", signed=True)) + self.assertEqual(row[1], bytes([i % 256])) + self.assertEqual(row[2], b"\x00\x01") + self.assertEqual(row[3], (2**70 + i).to_bytes(9, "big")) + self.assertEqual(row[4], ["a\r\n", "b\n", "c"] if i % 2 else ["a", "b", "c"]) + self.assertEqual(row[5], ["a b", "c"]) + self.assertEqual(row[6], ["a", "b", "c"]) + self.assertEqual(row[7], 511) + self.assertEqual(row[8], 258) + + def test_keyword_half_errors(self): + caught = keyword_half_errors(500) + self.assertEqual( + caught[:9], + ["OverflowError", "ValueError", "ValueError", "OverflowError", "TypeError", + "TypeError", "TypeError", "TypeError", "ValueError"], + ) + self.assertEqual(len(caught), 4500) + + def test_subclass_from_bytes(self): + r = subclass_from_bytes(2000) + self.assertIs(type(r), MyInt) + self.assertEqual(r, 258) + + def test_bound_receiver(self): + self.assertEqual(bound_receiver(2000), 2000 * (2 + 5)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_native_methods_on_stack_receivers.py b/tests/regrtest/test_native_methods_on_stack_receivers.py new file mode 100644 index 000000000..f785b6f47 --- /dev/null +++ b/tests/regrtest/test_native_methods_on_stack_receivers.py @@ -0,0 +1,106 @@ +"""Native container methods called on an expression's result. + +`o.items.append(x)`, `d[k].append(v)` and `make().append(x)` call the +method on a receiver the stack holds, not a local; compiled code checks the +receiver's type in line and runs the method's kernel there. The receiver +must then be released as the full call releases it (a temporary dies at +once, its finalizers before the next statement), and every other receiver +must take the general path. +""" + +import unittest + + +class Holder: + def __init__(self): + self.items = [] + self.table = {} + self.seen = set() + + +class Finalized: + count = 0 + + def __del__(self): + Finalized.count += 1 + + +class ListSub(list): + def append(self, value): + super().append(("sub", value)) + + +class StackReceiverTests(unittest.TestCase): + ROUNDS = 5000 + + def test_attribute_receivers(self): + h = Holder() + for i in range(self.ROUNDS): + h.items.append(i) + h.seen.add(i % 7) + h.table.get(i) + self.assertEqual(len(h.items), self.ROUNDS) + self.assertEqual(h.items[-1], self.ROUNDS - 1) + self.assertEqual(h.seen, set(range(7))) + + def test_subscript_receivers(self): + groups = {k: [] for k in range(5)} + rows = [[] for _ in range(3)] + for i in range(self.ROUNDS): + groups[i % 5].append(i) + rows[i % 3].append(i) + self.assertEqual([len(v) for v in groups.values()], [1000] * 5) + self.assertEqual(sum(len(r) for r in rows), self.ROUNDS) + + def test_temporary_receiver_dies_promptly(self): + def make(): + return [Finalized()] + + Finalized.count = 0 + for i in range(self.ROUNDS): + make().append(i) + self.assertEqual(Finalized.count, i + 1) + + def test_receiver_type_changes(self): + h = Holder() + values = [[], ListSub(), (), [], "str"] + out = [] + for i in range(self.ROUNDS): + h.items = values[i % len(values)] + try: + h.items.append(i) + except AttributeError: + out.append("no-append") + self.assertEqual(values[1][:2], [("sub", 1), ("sub", 6)]) + self.assertEqual(len(values[0]), self.ROUNDS // 5) + self.assertEqual(out.count("no-append"), 2 * self.ROUNDS // 5) + + def test_results_kept(self): + d = {"a": 1} + h = Holder() + h.table = d + got = [] + for _ in range(self.ROUNDS): + got.append(h.table.get("a")) + got.append(h.table.get("b", 2)) + self.assertEqual(got[:4], [1, 2, 1, 2]) + s = "abc" + h.text = s + for _ in range(self.ROUNDS): + self.assertTrue(h.text.startswith("a")) + self.assertEqual(h.text.upper(), "ABC") + + def test_small_int_and_const_arguments(self): + h = Holder() + for i in range(self.ROUNDS): + h.items.append(3) + h.items.append("x") + self.assertEqual(h.items[:4], [3, "x", 3, "x"]) + h.items.clear() + for i in range(100): + h.items.insert(0, i) + self.assertEqual(h.items[:3], [99, 98, 97]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_native_next_and_csv_reader.py b/tests/regrtest/test_native_next_and_csv_reader.py new file mode 100644 index 000000000..5b9691848 --- /dev/null +++ b/tests/regrtest/test_native_next_and_csv_reader.py @@ -0,0 +1,75 @@ +"""A class's native `__next__` stepped directly, and the CSV reader's state. + +Iterating an instance whose class has a native `__next__` (an +`io.StringIO`) calls it without looking it up each step; a subclass's +own `__next__`, or one assigned later, wins. The CSV reader keeps +`line_num` and its re-entry check as before. +""" + +import csv +import io +import unittest + +N = 3000 + + +class Shout(io.StringIO): + def __next__(self): + return super().__next__().upper() + + +class NativeNextTests(unittest.TestCase): + def test_stringio_lines(self): + text = "a\nb\nc\n" + for _ in range(N // 10): + r = list(io.StringIO(text)) + self.assertEqual(r, ["a\n", "b\n", "c\n"]) + self.assertEqual(list(Shout(text)), ["A\n", "B\n", "C\n"]) + s = io.StringIO(text) + self.assertEqual(next(s), "a\n") + self.assertEqual(list(s), ["b\n", "c\n"]) + + def test_assigned_later(self): + class Lines(io.StringIO): + pass + + for _ in range(N // 10): + self.assertEqual(list(Lines("x\ny\n")), ["x\n", "y\n"]) + def stop(self): + raise StopIteration + + Lines.__next__ = stop + self.assertEqual(list(Lines("x\ny\n")), []) + del Lines.__next__ + self.assertEqual(list(Lines("x\n")), ["x\n"]) + + +class CsvReaderStateTests(unittest.TestCase): + def test_line_num(self): + text = "a,b\n1,2\n3,\"4\n5\"\n" + for _ in range(N // 10): + r = csv.reader(io.StringIO(text)) + rows = [] + nums = [] + for row in r: + rows.append(row) + nums.append(r.line_num) + self.assertEqual(rows, [["a", "b"], ["1", "2"], ["3", "4\n5"]]) + self.assertEqual(nums, [1, 2, 4]) + + def test_reentry(self): + reader = None + + def lines(): + yield "a,b\n" + next(reader) + yield "c,d\n" + + reader = csv.reader(lines()) + self.assertEqual(next(reader), ["a", "b"]) + with self.assertRaises((csv.Error, ValueError, StopIteration)): + next(reader) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_native_values_through_builtins.py b/tests/regrtest/test_native_values_through_builtins.py new file mode 100644 index 000000000..8c4845f5d --- /dev/null +++ b/tests/regrtest/test_native_values_through_builtins.py @@ -0,0 +1,376 @@ +"""`datetime`, `date`, `time`, `timedelta` and `Decimal` values keep +their native comparison, arithmetic, hash, truth and unary operations +when a builtin asks for them: `sorted`, `max`, `min`, `sum`, `bisect`, +`heapq`, `in`, `list.index`, dict and set keys, `bool`, `abs`, `int`, +`float`, `round`, the `operator` functions. Each gives what the methods +give, and subclasses, special values, contexts and traps still decide.""" + +import bisect +import decimal +import functools +import heapq +import operator +import unittest +from datetime import date, datetime, time, timedelta, timezone +from decimal import Decimal as D +from fractions import Fraction + +N = 200 + +DTS = [datetime(2024, 1, 1) + timedelta(hours=7 * i % 23, days=i * 5 % 17) for i in range(20)] +DATES = [date(2024, 1, 1 + i * 7 % 28) for i in range(20)] +TDS = [timedelta(seconds=i * 37 % 100) for i in range(20)] +DECS = [D(i * 7 % 13) / 7 for i in range(20)] +TIMES = [time(i * 5 % 24, i * 7 % 60) for i in range(20)] + + +def by_methods(xs): + """`xs` sorted by `__lt__` calls alone (an insertion sort).""" + out = [] + for x in xs: + i = 0 + while i < len(out) and not x.__lt__(out[i]): + i += 1 + out.insert(i, x) + return out + + +class Ordering(unittest.TestCase): + def test_sorted_matches_the_methods(self): + for xs in (DTS, DATES, TDS, DECS, TIMES): + want = by_methods(xs) + for _ in range(N): + got = sorted(xs) + self.assertEqual(got, want) + self.assertEqual([id(x) for x in got], [id(x) for x in want]) + self.assertEqual(sorted(xs, reverse=True), want[::-1][:0] + sorted(want, reverse=True)) + + def test_max_min(self): + for xs in (DTS, DATES, TDS, DECS, TIMES): + want = by_methods(xs) + for _ in range(N): + got = (min(xs), max(xs)) + self.assertEqual(got, (want[0], want[-1])) + + def test_tuples_and_keys(self): + recs = [(d, i) for i, d in enumerate(DTS)] + for _ in range(N): + a = sorted(recs) + b = sorted(recs, key=operator.itemgetter(0)) + c = max(recs, key=lambda r: r[0]) + self.assertEqual([r[0] for r in a], sorted(DTS)) + self.assertEqual([r[0] for r in b], sorted(DTS)) + self.assertEqual(c[0], max(DTS)) + + def test_search(self): + s = sorted(DTS) + for _ in range(N): + got = (bisect.bisect_left(s, DTS[3]), DTS[3] in DTS, DTS.index(DTS[15]), DTS.count(DTS[2]), + datetime(2030, 1, 1) in DTS, DECS.index(D(0)), D("0.0") in DECS, 0 in DECS) + self.assertEqual(got[0], s.index(DTS[3])) + self.assertEqual(got[1:], (True, 15, DTS.count(DTS[2]), False, 0, True, True)) + + def test_heap(self): + for _ in range(N): + h = [] + for d in DTS[:8]: + heapq.heappush(h, d) + out = [heapq.heappop(h) for _ in range(8)] + self.assertEqual(out, sorted(DTS[:8])) + self.assertEqual(heapq.nsmallest(3, DECS), sorted(DECS)[:3]) + + def test_naive_and_aware_do_not_order(self): + mixed = [datetime(2024, 1, 1), datetime(2024, 1, 1, tzinfo=timezone.utc)] + for _ in range(20): + with self.assertRaises(TypeError): + sorted(mixed) + with self.assertRaises(TypeError): + max(mixed) + self.assertFalse(mixed[0] in mixed[1:]) + self.assertEqual(mixed.index(mixed[1]), 1) + + def test_unlike_kinds(self): + for _ in range(20): + with self.assertRaises(TypeError): + sorted([date(2024, 1, 1), timedelta(1)]) + with self.assertRaises(TypeError): + max(D(1), date(2024, 1, 1)) + self.assertFalse(date(2024, 1, 1) == D(1)) + self.assertFalse(date(2024, 1, 1) in [timedelta(1), D(5), 3]) + # (A `datetime` is a `date`, but they never compare equal.) + self.assertFalse(datetime(2024, 1, 1) == date(2024, 1, 1)) + self.assertNotIn(date(2024, 1, 1), [datetime(2024, 1, 1)]) + + def test_subclass_methods_decide(self): + class Backwards(D): + def __lt__(self, other): + return D.__gt__(self, other) + + class Loose(date): + def __eq__(self, other): + return True + + __hash__ = date.__hash__ + + xs = [Backwards(3), Backwards(1), Backwards(2)] + for _ in range(N): + got = sorted(xs) + found = Loose(2020, 1, 1) in [date(1999, 9, 9)] + self.assertEqual([int(x) for x in got], [3, 2, 1]) + self.assertTrue(found) + + +class Arithmetic(unittest.TestCase): + def test_sum(self): + for _ in range(N): + got = (sum(TDS, timedelta()), sum(DECS), sum(DECS, D(0)), + functools.reduce(operator.add, TDS), operator.sub(DTS[1], DTS[0]), + operator.add(DATES[0], TDS[3]), operator.mul(TDS[3], 2), operator.mul(D(3), D("1.5"))) + total = timedelta() + for t in TDS: + total = total.__add__(t) + dec = D(0) + for x in DECS: + dec = dec.__add__(x) + self.assertEqual(got, (total, dec, dec, total, DTS[1] - DTS[0], DATES[0] + TDS[3], TDS[3] * 2, D("4.5"))) + + def test_sum_errors(self): + for _ in range(20): + with self.assertRaises(TypeError): + sum(DATES, date(2024, 1, 1)) + with self.assertRaises(TypeError): + sum(TDS) + with self.assertRaises(OverflowError): + sum([date.max, timedelta(1)][1:], date.max) + with self.assertRaises(TypeError): + operator.add(D(1), 1.5) + + def test_context_is_used(self): + with decimal.localcontext() as ctx: + ctx.prec = 3 + for _ in range(N): + got = (sum([D("1.2345"), D("2.3456")]), +D("1.23456"), -D("9.87654"), abs(D("-5.55555")), + operator.add(D("1.2345"), D(1))) + self.assertEqual(got, (D("3.58"), D("1.23"), D("-9.88"), D("5.56"), D("2.23"))) + self.assertEqual(+D("1.23456"), D("1.23456")) + + def test_trapped_conditions_raise(self): + with decimal.localcontext() as ctx: + ctx.traps[decimal.Inexact] = True + ctx.prec = 3 + for _ in range(20): + with self.assertRaises(decimal.Inexact): + sum([D("1.2345"), D("2.3456")]) + with self.assertRaises(decimal.Inexact): + +D("1.23456") + self.assertEqual(sum([D("1.2"), D("2.3")]), D("3.5")) + + def test_unary_and_abs(self): + td = timedelta(days=-1, seconds=30) + for _ in range(N): + got = (-td, +td, abs(td), -D("1.5"), +D("-0"), abs(D("-2.50")), operator.neg(td), operator.pos(D(2)), + operator.abs(td)) + self.assertEqual(got, (timedelta(days=1, seconds=-30), td, timedelta(seconds=86370), D("-1.5"), D("0"), + D("2.50"), timedelta(days=1, seconds=-30), D(2), timedelta(seconds=86370))) + self.assertEqual(str(abs(D("-2.50"))), "2.50") + self.assertEqual(str(-D("0")), "0") + self.assertTrue((-D("NaN")).is_nan()) + self.assertEqual(-D("Infinity"), D("-Infinity")) + for _ in range(20): + with self.assertRaises(TypeError): + -date(2024, 1, 1) + with self.assertRaises(TypeError): + abs(datetime(2024, 1, 1)) + with self.assertRaises(TypeError): + ~D(1) + + def test_subclass_operator_methods_decide(self): + class Flipped(timedelta): + def __neg__(self): + return "neg" + + def __abs__(self): + return "abs" + + def __bool__(self): + return False + + def __add__(self, other): + return "add" + + f = Flipped(1) + for _ in range(N): + got = (-f, abs(f), bool(f), operator.add(f, f), sum([f], f), not f) + self.assertEqual(got, ("neg", "abs", False, "add", "add", True)) + + +class Truth(unittest.TestCase): + def test_bool(self): + for _ in range(N): + got = (bool(D(0)), bool(D("0.00")), bool(D("-0")), bool(D("0.01")), bool(D("NaN")), + bool(timedelta(0)), bool(timedelta(microseconds=1)), bool(date(1, 1, 1)), bool(time(0)), + not D(0), not timedelta(1)) + self.assertEqual(got, (False, False, False, True, True, False, True, True, True, True, False)) + + def test_conditions(self): + zeros = picks = 0 + for i in range(N): + x = D(i % 3) + t = timedelta(seconds=i % 2) + if x: + picks += 1 + if not t: + zeros += 1 + y = x or D(7) + z = t and "yes" + self.assertEqual((picks, zeros), (N - (N + 2) // 3, N // 2)) + self.assertEqual((y, z), (D((N - 1) % 3) or D(7), timedelta(seconds=(N - 1) % 2) and "yes")) + self.assertEqual([x for x in DECS if x], [x for x in DECS if x != 0]) + self.assertEqual(any(TDS), True) + self.assertEqual(all(TDS), all(t != timedelta(0) for t in TDS)) + + +class Conversions(unittest.TestCase): + def test_int_float_round(self): + x = D("123.456789") + for _ in range(N): + got = (int(x), float(x), round(x), round(x, 2), int(D("-7.9")), float(D("0.1")), round(D("2.5")), + round(D("3.5")), operator.index(True)) + self.assertEqual(got, (123, 123.456789, 123, D("123.46"), -7, 0.1, 2, 4, 1)) + self.assertIs(type(round(x)), int) + self.assertIs(type(round(x, 2)), D) + + def test_special_values_raise(self): + for _ in range(20): + with self.assertRaises(ValueError): + int(D("NaN")) + with self.assertRaises(OverflowError): + int(D("Infinity")) + with self.assertRaises(ValueError): + round(D("NaN")) + self.assertEqual(float(D("-Infinity")), float("-inf")) + self.assertNotEqual(float(D("NaN")), float(D("NaN"))) + with self.assertRaises(TypeError): + int(timedelta(1)) + with self.assertRaises(TypeError): + float(date(2024, 1, 1)) + + +class Numbers(unittest.TestCase): + def test_decimal_and_int(self): + x = D("2.5") + for _ in range(N): + got = (x > 2, x < 3, x == 2, x != 2, x >= True, D(3) == 3, D(10**30) == 10**30, x <= -(10**40), + max(x, 2, 3), sorted([x, 1, 3, D(2)]), 3 in [D(3)], D(1) == True) + self.assertEqual(got, (True, True, False, True, True, True, True, False, 3, [1, D(2), x, 3], True, True)) + + def test_decimal_and_float(self): + x = D("2.5") + with decimal.localcontext() as ctx: + for _ in range(N): + ctx.clear_flags() + got = (x == 2.5, x != 2.5, x == 0.1, D("0.1") == 0.1, x > 2.4, x < 2.4, x <= 2.5, 2.5 in [x]) + flagged = ctx.flags[decimal.FloatOperation] + self.assertEqual(got, (True, False, False, False, True, False, True, True)) + self.assertTrue(flagged) + self.assertEqual(x == float("nan"), False) + self.assertEqual(x < float("inf"), True) + self.assertEqual(D("Infinity") == float("inf"), True) + + def test_float_trap(self): + x = D("2.5") + with decimal.localcontext() as ctx: + ctx.traps[decimal.FloatOperation] = True + for _ in range(20): + ctx.clear_flags() + # (Equality records the condition without raising.) + self.assertTrue(x == 2.5) + self.assertTrue(ctx.flags[decimal.FloatOperation]) + with self.assertRaises(decimal.FloatOperation): + x < 2.5 + with self.assertRaises(decimal.FloatOperation): + sorted([x, 1.5]) + self.assertEqual(sorted([x, 1, D(0)]), [D(0), 1, x]) + + def test_nan_comparisons(self): + nan = D("NaN") + for _ in range(20): + self.assertFalse(nan == nan) + self.assertTrue(nan != D(1)) + self.assertFalse(nan == 1) + self.assertFalse(nan == 1.5) + with self.assertRaises(decimal.InvalidOperation): + nan < D(1) + with self.assertRaises(decimal.InvalidOperation): + D(1) > nan + with self.assertRaises(decimal.InvalidOperation): + sorted([D(1), nan]) + + def test_other_numbers(self): + x = D("0.5") + for _ in range(20): + self.assertTrue(x == Fraction(1, 2)) + self.assertTrue(x < Fraction(2, 3)) + self.assertFalse(x == "0.5") + self.assertTrue(x == 0.5 + 0j) + with self.assertRaises(TypeError): + x < "1" + with self.assertRaises(TypeError): + x < 1j + + +class Keys(unittest.TestCase): + def test_decimal_keys(self): + x = D("123.456789") + for i in range(N): + d = {x: 1, D(2): "two"} + got = (d[x], d[D("123.456789")], d[2], d[D("2.0")], D(2) in d, 2.0 in d, x in {D(1), D(3)}, + D("3.00") in {D(1), D(3)}, d.get(D(9)), len({D(1): "a", D("1.0"): "b"}), + {1: "a", D(1): "b"}, {D(1): "a", 1: "b", True: "c"}) + self.assertEqual(got[:10], (1, 1, "two", "two", True, True, False, True, None, 1)) + self.assertEqual(got[10], {1: "b"}) + self.assertEqual(list(got[10]), [1]) + self.assertIs(type(list(got[10])[0]), int) + self.assertEqual(list(got[11].items()), [(D(1), "c")]) + self.assertEqual(hash(D(5)), hash(5)) + self.assertEqual(hash(D("0.5")), hash(0.5)) + self.assertEqual(len(set(DECS)), len({str(+x.normalize()) for x in DECS})) + + def test_date_keys(self): + d1, dt1, td1, t1 = date(2024, 5, 17), datetime(2024, 5, 17, 1, 2, 3), timedelta(1), time(1, 2) + for i in range(N): + d = {d1: "d", dt1: "dt", td1: "td", t1: "t"} + got = (d[date(2024, 5, 17)], d[datetime(2024, 5, 17, 1, 2, 3)], d[timedelta(hours=24)], d[time(1, 2)], + date(2024, 5, 18) in d, len({d1: 1, date(2024, 5, 17): 2}), {d1: 1, date(2024, 5, 17): 2}[d1], + {date(2024, 1, i % 28 + 1): i}.popitem()[1]) + self.assertEqual(got, ("d", "dt", "td", "t", False, 1, 2, N - 1)) + self.assertEqual(len(set(DATES)), len({d.toordinal() for d in DATES})) + self.assertEqual(len({d: 1 for d in DTS}), len(set(DTS))) + aware = datetime(2024, 5, 17, 1, 2, 3, tzinfo=timezone.utc) + other = aware.astimezone(timezone(timedelta(hours=5))) + self.assertEqual({aware: 1}[other], 1) + self.assertNotIn(dt1, {aware: 1}) + + def test_unhashable_and_special(self): + for _ in range(20): + with self.assertRaises(TypeError): + {D("sNaN"): 1} + self.assertEqual(len({D("NaN"): 1, D("NaN"): 2}), 2) + self.assertEqual(len({D("Infinity"): 1, float("inf"): 2}), 1) + + def test_subclass_hash_decides(self): + class Odd(D): + def __hash__(self): + return 7 + + def __eq__(self, other): + return isinstance(other, Odd) + + for _ in range(N): + d = {Odd(1): "a", Odd(2): "b"} + got = (len(d), d[Odd(99)], Odd(5) in d, D(1) in d) + self.assertEqual(got, (1, "b", True, False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_ne_inverts_eq_lane.py b/tests/regrtest/test_ne_inverts_eq_lane.py new file mode 100644 index 000000000..9886f7a62 --- /dev/null +++ b/tests/regrtest/test_ne_inverts_eq_lane.py @@ -0,0 +1,144 @@ +"""`a != b` in compiled code where the class defines `__eq__` but not +`__ne__` (`object.__ne__` inverts the method's answer): bool answers, +`NotImplemented` (the reflected method, then identity), a non-bool answer +(its truth inverted), a subclass operand whose own method goes first, a +class that later gains `__ne__`, and `total_ordering`'s `__gt__`, which +uses `!=`.""" + +import functools +import unittest + +N = 2000 + + +class E: + __slots__ = ("v",) + + def __init__(self, v): + self.v = v + + def __eq__(self, o): + return isinstance(o, E) and self.v == o.v + + __hash__ = None + + +class NI: + def __init__(self, v): + self.v = v + + def __eq__(self, o): + if not isinstance(o, NI): + return NotImplemented + return self.v == o.v + + +class Other: + def __eq__(self, o): + return "yes" + + +class Num: + def __init__(self, v): + self.v = v + + def __eq__(self, o): + return self.v - o.v + + +class Sub(E): + __slots__ = () + + def __ne__(self, o): + return "sub" + + +class Late: + def __init__(self, v): + self.v = v + + def __eq__(self, o): + return self.v == o.v + + +@functools.total_ordering +class V: + def __init__(self, v): + self.v = v + + def __eq__(self, o): + return self.v == o.v + + def __lt__(self, o): + return self.v < o.v + + +def ne_loop(a, b, n): + t = 0 + for _ in range(n): + if a != b: + t += 1 + return t + + +def ne_value(a, b): + return a != b + + +class NeInvertsEqTests(unittest.TestCase): + def test_bool_answers(self): + self.assertEqual(ne_loop(E(1), E(2), N), N) + self.assertEqual(ne_loop(E(1), E(1), N), 0) + self.assertEqual(ne_loop(E(1), 5, N), N) + + def test_not_implemented(self): + self.assertEqual(ne_loop(NI(1), NI(1), N), 0) + # NotImplemented from both sides: identity decides. + x = NI(1) + self.assertEqual(ne_loop(x, 3, N), N) + for _ in range(N // 10): + self.assertIs(ne_value(x, x), False) + # The reflected `Other.__eq__` answers through `__ne__`'s default. + self.assertIs(ne_value(x, Other()), False) + + def test_non_bool_answer(self): + for _ in range(N // 10): + self.assertIs(ne_value(Num(3), Num(3)), True) + self.assertIs(ne_value(Num(3), Num(1)), False) + + def test_subclass_goes_first(self): + for _ in range(N // 10): + self.assertEqual(ne_value(E(1), Sub(1)), "sub") + self.assertIs(ne_value(Sub(1), E(1)), "sub") + + def test_class_gains_ne(self): + a, b = Late(1), Late(1) + self.assertEqual(ne_loop(a, b, N), 0) + Late.__ne__ = lambda self, o: True + try: + self.assertEqual(ne_loop(a, b, N), N) + finally: + del Late.__ne__ + self.assertEqual(ne_loop(a, b, N), 0) + + def test_total_ordering(self): + vs = [V(i % 7) for i in range(10)] + for _ in range(N // 10): + self.assertEqual(max(vs).v, 6) + self.assertEqual(min(vs).v, 0) + self.assertTrue(vs[1] > vs[0]) + self.assertFalse(vs[0] > vs[0]) + self.assertTrue(vs[1] >= vs[1]) + + def test_raising_eq(self): + class Bad: + def __eq__(self, o): + raise KeyError("eq") + + for _ in range(N // 100): + with self.assertRaises(KeyError): + ne_value(Bad(), Bad()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_nested_helper_calls.py b/tests/regrtest/test_nested_helper_calls.py new file mode 100644 index 000000000..5da073ef2 --- /dev/null +++ b/tests/regrtest/test_nested_helper_calls.py @@ -0,0 +1,138 @@ +"""Hot loops calling short helpers that call helpers of their own. + +The frame JIT lowers a short callee's body into its caller, and a callee's +callee in turn once the frameless evaluator has run it; tier 2 leaves a +loop whose guarded calls run frameless to the frame JIT. These loops check +results, rebinding of the helpers mid-loop, exceptions raised from the +innermost helper, and helpers with defaults and closures. +""" + +import unittest + + +def g_leaf(x): + return x + 1 + + +def g_mid(x): + y = g_leaf(x) + return y + + +def g_two(x): + a = x * 2 + if a > 1000000: + a = 0 + return a + 1 + + +def g_raise(x): + if x == 7777: + raise ValueError(x) + return x + + +def g_mid_raise(x): + return g_raise(x) + 1 + + +def g_default(x, k=3): + return g_leaf(x) * k + + +class NestedHelperTests(unittest.TestCase): + N = 20000 + + def test_global_chain(self): + for _ in range(3): + t = 0 + for i in range(self.N): + t = g_mid(t) + self.assertEqual(t, self.N) + + def test_closure_chain(self): + def leaf(x): + return x + 2 + + def mid(x): + y = leaf(x) + return y + + for _ in range(3): + t = 0 + for i in range(self.N): + t = mid(t) + self.assertEqual(t, 2 * self.N) + + def test_branchy_helper(self): + expect = 0 + for i in range(self.N): + a = expect * 2 + if a > 1000000: + a = 0 + expect = a + 1 + for _ in range(3): + t = 0 + for i in range(self.N): + t = g_two(t) + self.assertEqual(t, expect) + + def test_float_loop_with_helper(self): + expect = 0.0 + for i in range(self.N): + expect = expect * 0.5 + (i * 2 % 1000001 + 1) * 1.5 - 0.25 * expect + for _ in range(3): + t = 0.0 + for i in range(self.N): + t = t * 0.5 + g_two(i) * 1.5 - 0.25 * t + self.assertAlmostEqual(t, expect) + + def test_rebinding_inner_helper(self): + global g_leaf + saved = g_leaf + try: + for _ in range(3): + t = 0 + for i in range(self.N): + if i == self.N // 2: + g_leaf = lambda x: x + 10 # noqa: E731 + t = g_mid(t) + self.assertEqual(t, self.N // 2 + 10 * (self.N - self.N // 2)) + g_leaf = saved + finally: + g_leaf = saved + + def test_raise_from_inner_helper(self): + for _ in range(3): + t = 0 + with self.assertRaises(ValueError) as cm: + for i in range(self.N): + t += g_mid_raise(i) + self.assertEqual(cm.exception.args, (7777,)) + self.assertEqual(t, sum(range(7777)) + 7777) + + def test_defaults(self): + for _ in range(3): + t = 0 + for i in range(self.N): + t += g_default(i) + self.assertEqual(t, 3 * sum(i + 1 for i in range(self.N))) + t = 0 + for i in range(self.N): + t += g_default(i, 2) + self.assertEqual(t, 2 * sum(i + 1 for i in range(self.N))) + + def test_short_comprehension_helper(self): + # A helper whose only loop is a short comprehension, called often. + def values(xs): + return [g_leaf(x) for x in xs] + + for _ in range(3): + out = 0 + for i in range(self.N // 4): + out += sum(values((i, i + 1))) + self.assertEqual(out, sum(2 * i + 3 for i in range(self.N // 4))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_new_returns_subclass.py b/tests/regrtest/test_new_returns_subclass.py new file mode 100644 index 000000000..e0b13a239 --- /dev/null +++ b/tests/regrtest/test_new_returns_subclass.py @@ -0,0 +1,54 @@ +"""`__new__` returning an instance of a subclass, or of another class. + +`type.__call__` runs `type(obj).__init__` when `__new__` returns an +instance of the class called or of a subclass (`pathlib.Path.__new__` +makes a `PosixPath`), and no `__init__` at all for anything else. Compiled +code chains the subclass's own `__init__` directly. Run it past the compile +threshold. +""" + +import pathlib + +log = [] + + +class Base: + def __new__(cls, *args, **kwargs): + if cls is Base: + cls = Sub + return object.__new__(cls) + + def __init__(self, x): + log.append(("base", x)) + + +class Sub(Base): + def __init__(self, x): + log.append(("sub", x)) + + +class Other: + def __init__(self, *a): + log.append(("other",)) + + +class Odd: + def __new__(cls, x): + return Other() + + def __init__(self, x): + log.append(("odd", x)) + + +for i in range(3000): + log.clear() + b = Base(i) + assert type(b) is Sub and log == [("sub", i)], log + log.clear() + s = Sub(i) + assert type(s) is Sub and log == [("sub", i)], log + log.clear() + o = Odd(i) + assert type(o) is Other and log == [("other",)], log + p = pathlib.Path("/usr/local") / "lib" / "f.txt" + assert str(p) == "/usr/local/lib/f.txt" and p.suffix == ".txt" diff --git a/tests/regrtest/test_next_of_dict_iterators.py b/tests/regrtest/test_next_of_dict_iterators.py new file mode 100644 index 000000000..267e2adc9 --- /dev/null +++ b/tests/regrtest/test_next_of_dict_iterators.py @@ -0,0 +1,85 @@ +"""`next()` of a dict's or dict view's iterator, and `iter()` of a view. + +`next(iter(d))` steps a dict iterator in place, as a `for` loop does; a +dict changed in size mid-iteration, and the end (with or without a +default), are still the full call's to report, with CPython's errors. +`iter()` of a view or a `mappingproxy` makes its iterator directly. +""" + +import types +import unittest + + +class NextOfDictIteratorTests(unittest.TestCase): + def test_first_items(self): + d = {"a": 1, "b": 2, "c": 3} + for _ in range(300): + self.assertEqual(next(iter(d)), "a") + self.assertEqual(next(iter(d.keys())), "a") + self.assertEqual(next(iter(d.values())), 1) + self.assertEqual(next(iter(d.items())), ("a", 1)) + self.assertEqual(next(iter(d.values()), None), 1) + self.assertEqual(next(iter({}), "empty"), "empty") + + def test_steps_and_end(self): + d = {i: str(i) for i in range(5)} + for _ in range(100): + it = iter(d.items()) + got = [next(it) for _ in range(5)] + self.assertEqual(got, list(d.items())) + self.assertIsNone(next(it, None)) + with self.assertRaises(StopIteration): + next(it) + # (An exhausted iterator stays exhausted after the dict grows.) + d[99] = "x" + self.assertIsNone(next(it, None)) + del d[99] + + def test_mutation(self): + for _ in range(100): + d = {1: 1, 2: 2} + it = iter(d) + self.assertEqual(next(it), 1) + d[3] = 3 + with self.assertRaisesRegex(RuntimeError, "dictionary changed size during iteration"): + next(it) + d = {1: 1, 2: 2} + it = iter(d.values()) + next(it) + d[2] = "changed" + self.assertEqual(next(it), "changed") + + def test_heap_keys_and_values(self): + d = {("k", i): [i] for i in range(4)} + for _ in range(100): + k = next(iter(d)) + self.assertEqual(k, ("k", 0)) + v = next(iter(d.values())) + v.append(0) + v.pop() + self.assertEqual(d[("k", 0)], [0]) + + def test_views_and_proxies(self): + d = {"x": 1, "y": 2} + proxy = types.MappingProxyType(d) + for _ in range(300): + self.assertEqual(list(iter(d.keys())), ["x", "y"]) + self.assertEqual(list(iter(d.items())), [("x", 1), ("y", 2)]) + self.assertEqual(list(iter(proxy)), ["x", "y"]) + self.assertEqual(list(iter(d.values())), [1, 2]) + ns = type("C", (), {"q": 1}).__dict__ + self.assertEqual(next(iter(ns)), list(ns)[0]) + + def test_subclass(self): + class D(dict): + def __iter__(self): + yield "own" + + d = D(a=1) + for _ in range(100): + self.assertEqual(next(iter(d)), "own") + self.assertEqual(next(iter(d.keys())), "a") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_non_data_descriptor_reads.py b/tests/regrtest/test_non_data_descriptor_reads.py new file mode 100644 index 000000000..3def7a48a --- /dev/null +++ b/tests/regrtest/test_non_data_descriptor_reads.py @@ -0,0 +1,125 @@ +"""Reads through a Python non-data descriptor. + +A class attribute that is an instance of a class with a plain `__get__` +and no `__set__` or `__delete__` yields to the instance's own entry, and +otherwise runs its `__get__`: both in place in compiled code once warm. +`functools.cached_property` is the common case. Shadowing, deletion, a +descriptor class gaining `__set__`, and an `AttributeError` from `__get__` +falling back to `__getattr__` all read as CPython reads them. +""" + +import functools +import unittest + +N = 3000 + + +class Get: + calls = 0 + + def __get__(self, inst, owner=None): + Get.calls += 1 + return ("got", inst is None, owner.__name__) + + +class Host: + v = Get() + + +class CP: + made = 0 + + @functools.cached_property + def v(self): + CP.made += 1 + return [self] + + +class Raising: + def __get__(self, inst, owner=None): + raise AttributeError("nope") + + +class Fallback: + v = Raising() + + def __getattr__(self, name): + return ("fallback", name) + + +class NonDataDescriptorTests(unittest.TestCase): + def test_get_runs_without_instance_entry(self): + h = Host() + Get.calls = 0 + for _ in range(N): + r = h.v + self.assertEqual(r, ("got", False, "Host")) + self.assertEqual(Get.calls, N) + self.assertEqual(Host.v, ("got", True, "Host")) + + def test_instance_entry_shadows(self): + h = Host() + out = [] + for i in range(N): + if i == N // 3: + h.v = "own" + if i == 2 * N // 3: + del h.v + out.append(h.v) + self.assertEqual(out[0], ("got", False, "Host")) + self.assertEqual(out[N // 3], "own") + self.assertEqual(out[N // 2], "own") + self.assertEqual(out[-1], ("got", False, "Host")) + + def test_descriptor_class_gains_set(self): + class G: + def __get__(self, inst, owner=None): + return "descr" + + class K: + v = G() + + k = K() + k.__dict__["v"] = "own" + out = [] + for i in range(N): + if i == N // 2: + G.__set__ = lambda self, inst, value: None + out.append(k.v) + self.assertEqual(out[0], "own") + self.assertEqual(out[-1], "descr") + + def test_cached_property(self): + CP.made = 0 + objs = [] + for _ in range(N): + o = CP() + first = o.v + again = o.v + self.assertIs(first, again) + objs.append(o) + self.assertEqual(CP.made, N) + self.assertEqual(objs[-1].v, [objs[-1]]) + del objs[-1].v + self.assertEqual(objs[-1].v, [objs[-1]]) + self.assertEqual(CP.made, N + 1) + + def test_attribute_error_falls_back(self): + f = Fallback() + for _ in range(N): + r = f.v + self.assertEqual(r, ("fallback", "v")) + + def test_slots_instance(self): + class S: + __slots__ = ("x",) + v = Get() + + s = S() + for _ in range(N): + r = s.v + self.assertEqual(r, ("got", False, "S")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_none_bool_keys.py b/tests/regrtest/test_none_bool_keys.py new file mode 100644 index 000000000..58745bbf7 --- /dev/null +++ b/tests/regrtest/test_none_bool_keys.py @@ -0,0 +1,65 @@ +"""`None`, `True` and `False` as dict keys on the native probe paths. + +They hash and compare natively, so stores and lookups take the fast +paths; a `bool` probe still finds an equal `int` key (and the reverse), +and a store keeps the key already there, in dicts, sets, `OrderedDict`, +`defaultdict`, `Counter` and `lru_cache`. Run it past the compile +threshold. +""" + +import functools +from collections import Counter, OrderedDict, defaultdict + + +class R: + def __init__(self): + self.reg = {} + + def register(self, name, value, obj): + registry = self.reg.setdefault(name, {}) + registry[value] = obj + + +@functools.lru_cache(maxsize=None) +def cached(x): + return (type(x).__name__, x) + + +def run(n): + r = R() + for i in range(n): + r.register("a", None, i) + r.register("a", True, i) + r.register("a", "s", i) + reg = r.reg["a"] + assert reg[None] == i and reg[True] == i and reg[1] == i + assert list(reg) == [None, True, "s"] + d = {1: "one", 0: "zero"} + assert d.get(True) == "one" and d[False] == "zero" and True in d + d[True] = "t" + assert list(d.items()) == [(1, "t"), (0, "zero")] + assert type(next(iter(d))) is int + assert d.setdefault(False, "f") == "zero" and d.pop(True) == "t" + e = {True: 1, None: 2} + assert e.get(1) == 1 and e[None] == 2 and e.get(False) is None + e[1] = 5 + assert list(e.items()) == [(True, 5), (None, 2)] + assert 1.0 in e and e[1.0] == 5 + s = {1, None} + assert True in s and None in s and False not in s + od = OrderedDict([(1, "a"), (None, "b")]) + od[True] = "c" + od.move_to_end(None) + assert list(od.items()) == [(1, "c"), (None, "b")] and od.get(True) == "c" + dd = defaultdict(int) + dd[None] += 1 + dd[True] += 1 + dd[1] += 1 + assert dict(dd) == {None: 1, True: 2} + c = Counter([True, 1, None, False, 0]) + assert c[1] == 2 and c[None] == 1 and c[0] == 2 + assert cached(True) == cached(1) or cached(1) == ("int", 1) + + +run(2000) +print("ok") diff --git a/tests/regrtest/test_numeric_method_arity.py b/tests/regrtest/test_numeric_method_arity.py new file mode 100644 index 000000000..14f6ca318 --- /dev/null +++ b/tests/regrtest/test_numeric_method_arity.py @@ -0,0 +1,25 @@ +"""`round()` of a bool and the arity of int's and float's no-argument methods. + +`round(True)` is `int.__round__(True)`, a plain `int`, with or without a +non-negative `ndigits`. `float.hex`, `int.bit_length` and the other +methods that take no arguments reject an extra one with a `TypeError`. +""" + +for args in [(True,), (False,), (True, 2), (True, None), (False, -1)]: + r = round(*args) + assert type(r) is int and r == int(args[0]), (args, r) + +calls = [ + (1.5).hex, (1.5).is_integer, (1.5).as_integer_ratio, (1.5).conjugate, + (3).bit_length, (3).bit_count, (3).is_integer, (3).as_integer_ratio, + (3).conjugate, True.bit_length, +] +for call in calls: + call() + try: + call(1) + except TypeError as e: + assert "takes no arguments (1 given)" in str(e), e + else: + raise AssertionError(f"{call} accepted an argument") +print("ok") diff --git a/tests/regrtest/test_object_field_reads_in_loops.py b/tests/regrtest/test_object_field_reads_in_loops.py new file mode 100644 index 000000000..c0f7a41cb --- /dev/null +++ b/tests/regrtest/test_object_field_reads_in_loops.py @@ -0,0 +1,214 @@ +"""Object, str and bytes fields read in hot loops give the field's value. + +A compiled loop that reads `obj.name` (a string, bytes or instance field) +keeps a handle on the value it read last and takes the same handle again +while the field still holds that value. Whenever the field holds +something else (another object of the lane's type, an equal but distinct +one, `None`, a value of another type, nothing) the read gives what the +field holds now. +""" + +import unittest + +N = 5000 + + +class Node: + def __init__(self, label, payload=b"p", nxt=None): + self.label = label + self.payload = payload + self.next = nxt + self.count = 0 + + +class SlotNode: + __slots__ = ("label", "payload", "next", "count") + + def __init__(self, label, payload=b"p", nxt=None): + self.label = label + self.payload = payload + self.next = nxt + self.count = 0 + + +def count_label(obj, want, n): + hits = 0 + for _ in range(n): + if obj.label == want: + hits += 1 + return hits + + +def label_lengths(obj, n): + total = 0 + for _ in range(n): + total += len(obj.label) + return total + + +def payload_lengths(obj, n): + total = 0 + for _ in range(n): + total += len(obj.payload) + return total + + +def follow(obj, n): + total = 0 + for _ in range(n): + total += obj.next.count + return total + + +def labels_equal(a, b, n): + same = 0 + for _ in range(n): + if a.label == b.label: + same += 1 + return same + + +class FieldReadTests(unittest.TestCase): + kinds = (Node, SlotNode) + + def test_stable_fields(self): + for cls in self.kinds: + o = cls("abc", b"12345") + self.assertEqual(count_label(o, "abc", N), N) + self.assertEqual(count_label(o, "abd", N), 0) + self.assertEqual(label_lengths(o, N), 3 * N) + self.assertEqual(payload_lengths(o, N), 5 * N) + self.assertEqual(labels_equal(o, cls("abc"), N), N) + + def test_field_rebound_between_calls(self): + for cls in self.kinds: + o = cls("abc") + self.assertEqual(label_lengths(o, N), 3 * N) + o.label = "longer label" + self.assertEqual(label_lengths(o, N), 12 * N) + o.label = "".join(["a", "bc"]) # equal to the first, another object + self.assertEqual(label_lengths(o, N), 3 * N) + self.assertEqual(count_label(o, "abc", N), N) + o.payload = b"" + self.assertEqual(payload_lengths(o, N), 0) + + def test_field_rebound_inside_the_loop(self): + for cls in self.kinds: + o = cls("a") + labels = ["a", "bb", "ccc", "a", "dddd"] + total = 0 + for i in range(N): + o.label = labels[i % 5] + total += len(o.label) + self.assertEqual(total, (N // 5) * (1 + 2 + 3 + 1 + 4)) + + def test_alternating_receivers(self): + for cls in self.kinds: + objs = [cls("x"), cls("yy"), cls("zzz")] + total = 0 + for i in range(N): + total += len(objs[i % 3].label) + self.assertEqual(total, (N // 3) * 6 + sum((1, 2, 3)[: N % 3])) + + def test_instance_field(self): + for cls in self.kinds: + leaf = cls("leaf") + leaf.count = 7 + head = cls("head", nxt=leaf) + self.assertEqual(follow(head, N), 7 * N) + other = cls("other") + other.count = 2 + head.next = other + self.assertEqual(follow(head, N), 2 * N) + head.next = leaf + leaf.count = 1 + self.assertEqual(follow(head, N), N) + self.assertIs(head.next, leaf) + + def test_none_and_other_types(self): + for cls in self.kinds: + leaf = cls("leaf") + head = cls("head", nxt=leaf) + self.assertEqual(follow(head, N), 0) + head.next = None + with self.assertRaises(AttributeError): + follow(head, 3) + head.next = leaf + self.assertEqual(follow(head, 10), 0) + o = cls("abc") + self.assertEqual(label_lengths(o, N), 3 * N) + o.label = [1, 2, 3, 4] + self.assertEqual(label_lengths(o, 10), 40) + o.label = b"xy" + self.assertEqual(label_lengths(o, 10), 20) + o.label = 5 + with self.assertRaises(TypeError): + label_lengths(o, 3) + o.label = "back" + self.assertEqual(label_lengths(o, N), 4 * N) + + def test_deleted_field(self): + for cls in self.kinds: + o = cls("abc") + self.assertEqual(label_lengths(o, N), 3 * N) + del o.label + with self.assertRaises(AttributeError): + label_lengths(o, 3) + o.label = "re" + self.assertEqual(label_lengths(o, N), 2 * N) + + def test_the_value_read_is_the_object_stored(self): + for cls in self.kinds: + first = "".join(["id", "entity"]) + second = "".join(["id", "entity"]) + self.assertIsNot(first, second) + o = cls(first) + seen = None + for i in range(N): + seen = o.label + self.assertIs(seen, first) + o.label = second + for i in range(N): + seen = o.label + self.assertIs(seen, second) + + def test_nested_calls_of_one_loop(self): + # The same code runs in several activations at once, each with + # its own receivers. + def walk(node, depth): + total = 0 + for _ in range(40): + total += len(node.label) + if depth: + total += walk(node.next, depth - 1) + return total + + for cls in self.kinds: + chain = None + for k in range(12, 0, -1): + chain = cls("n" * k, nxt=chain) + want = 40 * sum(range(1, 13)) + for _ in range(200): + self.assertEqual(walk(chain, 11), want) + + def test_released_values_are_not_kept_alive_forever(self): + import gc + import weakref + + class Payload: + pass + + for cls in self.kinds: + leaf = Payload() + leaf.count = 3 + ref = weakref.ref(leaf) + head = cls("head", nxt=leaf) + self.assertEqual(follow(head, N), 3 * N) + head.next = None + del leaf + gc.collect() + self.assertIsNone(ref()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_object_setattr_fast.py b/tests/regrtest/test_object_setattr_fast.py new file mode 100644 index 000000000..6b4b18f9f --- /dev/null +++ b/tests/regrtest/test_object_setattr_fast.py @@ -0,0 +1,118 @@ +"""`object.__setattr__` on plain instances, its compiled fast half included. + +A store into a plain instance's own dict or a writable `__slots__` member +takes the native half; properties and other data descriptors, read-only +and missing slots, exceptions' `args`, a published `__dict__`, and a +replaced value's finalizer behave as in CPython. Run it past the compile +threshold. +""" + +import dataclasses + + +@dataclasses.dataclass(frozen=True) +class Frozen: + a: int + b: str + + +class Plain: + pass + + +class Slotted: + __slots__ = ("x", "y") + + +class WithProp: + def __init__(self): + self.log = [] + + @property + def p(self): + return self.log + + @p.setter + def p(self, v): + self.log.append(v) + + +class Desc: + def __set_name__(self, owner, name): + self.name = "_" + name + + def __get__(self, obj, cls=None): + return getattr(obj, self.name, None) + + def __set__(self, obj, v): + object.__setattr__(obj, self.name, v * 2) + + +class WithDesc: + d = Desc() + + +class D: + log = [] + + def __init__(self, n): + self.n = n + + def __del__(self): + D.log.append(self.n) + + +class E(Exception): + pass + + +def run(n): + for i in range(n): + f = Frozen(i, "x") + assert (f.a, f.b) == (i, "x") + try: + f.a = 1 + except dataclasses.FrozenInstanceError: + pass + else: + raise AssertionError("frozen") + object.__setattr__(f, "a", i + 1) + assert f.a == i + 1 and f == Frozen(i + 1, "x") + p = Plain() + object.__setattr__(p, "v", i) + object.__setattr__(p, "v", [i]) + assert p.v == [i] and p.__dict__ == {"v": [i]} + s = Slotted() + object.__setattr__(s, "x", i) + assert s.x == i + try: + object.__setattr__(s, "z", 1) + except AttributeError: + pass + else: + raise AssertionError("no slot z") + w = WithProp() + object.__setattr__(w, "p", i) + assert w.log == [i] + wd = WithDesc() + object.__setattr__(wd, "d", i) + assert wd.d == 2 * i + e = E(1) + object.__setattr__(e, "args", [2, 3]) + assert e.args == (2, 3) + pd = Plain() + dd = pd.__dict__ + object.__setattr__(pd, "k", i) + assert dd["k"] == i + h = Plain() + object.__setattr__(h, "held", D(i)) + D.log.clear() + object.__setattr__(h, "held", None) + assert D.log == [i], D.log + o = Plain() + o.__setattr__("m", i) + assert o.m == i + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_odict_fresh_store.py b/tests/regrtest/test_odict_fresh_store.py new file mode 100644 index 000000000..27ee49205 --- /dev/null +++ b/tests/regrtest/test_odict_fresh_store.py @@ -0,0 +1,124 @@ +"""`OrderedDict` stores, construction from pairs, and `list(od)`. + +A fresh `OrderedDict`'s first `od[key] = value` starts its order in place, +as the full store does; construction from an iterable unpacks 2-tuples +directly and anything else as CPython's `odict` does, with its errors. +`list(od)` of an exact `OrderedDict` takes the keys in order at once; a +subclass's own `__iter__` iterates. +""" + +import unittest +from collections import OrderedDict + +N = 3000 + + +class S(OrderedDict): + def __setitem__(self, k, v): + super().__setitem__(k, v * 10) + + +class OdictFreshStoreTests(unittest.TestCase): + def test_fresh_stores_keep_order(self): + for _ in range(N): + o = OrderedDict() + o["b"] = 1 + o["a"] = 2 + o["b"] = 3 + self.assertEqual(list(o.items()), [("b", 3), ("a", 2)]) + o.move_to_end("b") + self.assertEqual(list(o), ["a", "b"]) + del o["a"] + self.assertEqual(list(o), ["b"]) + + def test_construction_from_pairs(self): + P = [("a", 1), ("b", 2)] + for _ in range(N): + g = OrderedDict((k, v) for k, v in P) + m = OrderedDict(iter([("x", 1), ["y", 2], "zq"])) + self.assertEqual(list(g.items()), P) + self.assertEqual(list(m.items()), [("x", 1), ("y", 2), ("z", "q")]) + + def test_pair_errors(self): + for bad, msg in [([()], "need more than 0"), ([(1,)], "need more than 1"), + ([(1, 2, 3)], "too many values")]: + with self.assertRaises(ValueError) as cm: + OrderedDict(iter(bad)) + self.assertIn(msg, str(cm.exception)) + + def test_subclass_setitem(self): + for _ in range(N): + s = S(iter([("a", 1)])) + s["b"] = 2 + self.assertEqual(dict(s), {"a": 10, "b": 20}) + + def test_unhashable_key(self): + o = OrderedDict() + with self.assertRaises(TypeError): + o[[1]] = 2 + self.assertEqual(list(o), []) + + def test_list_of_keys(self): + o = OrderedDict([("a", 1), ("b", 2), ("c", 3)]) + o.move_to_end("a") + del o["b"] + o["d"] = 4 + for _ in range(N): + r = list(o) + t = tuple(o) + self.assertEqual(r, ["c", "a", "d"]) + self.assertEqual(t, ("c", "a", "d")) + self.assertEqual(list(OrderedDict()), []) + + def test_list_of_keys_overridden(self): + class R(OrderedDict): + def __iter__(self): + return iter(["z"]) + + for _ in range(N): + r = list(R(a=1)) + self.assertEqual(r, ["z"]) + self.assertEqual(list(OrderedDict(a=1)), ["a"]) + + def test_list_of_views(self): + o = OrderedDict([("a", 1), ("b", 2), ("c", 3)]) + o.move_to_end("a") + for _ in range(N): + k = list(o.keys()) + v = list(o.values()) + i = list(o.items()) + self.assertEqual(k, ["b", "c", "a"]) + self.assertEqual(v, [2, 3, 1]) + self.assertEqual(i, [("b", 2), ("c", 3), ("a", 1)]) + + def test_views_with_python_keys(self): + class K: + def __init__(self, n): + self.n = n + + def __hash__(self): + return hash(self.n) + + def __eq__(self, other): + return isinstance(other, K) and other.n == self.n + + o = OrderedDict([(K(1), "x"), (K(2), "y")]) + for _ in range(N): + v = list(o.values()) + i = [(k.n, w) for k, w in list(o.items())] + self.assertEqual(v, ["x", "y"]) + self.assertEqual(i, [(1, "x"), (2, "y")]) + + def test_subclass_views(self): + class O2(OrderedDict): + pass + + o = O2(a=1) + o["b"] = 2 + for _ in range(N): + i = list(o.items()) + self.assertEqual(i, [("a", 1), ("b", 2)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_odict_from_dict_whole.py b/tests/regrtest/test_odict_from_dict_whole.py new file mode 100644 index 000000000..7ddaea33b --- /dev/null +++ b/tests/regrtest/test_odict_from_dict_whole.py @@ -0,0 +1,116 @@ +"""`OrderedDict(d)` of an exact dict, and `list()` of deques and odicts. + +The exact class copies a dict whose keys hash natively as whole tables; +the order, the values, later order operations, independence from the +source and keys that run code must all stay as `__init__`'s stores leave +them. `list(od)` and `list(deque)` remember per class whether `__iter__` +is native; a class changed afterward must be asked again. +""" + +import unittest +from collections import OrderedDict, deque + + +class Key: + def __init__(self, n): + self.n = n + + def __hash__(self): + return hash(self.n) + + def __eq__(self, other): + return isinstance(other, Key) and other.n == self.n + + def __repr__(self): + return f"Key({self.n})" + + +class FromDictTests(unittest.TestCase): + def test_order_values_and_independence(self): + src = {"b": 1, "a": 2, 3: [4], (5, 6): None, 7.5: "x", b"z": 0} + for _ in range(300): + od = OrderedDict(src) + self.assertEqual(list(od.items()), list(src.items())) + self.assertIs(od[3], src[3]) + self.assertEqual(od, src) + src["new"] = 1 + del src["b"] + self.assertEqual(list(od), ["b", "a", 3, (5, 6), 7.5, b"z"]) + od["c"] = 9 + self.assertNotIn("c", src) + + def test_order_operations_after(self): + od = OrderedDict({"a": 1, "b": 2, "c": 3, "d": 4}) + od.move_to_end("a") + od.move_to_end("d", last=False) + self.assertEqual(list(od), ["d", "b", "c", "a"]) + self.assertEqual(list(reversed(od)), ["a", "c", "b", "d"]) + del od["b"] + self.assertEqual(od.popitem(), ("a", 1)) + self.assertEqual(od.popitem(last=False), ("d", 4)) + self.assertEqual(list(od.items()), [("c", 3)]) + self.assertNotEqual(OrderedDict({"x": 1, "y": 2}), OrderedDict({"y": 2, "x": 1})) + self.assertEqual(OrderedDict({"x": 1, "y": 2}), {"y": 2, "x": 1}) + + def test_keys_that_run_code(self): + src = {Key(1): "a", "s": "b", Key(2): "c"} + od = OrderedDict(src) + self.assertEqual(list(od.values()), ["a", "b", "c"]) + self.assertEqual(od[Key(2)], "c") + od.move_to_end(Key(1)) + self.assertEqual(list(od.values()), ["b", "c", "a"]) + + def test_empty_and_subclass(self): + self.assertEqual(list(OrderedDict({})), []) + + class Sub(OrderedDict): + def __setitem__(self, key, value): + super().__setitem__(key, value * 2) + + sub = Sub({"a": 1, "b": 2}) + self.assertIs(type(sub), Sub) + self.assertEqual(list(sub.items()), [("a", 2), ("b", 4)]) + + def test_fromkeys_then_list(self): + words = "the quick brown fox jumps over the lazy dog".split() + for _ in range(300): + self.assertEqual( + list(OrderedDict.fromkeys(words)), + ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog"], + ) + + +class ListOfDequeAndOdictTests(unittest.TestCase): + def test_alternating(self): + d = deque([1, 2, 3]) + od = OrderedDict.fromkeys("abc") + for _ in range(300): + self.assertEqual(list(d), [1, 2, 3]) + self.assertEqual(list(od), ["a", "b", "c"]) + self.assertEqual(sum(d), 6) + + def test_class_changed_later(self): + class D(deque): + pass + + class O(OrderedDict): + pass + + d = D([1, 2, 3]) + o = O.fromkeys("xy") + for _ in range(50): + self.assertEqual(list(d), [1, 2, 3]) + self.assertEqual(list(o), ["x", "y"]) + D.__iter__ = lambda self: iter([9]) + O.__iter__ = lambda self: iter(["z"]) + self.assertEqual(list(d), [9]) + self.assertEqual(list(o), ["z"]) + self.assertEqual(sorted(d), [9]) + del D.__iter__ + del O.__iter__ + self.assertEqual(list(d), [1, 2, 3]) + self.assertEqual(list(o), ["x", "y"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_odict_fromkeys_one_pass.py b/tests/regrtest/test_odict_fromkeys_one_pass.py new file mode 100644 index 000000000..a37ef818d --- /dev/null +++ b/tests/regrtest/test_odict_fromkeys_one_pass.py @@ -0,0 +1,57 @@ +"""`OrderedDict.fromkeys` of a list, tuple or str in one native pass. + +An exact `OrderedDict` takes the keys through `dict.fromkeys` and its +native update; the order (first occurrences), the shared value, subclasses' +own `__setitem__`, other iterables and CPython's wording for an unhashable +key must all stay as the per-key loop has them. +""" + +import unittest +from collections import OrderedDict + + +class Tagged(OrderedDict): + def __setitem__(self, key, value): + super().__setitem__(key, ("tagged", value)) + + +class FromkeysTests(unittest.TestCase): + def test_order_and_values(self): + words = ["b", "a", "c", "a", 1, 2.0, (1, 2), "b"] + for _ in range(300): + od = OrderedDict.fromkeys(words, 0) + self.assertEqual(list(od.items()), [("b", 0), ("a", 0), ("c", 0), (1, 0), (2.0, 0), ((1, 2), 0)]) + self.assertIs(type(od), OrderedDict) + shared = [] + od = OrderedDict.fromkeys(("x", "y"), shared) + self.assertIs(od["x"], od["y"]) + self.assertEqual(list(OrderedDict.fromkeys("hello")), ["h", "e", "l", "o"]) + self.assertEqual(OrderedDict.fromkeys([]), OrderedDict()) + + def test_order_operations_after(self): + od = OrderedDict.fromkeys("abcd") + od.move_to_end("a") + self.assertEqual(list(od), ["b", "c", "d", "a"]) + self.assertEqual(od.popitem(), ("a", None)) + self.assertEqual(od.popitem(last=False), ("b", None)) + od["z"] = 1 + self.assertEqual(list(od), ["c", "d", "z"]) + + def test_subclass_setitem(self): + od = Tagged.fromkeys(["a", "b"], 1) + self.assertIs(type(od), Tagged) + self.assertEqual(list(od.items()), [("a", ("tagged", 1)), ("b", ("tagged", 1))]) + + def test_other_iterables(self): + self.assertEqual(list(OrderedDict.fromkeys(x for x in "abca")), ["a", "b", "c"]) + self.assertEqual(list(OrderedDict.fromkeys({"q": 1, "r": 2})), ["q", "r"]) + self.assertEqual(list(OrderedDict.fromkeys(range(3))), [0, 1, 2]) + + def test_unhashable(self): + for bad in ([[1]], ([1], 2), [1, [2]]): + with self.assertRaisesRegex(TypeError, "^unhashable type: 'list'$"): + OrderedDict.fromkeys(bad) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_odict_store_leaf.py b/tests/regrtest/test_odict_store_leaf.py new file mode 100644 index 000000000..5fa3aae51 --- /dev/null +++ b/tests/regrtest/test_odict_store_leaf.py @@ -0,0 +1,107 @@ +"""`od[k] = v` on an `OrderedDict` in compiled code. + +A store by a `str` or `int` key goes straight to the class's own +`__setitem__`; new keys append to the order, existing keys keep their +place; a subclass's Python `__setitem__` (defined up front or added +mid-loop) still runs; unhashable keys raise; keys with a Python `__eq__` +or `__hash__`, and a displaced value's finalizer, behave as in CPython. +Run it past the compile thresholds, in a loop and in a called function. +""" + +from collections import OrderedDict + + +class Logged(OrderedDict): + calls = 0 + + def __setitem__(self, k, v): + Logged.calls += 1 + super().__setitem__(k, v) + + +class Plain(OrderedDict): + pass + + +class K: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, K) and self.v == other.v + + +class D: + log = [] + + def __init__(self, n): + self.n = n + + def __del__(self): + D.log.append(self.n) + + +def store(od, k, v): + od[k] = v + + +def loop(od, n): + for i in range(n): + od[i % 7] = i + od["k" + str(i % 3)] = i + + +def check(cls, n): + od = cls((j, None) for j in range(5)) + od.move_to_end(0) + loop(od, n) + for i in range(n): + store(od, i % 7, i) + last = n - 1 + expect = [1, 2, 3, 4, 0, "k0", "k1", "k2", 5, 6] + assert list(od) == expect, list(od) + assert od[last % 7] == last + return od + + +N = 3000 +check(OrderedDict, N) +check(Plain, N) +Logged.calls = 0 +check(Logged, N) +assert Logged.calls == 3 * N + 5, Logged.calls + + +class Late(OrderedDict): + pass + + +late = Late() +seen = [] +for i in range(N): + if i == N // 2: + Late.__setitem__ = lambda self, k, v: seen.append(k) + store(late, i % 5, i) +assert len(seen) == N - N // 2 and list(late) == [0, 1, 2, 3, 4], (len(seen), list(late)) + +od = OrderedDict() +for i in range(N): + store(od, K(i % 4), i) + try: + store(od, [i], i) + except TypeError: + pass + else: + raise AssertionError("unhashable key") +assert [k.v for k in od] == [0, 1, 2, 3] + +od = OrderedDict() +for i in range(N): + D.log.clear() + store(od, "x", D(i)) + if i: + assert D.log == [i - 1], (i, D.log) +print("ok") diff --git a/tests/regrtest/test_operator_callables_on_instances.py b/tests/regrtest/test_operator_callables_on_instances.py new file mode 100644 index 000000000..e8b31cb28 --- /dev/null +++ b/tests/regrtest/test_operator_callables_on_instances.py @@ -0,0 +1,96 @@ +"""`operator`'s callables on instances, from compiled loops. + +`methodcaller`, `itemgetter` and `attrgetter` are native calls. When one +reaches Python code (a method, a `__getitem__`, a property), compiled code +runs its native body in place with the callable first, so the Python code +sees the right arguments, its errors carry their traceback, and the +loop's own handlers catch them. +""" + +import operator +import sys +import traceback +import unittest + + +class Box: + def __init__(self, v): + self.v = v + + def scaled(self, k, extra=0): + return self.v * k + extra + + def fail(self): + raise ValueError("from method") + + def items(self): + yield self.v + yield self.v + 1 + + def __getitem__(self, i): + if i == "bad": + raise KeyError(i) + return (self.v, i) + + @property + def double(self): + return self.v * 2 + + +class OperatorCallableTests(unittest.TestCase): + def test_methodcaller_python_methods(self): + boxes = [Box(i) for i in range(10)] + m = operator.methodcaller("scaled", 3) + m2 = operator.methodcaller("scaled", 2, 5) + for _ in range(200): + self.assertEqual([m(b) for b in boxes], [3 * i for i in range(10)]) + self.assertEqual(m2(boxes[4]), 13) + mk = operator.methodcaller("scaled", 2, extra=1) + self.assertEqual(mk(boxes[3]), 7) + gen = operator.methodcaller("items") + self.assertEqual(list(gen(boxes[2])), [2, 3]) + + def test_errors_from_compiled_loops(self): + fail = operator.methodcaller("fail") + b = Box(1) + caught = 0 + for _ in range(300): + try: + fail(b) + except ValueError as e: + caught += 1 + tb = traceback.extract_tb(e.__traceback__) + self.assertEqual(tb[-1].name, "fail") + self.assertEqual(caught, 300) + missing = operator.methodcaller("nope") + for _ in range(100): + with self.assertRaises(AttributeError): + missing(b) + + def test_getters(self): + boxes = [Box(i) for i in range(5)] + ig = operator.itemgetter(7) + ig2 = operator.itemgetter(1, 2) + ag = operator.attrgetter("double") + for _ in range(300): + self.assertEqual([ig(x) for x in boxes], [(i, 7) for i in range(5)]) + self.assertEqual(ig2(boxes[1]), ((1, 1), (1, 2))) + self.assertEqual([ag(x) for x in boxes], [0, 2, 4, 6, 8]) + bad = operator.itemgetter("bad") + for _ in range(100): + with self.assertRaises(KeyError): + bad(boxes[0]) + self.assertEqual(sorted(boxes, key=operator.attrgetter("double"), reverse=True)[0].v, 4) + + def test_refcounts_and_identity(self): + b = Box(5) + m = operator.methodcaller("scaled", 1) + before = sys.getrefcount(b) + for _ in range(500): + m(b) + self.assertEqual(sys.getrefcount(b), before) + self.assertEqual(sys.getrefcount(m), sys.getrefcount(m)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_operator_dunder_counting_loops.py b/tests/regrtest/test_operator_dunder_counting_loops.py new file mode 100644 index 000000000..a9d951a4a --- /dev/null +++ b/tests/regrtest/test_operator_dunder_counting_loops.py @@ -0,0 +1,102 @@ +"""Counting loops over instance comparisons and subscripts. + +A loop that sums `int`s around `a < b` or `obj[i]` of instances with +Python methods runs where the method call is cheapest (the frame JIT, +which calls or lowers it directly) rather than in tier 2. The results +must match: reflected and `NotImplemented` comparisons, a method rebound +mid-run, mixed operand types at one site, and methods that raise. +""" + +import unittest + + +class V: + def __init__(self, x): + self.x = x + + def __lt__(self, other): + if not isinstance(other, V): + return NotImplemented + return self.x < other.x + + def __eq__(self, other): + return isinstance(other, V) and self.x == other.x + + __hash__ = object.__hash__ + + +class W: + def __init__(self, x): + self.x = x + + def __gt__(self, other): + return self.x > other.x + + +class Seq: + def __init__(self, d): + self.d = d + + def __getitem__(self, i): + return self.d[i] + + +def count_lt(a, b, n): + c = 0 + for _ in range(n): + if a < b: + c += 1 + return c + + +def count_eq(a, b, n): + c = 0 + for i in range(n): + if a == b: + c += i + return c + + +def sum_items(s, n): + t = 0 + for i in range(n): + t += s[i % 3] + return t + + +class CountingLoopTests(unittest.TestCase): + def test_lt_and_eq(self): + for _ in range(20): + self.assertEqual(count_lt(V(1), V(2), 500), 500) + self.assertEqual(count_lt(V(3), V(2), 500), 0) + self.assertEqual(count_eq(V(1), V(1), 100), 4950) + self.assertEqual(count_eq(V(1), 1, 100), 0) + + def test_reflected(self): + # `V < W`: V.__lt__ declines, W.__gt__ answers. + for _ in range(20): + self.assertEqual(count_lt(V(1), W(2), 300), 300) + with self.assertRaises(TypeError): + count_lt(V(1), 5, 10) + + def test_rebound(self): + class R: + def __lt__(self, other): + return True + + a, b = R(), R() + self.assertEqual(count_lt(a, b, 1000), 1000) + R.__lt__ = lambda self, other: False + self.assertEqual(count_lt(a, b, 1000), 0) + + def test_subscript_sums(self): + s = Seq([1, 2, 3]) + for _ in range(20): + self.assertEqual(sum_items(s, 300), 600) + self.assertEqual(sum_items([1, 2, 3], 300), 600) + with self.assertRaises(IndexError): + sum_items(Seq([1]), 10) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_operator_getter_construction.py b/tests/regrtest/test_operator_getter_construction.py new file mode 100644 index 000000000..8e775698d --- /dev/null +++ b/tests/regrtest/test_operator_getter_construction.py @@ -0,0 +1,80 @@ +"""Building `itemgetter`, `attrgetter` and `methodcaller` objects. + +The exact classes build their instances natively, as CPython's C +constructors do: the same repr, pickling and calls as the Python +`__init__` gives. A subclass, keywords to `methodcaller`, a non-`str` +name, or a class changed since (its `__init__` replaced) go through the +Python methods. +""" + +import operator +import pickle +import unittest + + +class GetterConstructionTests(unittest.TestCase): + def test_fields_and_calls(self): + for _ in range(300): + g = operator.itemgetter(1) + self.assertEqual(g([5, 6]), 6) + g2 = operator.itemgetter(0, 2) + self.assertEqual(g2("abc"), ("a", "c")) + a = operator.attrgetter("real", "imag") + self.assertEqual(a(3 + 4j), (3.0, 4.0)) + m = operator.methodcaller("split", ",") + self.assertEqual(m("a,b"), ["a", "b"]) + self.assertEqual(repr(operator.itemgetter(1, "x")), "operator.itemgetter(1, 'x')") + self.assertEqual(repr(operator.attrgetter("a.b")), "operator.attrgetter('a.b')") + self.assertEqual(repr(operator.methodcaller("f", 1)), "operator.methodcaller('f', 1)") + + def test_pickle_and_identity(self): + for obj in (operator.itemgetter(2), operator.attrgetter("x"), operator.methodcaller("f", 1)): + back = pickle.loads(pickle.dumps(obj)) + self.assertEqual(repr(back), repr(obj)) + self.assertIsNot(back, obj) + self.assertIsNot(operator.methodcaller("f"), operator.methodcaller("f")) + + def test_other_shapes(self): + m = operator.methodcaller("split", sep=",") + self.assertEqual(repr(m), "operator.methodcaller('split', sep=',')") + self.assertEqual(m("a,b"), ["a", "b"]) + with self.assertRaises(TypeError): + operator.attrgetter(1) + with self.assertRaises(TypeError): + operator.methodcaller(5) + with self.assertRaises(TypeError): + operator.itemgetter() + + try: + class G(operator.itemgetter): + pass + except TypeError: + return # (CPython's C class isn't an acceptable base.) + for _ in range(100): + self.assertIs(type(G(1)), G) + self.assertEqual(G(1)([7, 8]), 8) + + def test_patched_class(self): + calls = [] + cls = operator.attrgetter + orig = cls.__init__ + + def init(self, *attrs): + calls.append(attrs) + orig(self, *attrs) + + try: + cls.__init__ = init + except TypeError: + self.skipTest("an immutable type (CPython's C class)") + try: + for _ in range(50): + operator.attrgetter("real") + finally: + cls.__init__ = orig + self.assertEqual(len(calls), 50) + self.assertEqual(operator.attrgetter("real")(5), 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_operator_unary_compare_leaf.py b/tests/regrtest/test_operator_unary_compare_leaf.py new file mode 100644 index 000000000..e93d96ae0 --- /dev/null +++ b/tests/regrtest/test_operator_unary_compare_leaf.py @@ -0,0 +1,139 @@ +"""operator's unary and comparison functions, and float's reading methods, +called from compiled loops and as sort keys: plain ints and floats take the +in-place path, and everything else (a machine int's negation that +overflows, NaN, bools, big ints, str, instances with dunders, float +subclasses) gives the general call's value or error.""" + +import operator +import unittest + + +class Neg: + def __neg__(self): + return "neg" + + def __lt__(self, other): + return "lt" + + +class F(float): + def is_integer(self): + return "mine" + + +def unary(n): + out = None + big = -(2**63) + for i in range(n): + out = ( + operator.neg(5), + operator.neg(-2.5), + operator.neg(big), + operator.pos(7), + operator.pos(-0.0), + operator.invert(5), + operator.inv(-1), + operator.neg(True), + operator.invert(False), + operator.neg(2**70), + operator.neg(Neg()), + ) + return out + + +def compare(n): + out = None + nan = float("nan") + for i in range(n): + out = ( + operator.lt(1, 2), + operator.le(2, 2), + operator.eq(3, 3), + operator.ne(3, 3), + operator.gt(1.5, 0.5), + operator.ge(0.5, 1.5), + operator.lt(nan, 1.0), + operator.ge(nan, nan), + operator.eq(nan, nan), + operator.ne(nan, nan), + operator.lt(1, 2.5), + operator.lt("a", "b"), + operator.lt(Neg(), 1), + operator.eq(True, 1), + ) + return out + + +def floats(n): + out = None + for i in range(n): + out = ( + (3.0).is_integer(), + (3.5).is_integer(), + float("inf").is_integer(), + (0.75).as_integer_ratio(), + (-2.0).hex(), + (1.5).conjugate(), + F(2.0).is_integer(), + ) + return out + + +class OperatorLeafTests(unittest.TestCase): + def test_unary(self): + want = (-5, 2.5, 2**63, 7, -0.0, -6, 0, -1, -1, -(2**70), "neg") + for n in (1, 500): + got = unary(n) + self.assertEqual(got, want) + self.assertEqual(type(got[2]), int) + self.assertEqual(str(unary(300)[4]), "-0.0") + + def test_compare(self): + want = (True, True, True, False, True, False, False, False, False, True, + True, True, "lt", True) + for n in (1, 500): + self.assertEqual(compare(n), want) + + def test_errors(self): + def bad(n): + caught = 0 + for i in range(n): + try: + operator.neg("x") + except TypeError: + caught += 1 + try: + operator.lt(1, "x") + except TypeError: + caught += 1 + return caught + + self.assertEqual(bad(400), 800) + with self.assertRaises(TypeError): + operator.neg() + with self.assertRaises(TypeError): + operator.lt(1) + + def test_sort_keys(self): + xs = [5, -3, 8, 0, 2**70, -(2**63)] + for _ in range(300): + self.assertEqual(sorted(xs, key=operator.neg), + [2**70, 8, 5, 0, -3, -(2**63)]) + ys = list(xs) + ys.sort(key=operator.invert) + self.assertEqual(ys, [2**70, 8, 5, 0, -3, -(2**63)]) + with self.assertRaises(TypeError): + sorted([1, "a"], key=operator.neg) + + def test_floats(self): + want = (True, False, False, (3, 4), "-0x1.0000000000000p+1", 1.5, "mine") + for n in (1, 500): + self.assertEqual(floats(n), want) + with self.assertRaises(OverflowError): + float("inf").as_integer_ratio() + with self.assertRaises(ValueError): + float("nan").as_integer_ratio() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_ordered_dict_loop_iterators.py b/tests/regrtest/test_ordered_dict_loop_iterators.py new file mode 100644 index 000000000..fcc1fae99 --- /dev/null +++ b/tests/regrtest/test_ordered_dict_loop_iterators.py @@ -0,0 +1,190 @@ +"""`for` loops over an `OrderedDict` and over its `keys()`, `values()` +and `items()` views build the order iterator with no Python code: the +same items, the same errors on mutation, and overrides stay in charge.""" + +import gc +import unittest +import weakref +from collections import OrderedDict + +N = 300 + + +class Sub(OrderedDict): + pass + + +class LoudIter(OrderedDict): + def __iter__(self): + return iter(["loud"]) + + +class LoudItems(OrderedDict): + def items(self): + return [("loud", 0)] + + +def pairs(n): + return [("k%d" % i, i) for i in range(n)] + + +class Loops(unittest.TestCase): + def test_keys_in_order(self): + od = OrderedDict(pairs(5)) + od.move_to_end("k1") + od["k9"] = 9 + del od["k3"] + for _ in range(N): + got = [] + for k in od: + got.append(k) + self.assertEqual(got, ["k0", "k2", "k4", "k1", "k9"]) + self.assertEqual(got, list(od)) + self.assertEqual(got, list(od.keys())) + + def test_views(self): + od = OrderedDict(pairs(4)) + od.move_to_end("k0") + for _ in range(N): + ks, vs, kvs = [], [], [] + for k in od.keys(): + ks.append(k) + for v in od.values(): + vs.append(v) + for k, v in od.items(): + kvs.append((k, v)) + self.assertEqual(ks, ["k1", "k2", "k3", "k0"]) + self.assertEqual(vs, [1, 2, 3, 0]) + self.assertEqual(kvs, list(zip(ks, vs))) + self.assertEqual(kvs, list(od.items())) + + def test_held_view(self): + od = OrderedDict(pairs(3)) + items, keys = od.items(), od.keys() + for i in range(N): + total = 0 + for k, v in items: + total += v + for k in keys: + total += len(k) + self.assertEqual(total, 3 + 6) + od["zz"] = 10 + self.assertEqual([k for k in keys], ["k0", "k1", "k2", "zz"]) + self.assertEqual(sum(v for _, v in items), 13) + + def test_empty_and_fresh(self): + for _ in range(N): + for k in OrderedDict(): + self.fail("no keys") + for k, v in OrderedDict().items(): + self.fail("no items") + bare = OrderedDict.__new__(OrderedDict) + for k in bare: + self.fail("no keys") + bare["a"] = 1 + self.assertEqual([k for k in bare], ["a"]) + + def test_subclasses(self): + s = Sub(pairs(3)) + for _ in range(N): + a = [k for k in s] + b = [kv for kv in s.items()] + c = [k for k in LoudIter(pairs(3))] + d = [kv for kv in LoudItems(pairs(3)).items()] + self.assertEqual(a, ["k0", "k1", "k2"]) + self.assertEqual(b, pairs(3)) + self.assertEqual(c, ["loud"]) + self.assertEqual(d, [("loud", 0)]) + + def test_break_nested_and_else(self): + od = OrderedDict(pairs(6)) + for _ in range(N): + seen = 0 + for k in od: + if k == "k4": + break + for k2, v2 in od.items(): + seen += v2 > od[k] + else: + self.fail("the loop broke") + self.assertEqual(seen, 5 + 4 + 3 + 2) + + def test_mutation_during_the_loop(self): + for _ in range(20): + od = OrderedDict(pairs(4)) + with self.assertRaises(RuntimeError): + for k in od: + od["new"] = 1 + od = OrderedDict(pairs(4)) + with self.assertRaises(RuntimeError): + for k, v in od.items(): + del od[k] + od = OrderedDict(pairs(4)) + seen = [] + for k in od: + od[k] = "changed" + seen.append(k) + self.assertEqual(seen, ["k0", "k1", "k2", "k3"]) + self.assertEqual(list(od.values()), ["changed"] * 4) + + def test_values_follow_updates(self): + od = OrderedDict(pairs(3)) + for i in range(N): + od["k1"] = i + got = [v for v in od.values()] + self.assertEqual(got, [0, N - 1, 2]) + + def test_loop_in_a_generator(self): + def walk(od): + for k, v in od.items(): + yield k, v + + od = OrderedDict(pairs(3)) + for _ in range(N): + g = walk(od) + first = next(g) + rest = list(g) + self.assertEqual([first] + rest, pairs(3)) + + def test_dict_dies_after_its_loop(self): + class Value: + pass + + refs = [] + for _ in range(30): + od = OrderedDict() + v = Value() + od["v"] = v + refs.append(weakref.ref(v)) + for k in od: + pass + for k, x in od.items(): + pass + del od, v, x + gc.collect() + self.assertEqual(sum(r() is not None for r in refs), 0) + + def test_iterator_objects_still_work(self): + od = OrderedDict(pairs(3)) + for _ in range(N): + it = iter(od) + first = next(it) + rest = [k for k in it] + self.assertEqual((first, rest), ("k0", ["k1", "k2"])) + self.assertEqual(list(reversed(od)), ["k2", "k1", "k0"]) + self.assertEqual([k for k in reversed(od.keys())], ["k2", "k1", "k0"]) + + def test_class_change_is_seen(self): + class Late(OrderedDict): + pass + + od = Late(pairs(2)) + for _ in range(N): + self.assertEqual([k for k in od], ["k0", "k1"]) + Late.__iter__ = lambda self: iter(("late",)) + for _ in range(N): + self.assertEqual([k for k in od], ["late"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_ordered_dict_move_to_end_order.py b/tests/regrtest/test_ordered_dict_move_to_end_order.py new file mode 100644 index 000000000..20b81d994 --- /dev/null +++ b/tests/regrtest/test_ordered_dict_move_to_end_order.py @@ -0,0 +1,88 @@ +"""`OrderedDict.move_to_end` to either end, from every position. + +A move to the front renumbers every entry it passes, in one pass over the +table when the run is a good share of it. The order, the lookups, and the +order after later inserts and removals must match a list kept alongside, +for dicts small enough to have no table and large ones. +""" + +import collections +import random +import unittest + + +class MoveToEndOrder(unittest.TestCase): + def check(self, od, model): + self.assertEqual(list(od), model) + for i, k in enumerate(model): + self.assertEqual(od[k], k * 10) + self.assertIn(k, od) + self.assertNotIn(-1, od) + + def test_every_position(self): + for n in (2, 5, 8, 9, 16, 40, 200): + for last in (False, True): + for at in range(n): + od = collections.OrderedDict((k, k * 10) for k in range(n)) + model = list(range(n)) + k = model[at] + od.move_to_end(k, last=last) + model.remove(k) + if last: + model.append(k) + else: + model.insert(0, k) + self.check(od, model) + + def test_back_and_forth(self): + words = "The quick brown fox jumps over the lazy dog".split() + od = collections.OrderedDict((w, i) for i, w in enumerate(words)) + before = list(od.items()) + for _ in range(3000): + od.move_to_end("fox") + od.move_to_end("fox", last=False) + self.assertEqual(list(od)[0], "fox") + rest = [kv for kv in before if kv[0] != "fox"] + self.assertEqual(list(od.items())[1:], rest) + self.assertEqual(od["fox"], 3) + + def test_random_moves_with_edits(self): + rng = random.Random(7) + for n in (12, 64, 300): + od = collections.OrderedDict((k, k * 10) for k in range(n)) + model = list(range(n)) + nxt = n + for step in range(2000): + op = rng.random() + if op < 0.6 and model: + k = rng.choice(model) + last = rng.random() < 0.5 + od.move_to_end(k, last=last) + model.remove(k) + model.append(k) if last else model.insert(0, k) + elif op < 0.8 and model: + k = rng.choice(model) + del od[k] + model.remove(k) + else: + od[nxt] = nxt * 10 + model.append(nxt) + nxt += 1 + if step % 97 == 0: + self.check(od, model) + self.check(od, model) + self.assertEqual(list(reversed(od)), model[::-1]) + if model: + k, v = od.popitem(last=False) + self.assertEqual((k, v), (model[0], model[0] * 10)) + + def test_missing_key(self): + od = collections.OrderedDict.fromkeys("abcde") + for _ in range(200): + with self.assertRaises(KeyError): + od.move_to_end("z", last=False) + self.assertEqual("".join(od), "abcde") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_pairwise_fused_pair.py b/tests/regrtest/test_pairwise_fused_pair.py new file mode 100644 index 000000000..2446f4300 --- /dev/null +++ b/tests/regrtest/test_pairwise_fused_pair.py @@ -0,0 +1,151 @@ +"""`for a, b in pairwise(xs)` loops whose pairs go straight to the targets. + +Each step of a `pairwise` over a list's, tuple's, or other plain cursor +gives the previous item and the new one with no tuple built, its first +step included. Each case runs hot with heap items and must agree with +CPython: short sources, a list that grows during the loop, a loop broken +and resumed, kept pairs, other sources, and reference counts. +""" + +import sys +import unittest +from itertools import pairwise + +N = 400 + + +class Item: + def __init__(self, k): + self.k = k + + +class PairwiseFusedPairTests(unittest.TestCase): + def test_list_of_strings(self): + words = ["w%d" % i for i in range(6)] + + def run(): + out = None + for _ in range(N): + out = [] + for a, b in pairwise(words): + out.append(a + b) + return out + + self.assertEqual(run(), ["w0w1", "w1w2", "w2w3", "w3w4", "w4w5"]) + + def test_short_sources(self): + def run(xs): + out = None + for _ in range(N): + out = [(a, b) for a, b in pairwise(xs)] + return out + + self.assertEqual(run([]), []) + self.assertEqual(run(["a"]), []) + self.assertEqual(run(["a", "b"]), [("a", "b")]) + self.assertEqual(run(("a", "b", "c")), [("a", "b"), ("b", "c")]) + + def test_other_sources(self): + def run(make): + out = None + for _ in range(N): + out = [a * 10 + b for a, b in pairwise(make())] + return out + + self.assertEqual(run(lambda: range(5)), [1, 12, 23, 34]) + self.assertEqual(run(lambda: (i for i in range(5))), [1, 12, 23, 34]) + self.assertEqual(run(lambda: iter([0, 1, 2, 3, 4])), [1, 12, 23, 34]) + out = None + for _ in range(N): + out = ["".join(p) for p in pairwise("abcd")] + self.assertEqual(out, ["ab", "bc", "cd"]) + + def test_list_grows(self): + def run(): + out = None + for _ in range(N): + xs = ["x0", "x1"] + out = [] + for a, b in pairwise(xs): + if len(xs) < 5: + xs.append("x%d" % len(xs)) + out.append(b) + return out + + self.assertEqual(run(), ["x1", "x2", "x3", "x4"]) + + def test_break_and_resume(self): + xs = [Item(i) for i in range(8)] + + def run(): + out = None + for _ in range(N): + p = pairwise(xs) + out = [] + for a, b in p: + out.append(a.k) + if b.k == 3: + break + for a, b in p: + out.append(b.k) + return out + + self.assertEqual(run(), [0, 1, 2, 4, 5, 6, 7]) + + def test_kept_pairs(self): + xs = [[i] for i in range(5)] + + def run(): + kept = None + for _ in range(N): + kept = [] + for pair in pairwise(xs): + kept.append(pair) + return kept + + kept = run() + self.assertEqual(kept, [(xs[i], xs[i + 1]) for i in range(4)]) + self.assertTrue(all(type(p) is tuple for p in kept)) + + def test_nested_pairwise(self): + def run(): + out = None + for _ in range(N): + out = [(a, b) for a, b in pairwise(pairwise("abcd"))] + return out + + self.assertEqual( + run(), + [(("a", "b"), ("b", "c")), (("b", "c"), ("c", "d"))], + ) + + def test_refcounts(self): + objs = [Item(i) for i in range(6)] + before = [sys.getrefcount(o) for o in objs] + + def run(): + total = 0 + for _ in range(N): + for a, b in pairwise(objs): + total += b.k - a.k + return total + + self.assertEqual(run(), N * 5) + self.assertEqual([sys.getrefcount(o) for o in objs], before) + + def test_exhausted_stays_exhausted(self): + def run(): + out = None + for _ in range(N): + xs = ["a", "b", "c"] + p = pairwise(xs) + out = [b for a, b in p] + xs.append("d") + out += [b for a, b in p] + return out + + self.assertEqual(run(), ["b", "c"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_partial_builtin_type_calls.py b/tests/regrtest/test_partial_builtin_type_calls.py new file mode 100644 index 000000000..59d2b1050 --- /dev/null +++ b/tests/regrtest/test_partial_builtin_type_calls.py @@ -0,0 +1,45 @@ +"""functools.partial over a builtin type from compiled loops: int with a +stored base (as keyword or position), str with an encoding, enumerate +with a start, keywords the call repeats or the type doesn't take, and a +bad value's error, each matching CPython.""" + +import functools +import unittest + + +def run(n, f, *args, **kw): + out = None + for i in range(n): + out = f(*args, **kw) + return out + + +class PartialTypeTests(unittest.TestCase): + def test_int(self): + hexint = functools.partial(int, base=16) + for n in (1, 400): + self.assertEqual(run(n, hexint, "ff"), 255) + self.assertEqual(run(n, functools.partial(int, "11"), base=2), 3) + self.assertEqual(run(n, functools.partial(int, "11", 8)), 9) + self.assertEqual(run(n, functools.partial(int), "7"), 7) + self.assertEqual(run(n, hexint, "10", base=8), 8) + with self.assertRaises(ValueError): + run(300, hexint, "zz") + with self.assertRaises(TypeError): + run(300, hexint, "ff", 10) + with self.assertRaises(TypeError): + run(300, functools.partial(int, x="1")) + + def test_str_and_enumerate(self): + dec = functools.partial(str, encoding="utf-8") + en = functools.partial(enumerate, start=5) + for n in (1, 400): + self.assertEqual(run(n, dec, b"ab"), "ab") + self.assertEqual(list(run(n, en, "ab")), [(5, "a"), (6, "b")]) + self.assertEqual(run(n, functools.partial(str, b"x", "ascii")), "x") + with self.assertRaises(TypeError): + run(300, functools.partial(str, spam=1), "x") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_partial_construction.py b/tests/regrtest/test_partial_construction.py new file mode 100644 index 000000000..5a68d512a --- /dev/null +++ b/tests/regrtest/test_partial_construction.py @@ -0,0 +1,48 @@ +"""`functools.partial(func, *args)` builds in place. + +The exact class's plain construction over a callable that isn't itself a +partial, without placeholders, lays the instance out as the native +`__new__` does; nested partials, placeholders, keywords, subclasses and +errors keep the full constructor. +""" + +import functools +import pickle +import unittest +from functools import Placeholder, partial + +N = 3000 + + +def f(a, b, c=3): + return (a, b, c) + + +class P2(partial): + pass + + +class PartialConstructionTests(unittest.TestCase): + def test_shapes(self): + for _ in range(N): + p = partial(f, 1) + q = partial(p, 2) + r = partial(f, Placeholder, 5) + s = partial(f, c=9) + t = P2(f, 1) + self.assertEqual((p(2), q(), r(7), s(1, 2), t(2)), ((1, 2, 3),) * 2 + ((7, 5, 3), (1, 2, 9), (1, 2, 3))) + self.assertIs(p.func, f) + self.assertEqual((p.args, p.keywords, q.args), ((1,), {}, (1, 2))) + self.assertIs(type(t), P2) + self.assertEqual(p.__dict__, {}) + + def test_errors_and_pickle(self): + with self.assertRaises(TypeError): + partial(1) + with self.assertRaises(TypeError): + partial() + self.assertEqual(pickle.loads(pickle.dumps(partial(max, 1)))(5), 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_partial_leaf_keyword_calls.py b/tests/regrtest/test_partial_leaf_keyword_calls.py new file mode 100644 index 000000000..6cf0b834a --- /dev/null +++ b/tests/regrtest/test_partial_leaf_keyword_calls.py @@ -0,0 +1,173 @@ +"""Keyword calls of a `functools.partial` over a small Python function. + +A call such as `p(x, c=1)` of a placeholder-free partial whose function is +a pure leaf is evaluated in place, the partial's stored keywords and the +call's bound by name. It must give what the full call gives: a call +keyword overriding a stored one, a keyword that names a positional +parameter, defaults, unexpected or duplicate keywords, a missing +argument, operands the evaluation declines, a replaced `__code__` or +`__defaults__`, a partial subclass, placeholders, and a trace hook. +""" + +import functools +import sys +import unittest + +ROUNDS = 3000 + + +def fk(a, b=1, *, c=2): + return a + b + c + + +def pos3(a, b, c): + return a * 100 + b * 10 + c + + +def kwonly(a, *, k): + return a - k + + +class Num: + def __init__(self, v): + self.v = v + + def __add__(self, other): + return Num(self.v + (other.v if isinstance(other, Num) else other)) + + __radd__ = __add__ + + def __eq__(self, other): + return isinstance(other, Num) and self.v == other.v + + def __repr__(self): + return f"Num({self.v})" + + +def run(fn): + out = None + for _ in range(ROUNDS): + out = fn() + return out + + +class PartialLeafKeywordTests(unittest.TestCase): + def test_stored_and_call_keywords(self): + p = functools.partial(fk, b=5) + self.assertEqual(run(lambda: p(1, c=1)), 7) + self.assertEqual(run(lambda: p(1, c=10)), 16) + self.assertEqual(run(lambda: p(1)), 8) + + def test_call_keyword_overrides_stored(self): + p = functools.partial(fk, b=5, c=7) + self.assertEqual(run(lambda: p(1, b=2)), 10) + self.assertEqual(run(lambda: p(1, c=0, b=0)), 1) + self.assertEqual(p.keywords, {"b": 5, "c": 7}) + + def test_positional_stored(self): + p = functools.partial(fk, 5) + self.assertEqual(run(lambda: p(c=3)), 9) + self.assertEqual(run(lambda: p(b=0, c=0)), 5) + q = functools.partial(pos3, 1) + self.assertEqual(run(lambda: q(c=3, b=2)), 123) + self.assertEqual(run(lambda: q(2, c=3)), 123) + + def test_keyword_names_positional(self): + p = functools.partial(pos3, c=9) + self.assertEqual(run(lambda: p(1, b=2)), 129) + self.assertEqual(run(lambda: p(a=1, b=2)), 129) + + def test_errors(self): + p = functools.partial(fk, b=5) + run(lambda: p(1, c=1)) + with self.assertRaises(TypeError): + p(1, d=1) + with self.assertRaises(TypeError): + p(1, 2, b=3) + with self.assertRaises(TypeError): + p(c=1) + q = functools.partial(kwonly, 1) + self.assertEqual(run(lambda: q(k=3)), -2) + with self.assertRaises(TypeError): + q(2, k=3) + with self.assertRaises(TypeError): + q() + + def test_declined_operands(self): + p = functools.partial(fk, b=5) + run(lambda: p(1, c=1)) + self.assertEqual(p(1.5, c=1), 7.5) + self.assertEqual(p(Num(1), c=1), Num(7)) + self.assertEqual(p(2**80, c=1), 2**80 + 6) + with self.assertRaises(TypeError): + p("x", c=1) + self.assertEqual(run(lambda: p(1, c=1)), 7) + + def test_code_and_defaults_replaced(self): + def g(a, b=1, *, c=2): + return a + b + c + + p = functools.partial(g, b=5) + self.assertEqual(run(lambda: p(1, c=1)), 7) + g.__kwdefaults__ = {"c": 100} + self.assertEqual(p(1), 106) + self.assertEqual(p(1, c=1), 7) + + def h(a, b=1, *, c=2): + return a * b * c + + g.__code__ = h.__code__ + self.assertEqual(p(2, c=3), 30) + self.assertEqual(run(lambda: p(2, c=3)), 30) + + def test_subclass_and_placeholder(self): + class P(functools.partial): + pass + + p = P(fk, b=5) + self.assertEqual(run(lambda: p(1, c=1)), 7) + + class Q(functools.partial): + # (Through the class: WeavePy's `super().__call__` of a + # partial passes the wrong first argument, a separate bug.) + def __call__(self, *args, **kw): + return ("Q", functools.partial.__call__(self, *args, **kw)) + + q = Q(fk, b=5) + self.assertEqual(run(lambda: q(1, c=1)), ("Q", 7)) + if hasattr(functools, "Placeholder"): + r = functools.partial(pos3, functools.Placeholder, 2) + self.assertEqual(run(lambda: r(1, c=3)), 123) + + def test_heap_arguments(self): + def join(a, b, *, sep): + return a + sep + b + + p = functools.partial(join, sep="-") + self.assertEqual(run(lambda: p("x" * 3, "y" * 2, sep="+")), "xxx+yy") + self.assertEqual(run(lambda: p("a", "b")), "a-b") + items = [str(i) for i in range(50)] + self.assertEqual( + [p(s, s, sep=s) for s in items], [s * 3 for s in items] + ) + + def test_trace_hook(self): + p = functools.partial(fk, b=5) + run(lambda: p(1, c=1)) + seen = [] + + def tracer(frame, event, arg): + if event == "call" and frame.f_code is fk.__code__: + seen.append(dict(frame.f_locals)) + return None + + sys.settrace(tracer) + try: + self.assertEqual(p(1, c=1), 7) + finally: + sys.settrace(None) + self.assertEqual(seen, [{"a": 1, "b": 5, "c": 1}]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_partial_native_lane.py b/tests/regrtest/test_partial_native_lane.py new file mode 100644 index 000000000..efc3bc3a0 --- /dev/null +++ b/tests/regrtest/test_partial_native_lane.py @@ -0,0 +1,84 @@ +"""A compiled call site that settled on a builtin through a +`functools.partial` of it (`partial(operator.add, 3)(i)`): the stored +argument comes first, a raising call raises, and a site that then sees a +different partial, a partial with no stored argument, two stored +arguments, keywords, a subclass with its own `__call__`, or the builtin +itself gets the same results as the full call.""" + +import functools +import operator +import unittest + +N = 3000 + + +def call_each(f, xs): + out = [] + for x in xs: + out.append(f(x)) + return out + + +class PartialNativeLaneTests(unittest.TestCase): + def test_stored_argument_first(self): + sub = functools.partial(operator.sub, 100) + self.assertEqual(call_each(sub, range(N)), [100 - i for i in range(N)]) + add3 = functools.partial(operator.add, 3) + self.assertEqual(call_each(add3, range(N)), [i + 3 for i in range(N)]) + + def test_raises(self): + add3 = functools.partial(operator.add, 3) + call_each(add3, range(N)) + with self.assertRaises(TypeError): + call_each(add3, [1, "a"]) + self.assertEqual(call_each(add3, [1.5]), [4.5]) + + def test_site_sees_other_callees(self): + add3 = functools.partial(operator.add, 3) + call_each(add3, range(N)) + mul2 = functools.partial(operator.mul, 2) + self.assertEqual(call_each(mul2, [1, 2]), [2, 4]) + neg = functools.partial(operator.neg) + self.assertEqual(call_each(neg, [1, 2]), [-1, -2]) + self.assertEqual(call_each(operator.not_, [0, 1]), [True, False]) + three = functools.partial(operator.add, "a") + self.assertEqual(call_each(three, ["b", "c"]), ["ab", "ac"]) + + def test_two_stored_arguments_and_keywords(self): + add3 = functools.partial(operator.add, 3) + call_each(add3, range(N)) + pw = functools.partial(pow, 2, 5) + self.assertEqual(call_each(pw, [3, 7]), [2, 4]) + kw = functools.partial(int, base=2) + self.assertEqual(call_each(kw, ["101", "11"]), [5, 3]) + + def test_subclass_call(self): + class P(functools.partial): + def __call__(self, *args): + return ("sub", functools.partial.__call__(self, *args)) + + add3 = functools.partial(operator.add, 3) + call_each(add3, range(N)) + p = P(operator.add, 3) + self.assertEqual(call_each(p, [1, 2]), [("sub", 4), ("sub", 5)]) + + def test_operands_released(self): + class Box: + def __init__(self, v): + self.v = v + + def __add__(self, other): + return self.v + other + + import weakref + + b = Box(1) + r = weakref.ref(b) + addb = functools.partial(operator.add, b) + self.assertEqual(call_each(addb, range(N))[-1], N) + del addb, b + self.assertIsNone(r()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_percent_bare_s_instances.py b/tests/regrtest/test_percent_bare_s_instances.py new file mode 100644 index 000000000..c9c048d4d --- /dev/null +++ b/tests/regrtest/test_percent_bare_s_instances.py @@ -0,0 +1,99 @@ +"""`template % args` whose conversions are all bare `%s`, over instances +(with `str` and `int` arguments beside them), renders in one pass; the +text, a frameless or full `__str__`, `__str__` raising or returning a +non-string, `%%`, argument-count errors, tuple and `str` subclasses, +mappings, and exceptions match the general formatting.""" + +import unittest + + +class K: + def __init__(self, a): + self.a = a + + def __str__(self): + return "K%d" % self.a + + +class Leaf: + def __str__(self): + return "leaf" + + +class NoStr: + pass + + +class Bad: + def __str__(self): + return 3 + + +class Raiser: + def __str__(self): + raise KeyError("s") + + +class T(tuple): + pass + + +class S(str): + def __str__(self): + return "S!" + + +class M: + def __getitem__(self, k): + return "item" + + def __str__(self): + return "M" + + +class PercentBareSInstances(unittest.TestCase): + def test_text(self): + k = K(4) + leaf = Leaf() + for i in range(2000): + self.assertEqual("%s" % k, "K4") + self.assertEqual("%s" % leaf, "leaf") + self.assertEqual("<%s|%s>" % (k, leaf), "") + self.assertEqual("%s=%s (%s%%)" % ("x", k, i), "x=K4 (%d%%)" % i) + self.assertEqual("[%s]" % (K(i),), "[K%d]" % i) + self.assertTrue(("%s" % NoStr()).startswith("<")) + + def test_errors(self): + k = K(1) + for i in range(300): + with self.assertRaises(TypeError) as cm: + "%s" % Bad() + self.assertEqual(str(cm.exception), "__str__ returned non-string (type int)") + with self.assertRaises(KeyError): + "%s and %s" % (k, Raiser()) + with self.assertRaises(TypeError) as cm: + "%s %s" % k + self.assertEqual(str(cm.exception), "not enough arguments for format string") + with self.assertRaises(TypeError) as cm: + "%s" % (k, k) + self.assertEqual( + str(cm.exception), "not all arguments converted during string formatting" + ) + with self.assertRaises(TypeError): + "x" % k + + def test_other_shapes(self): + for i in range(300): + self.assertEqual("%s" % T((K(2),)), "K2") + self.assertEqual("%s %s" % T((K(2), 3)), "K2 3") + self.assertEqual("%s" % S("v"), "S!") + self.assertEqual("%s" % M(), "M") + self.assertEqual("x" % M(), "x") + self.assertEqual("%s" % ValueError("bad"), "bad") + self.assertEqual("%s|%s" % (K(1), 2.5), "K1|2.5") + self.assertEqual("%s|%s" % (K(1), True), "K1|True") + self.assertEqual("%5s|%s" % (K(1), K(2)), " K1|K2") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_percent_float_fixed.py b/tests/regrtest/test_percent_float_fixed.py new file mode 100644 index 000000000..fd0f7c87f --- /dev/null +++ b/tests/regrtest/test_percent_float_fixed.py @@ -0,0 +1,45 @@ +"""`%f` and `%F` formatting of floats, as CPython rounds them. + +Each case's exact decimal expansion rounds half to even at the +precision; zero precision, negative zero, subnormals, large magnitudes, +precisions past 17 and the sign, space, width and zero flags. Run past the +compile threshold. +""" + +CASES = [ + (0, 2.5, '2'), + (0, 3.5, '4'), + (1, 0.05, '0.1'), + (2, 2.675, '2.67'), + (2, 1.005, '1.00'), + (3, 3.14159, '3.142'), + (6, 0.3333333333333333, '0.333333'), + (0, -0.0, '-0'), + (2, -0.001, '-0.00'), + (17, 0.1, '0.10000000000000001'), + (20, 0.1, '0.10000000000000000555'), + (3, 1e+16, '10000000000000000.000'), + (2, 123456789.98765433, '123456789.99'), + (10, 5e-324, '0.0000000000'), + (4, 9.99995, '10.0000'), +] +FLAGS = [ + ('%+.2f', 2.5, '+2.50'), + ('% .1f', 0.25, ' 0.2'), + ('%-10.3f|', 1.5, '1.500 |'), + ('%010.4f', -3.14159, '-0003.1416'), + ('%F', 1e+20, '100000000000000000000.000000'), + ('%f', 0.1, '0.100000'), +] + + +def run(n): + for _ in range(n): + for p, v, want in CASES: + assert "%.*f" % (p, v) == want, (p, v, "%.*f" % (p, v), want) + for f, v, want in FLAGS: + assert f % v == want, (f, v, f % v, want) + + +run(300) +print("ok") diff --git a/tests/regrtest/test_percent_r_and_instance_repr.py b/tests/regrtest/test_percent_r_and_instance_repr.py new file mode 100644 index 000000000..a33c69128 --- /dev/null +++ b/tests/regrtest/test_percent_r_and_instance_repr.py @@ -0,0 +1,81 @@ +"""`%r` of plain values, and native reprs of instances with `__repr__`. + +`"%r" % x` renders an `int`, `bool`, `None` or `str` in place; widths, +flags, mapping keys, subclasses and other values take the general path. +A container's repr calls its items' Python `__repr__` directly; a raising +or non-string `__repr__`, a class whose `__repr__` changes, and +`object`'s default repr behave as before. +""" + +import unittest + +N = 3000 + + +class P: + def __init__(self, x): + self.x = x + + def __repr__(self): + return "P(%r)" % self.x + + +class Bad: + def __repr__(self): + raise ValueError("bad repr") + + +class Late: + pass + + +class S(str): + pass + + +class PercentReprTests(unittest.TestCase): + def test_plain_values(self): + for i in range(N): + r = "%r|%r|%r|%r|%r" % (i, "a'b", True, None, "x\n") + self.assertEqual(r, "%d|\"a'b\"|True|None|'x\\n'" % (N - 1)) + + def test_general_path(self): + for _ in range(N): + r = ("%5r|%-6r|" % (7, "x"), "%(a)r %(b)r" % {"a": -3, "b": "q"}, + "%r" % (S("z"),), "%r %r" % (2.5, [1]), "%r" % ((1, 2),)) + self.assertEqual(r, (" 7|'x' |", "-3 'q'", "'z'", "2.5 [1]", "(1, 2)")) + + +class InstanceReprTests(unittest.TestCase): + def test_container_reprs(self): + ps = [P(i) for i in range(3)] + for _ in range(N): + r = (repr(ps), repr({"k": ps[0]}), repr((ps[1],)), str(ps), f"{ps!r}") + self.assertEqual(r[0], "[P(0), P(1), P(2)]") + self.assertEqual(r[1], "{'k': P(0)}") + self.assertEqual(r[2], "(P(1),)") + self.assertEqual(r[3], r[0]) + self.assertEqual(r[4], r[0]) + + def test_raising_repr(self): + for _ in range(200): + with self.assertRaises(ValueError): + repr([Bad()]) + with self.assertRaises(ValueError): + repr({1: Bad()}) + + def test_repr_changes(self): + objs = [Late(), Late()] + out = [] + for i in range(N): + if i == N // 2: + Late.__repr__ = lambda self: "late" + out.append(repr(objs)) + self.assertTrue(out[0].startswith("[<")) + self.assertEqual(out[-1], "[late, late]") + del Late.__repr__ + self.assertTrue(repr(objs).startswith("[<")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_pickle_bytearrays_natively.py b/tests/regrtest/test_pickle_bytearrays_natively.py new file mode 100644 index 000000000..f73e519b0 --- /dev/null +++ b/tests/regrtest/test_pickle_bytearrays_natively.py @@ -0,0 +1,60 @@ +"""Protocol 5 bytearrays through the native pickler and unpickler. + +`BYTEARRAY8` is written natively (a large one outside the frame, as the +Python pickler writes it) and read back natively; the bytes must equal the +Python pickler's exactly, identity must survive the memo, and protocol 4 +keeps its `copyreg` reduction. +""" + +import pickle +import pickletools +import unittest + + +class PickleBytearrayTests(unittest.TestCase): + def check(self, value, proto): + data = pickle.dumps(value, proto) + self.assertEqual(data, pickle._dumps(value, proto)) + back = pickle.loads(data) + self.assertEqual(back, value) + self.assertEqual(pickle._loads(data), value) + return data, back + + def test_sizes(self): + for n in (0, 1, 255, 256, 65535, 65536, 70000): + value = bytearray(bytes(range(256)) * (n // 256 + 1))[:n] + for proto in (4, 5): + _, back = self.check(value, proto) + self.assertIs(type(back), bytearray) + + def test_opcode(self): + data = pickle.dumps(bytearray(b"abc"), 5) + ops = [op.name for op, _, _ in pickletools.genops(data)] + self.assertIn("BYTEARRAY8", ops) + data4 = pickle.dumps(bytearray(b"abc"), 4) + self.assertNotIn("BYTEARRAY8", [op.name for op, _, _ in pickletools.genops(data4)]) + + def test_memo_identity(self): + shared = bytearray(b"shared") + value = [shared, shared, (shared, b"x"), {"k": shared}] + _, back = self.check(value, 5) + self.assertIs(back[0], back[1]) + self.assertIs(back[0], back[2][0]) + self.assertIs(back[0], back[3]["k"]) + back[0].append(33) + self.assertEqual(back[1], bytearray(b"shared!")) + + def test_nested(self): + value = {"data": bytearray(b"v" * 1000), "meta": (1, "two", b"three"), "list": [bytearray()]} + for _ in range(200): + self.check(value, 5) + + def test_independent_copies(self): + a = bytearray(b"abc") + back = pickle.loads(pickle.dumps(a, 5)) + back[0] = 0 + self.assertEqual(a, bytearray(b"abc")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_pickle_dumps_loads_front.py b/tests/regrtest/test_pickle_dumps_loads_front.py new file mode 100644 index 000000000..942fbf7cb --- /dev/null +++ b/tests/regrtest/test_pickle_dumps_loads_front.py @@ -0,0 +1,176 @@ +"""`pickle.dumps` and `pickle.loads` take every documented argument form. + +Positional and keyword protocols, `fix_imports`, `buffer_callback`, +`encoding`, `errors` and `buffers` give the results the pickle engine +gives, wrong arguments raise `TypeError`, and a `str` passed to `loads` +is refused. A method of the Python pickler or unpickler whose code or +defaults change after many calls is seen at once, however many calls ran +before it changed. +""" + +import io +import pickle +import types +import unittest + + +class Point: + def __init__(self, x): + self.x = x + + +VALUES = [1, -5, 2**40, 2.5, "abc", b"xyz", [1, (2, 3)], {"a": 1}, None, True] + + +class ArgumentTests(unittest.TestCase): + def test_round_trips(self): + for value in VALUES: + for protocol in (None, 0, 2, 4, 5, -1, pickle.HIGHEST_PROTOCOL): + data = pickle.dumps(value, protocol) + self.assertEqual(pickle.loads(data), value) + self.assertEqual(pickle.dumps(value, protocol=protocol), data) + + def test_keywords(self): + data = pickle.dumps([1, 2], fix_imports=False) + self.assertEqual(pickle.loads(data, fix_imports=False), [1, 2]) + self.assertEqual(pickle.dumps(3, 4, buffer_callback=None), pickle.dumps(3, 4)) + self.assertEqual(pickle.loads(data, encoding="latin1", errors="ignore"), [1, 2]) + self.assertEqual(pickle.loads(data, buffers=None), [1, 2]) + self.assertEqual(pickle.loads(bytearray(data)), [1, 2]) + self.assertEqual(pickle.loads(memoryview(data)), [1, 2]) + + def test_out_of_band_buffers(self): + buffers = [] + value = pickle.PickleBuffer(b"payload") + data = pickle.dumps(value, 5, buffer_callback=buffers.append) + self.assertEqual(len(buffers), 1) + self.assertEqual(bytes(pickle.loads(data, buffers=buffers)), b"payload") + + def test_bad_arguments(self): + with self.assertRaises(TypeError): + pickle.dumps() + with self.assertRaises(TypeError): + pickle.dumps(1, 2, 3) + with self.assertRaises(TypeError): + pickle.dumps(1, protocol=2, nonsense=1) + with self.assertRaises(TypeError): + pickle.dumps(1, 2, protocol=2) + with self.assertRaises(TypeError): + pickle.loads() + with self.assertRaises(TypeError): + pickle.loads(b".", b".") + with self.assertRaises(TypeError): + pickle.loads(data=pickle.dumps(1)) + with self.assertRaises(TypeError): + pickle.loads("not bytes") + with self.assertRaises(ValueError): + pickle.dumps(1, pickle.HIGHEST_PROTOCOL + 1) + + def test_failures(self): + with self.assertRaises(Exception): + pickle.dumps(lambda: None) + with self.assertRaises(Exception): + pickle.loads(b"\x80\x05garbage") + with self.assertRaises(EOFError): + pickle.loads(b"") + + def test_instances(self): + for _ in range(50): + self.assertEqual(pickle.loads(pickle.dumps(Point(7))).x, 7) + + def test_names(self): + self.assertEqual(pickle.dumps.__name__, "dumps") + self.assertEqual(pickle.loads.__name__, "loads") + self.assertEqual(pickle.dumps.__module__, "_pickle") + self.assertEqual(pickle.loads.__module__, "_pickle") + self.assertEqual(repr(pickle.dumps), "") + self.assertEqual(repr(pickle.loads), "") + + +class ChangeTests(unittest.TestCase): + def warm(self): + for _ in range(200): + self.assertEqual(pickle.loads(pickle.dumps("abc")), "abc") + self.assertEqual(pickle.loads(pickle.dumps(["x", 1])), ["x", 1]) + + def test_pickler_method_code(self): + if not issubclass(pickle.Pickler, pickle._Pickler): + self.skipTest("the pickler is not the Python one") + self.warm() + save_str = pickle._Pickler.save_str + original = save_str.__code__ + pickle._front_test_save_str = types.FunctionType( + original, save_str.__globals__, "save_str_copy") + + def patched(self, obj): + _front_test_save_str(self, "patched" if obj == "abc" else obj) + + save_str.__code__ = patched.__code__ + try: + self.assertEqual(pickle.loads(pickle.dumps("abc")), "patched") + finally: + save_str.__code__ = original + del pickle._front_test_save_str + self.warm() + + def test_unpickler_method_code(self): + if not issubclass(pickle.Unpickler, pickle._Unpickler): + self.skipTest("the unpickler is not the Python one") + self.warm() + opcode = pickle.BININT1[0] + load = pickle._Unpickler.dispatch[opcode] + original = load.__code__ + + def patched(self): + self.append(int.from_bytes(self.read(1), "little") + 100) + + load.__code__ = patched.__code__ + try: + self.assertEqual(pickle.loads(pickle.dumps(5)), 105) + finally: + load.__code__ = original + self.assertEqual(pickle.loads(pickle.dumps(5)), 5) + self.warm() + + def test_pickler_method_defaults(self): + if not issubclass(pickle.Pickler, pickle._Pickler): + self.skipTest("the pickler is not the Python one") + self.warm() + save = pickle._Pickler.save + saved = save.__defaults__ + save.__defaults__ = saved + try: + self.assertEqual(pickle.loads(pickle.dumps(["x"])), ["x"]) + finally: + save.__defaults__ = saved + self.warm() + + def test_dispatch_entry_replaced(self): + if not issubclass(pickle.Pickler, pickle._Pickler): + self.skipTest("the pickler is not the Python one") + self.warm() + table = pickle._Pickler.dispatch + original = table[str] + calls = [] + + def counting(self, obj): + calls.append(obj) + original(self, obj) + + table[str] = counting + try: + self.assertEqual(pickle.loads(pickle.dumps("abc")), "abc") + finally: + table[str] = original + self.assertEqual(calls, ["abc"]) + self.warm() + + def test_through_a_file(self): + f = io.BytesIO() + pickle.dump([1, "a"], f) + f.seek(0) + self.assertEqual(pickle.load(f), [1, "a"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_poly_field_reads.py b/tests/regrtest/test_poly_field_reads.py new file mode 100644 index 000000000..80cf61806 --- /dev/null +++ b/tests/regrtest/test_poly_field_reads.py @@ -0,0 +1,288 @@ +"""Polymorphic field reads and class constants in compiled code. + +A base class's method reading `self.x` of two or more subclasses' instances +(each class with its own layout of the inherited fields), a field read off +a value on the stack (`self.v.value`), and `Cls.CONST` read in an inlined +body, which may come straight off the attribute site's cache with the +global's load. Each must see stores, deletions, shadowing, published +`__dict__`s, a third and fourth class, and a rebound global or constant, +run long enough to compile. +""" + +import unittest + +N = 6000 + + +class Box: + def __init__(self, value): + self.value = value + + +class Base: + def __init__(self, a, b): + self.a = a + self.b = b + self.d = 1 + + def pick(self): + if self.d == 1: + return self.a + return self.b + + def both(self): + return self.a + self.b + + +class Left(Base): + pass + + +class Right(Base): + def __init__(self, a, b): + self.extra = 0 + Base.__init__(self, a, b) + + +class Third(Base): + def __init__(self, a, b): + self.z = 9 + self.y = 8 + Base.__init__(self, a, b) + + +class Fourth(Base): + __slots__ = ("a", "b", "d") + + +def through(o): + return o.pick() + o.both() + + +def walk(objs): + t = 0 + for o in objs: + t += through(o) + return t + + +class Tag: + def __init__(self, value): + self.tag = "t" + self.value = value + + +class Holder: + def __init__(self, v): + self.v = v + + def total(self): + return self.v.value + + +class Pair(Holder): + def __init__(self, v, w): + self.w = w + Holder.__init__(self, v) + + def total(self): + return self.v.value + self.w.value + + +class Solo(Holder): + pass + + +def totals(objs): + t = 0 + for o in objs: + t += o.total() + return t + + +class Direction: + NONE = 0 + FORWARD = 1 + BACKWARD = -1 + + +class Step: + def __init__(self, d): + self.d = d + + def forward(self): + return self.d == Direction.FORWARD + + def code(self): + return Direction.BACKWARD + + +def count_forward(steps): + n = 0 + for s in steps: + if s.forward(): + n += 1 + n += s.code() + return n + + +def expect_walk(objs): + t = 0 + for o in objs: + p = o.a if o.d == 1 else o.b + t += p + o.a + o.b + return t + + +class PolyFieldTests(unittest.TestCase): + def test_two_classes(self): + objs = [Left(1, 2), Right(3, 4)] * 4 + for _ in range(N): + self.assertEqual(walk(objs), expect_walk(objs)) + + def test_stores_seen(self): + objs = [Left(1, 2), Right(3, 4)] * 4 + for i in range(N): + objs[i % 8].a = i + objs[(i + 3) % 8].d = i % 2 + self.assertEqual(walk(objs), expect_walk(objs)) + + def test_third_and_fourth_class(self): + objs = [Left(1, 2), Right(3, 4)] * 4 + for _ in range(N): + walk(objs) + more = objs + [Third(5, 6), Fourth(7, 8), Third(9, 10)] + for _ in range(N // 4): + self.assertEqual(walk(more), expect_walk(more)) + + def test_deleted_field_raises(self): + objs = [Left(1, 2), Right(3, 4)] * 4 + for _ in range(N): + walk(objs) + victim = Right(5, 6) + del victim.b + with self.assertRaises(AttributeError): + walk(objs + [victim]) + victim.b = 7 + self.assertEqual(walk(objs + [victim]), expect_walk(objs + [victim])) + + def test_published_dict(self): + objs = [Left(1, 2), Right(3, 4)] * 4 + for _ in range(N): + walk(objs) + vars(objs[1])["a"] = 100 + objs[2].__dict__.update(b=50) + for _ in range(100): + self.assertEqual(walk(objs), expect_walk(objs)) + + def test_class_attribute_shadowing(self): + # (Classes of its own: a property turns its sites into property + # sites for good.) + class B2: + def __init__(self, a, b): + self.a = a + self.b = b + + def get(self): + return self.a + self.b + + class L2(B2): + pass + + class R2(B2): + pass + + def run(objs): + t = 0 + for o in objs: + t += o.get() + return t + + objs = [L2(1, 2), R2(3, 4)] * 4 + for _ in range(N): + self.assertEqual(run(objs), 40) + # A data descriptor on one class takes over its reads. + R2.a = property(lambda self: 1000) + self.assertEqual(run(objs), 4 * (3 + 1004)) + del R2.a + self.assertEqual(run(objs), 40) + + def test_field_off_stack(self): + objs = [Pair(Box(1), Tag(2)), Solo(Tag(3)), Solo(Box(4))] * 3 + for _ in range(N): + self.assertEqual(totals(objs), 3 * 10) + objs[0].v = Box(10) + objs[1].v.value = 20 + self.assertEqual(totals(objs), 3 * (12 + 20 + 4)) + del objs[2].v.value + with self.assertRaises(AttributeError): + totals(objs) + + def test_field_off_stack_released(self): + import weakref + + boxes = [Box(i) for i in range(8)] + refs = [weakref.ref(b) for b in boxes] + objs = [Pair(boxes[i], boxes[i + 1]) if i % 2 else Solo(boxes[i]) + for i in range(7)] + objs.append(Solo(Tag(1))) + for _ in range(N): + totals(objs) + del boxes + for o in objs: + o.v = None + if isinstance(o, Pair): + o.w = None + self.assertEqual([r() for r in refs], [None] * 8) + + def test_class_constant(self): + steps = [Step(1), Step(0), Step(-1)] + for _ in range(N): + self.assertEqual(count_forward(steps), 1 - 3) + + def test_class_constant_rebound(self): + steps = [Step(1), Step(0), Step(-1)] + for _ in range(N): + count_forward(steps) + old = Direction.FORWARD, Direction.BACKWARD + try: + Direction.FORWARD = 0 + Direction.BACKWARD = -5 + self.assertEqual(count_forward(steps), 1 - 15) + finally: + Direction.FORWARD, Direction.BACKWARD = old + self.assertEqual(count_forward(steps), 1 - 3) + + def test_global_rebound(self): + global Direction + steps = [Step(1), Step(0), Step(-1)] + for _ in range(N): + count_forward(steps) + saved = Direction + + class Other: + FORWARD = -1 + BACKWARD = 2 + + try: + Direction = Other + self.assertEqual(count_forward(steps), 1 + 6) + + class Plain: + pass + + inst = Plain() + inst.FORWARD = 0 + inst.BACKWARD = 1 + Direction = inst + self.assertEqual(count_forward(steps), 1 + 3) + Direction = Plain + with self.assertRaises(AttributeError): + count_forward(steps) + finally: + Direction = saved + self.assertEqual(count_forward(steps), 1 - 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_poly_field_slot_sites.py b/tests/regrtest/test_poly_field_slot_sites.py new file mode 100644 index 000000000..db1fdf80c --- /dev/null +++ b/tests/regrtest/test_poly_field_slot_sites.py @@ -0,0 +1,687 @@ +"""One attribute site read over several classes, slotted and plain. + +A compiled read keeps a few classes' field positions at the site: a plain +instance attribute's position in the instance's values, or a `__slots__` +member's position in the laid-out record. A read through a remembered +position must give what the full lookup gives: for an unset or deleted +slot, after a class replaces the member, for a subclass that declares the +slot again, for instances that publish their dict, and for sites that see +more classes than they remember. The same loops call tiny functions and +methods over receivers of alternating classes, which the loop tier hands +back to the per-site caches. +""" + +import unittest + +ROUNDS = 4000 + + +class S1: + __slots__ = ("a", "b") + + def __init__(self, a): + self.a = a + self.b = a + 1 + + def m(self): + return self.a + + @property + def p(self): + return self.a + + +class S2: + __slots__ = ("b", "a") + + def __init__(self, a): + self.b = a + 2 + self.a = a + + def m(self): + return self.a + 1 + + @property + def p(self): + return self.a + 1 + + +class S3: + __slots__ = ("x", "y", "a") + + def __init__(self, a): + self.x = None + self.y = None + self.a = a + + def m(self): + return self.a + 2 + + @property + def p(self): + return self.a + 2 + + +class S4(S1): + __slots__ = ("c",) + + def __init__(self, a): + S1.__init__(self, a) + self.c = -a + + +class S5(S1): + # Declares `a` again: the member read is this class's. + __slots__ = ("a",) + + def __init__(self, a): + self.a = a + self.b = a + 1 + + +class S6(S1): + # No `__slots__`: instances have a dict next to the laid-out record. + def __init__(self, a): + S1.__init__(self, a) + self.extra = a + + +class D1: + def __init__(self, a): + self.a = a + self.b = a + 1 + + def m(self): + return self.a + + @property + def p(self): + return self.a + + +class D2: + def __init__(self, a): + self.b = a + 2 + self.a = a + + def m(self): + return self.a + 1 + + @property + def p(self): + return self.a + 1 + + +class D3: + def __init__(self, a): + self.x = None + self.y = None + self.a = a + + def m(self): + return self.a + 2 + + @property + def p(self): + return self.a + 2 + + +class D4(D1): + def __init__(self, a): + self.first = 0 + D1.__init__(self, a) + + +class D5: + a = 1000 + + def __init__(self, a): + self.b = a + + +def rd(o): + return o.a + + +def rd_b(o): + return o.b + + +def call_m(o): + return o.m() + + +def read_p(o): + return o.p + + +def loop_inline(objs, n): + t = 0 + k = len(objs) + for i in range(n): + o = objs[i % k] + t += o.a + return t + + +def loop_callee(objs, n): + t = 0 + k = len(objs) + for i in range(n): + t += rd(objs[i % k]) + return t + + +def loop_list(objs): + t = 0 + for o in objs: + t += rd(o) + return t + + +def loop_append(objs): + out = [] + for o in objs: + out.append(rd(o)) + return out + + +def loop_filter(objs): + n = 0 + for o in objs: + if rd(o) > 50: + n += 1 + return n + + +def loop_comp(objs): + return [rd(o) for o in objs] + + +def loop_method(objs, n): + t = 0 + k = len(objs) + for i in range(n): + o = objs[i % k] + t += o.m() + return t + + +def loop_method_callee(objs, n): + t = 0 + k = len(objs) + for i in range(n): + t += call_m(objs[i % k]) + return t + + +def loop_property(objs, n): + t = 0 + k = len(objs) + for i in range(n): + o = objs[i % k] + t += o.p + return t + + +def loop_property_callee(objs, n): + t = 0 + k = len(objs) + for i in range(n): + t += read_p(objs[i % k]) + return t + + +class SlotSites(unittest.TestCase): + def check(self, classes): + objs = [cls(10 * (i + 1)) for i, cls in enumerate(classes)] + vals = [10 * (i + 1) for i in range(len(classes))] + k = len(objs) + n = ROUNDS + whole, rest = divmod(n, k) + want = whole * sum(vals) + sum(vals[:rest]) + for _ in range(4): + self.assertEqual(loop_inline(objs, n), want) + self.assertEqual(loop_callee(objs, n), want) + many = objs * 40 + for _ in range(60): + self.assertEqual(loop_list(many), 40 * sum(vals)) + self.assertEqual(loop_append(many), vals * 40) + self.assertEqual(loop_comp(many), vals * 40) + self.assertEqual(loop_filter(many), 40 * sum(1 for v in vals if v > 50)) + + def test_one_class(self): + self.check([S1]) + + def test_two_classes(self): + self.check([S1, S2]) + + def test_three_classes(self): + self.check([S1, S2, S3]) + + def test_five_classes(self): + self.check([S1, S2, S3, S4, S5]) + + def test_seven_classes_mixed(self): + self.check([S1, D1, S2, D2, S3, D3, S6]) + + def test_dict_classes(self): + self.check([D1, D2]) + self.check([D1, D2, D3, D4]) + + def test_class_attribute_among_fields(self): + objs = [D1(1), D5(2), D2(3), S2(4)] + want = (1 + 1000 + 3 + 4) * (ROUNDS // 4) + for _ in range(4): + self.assertEqual(loop_inline(objs, ROUNDS), want) + self.assertEqual(loop_callee(objs, ROUNDS), want) + + def test_redeclared_slot(self): + o = S5(7) + self.assertEqual(rd(o), 7) + objs = [S1(1), o, S2(2)] + for _ in range(ROUNDS): + self.assertEqual(rd(objs[0]), 1) + self.assertEqual(rd(objs[1]), 7) + self.assertEqual(rd(objs[2]), 2) + o.a = 8 + self.assertEqual(rd(o), 8) + self.assertEqual(rd_b(o), 8) + + def test_unset_slot_raises(self): + objs = [S1(1), S2(2), S3(3)] + for _ in range(ROUNDS): + for o in objs: + rd(o) + bare = S2.__new__(S2) + for _ in range(50): + with self.assertRaises(AttributeError) as cm: + rd(bare) + self.assertEqual(cm.exception.name, "a") + self.assertIs(cm.exception.obj, bare) + bare.a = 5 + self.assertEqual(rd(bare), 5) + self.assertEqual([rd(o) for o in objs], [1, 2, 3]) + + def test_deleted_slot_raises(self): + objs = [S1(1), S2(2)] + t = 0 + for i in range(ROUNDS): + t += rd(objs[i & 1]) + self.assertEqual(t, 3 * (ROUNDS // 2)) + del objs[1].a + for i in range(200): + if i & 1: + with self.assertRaises(AttributeError): + rd(objs[1]) + else: + self.assertEqual(rd(objs[0]), 1) + objs[1].a = 9 + self.assertEqual(rd(objs[1]), 9) + + def test_slot_miss_reaches_getattr_hook(self): + class H: + __slots__ = ("a",) + + def __getattr__(self, name): + return "hook:" + name + + class G: + __slots__ = ("a",) + + def __init__(self): + self.a = "set" + + objs = [G(), H()] + for i in range(ROUNDS): + self.assertEqual(rd(objs[i & 1]), "hook:a" if i & 1 else "set") + objs[1].a = "now" + for i in range(200): + self.assertEqual(rd(objs[i & 1]), "now" if i & 1 else "set") + del objs[1].a + for i in range(200): + self.assertEqual(rd(objs[i & 1]), "hook:a" if i & 1 else "set") + + def test_member_replaced_on_class(self): + class P: + __slots__ = ("a",) + + def __init__(self, a): + self.a = a + + class Q: + __slots__ = ("z", "a") + + def __init__(self, a): + self.z = None + self.a = a + + objs = [P(1), Q(2)] + t = 0 + for i in range(ROUNDS): + t += rd(objs[i & 1]) + self.assertEqual(t, 3 * (ROUNDS // 2)) + member = Q.__dict__["a"] + Q.a = property(lambda self: 40) + t = 0 + for i in range(ROUNDS): + t += rd(objs[i & 1]) + self.assertEqual(t, 41 * (ROUNDS // 2)) + Q.a = 77 + t = 0 + for i in range(200): + t += rd(objs[i & 1]) + self.assertEqual(t, 78 * 100) + Q.a = member + t = 0 + for i in range(ROUNDS): + t += rd(objs[i & 1]) + self.assertEqual(t, 3 * (ROUNDS // 2)) + del Q.a + for i in range(100): + with self.assertRaises(AttributeError): + rd(objs[1]) + self.assertEqual(rd(objs[0]), 1) + + def test_getattribute_added(self): + class P: + __slots__ = ("a",) + + def __init__(self, a): + self.a = a + + class Q: + __slots__ = ("a",) + + def __init__(self, a): + self.a = a + + objs = [P(1), Q(2)] + for i in range(ROUNDS): + rd(objs[i & 1]) + Q.__getattribute__ = lambda self, name: "all:" + name + for i in range(200): + self.assertEqual(rd(objs[i & 1]), "all:a" if i & 1 else 1) + del Q.__getattribute__ + for i in range(200): + self.assertEqual(rd(objs[i & 1]), 2 if i & 1 else 1) + + def test_slots_with_dict_subclass(self): + objs = [S6(1), S1(2), S6(3)] + objs[0].__dict__["a"] = "shadow" # a member is a data descriptor + t = 0 + for i in range(ROUNDS): + t += rd(objs[i % 3]) + self.assertEqual(t, 6 * (ROUNDS // 3) + 1) + self.assertEqual(vars(objs[0])["a"], "shadow") + + def test_class_reassigned(self): + class P: + __slots__ = ("a", "b") + + class Q: + __slots__ = ("a", "b") + + @property + def twice(self): + return self.a * 2 + + o = P() + o.a, o.b = 3, 4 + other = S2(10) + for i in range(ROUNDS): + self.assertEqual(rd(o if i & 1 else other), 3 if i & 1 else 10) + o.__class__ = Q + for i in range(ROUNDS): + self.assertEqual(rd(o if i & 1 else other), 3 if i & 1 else 10) + self.assertEqual(o.twice, 6) + self.assertEqual(rd_b(o), 4) + + +class DictSites(unittest.TestCase): + def test_published_dict(self): + objs = [D1(1), D2(2), D3(3)] + t = 0 + for i in range(ROUNDS): + t += rd(objs[i % 3]) + d = vars(objs[1]) + d["a"] = 20 + t = 0 + for i in range(300): + t += rd(objs[i % 3]) + self.assertEqual(t, 24 * 100) + del d["a"] + for i in range(60): + if i % 3 == 1: + with self.assertRaises(AttributeError): + rd(objs[1]) + else: + rd(objs[i % 3]) + d["zz"] = 0 + d["a"] = 5 + t = 0 + for i in range(300): + t += rd(objs[i % 3]) + self.assertEqual(t, 9 * 100) + + def test_attribute_added_late(self): + objs = [D1(1), D5(2)] + t = 0 + for i in range(ROUNDS): + t += rd(objs[i & 1]) + self.assertEqual(t, 1001 * (ROUNDS // 2)) + objs[1].a = 6 + t = 0 + for i in range(ROUNDS): + t += rd(objs[i & 1]) + self.assertEqual(t, 7 * (ROUNDS // 2)) + del objs[1].a + t = 0 + for i in range(200): + t += rd(objs[i & 1]) + self.assertEqual(t, 1001 * 100) + + def test_instances_of_one_class_with_different_shapes(self): + x = D1(1) + y = D1(2) + y.c = 0 + del y.a + y.a = 22 + z = D2(3) + t = 0 + for i in range(ROUNDS): + t += rd((x, y, z)[i % 3]) + self.assertEqual(t, 26 * (ROUNDS // 3) + 1) + + +class MethodAndPropertySites(unittest.TestCase): + def check(self, classes, plus): + objs = [cls(10) for cls in classes] + k = len(objs) + whole, rest = divmod(ROUNDS, k) + vals = [10 + p for p in plus] + want = whole * sum(vals) + sum(vals[:rest]) + for _ in range(5): + self.assertEqual(loop_method(objs, ROUNDS), want) + self.assertEqual(loop_method_callee(objs, ROUNDS), want) + self.assertEqual(loop_property(objs, ROUNDS), want) + self.assertEqual(loop_property_callee(objs, ROUNDS), want) + + def test_two_slotted(self): + self.check([S1, S2], [0, 1]) + + def test_three_slotted(self): + self.check([S1, S2, S3], [0, 1, 2]) + + def test_two_plain(self): + self.check([D1, D2], [0, 1]) + + def test_six_mixed(self): + self.check([S1, D2, S3, D1, S2, D3], [0, 1, 2, 0, 1, 2]) + + def test_method_replaced_between_runs(self): + class A: + def __init__(self, a): + self.a = a + + def m(self): + return self.a + + class B(A): + def m(self): + return self.a + 100 + + objs = [A(1), B(2)] + for _ in range(4): + self.assertEqual(loop_method(objs, ROUNDS), 103 * (ROUNDS // 2)) + B.m = lambda self: -self.a + for _ in range(4): + self.assertEqual(loop_method(objs, ROUNDS), -1 * (ROUNDS // 2)) + objs[0].m = lambda: 5 + for _ in range(4): + self.assertEqual(loop_method(objs, ROUNDS), 3 * (ROUNDS // 2)) + del B.m + for _ in range(4): + self.assertEqual(loop_method(objs, ROUNDS), 7 * (ROUNDS // 2)) + + def test_getter_over_unset_and_deleted_slots(self): + class P: + __slots__ = ("a", "b") + + def __init__(self, a): + self.a = a + + @property + def p(self): + return self.a + + class Q(P): + __slots__ = () + + class R(P): + __slots__ = ("c",) + + objs = [P(1), Q(2), R(3)] + for _ in range(4): + self.assertEqual(loop_property(objs, ROUNDS), 6 * (ROUNDS // 3) + 1) + self.assertEqual(loop_property_callee(objs, ROUNDS), 6 * (ROUNDS // 3) + 1) + bare = Q.__new__(Q) + for _ in range(60): + with self.assertRaises(AttributeError) as cm: + read_p(bare) + self.assertEqual(cm.exception.name, "a") + self.assertEqual(read_p(objs[1]), 2) + del objs[1].a + for _ in range(60): + with self.assertRaises(AttributeError): + read_p(objs[1]) + self.assertEqual(read_p(objs[0]), 1) + self.assertEqual(read_p(objs[2]), 3) + objs[1].a = 20 + for _ in range(4): + self.assertEqual(loop_property(objs, ROUNDS), 24 * (ROUNDS // 3) + 1) + + def test_getter_after_member_replaced(self): + class P: + __slots__ = ("a",) + + def __init__(self, a): + self.a = a + + @property + def p(self): + return self.a + + class Q(P): + __slots__ = () + + class E(P): + pass + + objs = [P(1), Q(2), E(3)] + want = 6 * (ROUNDS // 3) + 1 + for _ in range(4): + self.assertEqual(loop_property(objs, ROUNDS), want) + self.assertEqual(loop_property_callee(objs, ROUNDS), want) + objs[2].__dict__["a"] = "shadow" # the member still wins + for _ in range(2): + self.assertEqual(loop_property_callee(objs, ROUNDS), want) + Q.a = 50 + for _ in range(4): + self.assertEqual(loop_property(objs, ROUNDS), 54 * (ROUNDS // 3) + 1) + self.assertEqual(loop_property_callee(objs, ROUNDS), 54 * (ROUNDS // 3) + 1) + del Q.a + E.a = property(lambda self: 300) + for _ in range(4): + self.assertEqual(loop_property(objs, ROUNDS), 303 * (ROUNDS // 3) + 1) + self.assertEqual(loop_property_callee(objs, ROUNDS), 303 * (ROUNDS // 3) + 1) + del E.a + for _ in range(4): + self.assertEqual(loop_property_callee(objs, ROUNDS), want) + + def test_getter_over_dict_shapes(self): + class A: + def __init__(self, a): + self.a = a + + @property + def p(self): + return self.a + + class B(A): + def __init__(self, a): + self.z = 0 + self.a = a + + class C(A): + a = 700 + + def __init__(self, a): + self.z = a + + objs = [A(1), B(2), C(3)] + want = 703 * (ROUNDS // 3) + 1 + for _ in range(4): + self.assertEqual(loop_property(objs, ROUNDS), want) + self.assertEqual(loop_property_callee(objs, ROUNDS), want) + objs[2].a = 9 + for _ in range(4): + self.assertEqual(loop_property_callee(objs, ROUNDS), 12 * (ROUNDS // 3) + 1) + del objs[1].a + for _ in range(30): + with self.assertRaises(AttributeError): + read_p(objs[1]) + self.assertEqual(read_p(objs[0]), 1) + self.assertEqual(read_p(objs[2]), 9) + vars(objs[1])["a"] = 5 + for _ in range(4): + self.assertEqual(loop_property(objs, ROUNDS), 15 * (ROUNDS // 3) + 1) + B.p = property(lambda self: -1) + for _ in range(4): + self.assertEqual(loop_property(objs, ROUNDS), 9 * (ROUNDS // 3) + 1) + self.assertEqual(loop_property_callee(objs, ROUNDS), 9 * (ROUNDS // 3) + 1) + + def test_missing_method_on_surprise_receiver(self): + class A: + def m(self): + return 1 + + class B: + pass + + objs = [A()] + for _ in range(4): + self.assertEqual(loop_method(objs, ROUNDS), ROUNDS) + objs.append(B()) + for _ in range(20): + with self.assertRaises(AttributeError) as cm: + loop_method(objs, ROUNDS) + self.assertEqual(cm.exception.name, "m") + objs[1] = 7 + for _ in range(5): + with self.assertRaises(AttributeError): + loop_method(objs, ROUNDS) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_polymorphic_attr_sites.py b/tests/regrtest/test_polymorphic_attr_sites.py new file mode 100644 index 000000000..e217b597e --- /dev/null +++ b/tests/regrtest/test_polymorphic_attr_sites.py @@ -0,0 +1,182 @@ +"""One attribute site read over three or more receiver classes. + +A compiled read remembers two classes' field positions in line and up to +four more in the site's table. A read through the table must give what +the full lookup gives: after a class gains a property or a +`__getattribute__`, after an instance drops the attribute or publishes its +dict, for receivers in a local and receivers left on the stack. +""" + +import unittest + +ROUNDS = 3000 + + +class Base: + kind = "base" + + def __init__(self, n): + self.dest = "d%d" % n + self.nargs = n + + +class A(Base): + pass + + +class B(Base): + def __init__(self, n): + self.extra = None + super().__init__(n) + + +class C(Base): + def __init__(self, n): + self.first = 1 + self.second = 2 + super().__init__(n) + + +class D(Base): + __slots__ = ("slot",) + + def __init__(self, n): + self.slot = n + super().__init__(n) + + +class E(Base): + def __init__(self, n): + super().__init__(n) + self.tail = n + + +def read_local(objs): + total = 0 + names = [] + for o in objs: + total += o.nargs + names.append(o.dest) + return total, names + + +def make(n): + return [A(n), B(n + 1), C(n + 2), D(n + 3), E(n + 4)][n % 5] + + +def read_stack(n): + # The receiver is a temporary: it leaves with the read. + return make(n).nargs + len(make(n).dest) + + +def read_kind(objs): + return [o.kind for o in objs] + + +class PolymorphicSiteTests(unittest.TestCase): + def setUp(self): + self.objs = [A(1), B(2), C(3), D(4), E(5)] + + def test_five_classes_at_one_site(self): + want = (15, ["d1", "d2", "d3", "d4", "d5"]) + for _ in range(ROUNDS): + self.assertEqual(read_local(self.objs), want) + + def test_stack_receivers(self): + for i in range(ROUNDS): + k = i % 5 + self.assertEqual(read_stack(i), i + k + len("d%d" % (i + k))) + + def test_fresh_instances_each_round(self): + for i in range(ROUNDS): + objs = [A(i), B(i), C(i), D(i), E(i)] + total, names = read_local(objs) + self.assertEqual(total, 5 * i) + self.assertEqual(names, ["d%d" % i] * 5) + + def test_instance_drops_the_attribute(self): + for _ in range(ROUNDS): + read_local(self.objs) + del self.objs[2].nargs + with self.assertRaises(AttributeError): + read_local(self.objs) + C.nargs = 100 + try: + self.assertEqual(read_local(self.objs)[0], 1 + 2 + 100 + 4 + 5) + finally: + del C.nargs + self.objs[2].nargs = 3 + self.assertEqual(read_local(self.objs)[0], 15) + + def test_class_gains_a_property(self): + for _ in range(ROUNDS): + read_local(self.objs) + E.nargs = property(lambda self: -1, lambda self, v: None) + try: + for _ in range(50): + self.assertEqual(read_local(self.objs)[0], 1 + 2 + 3 + 4 - 1) + finally: + del E.nargs + for _ in range(50): + self.assertEqual(read_local(self.objs)[0], 15) + + def test_class_gains_getattribute(self): + for _ in range(ROUNDS): + read_local(self.objs) + + def hook(self, name): + if name == "nargs": + return 1000 + return object.__getattribute__(self, name) + + B.__getattribute__ = hook + try: + for _ in range(50): + self.assertEqual(read_local(self.objs)[0], 1 + 1000 + 3 + 4 + 5) + finally: + del B.__getattribute__ + for _ in range(50): + self.assertEqual(read_local(self.objs)[0], 15) + + def test_published_dict(self): + for _ in range(ROUNDS): + read_local(self.objs) + d = vars(self.objs[3]) + d["nargs"] = 40 + self.assertEqual(read_local(self.objs)[0], 1 + 2 + 3 + 40 + 5) + d["zzz"] = 0 + del d["dest"] + with self.assertRaises(AttributeError): + read_local(self.objs) + d["dest"] = "back" + self.assertEqual(read_local(self.objs), (51, ["d1", "d2", "d3", "back", "d5"])) + + def test_class_attribute_under_many_classes(self): + for _ in range(ROUNDS): + self.assertEqual(read_kind(self.objs), ["base"] * 5) + self.objs[1].kind = "mine" + C.kind = "c" + try: + self.assertEqual(read_kind(self.objs), ["base", "mine", "c", "base", "base"]) + finally: + del C.kind + self.assertEqual(read_kind(self.objs), ["base", "mine", "base", "base", "base"]) + + def test_last_reference_leaves_with_the_read(self): + dropped = [] + + class F(Base): + def __del__(self): + dropped.append(self.nargs) + + def one(n): + return F(n).nargs + + for i in range(200): + read_local(self.objs) + self.assertEqual(one(i), i) + self.assertEqual(dropped, list(range(200))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_property_poly_sites.py b/tests/regrtest/test_property_poly_sites.py new file mode 100644 index 000000000..3e65ccdfe --- /dev/null +++ b/tests/regrtest/test_property_poly_sites.py @@ -0,0 +1,84 @@ +"""Property reads at a compiled site that sees several classes. + +`email`'s token tree reads `x.value` and `x.all_defects` over two node +classes, each with a property of its own; one getter runs as an +activation (it joins a generator), the other is a leaf. The site keeps +each class's getter. A class whose property changes, a subclass that +replaces the property with a plain attribute, and a getter that raises +keep CPython's behavior. Items are heap objects. Run it past the compile +threshold. +""" + + +class Leaf(str): + def __new__(cls, value): + self = super().__new__(cls, value) + self.defects = [] + return self + + @property + def value(self): + return str(self) + + @property + def all_defects(self): + return list(self.defects) + + +class Node(list): + def __init__(self, *args): + super().__init__(*args) + self.defects = [object()] + + @property + def value(self): + return "".join(x.value for x in self if x.value) + + @property + def all_defects(self): + return sum((x.all_defects for x in self), self.defects) + + +class Plain(Leaf): + value = "plain" + + +class Raises(Leaf): + @property + def value(self): + raise AttributeError("no value") + + +def values(xs): + return [x.value for x in xs] + + +def tree(): + return Node([Node([Leaf("a"), Leaf("b")]), Leaf("c"), Node([Node([Leaf("d")])])]) + + +class Swap: + @property + def value(self): + return 1 + + +for i in range(3000): + t = tree() + assert t.value == "abcd" + assert len(t.all_defects) == 4 + assert values([Leaf("x"), Node([Leaf("y")]), Plain("z")]) == ["x", "y", "plain"] + try: + values([Leaf("x"), Raises("r")]) + except AttributeError as e: + assert str(e) == "no value" + else: + raise AssertionError("no raise") + s = Swap() + assert values([s, Leaf("q")]) == [i % 2 + 1 if i > 1500 else 1, "q"] + if i == 1500: + Swap.value = property(lambda self: 2) + if i == 1501: + Swap.value = property(lambda self: 1) + if i > 1501: + Swap.value = property(lambda self, i=i: (i + 1) % 2 + 1) diff --git a/tests/regrtest/test_published_dict_reads.py b/tests/regrtest/test_published_dict_reads.py new file mode 100644 index 000000000..66cf81156 --- /dev/null +++ b/tests/regrtest/test_published_dict_reads.py @@ -0,0 +1,54 @@ +"""Attribute reads of instances whose `__dict__` was published. + +`copy.copy`, `pickle` and `vars()` publish an instance's dictionary. +Compiled code then reads an attribute through the position the site last +found the name at. That position has to follow a key deleted and added +back, a class that gains a data descriptor for the name, and a dict +replaced through `__dict__`. Run it past the compile threshold. +""" + +import copy + + +class P: + def __init__(self): + self.a = 1 + self.b = 2 + + +def read(o): + return o.a + o.b + + +q = copy.copy(P()) +r = P() +vars(r) +for _ in range(3000): + assert read(q) == 3 + assert read(r) == 3 + +del r.a +r.c = 5 +r.a = 10 +for _ in range(100): + assert read(r) == 12, read(r) + +r.__dict__ = {"b": 7, "a": 1} +for _ in range(100): + assert read(r) == 8, read(r) + +P.a = property(lambda self: 100) +for _ in range(100): + assert read(r) == 107, read(r) + assert read(q) == 102, read(q) +del P.a +for _ in range(100): + assert read(q) == 3, read(q) + +del q.b +try: + read(q) +except AttributeError: + pass +else: + raise AssertionError("no AttributeError") diff --git a/tests/regrtest/test_pure_builtin_constructors.py b/tests/regrtest/test_pure_builtin_constructors.py new file mode 100644 index 000000000..f6b00c98c --- /dev/null +++ b/tests/regrtest/test_pure_builtin_constructors.py @@ -0,0 +1,77 @@ +"""Builtin types whose calls build the object directly. + +`object()`, `threading.Lock()`, `threading.RLock()`, `io.BytesIO()`, +`io.StringIO()`, `complex()` of plain numbers and `memoryview()` of +`bytes` or a `bytearray` skip the generic constructor when the call has nothing +for it to do; each object is new and works, arguments the shortcut +doesn't take (or rejects) behave as before, and subclasses construct as +they did. Run it past the compile threshold. +""" + +import _thread +import io +import threading +import warnings + + +class Sub: + pass + + +def run(n): + prev = None + for i in range(n): + o = object() + assert type(o) is object and o is not prev and not hasattr(o, "__dict__") + prev = o + lk = threading.Lock() + assert type(lk) is _thread.LockType and not lk.locked() + with lk: + assert lk.locked() and not lk.acquire(False) + assert lk.acquire(timeout=0.01) + lk.release() + rl = threading.RLock() + with rl: + with rl: + assert rl._is_owned() + assert not rl._is_owned() + assert type(Sub()) is Sub + c = complex(i, -0.0) + assert c.real == i and str(c.imag) == "-0.0" and complex() == 0j + assert complex(True) == 1 and complex(1.5, 2) == 1.5 + 2j + assert complex("1+2j") == 1 + 2j and complex(1 + 1j) == 1 + 1j + ba = bytearray(b"xy") + mv = memoryview(ba) + assert mv.obj is ba and bytes(mv) == b"xy" + try: + ba.append(1) + except BufferError: + pass + else: + raise AssertionError("resized an exported bytearray") + mv.release() + ba.append(1) + assert memoryview(b"ab")[1] == 98 + try: + object(1) + except TypeError: + pass + else: + raise AssertionError("object() took an argument") + try: + _thread.LockType(1) + except TypeError: + pass + else: + raise AssertionError("lock() took an argument") + + +run(3000) +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + try: + threading.RLock(1) + except TypeError: + pass +assert any(issubclass(w.category, DeprecationWarning) for w in caught), caught +print("ok") diff --git a/tests/regrtest/test_python_classmethod_sites.py b/tests/regrtest/test_python_classmethod_sites.py new file mode 100644 index 000000000..3a1c1520a --- /dev/null +++ b/tests/regrtest/test_python_classmethod_sites.py @@ -0,0 +1,116 @@ +"""`Class.method(...)` of a Python class method, read off the class at a +site that remembers the class's entry, in loops short enough to stay +interpreted: inheritance, the method replaced on the class or a base, +other descriptors, metaclasses, and a changed MRO.""" + +import unittest + + +def call_m(cls, n): + out = [] + for i in range(n): + out.append(cls.m(i)) + return out + + +class PythonClassMethodSites(unittest.TestCase): + def test_own_and_inherited(self): + class A: + @classmethod + def m(cls, x): + return (cls.__name__, x) + + class B(A): + pass + + self.assertEqual(call_m(A, 300)[-1], ("A", 299)) + self.assertEqual(call_m(B, 300)[-1], ("B", 299)) + got = [call_m(c, 1)[0] for c in (A, B, A, B)] + self.assertEqual(got, [("A", 0), ("B", 0), ("A", 0), ("B", 0)]) + + def test_replaced_on_class_and_base(self): + class A: + @classmethod + def m(cls, x): + return ("old", cls.__name__) + + class B(A): + pass + + def run(cls): + out = [] + for i in range(300): + if i == 100: + A.m = classmethod(lambda cls, x: ("new", cls.__name__)) + elif i == 200: + B.m = staticmethod(lambda x: ("static", x)) + out.append(cls.m(i)) + return out + + got = run(B) + self.assertEqual(got[99], ("old", "B")) + self.assertEqual(got[100], ("new", "B")) + self.assertEqual(got[200], ("static", 200)) + del B.m + self.assertEqual(call_m(B, 1), [("new", "B")]) + A.m = 5 + with self.assertRaises(TypeError): + call_m(B, 1) + + def test_classmethod_over_other_callables(self): + class A: + m = classmethod(len) + + class B: + def __init__(self, x): + self.x = x + + m = classmethod(lambda cls, x: cls(x)) + + for _ in range(300): + self.assertEqual(B.m(3).x, 3) + with self.assertRaises(TypeError): + A.m(1) + + def test_metaclass_getattribute(self): + class Meta(type): + def __getattribute__(cls, name): + if name == "m": + return lambda x: ("meta", x) + return super().__getattribute__(name) + + class A(metaclass=Meta): + @classmethod + def m(cls, x): + return ("class", x) + + class B: + @classmethod + def m(cls, x): + return ("class", x) + + for i in range(300): + self.assertEqual(A.m(i), ("meta", i)) + self.assertEqual(B.m(i), ("class", i)) + + def test_mro_changed(self): + class A: + @classmethod + def m(cls, x): + return "A" + + class C: + @classmethod + def m(cls, x): + return "C" + + class B(A): + pass + + self.assertEqual(call_m(B, 300)[-1], "A") + B.__bases__ = (C,) + self.assertEqual(call_m(B, 1), ["C"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_python_hash_keys_and_minmax_keys.py b/tests/regrtest/test_python_hash_keys_and_minmax_keys.py new file mode 100644 index 000000000..bfc1f1ddf --- /dev/null +++ b/tests/regrtest/test_python_hash_keys_and_minmax_keys.py @@ -0,0 +1,140 @@ +"""Keys whose `__hash__` is Python code, and `min`/`max` with getter keys. + +Compiled code stores an `Enum` member or a frozen dataclass into a dict or +set (`d[k] = v`, `{k: v for ...}`, `{k for ...}`) with the hash its +`__hash__` computes, matching an entry by identity; an equal but distinct +key, a `__hash__` with side effects, and one that raises behave as before. +`min`/`max` evaluate `attrgetter`/`itemgetter` keys in place; errors from +keys and comparisons propagate as before. +""" + +import dataclasses +import enum +import operator +import unittest + +N = 3000 + + +class Color(enum.Enum): + RED = 1 + GREEN = 2 + BLUE = 3 + + +@dataclasses.dataclass(frozen=True) +class Pt: + x: int + y: int + + +class Counted: + calls = 0 + + def __init__(self, v): + self.v = v + + def __hash__(self): + Counted.calls += 1 + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, Counted) and other.v == self.v + + +class BadHash: + def __hash__(self): + raise RuntimeError("no hash") + + +class Obj: + def __init__(self, x): + self.x = x + + +class PythonHashKeyTests(unittest.TestCase): + def test_enum_keys(self): + colors = list(Color) + for i in range(N): + d = {c: c.value for c in colors} + s = {c for c in colors} + x = {} + x[colors[i % 3]] = i + x[colors[i % 3]] = i + 1 + self.assertEqual(d, {Color.RED: 1, Color.GREEN: 2, Color.BLUE: 3}) + self.assertEqual(s, set(colors)) + self.assertEqual(x, {colors[(N - 1) % 3]: N}) + + def test_equal_distinct_keys(self): + for i in range(N): + d = {} + d[Pt(1, 2)] = "a" + d[Pt(1, 2)] = "b" + m = {Pt(i % 2, 0): i for _ in range(3)} + s = {Pt(1, 1) for _ in range(3)} + self.assertEqual(d, {Pt(1, 2): "b"}) + self.assertEqual(len(d), 1) + self.assertEqual(len(m), 1) + self.assertEqual(s, {Pt(1, 1)}) + + def test_counted_hash(self): + Counted.calls = 0 + keys = [Counted(i) for i in range(10)] + for _ in range(100): + d = {k: 1 for k in keys} + self.assertEqual(len(d), 10) + self.assertEqual(Counted.calls, 1000) + Counted.calls = 0 + x = {} + for k in keys: + x[k] = 0 + self.assertEqual(Counted.calls, 10) + + def test_raising_hash(self): + b = BadHash() + for _ in range(200): + with self.assertRaises(RuntimeError): + {b: 1} + with self.assertRaises(RuntimeError): + {b for _ in range(1)} + d = {} + with self.assertRaises(RuntimeError): + d[b] = 1 + self.assertEqual(d, {}) + + +class MinMaxKeyTests(unittest.TestCase): + def test_getter_keys(self): + objs = [Obj(v) for v in (3, 9, 1, 9, 4)] + pairs = [(i, -i) for i in range(10)] + ag = operator.attrgetter("x") + ig = operator.itemgetter(1) + for _ in range(N): + r = (max(objs, key=ag), min(objs, key=ag), max(pairs, key=ig), min(pairs, key=ig)) + self.assertIs(r[0], objs[1]) + self.assertIs(r[1], objs[2]) + self.assertEqual(r[2:], ((0, 0), (9, -9))) + + def test_key_errors(self): + ag = operator.attrgetter("missing") + for _ in range(200): + with self.assertRaises(AttributeError): + max([Obj(1), Obj(2)], key=ag) + with self.assertRaises(IndexError): + min([(1,), ()], key=operator.itemgetter(0)) + with self.assertRaises(TypeError): + max([Obj(1), Obj("a")], key=operator.attrgetter("x")) + self.assertEqual(max([], key=ag, default="d"), "d") + self.assertEqual(max([Obj(5)], key=operator.attrgetter("x")).x, 5) + with self.assertRaises(AttributeError): + max([Obj(5)], key=ag) + + def test_mixed_and_pure_keys(self): + objs = [Obj(v) for v in range(20)] + for _ in range(N): + r = (max(objs, key=lambda o: -o.x), min(objs, key=lambda o: o.x % 7)) + self.assertEqual((r[0].x, r[1].x), (0, 0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_python_iter_over_native_classes.py b/tests/regrtest/test_python_iter_over_native_classes.py new file mode 100644 index 000000000..a8defe0b1 --- /dev/null +++ b/tests/regrtest/test_python_iter_over_native_classes.py @@ -0,0 +1,104 @@ +"""`for x in obj` in compiled code where `obj`'s class defines `__iter__` in +Python, over classes whose own iteration is native (a deque, an +`OrderedDict` and its views, an array, an `xml.etree` element), and over +plain classes with and without an `__iter__`.""" + +import array +import collections +import unittest +import xml.etree.ElementTree as ET + + +def walk(obj): + out = [] + for x in obj: + out.append(x) + return out + + +class PythonIterOverNativeClasses(unittest.TestCase): + def test_plain_class(self): + class Pair: + def __iter__(self): + return iter((1, 2)) + + class Gen: + def __iter__(self): + yield "a" + yield "b" + + for _ in range(3000): + self.assertEqual(walk(Pair()), [1, 2]) + self.assertEqual(walk(Gen()), ["a", "b"]) + + def test_getitem_only(self): + class Seq: + def __getitem__(self, i): + if i >= 3: + raise IndexError(i) + return i * 10 + + for _ in range(2000): + self.assertEqual(walk(Seq()), [0, 10, 20]) + + def test_native_classes_overridden(self): + class D(collections.deque): + def __iter__(self): + yield "deque override" + + class O(collections.OrderedDict): + def __iter__(self): + yield "odict override" + + class A(array.array): + def __iter__(self): + yield "array override" + + class E(ET.Element): + def __iter__(self): + yield "element override" + + d, o, a, e = D([1, 2]), O(k=1), A("i", [1, 2]), E("t") + e.append(ET.Element("child")) + for _ in range(2000): + self.assertEqual(walk(d), ["deque override"]) + self.assertEqual(walk(o), ["odict override"]) + self.assertEqual(walk(a), ["array override"]) + self.assertEqual(walk(e), ["element override"]) + + def test_native_classes_kept(self): + d = collections.deque([1, 2]) + o = collections.OrderedDict(a=1, b=2) + a = array.array("i", [3, 4]) + e = ET.Element("t") + e.append(ET.Element("c1")) + e.append(ET.Element("c2")) + for _ in range(2000): + self.assertEqual(walk(d), [1, 2]) + self.assertEqual(walk(o), ["a", "b"]) + self.assertEqual(walk(o.items()), [("a", 1), ("b", 2)]) + self.assertEqual(walk(a), [3, 4]) + self.assertEqual([c.tag for c in walk(e)], ["c1", "c2"]) + + def test_iter_assigned_later(self): + class C: + def __getitem__(self, i): + if i >= 2: + raise IndexError(i) + return i + + c = C() + for _ in range(1000): + self.assertEqual(walk(c), [0, 1]) + C.__iter__ = lambda self: iter("xy") + self.assertEqual(walk(c), ["x", "y"]) + del C.__iter__ + self.assertEqual(walk(c), [0, 1]) + d = collections.deque([5]) + collections_deque_iter = collections.deque.__iter__ + self.assertEqual(walk(d), [5]) + self.assertIs(collections.deque.__iter__, collections_deque_iter) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_python_iterator_ends.py b/tests/regrtest/test_python_iterator_ends.py new file mode 100644 index 000000000..d571ffc22 --- /dev/null +++ b/tests/regrtest/test_python_iterator_ends.py @@ -0,0 +1,198 @@ +"""Python iterator classes stepped frameless, and their ends. + +`for` loops, `list()` and `next()` step a plain iterator class's +`__next__` without a frame, and a bare `raise StopIteration` ends the +loop without the exception being built. Stores made before the raise, +other exceptions, `StopIteration` subclasses and values, finalizers, tracing, +and `next()` with and without a default behave as before. +""" + +import gc +import sys +import unittest + +N = 3000 + + +class Bounded: + def __init__(self, n): + self.i = 0 + self.n = n + + def __iter__(self): + return self + + def __next__(self): + i = self.i + if i >= self.n: + raise StopIteration + self.i = i + 1 + return i + + +class Counter: + def __init__(self): + self.i = 0 + + def __iter__(self): + return self + + def __next__(self): + self.i += 1 + return self.i + + +class MarksDone: + def __init__(self, n): + self.i = 0 + self.n = n + self.done = False + + def __iter__(self): + return self + + def __next__(self): + if self.i >= self.n: + self.done = True + raise StopIteration + self.i += 1 + return self.i + + +class MyStop(StopIteration): + pass + + +class SubclassEnd(Bounded): + def __next__(self): + if self.i >= self.n: + raise MyStop + self.i += 1 + return self.i + + +class RaisesKey(Bounded): + def __next__(self): + if self.i >= self.n: + raise KeyError(self.i) + self.i += 1 + return self.i + + +class PythonIteratorEndTests(unittest.TestCase): + def test_for_and_list(self): + total = 0 + for _ in range(N): + for x in Bounded(5): + total += x + self.assertEqual(total, 10 * N) + for _ in range(N): + r = list(Bounded(4)) + self.assertEqual(r, [0, 1, 2, 3]) + b = Bounded(3) + for _ in range(N): + for x in b: + pass + self.assertEqual(b.i, 3) + + def test_next(self): + c = Counter() + for _ in range(N): + v = next(c) + self.assertEqual(v, N) + b = Bounded(0) + for _ in range(N): + self.assertIsNone(next(b, None)) + for _ in range(N): + try: + next(b) + except StopIteration as e: + caught = e + self.assertIsNone(caught.value) + names = [] + tb = caught.__traceback__ + while tb is not None: + names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + self.assertEqual(names, ["test_next", "__next__"]) + + def test_store_before_raise(self): + for _ in range(N): + m = MarksDone(2) + self.assertEqual(list(m), [1, 2]) + self.assertTrue(m.done) + for _ in range(N): + m = MarksDone(1) + for _ in m: + pass + self.assertTrue(m.done) + + def test_other_ends(self): + for _ in range(N): + self.assertEqual(list(SubclassEnd(2)), [1, 2]) + for _ in range(N): + got = [] + with self.assertRaises(KeyError): + for x in RaisesKey(2): + got.append(x) + self.assertEqual(got, [1, 2]) + + def test_value_and_generator(self): + class WithValue(Bounded): + def __next__(self): + if self.i >= self.n: + raise StopIteration(7) + self.i += 1 + return self.i + + for _ in range(N): + try: + next(WithValue(0)) + except StopIteration as e: + self.assertEqual(e.value, 7) + + def gen(): + yield next(Bounded(0)) + + for _ in range(300): + with self.assertRaises(RuntimeError) as cm: + list(gen()) + self.assertIsInstance(cm.exception.__cause__, StopIteration) + + def test_finalizer_at_end(self): + deleted = [] + + class Fin(Bounded): + def __del__(self): + deleted.append(self.n) + + for k in range(N): + for x in Fin(2): + pass + gc.collect() + self.assertEqual(len(deleted), N) + + def test_tracing_sees_raise(self): + b = Bounded(1) + for _ in range(N): + b.i = 0 + list(b) + events = [] + + def tracer(frame, event, arg): + if event == "exception" and frame.f_code.co_name == "__next__": + events.append(arg[0]) + return tracer + + sys.settrace(tracer) + try: + b.i = 0 + r = list(b) + finally: + sys.settrace(None) + self.assertEqual(r, [0]) + self.assertEqual(events, [StopIteration]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_python_iterator_lane.py b/tests/regrtest/test_python_iterator_lane.py new file mode 100644 index 000000000..8a104e9e8 --- /dev/null +++ b/tests/regrtest/test_python_iterator_lane.py @@ -0,0 +1,93 @@ +"""`for x in it` over an iterator class whose `__next__` isn't a leaf. + +The loop calls `__next__` with its activation waiting (no full step); +a `StopIteration` from it, however deep, ends the loop as `FOR_ITER` +ends it, other exceptions propagate with their tracebacks, and the +iterator's own state is what Python code sees. +""" + +import sys +import unittest + +N = 3000 + + +class Lines: + def __init__(self, data): + self.data = list(data) + self.i = 0 + + def __iter__(self): + return self + + def _read(self): + if self.i >= len(self.data): + raise StopIteration + v = self.data[self.i] + self.i += 1 + return v + + def __next__(self): + return self._read().upper() + + +class Deep(Lines): + def __next__(self): + return next(iter(self._read())) + + +class Boom(Lines): + def __next__(self): + if self.i == 2: + raise ValueError("boom") + return self._read() + + +class Framey(Lines): + def __next__(self): + v = self._read() + return (v, sys._getframe(1).f_code.co_name) + + +def collect(it): + out = [] + for x in it: + out.append(x) + return out + + +class PythonIteratorLaneTests(unittest.TestCase): + def test_loops(self): + for _ in range(N): + a = collect(Lines("abc")) + b = collect(Deep(["xy", "z"])) + self.assertEqual(a, ["A", "B", "C"]) + self.assertEqual(b, ["x", "z"]) + + def test_errors(self): + for _ in range(100): + try: + collect(Boom("abcd")) + except ValueError as e: + tb = e.__traceback__ + else: + self.fail("no ValueError") + names = [] + while tb is not None: + names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + self.assertEqual(names[-2:], ["collect", "__next__"]) + + def test_frames_and_resume(self): + for _ in range(N): + r = collect(Framey("ab")) + self.assertEqual(r, [("a", "collect"), ("b", "collect")]) + it = Lines("abcd") + for x in it: + if x == "B": + break + self.assertEqual(collect(it), ["C", "D"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_random_int_methods_native.py b/tests/regrtest/test_random_int_methods_native.py new file mode 100644 index 000000000..35e6970e9 --- /dev/null +++ b/tests/regrtest/test_random_int_methods_native.py @@ -0,0 +1,137 @@ +"""`random.Random`'s `randint`, `randrange`, `choice` and `shuffle` run +natively. + +For the `Random` class itself, with plain int arguments, each draws exactly +as `_randbelow_with_getrandbits` does (the same numbers from the same +state), so seeded streams match CPython's. A subclass, an instance that +overrides `_randbelow` or `getrandbits`, other arguments, every error, and +any call a trace or profile hook could see take the Python methods. +""" + +import random +import unittest + + +def randbelow(r, n): + k = n.bit_length() + x = r.getrandbits(k) + while x >= n: + x = r.getrandbits(k) + return x + + +class RandomIntMethodsTests(unittest.TestCase): + def test_streams_match_the_algorithm(self): + for seed in (0, 1, 12345, 2**40 + 7): + a, b = random.Random(seed), random.Random(seed) + for _ in range(500): + self.assertEqual(a.randint(1, 6), 1 + randbelow(b, 6)) + self.assertEqual(a.randint(-5, 5), -5 + randbelow(b, 11)) + self.assertEqual(a.randint(0, 2**40), randbelow(b, 2**40 + 1)) + self.assertEqual(a.randint(0, 2**62), randbelow(b, 2**62 + 1)) + self.assertEqual(a.randrange(10), randbelow(b, 10)) + self.assertEqual(a.randrange(3, 30), 3 + randbelow(b, 27)) + self.assertEqual(a.randrange(3, 30, 1), 3 + randbelow(b, 27)) + xs = ["p", "q", "r"] + self.assertEqual(a.choice(xs), xs[randbelow(b, 3)]) + self.assertEqual(a.choice("abcde"), "abcde"[randbelow(b, 5)]) + self.assertEqual(a.choice((7, 8)), (7, 8)[randbelow(b, 2)]) + self.assertEqual(a.random(), b.random()) + self.assertEqual(a.getstate(), b.getstate()) + + def test_shuffle_matches_the_algorithm(self): + for seed in (0, 7, 99): + a, b = random.Random(seed), random.Random(seed) + for n in (0, 1, 2, 10, 100): + xs = list(range(n)) + ys = list(range(n)) + a.shuffle(xs) + for i in reversed(range(1, n)): + j = randbelow(b, i + 1) + ys[i], ys[j] = ys[j], ys[i] + self.assertEqual(xs, ys) + self.assertEqual(a.getstate(), b.getstate()) + words = ["a", "b", "c"] + random.shuffle(words) + self.assertEqual(sorted(words), ["a", "b", "c"]) + t = random.Random(1) + arr = bytearray(b"abc") + t.shuffle(arr) + self.assertEqual(sorted(arr), [97, 98, 99]) + with self.assertRaises(TypeError): + t.shuffle((1, 2)) + + def test_uniform_matches(self): + for seed in (0, 3): + a, b = random.Random(seed), random.Random(seed) + for _ in range(300): + self.assertEqual(a.uniform(1.5, 9.25), 1.5 + (9.25 - 1.5) * b.random()) + self.assertEqual(a.uniform(-3, 40), -3 + (40 - -3) * b.random()) + self.assertEqual(a.uniform(10, 2), 10 + (2 - 10) * b.random()) + g = random.Random(1) + g.random = [0.5].pop + self.assertEqual(g.uniform(0, 10), 5.0) + self.assertEqual(random.Random(2).uniform(2**80, 2**80), float(2**80)) + + def test_other_shapes(self): + r = random.Random(3) + self.assertEqual(r.randint(True, 3) in (1, 2, 3), True) + self.assertIn(r.choice("héllo"), "héllo") + self.assertIn(r.randrange(0, 10, 2), range(0, 10, 2)) + self.assertIn(r.randint(2**70, 2**70 + 1), (2**70, 2**70 + 1)) + with self.assertRaises(ValueError): + r.randint(5, 1) + with self.assertRaises(ValueError): + r.randrange(0) + with self.assertRaises(ValueError): + r.randrange(5, 5) + with self.assertRaises(IndexError): + r.choice([]) + with self.assertRaises(TypeError): + r.randint(1.5, 2) + self.assertIn(random.randint(1, 3), (1, 2, 3)) + self.assertIn(random.choice([4, 5]), (4, 5)) + self.assertIn(random.SystemRandom().randint(1, 3), (1, 2, 3)) + + def test_overrides(self): + class Fixed(random.Random): + def _randbelow(self, n): + return 0 + + f = Fixed(1) + self.assertEqual([f.randint(5, 9) for _ in range(5)], [5] * 5) + self.assertEqual(f.choice("xyz"), "x") + g = random.Random(1) + g._randbelow = lambda n: n - 1 + self.assertEqual(g.randint(5, 9), 9) + h = random.Random(1) + h.getrandbits = lambda k: 0 + self.assertEqual(h.randrange(10), 0) + + +class TracedTests(unittest.TestCase): + def test_trace_sees_the_python_methods(self): + import sys + + seen = [] + + def tracer(frame, event, arg): + if event == "call": + seen.append(frame.f_code.co_name) + return None + + r = random.Random(5) + sys.settrace(tracer) + try: + r.randint(1, 4) + r.choice([1, 2]) + r.shuffle([1, 2, 3]) + finally: + sys.settrace(None) + self.assertIn("randint", seen) + self.assertIn("choice", seen) + self.assertIn("shuffle", seen) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_random_shadow_checks.py b/tests/regrtest/test_random_shadow_checks.py new file mode 100644 index 000000000..31fb08552 --- /dev/null +++ b/tests/regrtest/test_random_shadow_checks.py @@ -0,0 +1,41 @@ +"""random.Random's natively served methods from compiled loops while no +instance attribute shadows `_randbelow` or `getrandbits` (now found by +the names' hashes): seeded sequences equal to CPython's, an instance +attribute that shadows getrandbits taking over (and removed again), and +a subclass overriding _randbelow, each matching CPython.""" + +import random +import unittest + + +def draws(n, r): + return [r.randint(1, 100) for i in range(n)] + [r.randrange(7) for i in range(n)] + + +class RandomShadowTests(unittest.TestCase): + def test_seeded(self): + a = draws(300, random.Random(1234)) + b = draws(300, random.Random(1234)) + self.assertEqual(a, b) + self.assertEqual(draws(5, random.Random(42)), [82, 15, 4, 95, 36, 1, 1, 1, 5, 0]) + + def test_instance_shadow(self): + r = random.Random(7) + draws(300, r) + r.getrandbits = lambda k: 0 + self.assertEqual([r.randrange(10) for i in range(300)], [0] * 300) + del r.getrandbits + r.seed(7) + self.assertEqual(draws(50, r), draws(50, random.Random(7))) + + def test_subclass_override(self): + class Fixed(random.Random): + def _randbelow(self, n): + return n - 1 + + r = Fixed(3) + self.assertEqual([r.randrange(10) for i in range(300)], [9] * 300) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_range_down_and_leaf_pow.py b/tests/regrtest/test_range_down_and_leaf_pow.py new file mode 100644 index 000000000..b95450a6c --- /dev/null +++ b/tests/regrtest/test_range_down_and_leaf_pow.py @@ -0,0 +1,44 @@ +"""Loops over descending ranges step in place in both compiled tiers, and +frameless callbacks raise ints to small powers; results match CPython, +overflow and negative exponents included.""" + +import sys +import unittest + + +class RangeDownLeafPow(unittest.TestCase): + def test_descending_ranges(self): + for _ in range(200): + self.assertEqual([i for i in range(10, -1, -1)], list(range(10, -1, -1))) + out = [] + for i in reversed(range(7)): + out.append(i) + self.assertEqual(out, [6, 5, 4, 3, 2, 1, 0]) + s = 0 + for i in range(100, 0, -3): + s += i + self.assertEqual(s, sum(range(100, 0, -3))) + self.assertEqual([i for i in range(0, 5, -1)], []) + self.assertEqual([i for i in range(5, 5, -1)], []) + + def test_extreme_bounds(self): + big = sys.maxsize + for _ in range(50): + self.assertEqual(list(range(big, big - 3, -1)), [big, big - 1, big - 2]) + self.assertEqual(list(range(-big, -big - 3, -1)), [-big, -big - 1, -big - 2]) + self.assertEqual(list(reversed(range(-3, 3, 2))), [1, -1, -3]) + + def test_leaf_pow(self): + xs = list(range(-5, 50)) + for _ in range(200): + self.assertEqual(min(xs, key=lambda x: (x - 25) ** 2), 25) + self.assertEqual(sorted(xs, key=lambda x: x ** 3)[:3], [-5, -4, -3]) + self.assertEqual(list(map(lambda x: x ** 0, [3, 0, -2])), [1, 1, 1]) + self.assertEqual(list(map(lambda x: 2 ** x, [10, 62, 63, 64])), + [1024, 2 ** 62, 2 ** 63, 2 ** 64]) + self.assertEqual(list(map(lambda x: x ** -1, [2, 4])), [0.5, 0.25]) + self.assertEqual(list(map(lambda x: x ** 2.0, [3])), [9.0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_re_compiled_pattern_calls.py b/tests/regrtest/test_re_compiled_pattern_calls.py new file mode 100644 index 000000000..1a62bb088 --- /dev/null +++ b/tests/regrtest/test_re_compiled_pattern_calls.py @@ -0,0 +1,39 @@ +"""`re` module functions called with an already compiled pattern. + +`re.match(pat, s)` and its siblings use the pattern as it is when the +flags are empty (`0`, `False` or `re.NOFLAG`), and raise `ValueError` for +any other flags, as CPython's `_compile` does. Strings and bytes patterns +still go through the cache. +""" + +import re + +SECTCRE = re.compile(r"\[(?P
.+)\]") +WORDS = re.compile(rb"\w+") + + +def run(n): + for _ in range(n): + assert re.match(SECTCRE, "key") is None + m = re.match(SECTCRE, "[sec]") + assert m and m.group("header") == "sec" and m.re is SECTCRE + assert re.search(SECTCRE, "x [a] y").span() == (2, 5) + assert re.fullmatch(SECTCRE, "[a]", re.NOFLAG) + assert re.match(SECTCRE, "[a]", False) + assert re.sub(SECTCRE, "<>", "[a] [b]") == "<>" + assert re.findall(WORDS, b"ab cd") == [b"ab", b"cd"] + assert re.split(re.compile(","), "a,b") == ["a", "b"] + assert [m.group() for m in re.finditer(WORDS, b"x y")] == [b"x", b"y"] + assert re.compile(SECTCRE) is SECTCRE + assert re.match(r"\d+", "12").group() == "12" + for flags in (re.I, 2, True): + try: + re.match(SECTCRE, "[a]", flags) + except ValueError: + pass + else: + raise AssertionError(flags) + + +run(2000) +print("ok") diff --git a/tests/regrtest/test_re_literal_prefix_search.py b/tests/regrtest/test_re_literal_prefix_search.py new file mode 100644 index 000000000..c6418211a --- /dev/null +++ b/tests/regrtest/test_re_literal_prefix_search.py @@ -0,0 +1,69 @@ +"""`re` searches whose patterns start with a literal find every match. + +One-character and longer literal prefixes, prefixes that overlap +themselves (`aab` in `aaab`), matches at the start, the very end and past +`pos`/`endpos` bounds, misses, prefixes followed by more pattern, case +folding, and subjects that are bytes, bytearrays, memoryviews, ASCII text +and non-ASCII text all give what a plain scan of every position gives. +""" + +import re +import unittest + + +def scan(pattern, subject, pos=0, endpos=None): + """The first match by trying `match` at every position.""" + endpos = len(subject) if endpos is None else endpos + for i in range(pos, endpos + 1): + m = pattern.match(subject, i, endpos) + if m: + return m.span() + return None + + +PATTERNS = [b"x", b"ab", b"aab", b"abab", b"\xfe\xff\x00\x01", b"a.c", b"ab+c", b"a[bc]d", b"zz", b"\x00"] +SUBJECTS = [b"", b"a", b"aaab", b"xxabababcab", b"cabcabd", b"abbbbc acd abd", + bytes(range(256)) * 3, b"a" * 50 + b"ab", b"zzz", b"\x00\x00z"] + + +class PrefixSearchTests(unittest.TestCase): + def test_bytes_like(self): + for raw in PATTERNS: + p = re.compile(raw) + for subj in SUBJECTS: + for kind in (bytes, bytearray, memoryview): + s = kind(subj) + m = p.search(s) + self.assertEqual(m.span() if m else None, scan(p, bytes(subj)), (raw, subj, kind)) + for pos, endpos in ((1, None), (2, len(subj) - 1), (0, 3), (len(subj), None)): + if endpos is not None and endpos < 0: + continue + m = p.search(s, pos, endpos if endpos is not None else len(subj)) + want = scan(p, bytes(subj), pos, endpos) + self.assertEqual(m.span() if m else None, want, (raw, subj, pos, endpos)) + + def test_text(self): + for raw in ("x", "ab", "aab", "é", "éa", "a.c", "日本"): + p = re.compile(raw) + for subj in ("", "aaab", "xxabababcab", "caébéa", "cabcabd", "日本語の日本", "a" * 40 + "ab"): + m = p.search(subj) + self.assertEqual(m.span() if m else None, scan(p, subj), (raw, subj)) + + def test_findall_and_ignorecase(self): + self.assertEqual(re.findall(b"ab", b"abxabyab"), [b"ab"] * 3) + self.assertEqual(re.findall(b"aa", b"aaaaa"), [b"aa", b"aa"]) + self.assertEqual([m.span() for m in re.finditer(b"aab", b"aaabaab")], [(1, 4), (4, 7)]) + self.assertEqual(re.search(b"AB", b"xxab", re.I).span(), (2, 4)) + self.assertEqual(re.search("Straße", "eine STRASSE", re.I), None) + self.assertEqual(re.sub(b"ab", b"-", bytearray(b"abcab")), b"-c-") + + def test_many(self): + p = re.compile(rb"\xfe\xff\x00\x01") + data = bytearray(bytes(range(256)) * 100) + for i in range(300): + self.assertEqual(p.search(data).span(), (254, 258)) + self.assertEqual(p.search(data, 300).span(), (510, 514)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_re_on_buffers_in_place.py b/tests/regrtest/test_re_on_buffers_in_place.py new file mode 100644 index 000000000..54b2204eb --- /dev/null +++ b/tests/regrtest/test_re_on_buffers_in_place.py @@ -0,0 +1,108 @@ +"""Regular expressions over a `bytearray` or a `memoryview`. + +A bytes pattern matches a `bytearray` or a plain `memoryview` window +where its bytes are, as it matches a `bytes` object: searching a large +buffer costs what the search reads, not a conversion of the whole +buffer. The pieces it returns are `bytes`, and every result equals the +result for the same bytes as a `bytes` object. +""" + +import re +import time +import unittest + +PATTERNS = [rb"a", rb"(a)(b)?", rb"\d+", rb"(?P\w+)@(\w+)", rb"^ab", rb"b$", rb"", rb"(a|b)*", rb"[^a]+", rb"\xfe\xff", rb"(?i)AB", rb"\bab\b"] +SUBJECTS = [b"", b"a", b"ab", b"abab 12 cd 345", b"me@host and you@there", b"xxabxx", b"\xfe\xff\x00\x01" * 3, b"AbaB ab"] + + +def results(pattern, subject): + m = pattern.search(subject) + return ( + None if m is None else (m.group(), m.groups(), m.span(), m.groupdict(), m.lastindex), + None if (m := pattern.match(subject)) is None else (m.group(0), m.span()), + None if (m := pattern.fullmatch(subject)) is None else m.span(), + pattern.findall(subject), + pattern.split(subject), + [m.span() for m in pattern.finditer(subject)], + pattern.sub(b"-", subject), + pattern.subn(b"<\\g<0>>", subject), + pattern.sub(lambda m: b"#", subject), + pattern.findall(subject, 1, 5), + pattern.search(subject, 2) is not None, + ) + + +def views(data): + return { + "bytearray": bytearray(data), + "memoryview": memoryview(data), + "window": memoryview(b"zz" + data + b"zz")[2:-2], + "bytearray window": memoryview(bytearray(b"z" + data))[1:], + } + + +class SameResultsTests(unittest.TestCase): + def test_every_buffer_kind_matches_like_bytes(self): + for raw in PATTERNS: + pattern = re.compile(raw) + for data in SUBJECTS: + want = results(pattern, data) + for name, subject in views(data).items(): + with self.subTest(pattern=raw, data=data, kind=name): + self.assertEqual(results(pattern, subject), want) + + def test_pieces_are_bytes(self): + for name, subject in views(b"key=value; other=thing").items(): + with self.subTest(kind=name): + m = re.search(rb"(\w+)=(\w+)", subject) + self.assertIs(type(m.group()), bytes) + self.assertIs(type(m.group(1)), bytes) + self.assertIs(m.string, subject) + for piece in re.findall(rb"\w+", subject) + re.split(rb"[=;]", subject): + self.assertIs(type(piece), bytes) + self.assertIs(type(re.sub(rb"=", b":", subject)), bytes) + self.assertEqual(re.findall(rb"(\w+)=(\w+)", subject), [(b"key", b"value"), (b"other", b"thing")]) + everything = re.search(rb".*", bytearray(b"abc")) + self.assertEqual(everything.group(), b"abc") + self.assertIs(type(everything.group()), bytes) + + def test_a_buffer_changed_after_the_match(self): + buf = bytearray(b"abc abc") + m = re.search(rb"b(c)", buf) + buf[1] = ord("X") + self.assertEqual(m.span(), (1, 3)) + buf.extend(b" more") + self.assertEqual(re.findall(rb"\w+", buf), [b"aXc", b"abc", b"more"]) + + def test_wrong_kinds(self): + with self.assertRaises(TypeError): + re.search("a", bytearray(b"a")) + with self.assertRaises(TypeError): + re.search("a", memoryview(b"a")) + with self.assertRaises(TypeError): + re.search(b"a", "a") + + +class CostTests(unittest.TestCase): + def test_a_search_costs_what_it_reads(self): + pattern = re.compile(rb"\xfe\xff\x00\x01") + + def best(buf): + t = float("inf") + for _ in range(3): + start = time.perf_counter() + for _ in range(200): + pattern.search(buf) + t = min(t, time.perf_counter() - start) + return t + + small = best(bytearray(range(256)) * 4) + large = best(bytearray(range(256)) * 4000) + # (The match is near the front either way; converting the whole + # buffer per search made the large one a thousand times slower.) + self.assertLess(large, small * 20 + 0.005) + self.assertLess(best(memoryview(bytes(range(256)) * 4000)), small * 20 + 0.005) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_re_pattern_keys.py b/tests/regrtest/test_re_pattern_keys.py new file mode 100644 index 000000000..c8d4cbdb0 --- /dev/null +++ b/tests/regrtest/test_re_pattern_keys.py @@ -0,0 +1,41 @@ +"""Compiled patterns as dict keys. + +`re._compile` probes its cache with `(type(p), p, flags)` for every +compiled pattern a module function is handed, and catches the +`KeyError`. A pattern hashes natively, and a miss raises in place. +Equal patterns that aren't the same object still find each other, and a +replaced `__hash__` is called. Run it past the compile threshold. +""" + +import re + +p = re.compile(r"\[(?P.+)\]") +q = re.compile(r"\[(?P.+)\]") +b = re.compile(rb"x+", re.I) +assert hash(p) == hash(q) and p == q + + +def probe(d, pat): + try: + return d[type(pat), pat, 0] + except KeyError as e: + assert e.args[0][1] is pat + return None + + +d = {(type(p), p, 0): 1} +for _ in range(3000): + assert probe(d, q) == 1 + assert probe(d, p) == 1 + assert probe(d, b) is None + assert probe({}, p) is None + assert re.match(p, "[x]").group("h") == "x" + assert re.sub(b, b"-", b"aXXb") == b"a-b" + +try: + re.Pattern.__hash__ = lambda self: 7 +except TypeError: + pass +else: + assert hash(p) == 7 + assert probe({(re.Pattern, p, 0): 2}, p) == 2 diff --git a/tests/regrtest/test_reference_counts_with_threads.py b/tests/regrtest/test_reference_counts_with_threads.py new file mode 100644 index 000000000..117183a19 --- /dev/null +++ b/tests/regrtest/test_reference_counts_with_threads.py @@ -0,0 +1,366 @@ +"""Reference counts stay exact while several threads run. + +With the GIL on, a thread's reference-count updates are plain (not +atomic) as long as every thread that touches an object holds the GIL: +workers take it before their first touch of an object and keep it through +their thread-local destructors, and a blocking call touches no object +while it has the GIL released. A count that lost an update would free an +object early (a crash, or another object at its address) or never; the +tests below make threads share objects through every kind of hand-off and +check each count and each object's death afterwards. + +The same checks run again with `WEAVEPY_ATOMIC_COUNTS=1`, which makes +counts atomic as soon as a second thread exists. +""" + +import gc +import os +import queue +import socket +import subprocess +import sys +import tempfile +import threading +import time +import unittest +import weakref + +THREADS = 6 +ROUNDS = 3000 + + +class Token: + """A heap object with a weak reference slot and a visible death.""" + + died = 0 + lock = threading.Lock() + + def __init__(self, tag): + self.tag = tag + + def __del__(self): + with Token.lock: + Token.died += 1 + + +def fast_switches(fn): + def run(self): + before = sys.getswitchinterval() + sys.setswitchinterval(1e-5) + try: + fn(self) + finally: + sys.setswitchinterval(before) + + run.__name__ = fn.__name__ + return run + + +def run_threads(target, n=THREADS, args=()): + errors = [] + + def body(k): + try: + target(k, *args) + except BaseException as e: # reported by the starting thread + errors.append(repr(e)) + + ts = [threading.Thread(target=body, args=(k,)) for k in range(n)] + for t in ts: + t.start() + for t in ts: + t.join() + return errors + + +class SharedCountTests(unittest.TestCase): + @fast_switches + def test_shared_objects_keep_their_counts(self): + shared = [Token(i) for i in range(8)] + text = "shared text %d" % len(shared) + big = 10**30 + tup = (text, big, shared[0]) + before = [sys.getrefcount(o) for o in shared] + before_text = sys.getrefcount(text) + before_big = sys.getrefcount(big) + before_tup = sys.getrefcount(tup) + + def churn(k): + mine = [] + d = {} + for i in range(ROUNDS): + o = shared[(i + k) % len(shared)] + mine.append(o) + mine.append(text) + mine.append(big) + d[i % 7] = (o, tup, text) + a, b, c = tup + if len(mine) > 30: + del mine[:15] + x = [o, a, b, c][i % 4] + del x + del mine, d + + self.assertEqual(run_threads(churn), []) + self.assertEqual([sys.getrefcount(o) for o in shared], before) + self.assertEqual(sys.getrefcount(text), before_text) + self.assertEqual(sys.getrefcount(big), before_big) + self.assertEqual(sys.getrefcount(tup), before_tup) + + @fast_switches + def test_objects_die_exactly_once(self): + with Token.lock: + start = Token.died + made = [0] * THREADS + refs = [[] for _ in range(THREADS)] + + def make_and_drop(k): + keep = [] + for i in range(ROUNDS): + t = Token((k, i)) + made[k] += 1 + if i % 50 == 0: + refs[k].append(weakref.ref(t)) + keep.append(t) + if len(keep) > 20: + keep.pop(0) + del t + del keep + + self.assertEqual(run_threads(make_and_drop), []) + gc.collect() + with Token.lock: + died = Token.died - start + self.assertEqual(died, sum(made)) + self.assertTrue(all(r() is None for rs in refs for r in rs)) + + @fast_switches + def test_queue_hand_off(self): + q = queue.Queue(maxsize=16) + out = queue.SimpleQueue() + n_items = 2000 + payload = Token("payload") + before = sys.getrefcount(payload) + + def producer(k): + for i in range(n_items): + q.put((k, i, payload, [payload, "item %d" % i])) + + def consumer(k): + total = 0 + while True: + item = q.get() + if item is None: + break + total += item[1] + self.assertIs(item[2], payload) + self.assertIs(item[3][0], payload) + out.put(total) + + consumers = [threading.Thread(target=consumer, args=(k,)) for k in range(3)] + for t in consumers: + t.start() + self.assertEqual(run_threads(producer, n=3), []) + for _ in consumers: + q.put(None) + for t in consumers: + t.join() + total = sum(out.get() for _ in consumers) + self.assertEqual(total, 3 * sum(range(n_items))) + self.assertEqual(sys.getrefcount(payload), before) + + @fast_switches + def test_blocking_calls_beside_churn(self): + shared = [Token(i) for i in range(4)] + before = [sys.getrefcount(o) for o in shared] + stop = threading.Event() + lock = threading.Lock() + cond = threading.Condition() + a, b = socket.socketpair() + tmp = tempfile.NamedTemporaryFile(delete=False) + tmp.close() + + def churn(k): + mine = [] + while not stop.is_set(): + mine.extend(shared) + if len(mine) > 40: + del mine[:20] + + def blockers(k): + for i in range(150): + o = shared[i % 4] + with lock: + held = [o, o] + time.sleep(0) + time.sleep(0.0002) + if k == 0: + a.sendall(b"x" * 64) + self.assertEqual(len(b.recv(64)), 64) + with open(tmp.name, "ab") as f: + f.write(b"line %d\n" % i) + with cond: + cond.wait(0.0001) + cond.notify_all() + with open(tmp.name, "rb") as f: + f.read() + del held, o + + churners = [threading.Thread(target=churn, args=(k,)) for k in range(2)] + for t in churners: + t.start() + try: + self.assertEqual(run_threads(blockers, n=4), []) + finally: + stop.set() + for t in churners: + t.join() + a.close() + b.close() + os.unlink(tmp.name) + self.assertEqual([sys.getrefcount(o) for o in shared], before) + + @fast_switches + def test_thread_locals_and_results_released_at_exit(self): + with Token.lock: + start = Token.died + local = threading.local() + cache_hits = [] + + def body(k): + local.token = Token(("local", k)) + local.items = [Token(("item", k, i)) for i in range(5)] + # Caches a thread keeps for itself (formats, interned names, + # attribute memos) are filled here and released at its exit. + import struct + + cache_hits.append(struct.pack("<%dh" % (k + 1), *range(k + 1))) + cache_hits.append(getattr(Token, "died") >= 0) + cache_hits.append(sys.intern("name_%d" % k)) + + for wave in range(20): + self.assertEqual(run_threads(body, n=4), []) + gc.collect() + with Token.lock: + died = Token.died - start + self.assertEqual(died, 20 * 4 * 6) + + @fast_switches + def test_threads_started_by_threads(self): + shared = Token("deep") + before = sys.getrefcount(shared) + results = [] + + def leaf(depth, bag): + bag.append(shared) + results.append(depth) + + def node(depth): + bag = [shared] + kids = [ + threading.Thread(target=node if depth < 3 else leaf, args=(depth + 1,) if depth < 3 else (depth + 1, bag)) + for _ in range(2) + ] + for t in kids: + t.start() + for t in kids: + t.join() + del bag + + top = threading.Thread(target=node, args=(0,)) + top.start() + top.join() + self.assertEqual(len(results), 16) + self.assertEqual(sys.getrefcount(shared), before) + + def test_counts_after_the_threads_are_gone(self): + # Once every worker is joined the program runs as it did before + # any started; a fresh round of threads starts from there again. + shared = Token("again") + before = sys.getrefcount(shared) + for _ in range(5): + + def body(k): + xs = [shared] * 100 + del xs + + self.assertEqual(run_threads(body, n=3), []) + ys = [shared for _ in range(1000)] + self.assertEqual(sys.getrefcount(shared), before + 1000) + del ys + self.assertEqual(sys.getrefcount(shared), before) + + +DAEMON_AT_EXIT = r""" +import sys, threading, time +shared = [object() for _ in range(50)] +started = threading.Event() +def spin(): + mine = [] + started.set() + while True: + mine.extend(shared) + if len(mine) > 500: + del mine[:250] +def sleeper(): + while True: + time.sleep(0.001) +for _ in range(3): + threading.Thread(target=spin, daemon=True).start() +threading.Thread(target=sleeper, daemon=True).start() +started.wait() +time.sleep(0.05) +class Loud: + def __del__(self): + sys.stdout.write("finalized\n") +keep = Loud() +if "raise" in sys.argv: + raise SystemExit("exit message %d" % len(shared)) +print("main done", len(shared)) +""" + + +class ExitTests(unittest.TestCase): + """The main thread's last steps beside threads that are still running.""" + + def run_child(self, *argv, env=None): + return subprocess.run( + [sys.executable, "-c", DAEMON_AT_EXIT, *argv], + capture_output=True, + text=True, + timeout=120, + env=env, + ) + + def test_exit_with_daemon_threads_running(self): + for _ in range(5): + r = self.run_child() + self.assertEqual(r.returncode, 0, r.stderr[-2000:]) + self.assertIn("main done 50", r.stdout) + + def test_system_exit_with_daemon_threads_running(self): + for _ in range(5): + r = self.run_child("raise") + self.assertEqual(r.returncode, 1, r.stderr[-2000:]) + self.assertIn("exit message 50", r.stderr) + + +class AtomicCountTests(unittest.TestCase): + """The same checks with counts atomic once a second thread exists.""" + + @unittest.skipIf(os.environ.get("WEAVEPY_ATOMIC_COUNTS"), "the atomic run itself") + def test_with_atomic_counts(self): + env = dict(os.environ, WEAVEPY_ATOMIC_COUNTS="1") + r = subprocess.run( + [sys.executable, __file__, "SharedCountTests", "ExitTests"], + env=env, + capture_output=True, + text=True, + timeout=600, + ) + self.assertEqual(r.returncode, 0, r.stderr[-3000:]) + self.assertIn("OK", r.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_reflected_number_ops.py b/tests/regrtest/test_reflected_number_ops.py new file mode 100644 index 000000000..079894b8c --- /dev/null +++ b/tests/regrtest/test_reflected_number_ops.py @@ -0,0 +1,139 @@ +"""Compiled `n obj` of a plain number (`int`, `float`, `bool`) and an +instance whose class's reflected method (`__radd__`, `__rmul__`, ...) is +a Python function calls it directly as `method(obj, n)`; the results and +the operand order, every operator, augmented forms, `NotImplemented` +(the operator's `TypeError`, its operands in written order), a missing +reflected method, raises, builtin subclasses, `**`, sites mixing numbers +and instances, and methods replaced later match the general operator.""" + +import unittest + + +class V: + def __init__(self, x): + self.x = x + + def __radd__(self, o): + return ("radd", o, self.x) + + def __rsub__(self, o): + return ("rsub", o, self.x) + + def __rmul__(self, o): + return V(o * self.x) + + def __rtruediv__(self, o): + return o / self.x + + def __rfloordiv__(self, o): + return o // self.x + + def __rmod__(self, o): + return o % self.x + + def __rlshift__(self, o): + return o << self.x + + def __rrshift__(self, o): + return o >> self.x + + def __rand__(self, o): + return o & self.x + + def __ror__(self, o): + return o | self.x + + def __rxor__(self, o): + return o ^ self.x + + def __rmatmul__(self, o): + return "rmatmul" + + def __rpow__(self, o): + return "rpow" + + +class NI: + def __radd__(self, o): + return NotImplemented + + +class Boom: + def __rmul__(self, o): + raise KeyError("rmul") + + +class Plain: + pass + + +class MyInt(int): + def __radd__(self, o): + return "myint" + + +class ReflectedNumberOps(unittest.TestCase): + def test_every_operator(self): + v = V(3) + out = [] + for i in range(2000): + out.append(( + i + v, 2.5 - v, (2 * v).x, 12 / v, 13 // v, 14 % v, 1 << v, + 64 >> v, 7 & v, 4 | v, 6 ^ v, 5 @ v, 2 ** v, True + v, + )) + self.assertEqual(out[7], ( + ("radd", 7, 3), ("rsub", 2.5, 3), 6, 4.0, 4, 2, 8, 8, 3, 7, 5, + "rmatmul", "rpow", ("radd", True, 3), + )) + + def test_augmented_and_mixed(self): + v = V(2) + acc = [] + for i in range(2000): + t = i + t += v + acc.append(t) + self.assertEqual(acc[5], ("radd", 5, 2)) + mixed = [V(1), 2, 2.5, V(4)] + res = [] + for i in range(1000): + for m in mixed: + r = 10 * m + res.append(r.x if isinstance(r, V) else r) + self.assertEqual(res[:4], [10, 20, 25.0, 40]) + + def test_errors(self): + for i in range(1000): + with self.assertRaises(TypeError) as cm: + 1 + NI() + with self.assertRaises(TypeError) as pm: + 1 + Plain() + with self.assertRaises(KeyError): + 3 * Boom() + with self.assertRaises(TypeError) as am: + x = 1 + x += NI() + self.assertEqual(str(cm.exception), "unsupported operand type(s) for +: 'int' and 'NI'") + self.assertEqual(str(pm.exception), "unsupported operand type(s) for +: 'int' and 'Plain'") + self.assertEqual(str(am.exception), "unsupported operand type(s) for +=: 'int' and 'NI'") + + def test_builtin_subclass_and_replaced(self): + for i in range(1000): + self.assertEqual(1 + MyInt(2), "myint") + + class K: + def __radd__(self, o): + return "one" + + k = K() + out = [] + for i in range(2000): + out.append(1 + k) + K.__radd__ = lambda self, o: "two" + for i in range(2000): + out.append(1 + k) + self.assertEqual((out.count("one"), out.count("two")), (2000, 2000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_reflected_orderings.py b/tests/regrtest/test_reflected_orderings.py new file mode 100644 index 000000000..4480738e5 --- /dev/null +++ b/tests/regrtest/test_reflected_orderings.py @@ -0,0 +1,125 @@ +"""Orderings answered by the reflected method. + +A class that defines only `__lt__` answers `a > b` through `b.__lt__(a)` +(`object`'s `__gt__` answers `NotImplemented`); the comparison lanes call +the reflected method directly. The protocol around it must stay CPython's: +`NotImplemented` answers, subclass priority, `TypeError` when nothing +answers, and `min`/`max`/`sorted` over such instances. +""" + +import functools +import unittest + + +class Lt: + def __init__(self, x): + self.x = x + + def __lt__(self, other): + if not isinstance(other, Lt): + return NotImplemented + return self.x < other.x + + +class LtCounting: + calls = 0 + + def __init__(self, x): + self.x = x + + def __lt__(self, other): + LtCounting.calls += 1 + return self.x < other.x + + +class GtOverride(Lt): + def __gt__(self, other): + return "override" + + +class Plain: + pass + + +class ReflectedOrderingTests(unittest.TestCase): + ROUNDS = 4000 + + def test_reflected_results(self): + a, b = Lt(1), Lt(2) + for _ in range(self.ROUNDS): + self.assertFalse(a > b) + self.assertTrue(b > a) + self.assertEqual([a > b, b > a, a < b], [False, True, True]) + with self.assertRaises(TypeError): + a >= b + + def test_each_comparison_calls_once(self): + a, b = LtCounting(1), LtCounting(2) + LtCounting.calls = 0 + for _ in range(self.ROUNDS): + b > a + self.assertEqual(LtCounting.calls, self.ROUNDS) + + def test_min_max_sorted(self): + items = [Lt(i * 7 % 50) for i in range(50)] + for _ in range(200): + self.assertEqual(max(items).x, 49) + self.assertEqual(min(items).x, 0) + self.assertEqual([v.x for v in sorted(items)][:3], [0, 1, 2]) + self.assertEqual(max(items, key=lambda v: -v.x).x, 0) + + def test_not_implemented_and_errors(self): + a = Lt(1) + for _ in range(3): + with self.assertRaises(TypeError): + a > 1 + with self.assertRaises(TypeError): + 1 < a + with self.assertRaises(TypeError): + Plain() > Plain() + with self.assertRaises(TypeError): + Plain() <= Plain() + + def test_subclass_priority(self): + a, s = Lt(1), GtOverride(5) + for _ in range(self.ROUNDS): + self.assertEqual(s > a, "override") + self.assertEqual(a < s, "override") + self.assertTrue(a > Lt(0)) + + def test_class_gains_method(self): + class C: + def __init__(self, x): + self.x = x + + def __lt__(self, other): + return self.x < other.x + + a, b = C(1), C(2) + for _ in range(self.ROUNDS): + self.assertTrue(b > a) + C.__gt__ = lambda self, other: "own" + self.assertEqual(b > a, "own") + del C.__gt__ + self.assertTrue(b > a) + + def test_total_ordering(self): + @functools.total_ordering + class T: + def __init__(self, x): + self.x = x + + def __eq__(self, other): + return self.x == other.x + + def __lt__(self, other): + return self.x < other.x + + for _ in range(self.ROUNDS): + self.assertTrue(T(2) > T(1)) + self.assertTrue(T(2) >= T(2)) + self.assertFalse(T(1) >= T(2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_regex_str_subclass_subjects.py b/tests/regrtest/test_regex_str_subclass_subjects.py new file mode 100644 index 000000000..ce5e5a465 --- /dev/null +++ b/tests/regrtest/test_regex_str_subclass_subjects.py @@ -0,0 +1,68 @@ +"""`findall` and `split` of a str subclass's instance. + +A compiled pattern's `findall` and `split` read a str subclass's instance +(`email`'s header tokens) as its string, in place in compiled code once +warm, and return exact strs, as CPython's slices of it are. A match keeps +the instance as its `string`. +""" + +import re +import unittest + +N = 3000 + + +class T(str): + pass + + +class RegexStrSubclassTests(unittest.TestCase): + def test_findall(self): + p = re.compile(r"[\x00-\x20\x7F]") + g = re.compile(r"(\w)(\w)") + cases = [ + ("hello", [], [("h", "e"), ("l", "l")]), + ("a b\x01c", [" ", "\x01"], []), + ("", [], []), + ("\u00e9 xy", [" "], [("x", "y")]), + ] + for s, want, groups in cases: + t = T(s) + for _ in range(N): + r = p.findall(t) + q = g.findall(t) + self.assertEqual(r, want) + self.assertTrue(all(type(x) is str for x in r)) + self.assertEqual(q, groups) + self.assertTrue(all(type(x) is str for pair in q for x in pair)) + + def test_split(self): + p = re.compile(r"\s+") + k = re.compile(r"(-)") + for _ in range(N): + a = p.split(T("a b c")) + b = p.split(T("whole")) + c = k.split(T("x-y"), 1) + self.assertEqual(a, ["a", "b", "c"]) + self.assertEqual(b, ["whole"]) + self.assertIs(type(b[0]), str) + self.assertEqual(c, ["x", "-", "y"]) + self.assertTrue(all(type(x) is str for x in a + c)) + + def test_match_keeps_instance(self): + t = T("a b") + p = re.compile(r"\s") + for _ in range(N): + m = p.search(t) + self.assertIs(m.string, t) + self.assertIs(type(m.group()), str) + + def test_bytes_pattern_rejects_str_subclass(self): + p = re.compile(rb"x") + for _ in range(100): + with self.assertRaises(TypeError): + p.findall(T("x")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_repr_dunder_direct.py b/tests/regrtest/test_repr_dunder_direct.py new file mode 100644 index 000000000..a4bc4c960 --- /dev/null +++ b/tests/regrtest/test_repr_dunder_direct.py @@ -0,0 +1,200 @@ +"""Compiled `repr(obj)` and f-string `!r` and `!s` conversions call a +class's Python `__repr__` or `__str__` directly; the text, a `str` +subclass result (kept as it is), a non-string result's TypeError, raises +(caught in the frame or past it), recursion guarded by +`reprlib.recursive_repr`, enum members and Decimals (answered natively), +objects without their own `__repr__`, `repr` shadowed, and methods +replaced later match the general call.""" + +import builtins +import enum +import reprlib +import unittest +from decimal import Decimal + + +class K: + def __init__(self, a): + self.a = a + self.calls = 0 + + def fmt(self): + return "K(%r)" % (self.a,) + + def __repr__(self): + self.calls += 1 + return self.fmt() + + +class Leaf: + def __repr__(self): + return "Leaf()" + + +class S(str): + pass + + +class SubResult: + def __repr__(self): + return S("sub") + + +class Bad: + def __repr__(self): + return 5 + + +class Raiser: + def __repr__(self): + raise KeyError("repr") + + +class Node: + def __init__(self): + self.kids = [] + + @reprlib.recursive_repr() + def __repr__(self): + return "Node(%s)" % ", ".join(repr(k) for k in self.kids) + + +class Color(enum.Enum): + RED = 1 + + +class Num(int): + pass + + +class Both: + def __str__(self): + return "str" + + def __repr__(self): + return "repr" + + +class ReprDunderDirect(unittest.TestCase): + def test_text(self): + k = K("x") + for i in range(3000): + self.assertEqual(repr(k), "K('x')") + self.assertEqual(k.calls, 3000) + o = Leaf() + for i in range(3000): + self.assertEqual(repr(o), "Leaf()") + + def test_subclass_result(self): + o = SubResult() + for i in range(1000): + r = repr(o) + self.assertEqual(r, "sub") + self.assertIs(type(r), S) + + def test_bad_result(self): + b = Bad() + for i in range(500): + with self.assertRaises(TypeError) as cm: + repr(b) + self.assertEqual(str(cm.exception), "__repr__ returned non-string (type int)") + + def test_raises(self): + r = Raiser() + n = 0 + for i in range(1000): + try: + repr(r) + except KeyError: + n += 1 + self.assertEqual(n, 1000) + + def show(o): + return repr(o) + "!" + + for i in range(1000): + with self.assertRaises(KeyError): + show(r) + self.assertEqual(show(K(i)), "K(%d)!" % i) + + def test_recursive(self): + a = Node() + b = Node() + a.kids.append(b) + b.kids.append(a) + for i in range(500): + self.assertEqual(repr(a), "Node(Node(...))") + + def test_other_objects(self): + d = Decimal("1.5") + for i in range(1000): + self.assertEqual(repr(i), "%d" % i) + self.assertEqual(repr(S("s")), "'s'") + self.assertEqual(repr(d), "Decimal('1.5')") + self.assertEqual(repr(KeyError(1)), "KeyError(1)") + self.assertTrue(repr(object()).startswith("4}", " sub") + self.assertEqual(k.calls, 4000) + for i in range(500): + with self.assertRaises(TypeError) as cm: + f"{Bad()!r}" + self.assertEqual(str(cm.exception), "__repr__ returned non-string (type int)") + with self.assertRaises(KeyError): + f"{Raiser()!r}" + + def test_native_text(self): + c = Color.RED + d = Decimal("-2.50") + n = Num(7) + for i in range(2000): + self.assertEqual(str(c), "Color.RED") + self.assertEqual(f"{c!s}", "Color.RED") + self.assertEqual(repr(c), "") + self.assertEqual(str(d), "-2.50") + self.assertEqual(repr(d), "Decimal('-2.50')") + self.assertEqual(f"{d!r} {d!s}", "Decimal('-2.50') -2.50") + self.assertEqual(str(n), "7") + self.assertEqual(f"{n!r}", "7") + + def test_repr_shadowed(self): + k = K(1) + real = builtins.repr + try: + for i in range(500): + self.assertEqual(repr(k), "K(1)") + builtins.repr = lambda o: "shadow" + got = repr(k) + finally: + builtins.repr = real + self.assertEqual(got, "shadow") + self.assertEqual(repr(k), "K(1)") + + def test_replaced(self): + class C: + def __repr__(self): + return "a" + + c = C() + out = [] + for i in range(1000): + out.append(repr(c)) + C.__repr__ = lambda self: "b" + for i in range(1000): + out.append(repr(c)) + c.__repr__ = lambda: "instance" + out.append(repr(c)) + del C.__repr__ + self.assertTrue(repr(c).startswith("<")) + self.assertEqual((out.count("a"), out.count("b")), (1000, 1001)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_reversed_list_in_compiled_loops.py b/tests/regrtest/test_reversed_list_in_compiled_loops.py new file mode 100644 index 000000000..bbdfaa145 --- /dev/null +++ b/tests/regrtest/test_reversed_list_in_compiled_loops.py @@ -0,0 +1,181 @@ +"""`for x in reversed(xs)` in a loop that runs long enough to be compiled. + +A reversed list's iterator steps from the last item to the first. It +reads the list as it is at each step, so items appended meanwhile are +never visited, a list that shrinks ends the loop once the cursor is past +its end, and an exhausted iterator stays exhausted. The loop gives the +same results however many times it runs. +""" + +import unittest + +ROUNDS = 400 + + +def total(xs): + t = 0 + for x in reversed(xs): + t += x + return t + + +def totals(xs, rounds): + acc = 0 + for _ in range(rounds): + t = 0 + for x in reversed(xs): + t += x + acc += t + return acc + + +def float_total(xs, rounds): + acc = 0.0 + for _ in range(rounds): + for x in reversed(xs): + acc += x * 0.5 + return acc + + +def joined(xs, rounds): + out = None + for _ in range(rounds): + parts = [] + for x in reversed(xs): + parts.append(x) + out = parts + return out + + +def mixed(xs, rounds): + ints = 0 + others = 0 + for _ in range(rounds): + for x in reversed(xs): + if type(x) is int: + ints += x + else: + others += 1 + return ints, others + + +def first_match(xs, want, rounds): + found = -1 + for _ in range(rounds): + i = len(xs) + for x in reversed(xs): + i -= 1 + if x == want: + found = i + break + return found + + +def shrinking(n, rounds): + seen = [] + for _ in range(rounds): + xs = list(range(n)) + got = 0 + for x in reversed(xs): + got += 1 + if x == n - 2: + del xs[2:] + seen.append(got) + return seen + + +def growing(n, rounds): + last = None + for _ in range(rounds): + xs = list(range(n)) + visited = [] + for x in reversed(xs): + visited.append(x) + if len(xs) < n + 5: + xs.append(100 + x) + last = (visited, len(xs)) + return last + + +class ReversedLoopTests(unittest.TestCase): + def test_sums(self): + xs = list(range(1000)) + self.assertEqual(total(xs), 499500) + self.assertEqual(totals(xs, ROUNDS), 499500 * ROUNDS) + self.assertEqual(totals([], ROUNDS), 0) + self.assertEqual(totals([5], ROUNDS), 5 * ROUNDS) + self.assertEqual(float_total([1.5, 2.5, 4.0], ROUNDS * 10), 4.0 * ROUNDS * 10) + + def test_order(self): + xs = ["a", "b", "c", "d"] + self.assertEqual(joined(xs, ROUNDS * 10), ["d", "c", "b", "a"]) + objs = [object() for _ in range(50)] + out = joined(objs, ROUNDS) + self.assertTrue(all(a is b for a, b in zip(out, objs[::-1]))) + + def test_mixed_items(self): + xs = [1, "a", 2, None, 3.5, 4, (5,), 10**30, True, 7] + rounds = ROUNDS * 5 + self.assertEqual(mixed(xs, rounds), ((1 + 2 + 4 + 7 + 10**30) * rounds, 5 * rounds)) + + def test_break(self): + xs = list(range(200)) + self.assertEqual(first_match(xs, 150, ROUNDS * 5), 150) + self.assertEqual(first_match(xs, -1, ROUNDS), -1) + + def test_a_list_that_shrinks_ends_the_loop(self): + # The cursor is at index n - 3 when the list drops to two items: + # past the end, so the loop is over. + self.assertEqual(shrinking(50, ROUNDS * 5), [2] * (ROUNDS * 5)) + + def test_appended_items_are_not_visited(self): + visited, size = growing(20, ROUNDS * 5) + self.assertEqual(visited, list(range(19, -1, -1))) + self.assertEqual(size, 25) + + def test_an_exhausted_iterator_stays_exhausted(self): + for _ in range(ROUNDS): + xs = [1, 2, 3] + it = reversed(xs) + got = [] + for x in it: + got.append(x) + xs.extend([4, 5, 6]) + for x in it: + got.append(x) + self.assertEqual(got, [3, 2, 1]) + self.assertEqual(list(it), []) + + def test_a_partly_used_iterator(self): + acc = 0 + for _ in range(ROUNDS * 5): + it = reversed([1, 2, 3, 4, 5]) + next(it) + next(it) + for x in it: + acc += x + self.assertEqual(acc, 6 * ROUNDS * 5) + + def test_reversed_of_other_sequences_in_the_same_loop(self): + def run(seqs, rounds): + acc = 0 + for _ in range(rounds): + for seq in seqs: + for x in reversed(seq): + acc += x + return acc + + seqs = [[1, 2, 3], (4, 5, 6), range(7, 10), [10], bytearray(b"\x01\x02"), {1: 0, 2: 0}] + self.assertEqual(run(seqs, ROUNDS * 3), (55 + 3 + 3) * ROUNDS * 3) + + def test_copies_of_a_reversed_list(self): + xs = list(range(300)) + for _ in range(ROUNDS): + self.assertEqual(list(reversed(xs)), xs[::-1]) + self.assertEqual(tuple(reversed(xs)), tuple(xs[::-1])) + self.assertEqual(sum(reversed(xs)), 44850) + self.assertEqual(max(reversed(xs)), 299) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_reversed_loop_end.py b/tests/regrtest/test_reversed_loop_end.py new file mode 100644 index 000000000..025011889 --- /dev/null +++ b/tests/regrtest/test_reversed_loop_end.py @@ -0,0 +1,47 @@ +"""The end of a `for x in reversed(xs)` loop in compiled code. + +An exhausted reversed iterator that only the loop holds leaves the stack +in place; one shared with the loop's body, a list subclass's, and a list +that shrank mid-loop end as in CPython. Run it past the compile +threshold. +""" + + +class L(list): + pass + + +def total(n, xs): + t = 0 + for _ in range(n): + for x in reversed(xs): + t += x + return t + + +def shared(xs): + it = reversed(xs) + out = [] + for x in it: + out.append(x) + out.append(next(it, None)) + return out, list(it) + + +def shrink(xs): + out = [] + for x in reversed(xs): + out.append(x) + if xs: + xs.pop(0) + return out + + +N = 3000 +assert total(N, list(range(10))) == 45 * N +assert total(N, L(range(10))) == 45 * N +assert total(N, []) == 0 +for _ in range(N // 10): + assert shared([1, 2, 3, 4, 5]) == ([5, 4, 3, 2, 1, None], []) + assert shrink([1, 2, 3, 4]) == [4, 4, 4, 4] +print("ok") diff --git a/tests/regrtest/test_reversed_nonsequence.py b/tests/regrtest/test_reversed_nonsequence.py new file mode 100644 index 000000000..e767b970f --- /dev/null +++ b/tests/regrtest/test_reversed_nonsequence.py @@ -0,0 +1,59 @@ +"""`reversed()` of something that isn't a sequence raises `TypeError`. + +CPython's `reversed` wants `__reversed__`, or `__len__` and `__getitem__`. +An iterator, a generator, a set or a native adapter has neither, so it +isn't reversible, even when iterating it would end (and an endless +`itertools.count()` must not be read to the end first). +""" + +import collections +import itertools + +for x in ( + itertools.count(), + itertools.repeat(1), + itertools.cycle([1]), + map(str, [1]), + zip([1]), + enumerate([1]), + filter(None, [1]), + iter([1]), + iter({}.items()), + (i for i in [1]), + {1}, + frozenset(), +): + try: + reversed(x) + except TypeError as e: + assert "not reversible" in str(e), e + else: + raise AssertionError(f"reversed() accepted {type(x).__name__}") + + +class Seq: + def __len__(self): + return 2 + + def __getitem__(self, i): + if i > 1: + raise IndexError + return i * 10 + + +class Rev: + def __reversed__(self): + return iter("zy") + + +class MyList(list): + pass + + +assert list(reversed(Seq())) == [10, 0] +assert list(reversed(Rev())) == ["z", "y"] +assert list(reversed(MyList([1, 2]))) == [2, 1] +assert list(reversed(collections.deque([1, 2]))) == [2, 1] +assert list(reversed({"a": 1, "b": 2})) == ["b", "a"] +assert list(reversed("ab")) == ["b", "a"] +assert list(reversed(range(3))) == [2, 1, 0] diff --git a/tests/regrtest/test_reversed_text_and_accumulate_end.py b/tests/regrtest/test_reversed_text_and_accumulate_end.py new file mode 100644 index 000000000..88f3bf6b1 --- /dev/null +++ b/tests/regrtest/test_reversed_text_and_accumulate_end.py @@ -0,0 +1,162 @@ +"""`reversed()` of text and bytes, builtin type calls, and `accumulate`'s end. + +`reversed(s)` of a `str` or `bytes` builds its iterator without the +general type call; builtin type constructors are reused across calls; and +a function-less `accumulate` or a `pairwise` over a list or tuple ends in +place; and compiled `list(x)`, `tuple(x)`, `set(x)`, `dict(x)` and +`str(x)` calls of adapters go straight to the container lane. Results, +errors, and the iterators' later behavior are unchanged. +""" + +import itertools +import unittest + +N = 3000 + + +class ReversedTextTests(unittest.TestCase): + def test_str_and_bytes(self): + for _ in range(N): + r = "".join(reversed("hello world")) + self.assertEqual(r, "dlrow olleh") + for _ in range(N): + r = list(reversed("héllo✓")) + self.assertEqual(r, ["✓", "o", "l", "l", "é", "h"]) + for _ in range(N): + r = bytes(reversed(b"abc")) + self.assertEqual(r, b"cba") + self.assertEqual(list(reversed("")), []) + it = reversed("ab") + self.assertEqual(it.__length_hint__(), 2) + self.assertEqual(next(it), "b") + self.assertEqual(list(it), ["a"]) + self.assertEqual(list(it), []) + + def test_type_calls(self): + for _ in range(N): + r = (int("ff", 16), str(5), complex(1, 2), bool(3), frozenset([1])) + self.assertEqual(r, (255, "5", 1 + 2j, True, frozenset([1]))) + with self.assertRaises(TypeError): + reversed(3) + with self.assertRaises(TypeError): + reversed("ab", "c") + with self.assertRaises(ValueError): + int("zz", 10) + + def test_accumulate_ends(self): + xs = [5, 1, 4, 2, 3] + for _ in range(N): + total = 0 + for x in itertools.accumulate(xs): + total += x + r = list(itertools.accumulate(tuple(xs))) + self.assertEqual(total, 5 + 6 + 10 + 12 + 15) + self.assertEqual(r, [5, 6, 10, 12, 15]) + a = itertools.accumulate([1, 2]) + self.assertEqual(list(a), [1, 3]) + self.assertEqual(list(a), []) + self.assertRaises(StopIteration, next, a) + b = itertools.accumulate([1.5, 2.5]) + for _ in b: + pass + self.assertEqual(next(b, "end"), "end") + self.assertEqual(list(itertools.accumulate([1, 2], initial=10)), [10, 11, 13]) + self.assertEqual(list(itertools.accumulate([2, 3], lambda a, b: a * b)), [2, 6]) + self.assertEqual(list(itertools.accumulate(["a", "b"])), ["a", "ab"]) + self.assertEqual(list(itertools.accumulate([])), []) + + + def test_pairwise_ends(self): + for _ in range(N): + r = list(itertools.pairwise([1, 2, 3])) + for a, b in itertools.pairwise((1, 2)): + pass + self.assertEqual(r, [(1, 2), (2, 3)]) + p = itertools.pairwise("abc") + self.assertEqual(list(p), [("a", "b"), ("b", "c")]) + self.assertEqual(list(p), []) + self.assertEqual(next(p, "end"), "end") + objs = [object(), object()] + self.assertEqual(list(itertools.pairwise(objs)), [(objs[0], objs[1])]) + self.assertEqual(list(itertools.pairwise([1])), []) + + + def test_combinatorics_and_keywords(self): + L = [1, 2, 3] + for _ in range(N): + r = ( + list(itertools.product(L, repeat=2))[-1], + list(itertools.product("ab", "c")), + list(itertools.permutations(L))[3], + list(itertools.combinations(L, 2)), + list(itertools.combinations_with_replacement("ab", 2)), + list(itertools.accumulate(L, initial=10)), + list(itertools.zip_longest("ab", "c", fillvalue="-")), + list(itertools.islice(itertools.count(start=5, step=2), 3)), + ) + self.assertEqual(r, ( + (3, 3), + [("a", "c"), ("b", "c")], + (2, 3, 1), + [(1, 2), (1, 3), (2, 3)], + [("a", "a"), ("a", "b"), ("b", "b")], + [10, 11, 13, 16], + [("a", "c"), ("b", "-")], + [5, 7, 9], + )) + self.assertEqual(list(itertools.combinations(L, 0)), [()]) + self.assertEqual(list(itertools.product(L, repeat=0)), [()]) + for _ in range(N // 10): + with self.assertRaises(ValueError): + itertools.product(L, repeat=-1) + with self.assertRaises(TypeError): + itertools.product(L, bogus=2) + with self.assertRaises(TypeError): + itertools.accumulate(L, initial=1, extra=2) + + +class ContainerLaneTests(unittest.TestCase): + def test_lane_calls(self): + xs = [3, -1, 2] + for _ in range(N): + r = ( + list(map(abs, xs)), + tuple(map(abs, xs)), + set(map(abs, xs)), + frozenset(map(abs, xs)), + dict(zip("abc", xs)), + str(map), + list(x * 2 for x in xs), + ) + self.assertEqual(r[0], [3, 1, 2]) + self.assertEqual(r[1], (3, 1, 2)) + self.assertEqual(r[2], {1, 2, 3}) + self.assertEqual(r[3], frozenset({1, 2, 3})) + self.assertEqual(r[4], {"a": 3, "b": -1, "c": 2}) + self.assertEqual(r[5], "") + self.assertEqual(r[6], [6, -2, 4]) + + def test_lane_errors(self): + def bad(x): + raise KeyError(x) + + for _ in range(N // 10): + with self.assertRaises(KeyError): + list(map(bad, [1])) + with self.assertRaises(TypeError): + set(map(list, [[1]])) + with self.assertRaises(ValueError): + dict(map(tuple, ["abc"])) + try: + tuple(map(bad, [7])) + except KeyError as e: + tb = e.__traceback__ + names = [] + while tb is not None: + names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + self.assertEqual(names, ["test_lane_errors", "bad"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_round_dunder.py b/tests/regrtest/test_round_dunder.py new file mode 100644 index 000000000..c732f5065 --- /dev/null +++ b/tests/regrtest/test_round_dunder.py @@ -0,0 +1,65 @@ +"""`round(obj)` and `round(obj, n)` of an instance whose class's +`__round__` is a Python function: found through the class's cache and +called with the instance (its `ndigits` default bound when left out); +the results, a method without the parameter (a TypeError for +`round(x, n)`), a raise, an `int` subclass, `Fraction`, and a method +replaced later all match the general call.""" + +import fractions +import unittest + + +class R: + def __init__(self, v): + self.v = v + + def __round__(self, ndigits=None): + return (self.v, ndigits) + + +class NoArg: + def __round__(self): + return "noarg" + + +class Boom: + def __round__(self, nd=None): + raise KeyError("round") + + +class MyInt(int): + def __round__(self, nd=None): + return "myint" + + +class RoundDunder(unittest.TestCase): + def test_values(self): + out = [] + for i in range(2000): + out.append((round(R(i)), round(R(i), 2), round(R(i), None), round(NoArg()), + round(MyInt(3)), round(fractions.Fraction(7, 2)), round(fractions.Fraction(7, 3), 1))) + self.assertEqual(out[5], ((5, None), (5, 2), (5, None), "noarg", "myint", 4, fractions.Fraction(23, 10))) + + def test_errors(self): + for i in range(500): + with self.assertRaises(TypeError): + round(NoArg(), 1) + with self.assertRaises(KeyError): + round(Boom()) + + def test_replaced(self): + class K: + def __round__(self, nd=None): + return 1 + + out = [] + for i in range(1000): + out.append(round(K())) + K.__round__ = lambda self, nd=None: 2 + for i in range(1000): + out.append(round(K())) + self.assertEqual((out.count(1), out.count(2)), (1000, 1000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_scandir_closed_state.py b/tests/regrtest/test_scandir_closed_state.py new file mode 100644 index 000000000..46c1fd1cd --- /dev/null +++ b/tests/regrtest/test_scandir_closed_state.py @@ -0,0 +1,125 @@ +"""A `ScandirIterator`'s closed state, in hot compiled loops. + +Closing an `os.scandir` iterator (`close()`, `__exit__`, exhaustion) +drops its entries and leaves nothing for its finalizer to do, so its death +runs no `__del__`; an iterator dropped open still warns, once. `for` +loops over it keep the iterator itself (its `__iter__` returns it) and +step it in place. +""" + +import gc +import os +import shutil +import tempfile +import unittest +import warnings + +N = 1500 + + +class ScandirClosedStateTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.root = tempfile.mkdtemp() + for name in ("a.txt", "b.txt", "c.py"): + with open(os.path.join(cls.root, name), "w"): + pass + os.mkdir(os.path.join(cls.root, "sub")) + cls.names = sorted(os.listdir(cls.root)) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.root) + + def collect_warnings(self, func): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", ResourceWarning) + result = func() + gc.collect() + return result, [w for w in caught if issubclass(w.category, ResourceWarning)] + + def test_next_after_close(self): + it = os.scandir(self.root) + next(it) + it.close() + with self.assertRaises(StopIteration): + next(it) + self.assertEqual(list(it), []) + it.close() + + def test_iter_returns_itself(self): + with os.scandir(self.root) as it: + self.assertIs(iter(it), it) + + def test_with_loops_do_not_warn(self): + root = self.root + + def run(): + seen = None + for _ in range(N): + with os.scandir(root) as it: + seen = sorted(e.name for e in it) + return seen + + seen, caught = self.collect_warnings(run) + self.assertEqual(seen, self.names) + self.assertEqual(caught, []) + + def test_bare_exhausted_loops_do_not_warn(self): + root = self.root + + def run(): + files = 0 + for _ in range(N): + for e in os.scandir(root): + files += e.is_file() + return files + + files, caught = self.collect_warnings(run) + self.assertEqual(files, 3 * N) + self.assertEqual(caught, []) + + def test_break_without_close_warns(self): + root = self.root + + def run(): + n = 0 + for _ in range(50): + for e in os.scandir(root): + n += 1 + break + return n + + n, caught = self.collect_warnings(run) + self.assertEqual(n, 50) + self.assertEqual(len(caught), 50) + + def test_explicit_del(self): + def open_then_del(): + it = os.scandir(self.root) + next(it) + it.__del__() + # The explicit call warned and closed it: nothing more at death. + del it + + _, caught = self.collect_warnings(open_then_del) + self.assertEqual(len(caught), 1) + + def closed_then_del(): + it = os.scandir(self.root) + it.close() + it.__del__() + del it + + _, caught = self.collect_warnings(closed_then_del) + self.assertEqual(caught, []) + + def test_entries_survive_close(self): + with os.scandir(self.root) as it: + entries = list(it) + self.assertEqual(sorted(e.name for e in entries), self.names) + self.assertEqual(sum(e.is_dir() for e in entries), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_scandir_compiled_loop.py b/tests/regrtest/test_scandir_compiled_loop.py new file mode 100644 index 000000000..879b29b29 --- /dev/null +++ b/tests/regrtest/test_scandir_compiled_loop.py @@ -0,0 +1,54 @@ +"""`for entry in os.scandir(...)` in compiled code. + +`glob` iterates `os.scandir()` in a `with` block. Compiled code and the +core loop step the iterator through its native `__next__` in place: the +entries are the directory's, an exhausted or closed iterator doesn't warn +when it goes, and an abandoned one still does. Run it past the compile +threshold. +""" + +import os +import tempfile +import warnings + +root = tempfile.mkdtemp() +for name in ("a.py", "b.txt", "c.py"): + with open(os.path.join(root, name), "w"): + pass +os.mkdir(os.path.join(root, "d")) +expected = sorted(os.listdir(root)) + + +def names_with(): + with os.scandir(root) as it: + return sorted(e.name for e in it) + + +def names_loop(): + out = [] + for e in os.scandir(root): + out.append((e.name, e.is_dir())) + return sorted(out) + + +def first_only(): + it = os.scandir(root) + for e in it: + break + it.close() + + +with warnings.catch_warnings(): + warnings.simplefilter("error", ResourceWarning) + for _ in range(3000): + assert names_with() == expected + assert [n for n, _ in names_loop()] == expected + assert dict(names_loop())["d"] is True + first_only() + +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", ResourceWarning) + it = os.scandir(root) + next(it) + del it +assert any(issubclass(w.category, ResourceWarning) for w in caught), caught diff --git a/tests/regrtest/test_scandir_entry_layout.py b/tests/regrtest/test_scandir_entry_layout.py new file mode 100644 index 000000000..78cee999d --- /dev/null +++ b/tests/regrtest/test_scandir_entry_layout.py @@ -0,0 +1,116 @@ +"""`os.DirEntry` attributes kept in the class's shared layout. + +Entries store name, path and kind (plus an inode or a bytes path) in one +order and are laid down at once; the stat caches arrive later. Every +accessor must keep reading the right values across str, bytes and fd +listings, directories given with and without a trailing slash, and +non-ASCII names, and entries must keep working after their files go. +""" + +import os +import shutil +import tempfile +import unittest + + +class ScandirEntryLayoutTests(unittest.TestCase): + def setUp(self): + self.top = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.top) + self.names = {"a.txt", "b", "café.txt", "sub"} + for name in ("a.txt", "b", "café.txt"): + with open(os.path.join(self.top, name), "w") as f: + f.write(name) + os.mkdir(os.path.join(self.top, "sub")) + if hasattr(os, "symlink"): + try: + os.symlink(os.path.join(self.top, "a.txt"), os.path.join(self.top, "link")) + self.names.add("link") + except OSError: + pass + + def check_entries(self, top, entries, as_bytes=False): + seen = set() + for e in entries: + name = os.fsdecode(e.name) if as_bytes else e.name + seen.add(name) + self.assertIsInstance(e.name, bytes if as_bytes else str) + self.assertIsInstance(e.path, bytes if as_bytes else str) + self.assertEqual(e.path, os.path.join(top, e.name)) + self.assertEqual(os.fspath(e), e.path) + self.assertEqual(repr(e), f"") + full = os.path.join(self.top, name) + self.assertEqual(e.is_dir(), os.path.isdir(full)) + self.assertEqual(e.is_file(), os.path.isfile(full)) + self.assertEqual(e.is_symlink(), os.path.islink(full)) + self.assertEqual(e.inode(), os.lstat(full).st_ino) + self.assertEqual(e.stat().st_mode, os.stat(full).st_mode) + self.assertEqual( + e.stat(follow_symlinks=False).st_mode, os.lstat(full).st_mode + ) + # (Cached: the same result again.) + self.assertIs(e.stat(), e.stat()) + self.assertEqual(seen, self.names) + + def test_str_listing(self): + for _ in range(200): + with os.scandir(self.top) as it: + self.check_entries(self.top, list(it)) + + def test_trailing_slash(self): + top = self.top + os.sep + for _ in range(50): + with os.scandir(top) as it: + self.check_entries(top, list(it)) + + def test_bytes_listing(self): + top = os.fsencode(self.top) + for _ in range(50): + with os.scandir(top) as it: + self.check_entries(top, list(it), as_bytes=True) + + def test_mixed_listings(self): + top_b = os.fsencode(self.top) + for _ in range(50): + with os.scandir(self.top) as it: + self.check_entries(self.top, list(it)) + with os.scandir(top_b) as it: + self.check_entries(top_b, list(it), as_bytes=True) + + @unittest.skipUnless(os.scandir in os.supports_fd, "scandir(fd) unsupported") + def test_fd_listing(self): + fd = os.open(self.top, os.O_RDONLY) + self.addCleanup(os.close, fd) + for _ in range(50): + with os.scandir(fd) as it: + entries = list(it) + self.assertEqual({e.name for e in entries}, self.names) + for e in entries: + self.assertEqual(e.path, e.name) + full = os.path.join(self.top, e.name) + self.assertEqual(e.is_dir(), os.path.isdir(full)) + self.assertEqual(e.inode(), os.lstat(full).st_ino) + self.assertEqual(e.stat(follow_symlinks=False).st_ino, e.inode()) + + def test_entries_outlive_their_files(self): + with os.scandir(self.top) as it: + entries = {e.name: e for e in it} + ino = os.lstat(os.path.join(self.top, "b")).st_ino + os.remove(os.path.join(self.top, "b")) + e = entries["b"] + self.assertEqual(e.inode(), ino) + self.assertTrue(e.is_file()) + self.assertEqual(e.name, "b") + + def test_walk(self): + for _ in range(50): + found = [] + for root, dirs, files in os.walk(self.top): + found.append((root, sorted(dirs), sorted(files))) + self.assertEqual(found[0][0], self.top) + self.assertEqual(found[0][1], ["sub"]) + self.assertEqual(len(found), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_scandir_next.py b/tests/regrtest/test_scandir_next.py new file mode 100644 index 000000000..1ec0cb909 --- /dev/null +++ b/tests/regrtest/test_scandir_next.py @@ -0,0 +1,94 @@ +"""`next()` of an `os.scandir` iterator. + +`os.walk` steps its directory listing with `next(scandir_it)`, which runs +the iterator's own step in place: entries come out as iteration gives +them, the default (or `StopIteration`) at the end, and an iterator run to +its end counts as closed (no `ResourceWarning` when it's dropped). +""" + +import gc +import os +import tempfile +import unittest +import warnings + + +class ScandirNextTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp() + for name in ("a", "b", "c"): + open(os.path.join(self.dir, name), "w").close() + os.mkdir(os.path.join(self.dir, "sub")) + + def tearDown(self): + for name in ("a", "b", "c"): + os.remove(os.path.join(self.dir, name)) + os.rmdir(os.path.join(self.dir, "sub")) + os.rmdir(self.dir) + + def test_next_matches_iteration(self): + for _ in range(500): + with os.scandir(self.dir) as it: + stepped = [] + while True: + try: + stepped.append(next(it).name) + except StopIteration: + break + with os.scandir(self.dir) as it: + iterated = [e.name for e in it] + self.assertEqual(sorted(stepped), ["a", "b", "c", "sub"]) + self.assertEqual(sorted(stepped), sorted(iterated)) + + def test_default_and_exhaustion(self): + for _ in range(500): + it = os.scandir(self.dir) + names = [next(it).name for _ in range(4)] + end = next(it, "done") + again = next(it, None) + self.assertEqual(len(names), 4) + self.assertEqual((end, again), ("done", None)) + with self.assertRaises(StopIteration): + next(it) + + def test_exhausted_iterator_does_not_warn(self): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + for _ in range(200): + it = os.scandir(self.dir) + while next(it, None) is not None: + pass + del it + gc.collect() + self.assertEqual([w for w in caught if issubclass(w.category, ResourceWarning)], []) + + def test_walk(self): + for _ in range(300): + seen = list(os.walk(self.dir)) + self.assertEqual(len(seen), 2) + top, dirs, files = seen[0] + self.assertEqual((top, dirs, sorted(files)), (self.dir, ["sub"], ["a", "b", "c"])) + self.assertEqual(seen[1], (os.path.join(self.dir, "sub"), [], [])) + + def test_other_iterators_unchanged(self): + class It: + def __init__(self): + self.n = 0 + + def __iter__(self): + return self + + def __next__(self): + self.n += 1 + if self.n > 2: + raise StopIteration + return self.n + + for _ in range(500): + it = It() + r = (next(it), next(it), next(it, "end")) + self.assertEqual(r, (1, 2, "end")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_seq_repeat_compiled.py b/tests/regrtest/test_seq_repeat_compiled.py new file mode 100644 index 000000000..47f2166f7 --- /dev/null +++ b/tests/regrtest/test_seq_repeat_compiled.py @@ -0,0 +1,55 @@ +"""Tuple and list repetition in compiled code. + +`argparse`'s metavar formatter returns `(result,) * tuple_size`. Compiled +code repeats a short tuple or list in place; a long result, a list's +in-place `*=`, and `t * 1` (the same tuple) keep the full handler's +behavior. Items are heap objects, so a wrong count shows. Run it past +the compile threshold. +""" + +import sys + + +class Item: + pass + + +def repeat(seq, n): + return seq * n + + +def rrepeat(seq, n): + return n * seq + + +def irepeat(seq, n): + seq *= n + return seq + + +item = Item() +base = sys.getrefcount(item) +for _ in range(3000): + t = (item, "a") + assert repeat(t, 3) == (item, "a") * 3 + assert rrepeat(t, 2) == (item, "a", item, "a") + assert repeat(t, 1) is t and rrepeat(t, 1) is t + assert repeat(t, 0) == () and repeat(t, -2) == () + assert irepeat(t, 2) == (item, "a", item, "a") + l = [item] + r = repeat(l, 2) + assert r == [item, item] and r is not l and l == [item] + assert rrepeat(l, 3) == [item] * 3 + m = irepeat(l, 2) + assert m is l and l == [item, item] + assert len(repeat((0,), 5000)) == 5000 + assert len(repeat([None], 5000)) == 5000 + del t, l, r, m +assert sys.getrefcount(item) == base, (sys.getrefcount(item), base) + +try: + repeat((1,), sys.maxsize) +except MemoryError: + pass +else: + raise AssertionError("no MemoryError") diff --git a/tests/regrtest/test_seq_subclass_subscript.py b/tests/regrtest/test_seq_subclass_subscript.py new file mode 100644 index 000000000..657959433 --- /dev/null +++ b/tests/regrtest/test_seq_subclass_subscript.py @@ -0,0 +1,52 @@ +"""Subscripts of `list` and `tuple` subclasses' instances. + +`email`'s `TokenList` (a `list` subclass) reads `self[0]` in its +properties. Compiled code and the core loop index the payload in place +when the class keeps the builtin `__getitem__`; a class that overrides +it, a slice, an out-of-range index and a non-int key keep the full +handler's behavior. Items are heap objects. Run it past the compile +threshold. +""" + + +class Item: + pass + + +class L(list): + def first(self): + return self[0] + + +class T(tuple): + pass + + +class Over(list): + def __getitem__(self, i): + return ("over", i) + + +def read(seq, i): + return seq[i] + + +a, b = Item(), Item() +lst, tup, over = L([a, b]), T((a, b)), Over([a]) +for _ in range(3000): + assert read(lst, 0) is a and read(lst, -1) is b and lst.first() is a + assert read(tup, 1) is b and read(tup, -2) is a + assert read(over, 0) == ("over", 0) + assert read(lst, slice(0, 1)) == [a] + try: + read(lst, 2) + except IndexError: + pass + else: + raise AssertionError("no IndexError") + try: + read(tup, "x") + except TypeError: + pass + else: + raise AssertionError("no TypeError") diff --git a/tests/regrtest/test_seqiter_getitem_step.py b/tests/regrtest/test_seqiter_getitem_step.py new file mode 100644 index 000000000..c63415ce8 --- /dev/null +++ b/tests/regrtest/test_seqiter_getitem_step.py @@ -0,0 +1,117 @@ +"""Iterating a class with only `__getitem__` steps the sequence's +`__getitem__` frameless; the items, the end at IndexError or +StopIteration, the iterator's state, and every case the step declines +match the general protocol.""" + +import unittest + + +class Seq: + def __init__(self, n): + self.n = n + + def __getitem__(self, i): + if i >= self.n: + raise IndexError + return i * 2 + + +class StopSeq: + def __getitem__(self, i): + if i >= 3: + raise StopIteration + return i + + +class Other(Exception): + pass + + +class BadSeq: + def __getitem__(self, i): + if i >= 2: + raise Other + return i + + +class SubErr(IndexError): + pass + + +class SubSeq: + def __getitem__(self, i): + if i >= 2: + raise SubErr + return i + + +class Grow: + def __init__(self): + self.items = [1, 2] + + def __getitem__(self, i): + return self.items[i] + + +class SeqIterStep(unittest.TestCase): + def test_items_and_end(self): + for _ in range(300): + self.assertEqual(list(Seq(4)), [0, 2, 4, 6]) + self.assertEqual([x for x in Seq(0)], []) + self.assertEqual(sum(x for x in Seq(10)), 90) + self.assertEqual(list(StopSeq()), [0, 1, 2]) + self.assertEqual(list(SubSeq()), [0, 1]) + + def test_other_exception_propagates(self): + for _ in range(100): + out = [] + with self.assertRaises(Other): + for x in BadSeq(): + out.append(x) + self.assertEqual(out, [0, 1]) + + def test_iterator_state(self): + s = Seq(5) + for _ in range(100): + it = iter(s) + self.assertEqual(next(it), 0) + for x in it: + if x == 4: + break + self.assertEqual(next(it), 6) + self.assertEqual(list(it), [8]) + self.assertEqual(list(it), []) + # Exhausted for good, even if the sequence grows. + s.n = 10 + self.assertEqual(list(it), []) + s.n = 5 + + def test_list_backed_sequence(self): + g = Grow() + for _ in range(100): + self.assertEqual(list(g), [1, 2]) + + def test_patched_getitem(self): + class P: + def __getitem__(self, i): + if i >= 2: + raise IndexError + return i + for _ in range(200): + self.assertEqual(list(P()), [0, 1]) + P.__getitem__ = lambda self, i: [9, 8][i] + self.assertEqual(list(P()), [9, 8]) + + def test_next_inside_getitem(self): + class Inner: + def __init__(self): + self.it = iter([1, 2]) + + def __getitem__(self, i): + return next(self.it) + for _ in range(100): + self.assertEqual(list(Inner()), [1, 2]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_sequence_copies_keep_items.py b/tests/regrtest/test_sequence_copies_keep_items.py new file mode 100644 index 000000000..156b41f18 --- /dev/null +++ b/tests/regrtest/test_sequence_copies_keep_items.py @@ -0,0 +1,233 @@ +"""Copies of a list's or tuple's items share the items, not the container. + +`tuple(xs)`, `list(xs)`, `xs[:]`, `xs.copy()`, `a + b`, `t * n`, +`(*xs,)` and slices copy the items in one pass. Each copy holds its own +reference to every item: dropping the copy, the source, or both, in any +order, releases each item exactly once, and an item only the copy holds +dies with the copy. +""" + +import gc +import sys +import unittest +import weakref + + +class Item: + """A heap item whose death can be observed.""" + + __slots__ = ("n", "__weakref__") + + def __init__(self, n): + self.n = n + + def __repr__(self): + return f"Item({self.n})" + + +def items(n): + return [Item(i) for i in range(n)] + + +COPIERS = { + "tuple(list)": lambda xs: tuple(xs), + "list(list)": lambda xs: list(xs), + "list(tuple)": lambda xs: list(tuple(xs)), + "tuple(tuple slice)": lambda xs: tuple(xs)[0:], + "xs[:]": lambda xs: xs[:], + "xs.copy()": lambda xs: xs.copy(), + "xs + []": lambda xs: xs + [], + "[] + xs": lambda xs: [] + xs, + "t + ()": lambda xs: tuple(xs) + (), + "[*xs]": lambda xs: [*xs], + "(*xs,)": lambda xs: (*xs,), + "xs * 1": lambda xs: xs * 1, + "t * 1": lambda xs: tuple(xs) * 1, + "sorted by n": lambda xs: sorted(xs, key=lambda item: item.n), + "list(reversed)": lambda xs: list(reversed(xs))[::-1], + "tuple(reversed)": lambda xs: tuple(reversed(xs))[::-1], + "extend": lambda xs: (lambda out: (out.extend(xs), out)[1])([]), + "extend tuple": lambda xs: (lambda out: (out.extend(tuple(xs)), out)[1])([]), +} + + +class CopiesShareItemsTests(unittest.TestCase): + def test_every_copy_holds_the_same_items(self): + for name, copy in COPIERS.items(): + for n in (0, 1, 2, 7, 300): + with self.subTest(name=name, n=n): + xs = items(n) + out = copy(xs) + self.assertEqual(len(out), n) + for a, b in zip(xs, out): + self.assertIs(a, b) + + def test_items_outlive_the_source(self): + for name, copy in COPIERS.items(): + with self.subTest(name=name): + xs = items(50) + refs = [weakref.ref(x) for x in xs] + out = copy(xs) + del xs + gc.collect() + self.assertTrue(all(r() is not None for r in refs)) + self.assertEqual([x.n for x in out], list(range(50))) + del out + gc.collect() + self.assertTrue(all(r() is None for r in refs)) + + def test_items_outlive_the_copy(self): + for name, copy in COPIERS.items(): + with self.subTest(name=name): + xs = items(50) + refs = [weakref.ref(x) for x in xs] + out = copy(xs) + del out + gc.collect() + self.assertTrue(all(r() is not None for r in refs)) + self.assertEqual([x.n for x in xs], list(range(50))) + del xs + gc.collect() + self.assertTrue(all(r() is None for r in refs)) + + def test_reference_counts_return_to_where_they_started(self): + probe = Item(-1) + xs = [probe] * 40 + ["text", 3, 2.5, None, (probe,)] + before = sys.getrefcount(probe) + for name, copy in COPIERS.items(): + if name == "sorted by n": + continue + with self.subTest(name=name): + for _ in range(30): + out = copy(xs) + self.assertEqual(sys.getrefcount(probe), before + 40) + del out + self.assertEqual(sys.getrefcount(probe), before) + + def test_a_copy_can_be_the_only_owner(self): + for name, copy in COPIERS.items(): + with self.subTest(name=name): + out = copy(items(20)) + self.assertEqual([x.n for x in out], list(range(20))) + refs = [weakref.ref(x) for x in out] + del out + gc.collect() + self.assertTrue(all(r() is None for r in refs)) + + +class ConcatAndRepeatTests(unittest.TestCase): + def test_tuple_concatenation(self): + a = tuple(items(5)) + b = tuple(items(3)) + c = a + b + self.assertEqual(len(c), 8) + self.assertTrue(all(x is y for x, y in zip(c, a + b))) + self.assertIs(c[0], a[0]) + self.assertIs(c[5], b[0]) + self.assertIs(a + (), a) + self.assertIs(() + a, a) + self.assertIs(() + (), ()) + + def test_list_concatenation_is_a_new_list(self): + a = items(4) + b = items(4) + c = a + b + self.assertIsNot(c, a) + c.append(None) + self.assertEqual(len(a), 4) + self.assertEqual(len(b), 4) + self.assertEqual([x.n for x in c[:8]], [0, 1, 2, 3, 0, 1, 2, 3]) + d = a + a + self.assertEqual(len(d), 8) + self.assertIs(d[0], d[4]) + + def test_repeats(self): + a = items(3) + for n in (-1, 0, 1, 2, 5, 400): + with self.subTest(n=n): + want = max(n, 0) * 3 + out = a * n + self.assertEqual(len(out), want) + self.assertTrue(all(out[i] is a[i % 3] for i in range(want))) + t = tuple(a) * n + self.assertEqual(len(t), want) + self.assertTrue(all(t[i] is a[i % 3] for i in range(want))) + ints = list(range(1000)) + self.assertEqual(ints * 2, ints + ints) + self.assertEqual((ints * 3)[2000:], ints) + self.assertEqual(ints, list(range(1000))) + t = tuple(a) + self.assertIs(t * 1, t) + + def test_extending_a_list_with_itself_doubles_it(self): + xs = items(6) + xs.extend(xs) + self.assertEqual([x.n for x in xs], [0, 1, 2, 3, 4, 5] * 2) + xs += xs + self.assertEqual(len(xs), 24) + + def test_slices(self): + xs = items(40) + t = tuple(xs) + for lo, hi, step in [ + (None, None, None), (3, 17, None), (-5, None, None), (None, -5, None), + (30, 10, None), (None, None, -1), (None, None, 3), (35, 2, -4), (100, 200, None), + ]: + with self.subTest(lo=lo, hi=hi, step=step): + want = [xs[i] for i in range(*slice(lo, hi, step).indices(40))] + got_list = xs[lo:hi:step] + got_tuple = t[lo:hi:step] + self.assertEqual(len(got_list), len(want)) + self.assertTrue(all(a is b for a, b in zip(got_list, want))) + self.assertIsInstance(got_tuple, tuple) + self.assertTrue(all(a is b for a, b in zip(got_tuple, want))) + self.assertIs(t[:], t) + self.assertIs(t[10:10], ()) + + +class TupleHashTests(unittest.TestCase): + def test_int_tuples_hash_as_cpython_does(self): + # The combination is fixed by the language's implementation, and an + # int's hash doesn't depend on the hash seed. + if sys.hash_info.width != 64: + self.skipTest("64-bit hashes") + self.assertEqual(hash(()), 5740354900026072187) + self.assertEqual(hash((1, 2, 3)), 529344067295497451) + self.assertEqual(hash((0,)), -8753497827991233192) + self.assertEqual(hash(tuple(range(1000))), -5792488972412445855) + self.assertEqual(hash((-1, -2, 2**61 - 1, 2**61, -(2**62))), hash((-2, -2, 0, 1, -2))) + + def test_equal_tuples_hash_equal(self): + a = tuple(range(1, 500)) + b = tuple(list(range(1, 500))) + self.assertEqual(hash(a), hash(b)) + self.assertEqual(hash(a[1:]), hash(tuple(range(2, 500)))) + self.assertEqual(hash(a + (7,)), hash((*a, 7))) + self.assertEqual(hash(("a", 1, "b")), hash(("a", 1) + ("b",))) + self.assertEqual(hash((1, 2.0, True)), hash((1.0, 2, 1))) + self.assertEqual(hash((1, (2, (3, "x")))), hash((1, (2, (3, "x"))))) + + def test_an_unhashable_item_still_raises(self): + for bad in ((1, 2, []), (1, "a", {}), tuple(range(100)) + ([],), ((1, [2]),)): + with self.subTest(bad=bad): + with self.assertRaises(TypeError): + hash(bad) + with self.assertRaises(TypeError): + {bad: 1} + + def test_a_python_hash_runs_once_per_hashing(self): + calls = [] + + class Key: + def __hash__(self): + calls.append(1) + return 7 + + t = (1, "a", Key(), 2) + h = hash(t) + self.assertEqual(hash((1, "a", 7, 2)), h) + self.assertGreaterEqual(len(calls), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_sequence_subclasses_through_builtins.py b/tests/regrtest/test_sequence_subclasses_through_builtins.py new file mode 100644 index 000000000..a54fc1d22 --- /dev/null +++ b/tests/regrtest/test_sequence_subclasses_through_builtins.py @@ -0,0 +1,514 @@ +"""A named tuple (or any `tuple`, `list`, `str`, `bytes`, `int` or +`float` subclass that keeps its base's comparisons and operators, an +`IntEnum` or `StrEnum` member among them) compares and adds as its +payload when a builtin asks: `sorted`, `max`, `min`, `sum`, `in`, +`list.index`, `bisect`, the `operator` functions. An immutable value's +subclass instance remembers its hash. Overrides still decide.""" + +import bisect +import collections +import enum +import functools +import operator +import unittest + +N = 200 + +Point = collections.namedtuple("Point", "x y") +Other = collections.namedtuple("Other", "x y") + + +class TS(tuple): + pass + + +class LS(list): + pass + + +class Backwards(tuple): + def __lt__(self, other): + return tuple.__gt__(self, other) + + +class NeverEqual(tuple): + def __eq__(self, other): + return False + + __hash__ = tuple.__hash__ + + +class Reflected(tuple): + """A subclass whose reflected comparison answers first.""" + + def __gt__(self, other): + return "reflected" + + +class Hashed(tuple): + calls = 0 + + def __hash__(self): + Hashed.calls += 1 + return 7 + + +class Name(str): + pass + + +class Count(int): + pass + + +PTS = [Point(i * 7 % 13, i) for i in range(20)] +RAW = [(p.x, p.y) for p in PTS] + + +class Ordering(unittest.TestCase): + def test_sorted_and_extremes(self): + for _ in range(N): + got = (sorted(PTS), max(PTS), min(PTS), sorted(PTS, reverse=True)[0]) + self.assertEqual([tuple(p) for p in got[0]], sorted(RAW)) + self.assertIs(type(got[0][0]), Point) + self.assertEqual((got[1], got[2], got[3]), (max(RAW), min(RAW), max(RAW))) + self.assertIs(got[1], PTS[RAW.index(max(RAW))]) + + def test_mixed_with_plain_tuples_and_other_classes(self): + mixed = [Point(2, 1), (1, 5), Other(1, 2), TS((3, 0)), (2, 0)] + for _ in range(N): + got = sorted(mixed) + self.assertEqual([tuple(x) for x in got], [(1, 2), (1, 5), (2, 0), (2, 1), (3, 0)]) + self.assertEqual([type(x) for x in got], [Other, tuple, tuple, Point, TS]) + for _ in range(N): + eq = (Point(1, 2) == (1, 2), (1, 2) == Point(1, 2), Point(1, 2) == Other(1, 2), Point(1, 2) != (1, 3), + Point(1, 2) < (1, 3), (1, 1) < Point(1, 2), Point(1, 2) <= Other(1, 2), Point(1, 2) == [1, 2]) + self.assertEqual(eq, (True, True, True, True, True, True, True, False)) + + def test_search(self): + s = sorted(PTS) + for _ in range(N): + got = (PTS[7] in PTS, (PTS[7].x, PTS[7].y) in PTS, Point(99, 99) in PTS, PTS.index(Point(*RAW[15])), + PTS.count(RAW[3]), bisect.bisect_left(s, PTS[3]), bisect.bisect_right(s, RAW[3])) + self.assertEqual(got[:5], (True, True, False, 15, 1)) + self.assertEqual(got[5], sorted(RAW).index(RAW[3])) + self.assertEqual(got[6], sorted(RAW).index(RAW[3]) + 1) + + def test_list_subclasses(self): + xs = [LS([3, 1]), LS([1, 2]), [2, 0], LS([1, 1])] + for _ in range(N): + got = (sorted(xs), max(xs), LS([1, 2]) == [1, 2], [1, 2] == LS([1, 2]), LS([1]) < LS([1, 0]), + LS([1, 2]) in xs, LS([1, 2]) == (1, 2)) + self.assertEqual(got[0], [[1, 1], [1, 2], [2, 0], [3, 1]]) + self.assertEqual(got[1:], ([3, 1], True, True, True, True, False)) + + def test_unorderable_items_raise(self): + for _ in range(20): + with self.assertRaises(TypeError): + sorted([Point(1, "a"), Point(1, 2)]) + with self.assertRaises(TypeError): + max(Point(1, None), Point(1, 2)) + with self.assertRaises(TypeError): + Point(1, 2) < [1, 2] + self.assertEqual(sorted([Point(1, "a"), Point(0, 2)]), [(0, 2), (1, "a")]) + + def test_overrides_decide(self): + xs = [Backwards((1,)), Backwards((3,)), Backwards((2,))] + for _ in range(N): + got = (sorted(xs), NeverEqual((1,)) in [NeverEqual((1,))], [NeverEqual((1,))].count(NeverEqual((1,))), + (1, 2) < Reflected((0, 0)), Point(1, 2) < Reflected((0, 0)), max(xs)) + self.assertEqual([tuple(x) for x in got[0]], [(3,), (2,), (1,)]) + # (A subclass of the left operand's class answers first; `Reflected` + # subclasses `tuple`, not `Point`.) + self.assertEqual(got[1:5], (False, 0, "reflected", False)) + # (`max` asks `__gt__`, which `Backwards` keeps.) + self.assertEqual(tuple(got[5]), (3,)) + self.assertEqual(tuple(min(xs)), (3,)) + + def test_class_edit_is_seen(self): + class Late(tuple): + pass + + xs = [Late((2,)), Late((1,))] + for _ in range(N): + self.assertEqual([tuple(x) for x in sorted(xs)], [(1,), (2,)]) + Late.__lt__ = lambda self, other: tuple.__gt__(self, other) + for _ in range(N): + self.assertEqual([tuple(x) for x in sorted(xs)], [(2,), (1,)]) + del Late.__lt__ + self.assertEqual([tuple(x) for x in sorted(xs)], [(1,), (2,)]) + + +class Hashes(unittest.TestCase): + def test_sets_and_dicts(self): + for _ in range(N): + got = (len(set(PTS)), len({p: 1 for p in PTS}), PTS[5] in set(PTS), RAW[5] in set(PTS), + {Point(1, 2): "a"}[(1, 2)], {(1, 2): "b"}[Other(1, 2)], hash(Point(1, 2)) == hash((1, 2)), + len({Point(1, 2), Other(1, 2), (1, 2), TS((1, 2))})) + self.assertEqual(got, (20, 20, True, True, "a", "b", True, 1)) + + def test_str_and_int_subclasses(self): + names = [Name("n%d" % (i % 5)) for i in range(20)] + counts = [Count(i % 4) for i in range(20)] + for _ in range(N): + got = (len(set(names)), len(set(counts)), {Name("k"): 1}["k"], {3: "x"}[Count(3)], + hash(Name("abc")) == hash("abc"), hash(Count(-1)) == hash(-1), Name("n1") in set(names)) + self.assertEqual(got, (5, 4, 1, "x", True, True, True)) + + def test_unhashable_payload(self): + bad = Point(1, []) + for _ in range(20): + with self.assertRaises(TypeError): + hash(bad) + with self.assertRaises(TypeError): + {bad} + bad.y.append(1) + with self.assertRaises(TypeError): + {bad: 1} + + def test_custom_hash_is_asked_once_a_value(self): + Hashed.calls = 0 + h = Hashed((1, 2)) + for _ in range(N): + s = {h} + d = {h: 1} + hit = h in s + self.assertTrue(hit) + self.assertEqual(hash(h), 7) + self.assertLessEqual(Hashed.calls, 3 * N + 1) + self.assertGreaterEqual(Hashed.calls, 1) + + def test_list_subclass_is_unhashable(self): + for _ in range(20): + with self.assertRaises(TypeError): + hash(LS([1])) + with self.assertRaises(TypeError): + {LS([1])} + + +class Ratio(float): + pass + + +class Blob(bytes): + pass + + +class Level(enum.IntEnum): + LOW = 1 + MID = 2 + HIGH = 3 + + +class Tag(enum.StrEnum): + X = "x" + Y = "y" + Z = "z" + + +class Loud(int): + def __lt__(self, other): + return "lt" + + def __add__(self, other): + return "add" + + def __eq__(self, other): + return "eq" + + __hash__ = int.__hash__ + + +class Scalars(unittest.TestCase): + def test_str_and_bytes_subclasses(self): + names = [Name("n%d" % (i * 7 % 13)) for i in range(20)] + raw = [str(n) for n in names] + blobs = [Blob(b"b%d" % (i * 5 % 7)) for i in range(10)] + for _ in range(N): + got = (sorted(names), max(names), min(names), names[7] in names, "n5" in names, Name("zz") in names, + names.index("n1"), names.count(Name("n0")), bisect.bisect_left(sorted(names), "n5"), + sorted(blobs)[0], max(blobs), Name("a") == "a", "a" == Name("a"), Name("a") < "b", + Name("a") == b"a", Blob(b"a") == b"a", Name("a") != Name("a")) + self.assertEqual(got[0], sorted(raw)) + self.assertIs(type(got[0][0]), Name) + self.assertEqual(got[1:9], (max(raw), min(raw), True, True, False, raw.index("n1"), raw.count("n0"), + sorted(raw).index("n5"))) + self.assertEqual(got[9:], (b"b0", b"b6", True, True, True, False, True, False)) + + def test_int_and_float_subclasses(self): + counts = [Count(i * 7 % 13) for i in range(20)] + raw = [int(c) for c in counts] + ratios = [Ratio(i * 7 % 13 / 4) for i in range(20)] + for _ in range(N): + got = (sorted(counts), max(counts), min(counts), sum(counts), sum(counts, Count(5)), sum(ratios), + counts[4] in counts, 6 in counts, 6.0 in counts, counts.index(Count(3)), sorted(ratios)[-1], + functools.reduce(operator.mul, counts[:5]), operator.add(Count(2), 3), operator.sub(3, Count(2)), + operator.truediv(Count(1), Ratio(4.0)), Count(2) ** Count(3), Count(7) // 2, Count(7) % Ratio(2.5), + Count(3) == 3.0, Ratio(2.0) == 2, Count(1) == True, Ratio("nan") == Ratio("nan"), + Count(5) < Ratio(5.5), 5.5 > Count(5)) + self.assertEqual(got[0], sorted(raw)) + self.assertIs(type(got[0][0]), Count) + self.assertEqual(got[1:4], (max(raw), min(raw), sum(raw))) + self.assertIs(type(got[3]), int) + self.assertEqual(got[4:11], (sum(raw) + 5, sum(float(r) for r in ratios), True, True, True, raw.index(3), + max(float(r) for r in ratios))) + self.assertEqual(got[11:18], (functools.reduce(operator.mul, raw[:5]), 5, 1, 0.25, 8, 3, 2.0)) + self.assertEqual(got[18:], (True, True, True, False, True, True)) + for value in (got[12], got[13], got[15], got[16]): + self.assertIs(type(value), int) + + def test_enum_members(self): + levels = [Level(1 + i % 3) for i in range(12)] + tags = [Tag("xyz"[i % 3]) for i in range(12)] + for _ in range(N): + got = (sorted(levels)[0], sorted(levels)[-1], max(levels), min(levels), sum(levels), Level.MID in levels, + 2 in levels, levels.count(Level.LOW), levels.index(3), sorted(tags)[0], max(tags), "y" in tags, + tags.index(Tag.Z), "".join(sorted(tags)[:3]), Level.LOW < Level.HIGH, Level.MID == 2, + Tag.X == "x", Level.LOW + Level.MID, operator.add(Level.HIGH, 1), max(Level.LOW, 2, Level.HIGH)) + self.assertIs(got[0], Level.LOW) + self.assertIs(got[1], Level.HIGH) + self.assertIs(got[2], Level.HIGH) + self.assertEqual(got[4:9], (24, True, True, 4, 2)) + self.assertIs(type(got[4]), int) + self.assertIs(got[9], Tag.X) + self.assertEqual(got[10:], (Tag.Z, True, 2, "xxx", True, True, True, 3, 4, Level.HIGH)) + self.assertIs(type(got[17]), int) + + def test_int_and_float_calls(self): + import decimal + + class Whole(int): + def __int__(self): + return 99 + + def __float__(self): + return 9.5 + + d = decimal.Decimal("7.75") + c, r, lvl, w = Count(5), Ratio(2.75), Level.HIGH, Whole(3) + big = Count(10**30) + for _ in range(N): + got = (int(c), float(c), int(r), float(r), int(lvl), float(lvl), int(d), float(d), int(w), float(w), + int(big), int(Ratio(-2.75)), float(Count(-4))) + self.assertEqual(got, (5, 5.0, 2, 2.75, 3, 3.0, 7, 7.75, 99, 9.5, 10**30, -2, -4.0)) + self.assertEqual([type(x) for x in got], + [int, float, int, float, int, float, int, float, int, float, int, int, float]) + for _ in range(20): + self.assertEqual(float(big), 1e30) + with self.assertRaises(ValueError): + int(Ratio("nan")) + with self.assertRaises(OverflowError): + int(Ratio("inf")) + with self.assertRaises(ValueError): + int(decimal.Decimal("NaN")) + with self.assertRaises(TypeError): + int(Name("x"), 10, 2) + self.assertEqual(int(Name("42")), 42) + self.assertEqual(float(Name("1.5")), 1.5) + self.assertEqual(int(Count(7)), 7) + + def test_operators_on_payloads(self): + class Shout(str): + def __add__(self, other): + return "shout" + + def __neg__(self): + return "no" + + class Right(str): + def __radd__(self, other): + return "right" + + class Minus(int): + def __neg__(self): + return "minus" + + def __pos__(self): + return "plus" + + a, b, c, lvl, blob = Name("ab"), Name("cd"), Count(5), Level.MID, Blob(b"xy") + for _ in range(N): + got = (a + b, a + "!", "!" + a, a * 2, 2 * a, blob + b"z", blob * 2, -c, +c, -lvl, +lvl, -Ratio(1.5), + -Count(-(2**63)), Shout("x") + "y", "y" + Right("x"), a + Right("x"), -Minus(1), +Minus(1), + Tag.X + Tag.Y, Tag.X * 3) + self.assertEqual(got, ("abcd", "ab!", "!ab", "abab", "abab", b"xyz", b"xyxy", -5, 5, -2, 2, -1.5, 2**63, + "shout", "right", "right", "minus", "plus", "xy", "xxx")) + for value in got[:5] + got[18:]: + self.assertIs(type(value), str) + for value in got[5:7]: + self.assertIs(type(value), bytes) + for value in got[7:11]: + self.assertIs(type(value), int) + self.assertIs(type(got[11]), float) + for _ in range(20): + with self.assertRaises(TypeError): + a + 1 + with self.assertRaises(TypeError): + a + blob + with self.assertRaises(TypeError): + -a + with self.assertRaises(TypeError): + a * 1.5 + + def test_value_subclass_keys_in_comprehensions(self): + names = [Name("n%d" % (i % 5)) for i in range(20)] + levels = [Level(1 + i % 3) for i in range(12)] + for _ in range(N): + d = {n: i for i, n in enumerate(names)} + e = {lvl: lvl.name for lvl in levels} + s = {t for t in (Tag.X, Tag.Y, Tag.X)} + hit = (d[Name("n3")], d["n4"], e[Level.MID], e[3], Tag.Y in s, "x" in s, Name("zz") in d) + self.assertEqual(len(d), 5) + self.assertEqual(list(d.values()), [15, 16, 17, 18, 19]) + self.assertIs(type(next(iter(d))), Name) + self.assertEqual(hit, (18, 19, "MID", "HIGH", True, True, False)) + self.assertEqual(e, {1: "LOW", 2: "MID", 3: "HIGH"}) + + def test_errors_surface(self): + for _ in range(20): + with self.assertRaises(ZeroDivisionError): + operator.truediv(Count(1), Count(0)) + with self.assertRaises(TypeError): + sorted([Count(1), Name("a")]) + with self.assertRaises(TypeError): + sum([Name("a"), Name("b")]) + with self.assertRaises(TypeError): + operator.add(Count(1), Name("a")) + with self.assertRaises(TypeError): + max(Level.LOW, Tag.X) + self.assertFalse(Count(1) == Name("1")) + self.assertNotIn(Name("1"), [Count(1), 1, 1.0]) + + def test_overrides_decide(self): + xs = [Loud(2), Loud(1)] + for _ in range(N): + got = (Loud(1) < Loud(2), operator.add(Loud(1), 2), sum([Loud(1)], Loud(0)), Loud(1) == 1, + 1 < Loud(2), Loud(5) in [Loud(9)], max(Loud(1), Loud(2)), 3 + Loud(1)) + self.assertEqual(got[:6], ("lt", "add", "add", "eq", True, True)) + self.assertEqual(int(got[6]), 2) + self.assertEqual(got[7], 4) + self.assertEqual(sorted(int(x) for x in sorted(xs)), [1, 2]) + + def test_hash_and_keys(self): + for _ in range(N): + got = (len({Level.LOW, Level.MID, Level.LOW, 1}), {Level.MID: "m"}[2], {Tag.X: 1}["x"], {"y": 2}[Tag.Y], + hash(Level.HIGH) == hash(3), hash(Tag.Z) == hash("z"), len({Ratio(1.0), Count(1), 1, True}), + Blob(b"k") in {b"k"}, {Blob(b"k"): 1}[b"k"]) + self.assertEqual(got, (2, "m", 1, 2, True, True, 1, True, 1)) + + def test_unhashable_subclasses_stay_unhashable(self): + class NoHashStr(str): + __hash__ = None + + class EqOnlyStr(str): + def __eq__(self, other): + return str.__eq__(self, other) + + class NoHashInt(int): + __hash__ = None + + class EqOnlyBytes(bytes): + def __eq__(self, other): + return bytes.__eq__(self, other) + + class NoHashFloat(float): + __hash__ = None + + for _ in range(3): + for value in (NoHashStr("x"), EqOnlyStr("x"), NoHashInt(3), EqOnlyBytes(b"x"), NoHashFloat(1.5)): + with self.subTest(cls=type(value).__name__): + with self.assertRaises(TypeError): + hash(value) + with self.assertRaises(TypeError): + {value: 1} + with self.assertRaises(TypeError): + {value} + with self.assertRaises(TypeError): + value in {"x": 1, 3: 2} + with self.assertRaises(TypeError): + {"x": 1}[value] + with self.assertRaises(TypeError): + {1, 2}.add(value) + + def test_custom_hash_decides(self): + class Odd(str): + def __hash__(self): + return 7 + + class Counting(int): + calls = 0 + + def __hash__(self): + Counting.calls += 1 + return int.__hash__(self) + + for _ in range(N): + got = (hash(Odd("a")), hash(Odd("b")), {Odd("a"): 1}.get("a"), Odd("a") in {Odd("a")}) + self.assertEqual(got, (7, 7, None, True)) + c = Counting(5) + before = Counting.calls + d = {c: 1} + self.assertEqual((d[5], Counting.calls > before), (1, True)) + + +class ReflectedFirst(unittest.TestCase): + """A subclass's instance on the right has its reflected comparison run + first, so the items compare right against left.""" + + def test_items_see_the_subclass_first(self): + log = [] + + class Probe: + def __init__(self, name): + self.name = name + + def __eq__(self, other): + log.append((self.name, other.name)) + return True + + __hash__ = None + + class L(list): + pass + + class L2(L): + pass + + class T(tuple): + pass + + a, b = Probe("a"), Probe("b") + cases = [ + (lambda: [a] == L([b]), ("b", "a")), + (lambda: L([a]) == [b], ("a", "b")), + (lambda: L([a]) == L([b]), ("a", "b")), + (lambda: L([a]) == L2([b]), ("b", "a")), + (lambda: L2([a]) == L([b]), ("a", "b")), + (lambda: (a,) == T((b,)), ("b", "a")), + (lambda: T((a,)) == (b,), ("a", "b")), + (lambda: [a] != L([b]), ("b", "a")), + (lambda: [a] <= L([b]), ("b", "a")), + (lambda: (a,) >= T((b,)), ("b", "a")), + ] + for _ in range(3): + for i, (compare, order) in enumerate(cases): + log.clear() + compare() + self.assertEqual(log, [order], i) + + def test_mirrored_orderings(self): + class L(list): + pass + + class T(tuple): + pass + + for _ in range(N): + got = ([1, 2] < L([1, 3]), [1, 3] < L([1, 2]), [1, 2] >= L([1, 2, 0]), (1, 2) > T((1, 1)), + (1,) <= T((1,)), sorted([[2], L([1]), [0]]), max([(1, 2), T((1, 3)), (0, 9)]), + L([1]) in [[1]], [1] in [L([1])], [[1], L([1])].count([1])) + self.assertEqual(got, (True, False, False, True, True, [[0], [1], [2]], (1, 3), True, True, 2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_sequence_walk_generators.py b/tests/regrtest/test_sequence_walk_generators.py new file mode 100644 index 000000000..274104e15 --- /dev/null +++ b/tests/regrtest/test_sequence_walk_generators.py @@ -0,0 +1,385 @@ +"""`collections.abc.Sequence` iteration, and subscripts that only delegate. + +`Sequence.__iter__` is a generator that walks `self[0]`, `self[1]`, ... +until an `IndexError`. A step of that walk whose `__getitem__` answers +with no code to run is taken on the suspended frame, and `obj[key]` of a +class whose `__getitem__` is `return self.items[key]` reads the item with +no call. These tests pin that the generator is still a generator (its +frame, `send`, `throw`, `close`), that the walk sees every change made +between steps, and what each delegating subscript answers. +""" + +import inspect +import itertools +import unittest +from collections import UserList +from collections.abc import Sequence + +ROUNDS = 300 + + +class Wraps(Sequence): + def __init__(self, xs): + self.xs = xs + + def __len__(self): + return len(self.xs) + + def __getitem__(self, i): + return self.xs[i] + + +class Computed(Sequence): + def __init__(self, n): + self.n = n + + def __len__(self): + return self.n + + def __getitem__(self, i): + if i >= self.n or i < -self.n: + raise IndexError(i) + return i * i + + +class Fails(Sequence): + def __len__(self): + return 6 + + def __getitem__(self, i): + if i == 3: + raise ValueError("three") + if i >= 6: + raise IndexError + return i + + +class LenLies(Sequence): + def __init__(self): + self.xs = [1, 2, 3] + + def __len__(self): + return 10 + + def __getitem__(self, i): + return self.xs[i] + + +class Plain: + def __init__(self, xs): + self.xs = xs + + def __getitem__(self, i): + return self.xs[i] + + +WALK = """ +def walk(self): + i = 0 + try: + while True: + v = self[i] + yield v + i += 1 + except IndexError: + return +""" + + +def outcome(f): + try: + return f() + except Exception as e: + return type(e).__name__, str(e) + + +class Consumers(unittest.TestCase): + def check(self, make, want): + for _ in range(ROUNDS): + q = make() + self.assertEqual(list(q), want) + self.assertEqual([v for v in q], want) + self.assertEqual(tuple(iter(q)), tuple(want)) + self.assertEqual(list(reversed(q)), want[::-1]) + self.assertEqual(list(zip(q, q)), list(zip(want, want))) + self.assertEqual(list(enumerate(q)), list(enumerate(want))) + self.assertEqual(sum(1 for _ in q), len(want)) + self.assertEqual(sorted(q, key=repr), sorted(want, key=repr)) + self.assertEqual(None in q, None in want) + if want: + self.assertTrue(want[-1] in q) + self.assertEqual(q.index(want[-1]), want.index(want[-1])) + self.assertEqual(q.count(want[0]), want.count(want[0])) + + def test_a_wrapped_list_and_tuple(self): + for n in (0, 1, 2, 7, 40): + xs = list(range(n)) + self.check(lambda: Wraps(xs), xs) + self.check(lambda: Wraps(tuple("abcde")), list("abcde")) + + def test_a_computed_item(self): + for n in (0, 1, 7): + self.check(lambda: Computed(n), [i * i for i in range(n)]) + + def test_a_user_list(self): + for n in (0, 1, 7, 40): + self.check(lambda: UserList(range(n)), list(range(n))) + + def test_errors_and_a_length_that_lies(self): + for _ in range(ROUNDS): + self.assertEqual(outcome(lambda: list(Fails())), ("ValueError", "three")) + self.assertEqual( + outcome(lambda: [v for v in Fails()]), ("ValueError", "three") + ) + q = LenLies() + self.assertEqual((list(q), [v for v in q]), ([1, 2, 3], [1, 2, 3])) + self.assertEqual((3 in q, 9 in q), (True, False)) + + +class TheGeneratorItself(unittest.TestCase): + def test_its_frame_and_methods(self): + for _ in range(ROUNDS): + q = Wraps([10, 20, 30, 40, 50]) + it = iter(q) + self.assertEqual(type(it).__name__, "generator") + self.assertEqual((next(it), next(it)), (10, 20)) + local = it.gi_frame.f_locals + self.assertEqual((local["i"], local["v"]), (1, 20)) + self.assertEqual((next(it), it.send(None)), (30, 40)) + # Suspended on the walk's `yield v`, five lines into the body. + self.assertEqual(it.gi_frame.f_lineno - it.gi_code.co_firstlineno, 5) + q.xs.append(60) + self.assertEqual(list(it), [50, 60]) + + def test_its_states(self): + for _ in range(ROUNDS): + g = iter(Wraps([1, 2])) + self.assertEqual(inspect.getgeneratorstate(g), "GEN_CREATED") + next(g) + self.assertEqual(inspect.getgeneratorstate(g), "GEN_SUSPENDED") + self.assertIsNotNone(g.gi_frame) + next(g) + self.assertEqual(next(g, "end"), "end") + self.assertEqual(inspect.getgeneratorstate(g), "GEN_CLOSED") + self.assertIsNone(g.gi_frame) + g = iter(Wraps([])) + self.assertEqual(next(g, "empty"), "empty") + self.assertEqual(inspect.getgeneratorstate(g), "GEN_CLOSED") + + def test_partial_consumers(self): + for _ in range(ROUNDS): + g = iter(Wraps([5, 6, 7])) + self.assertEqual(list(itertools.islice(g, 2)), [5, 6]) + self.assertEqual((list(g), list(g)), ([7], [])) + g = iter(Wraps([5, 6, 7])) + self.assertEqual(list(zip(g, g)), [(5, 6)]) + + def test_changes_between_steps(self): + for _ in range(ROUNDS): + q = Wraps([10, 20, 30]) + it = iter(q) + next(it) + next(it) + q.xs[:] = [1] + self.assertEqual(list(it), []) + + def test_throw_and_close(self): + for _ in range(ROUNDS): + it = iter(Wraps([1, 2, 3])) + next(it) + with self.assertRaises(KeyError): + it.throw(KeyError("k")) + self.assertEqual(list(it), []) + it = iter(Wraps([1, 2, 3])) + next(it) + next(it) + it.close() + self.assertEqual(list(it), []) + # The body's handler takes a thrown `IndexError` as the end. + it = iter(Wraps([1, 2, 3])) + next(it) + with self.assertRaises(StopIteration): + it.throw(IndexError) + + def test_a_getitem_swapped_between_steps(self): + class Swapped(Sequence): + def __init__(self): + self.xs = [1, 2, 3, 4, 5, 6] + + def __len__(self): + return 6 + + def __getitem__(self, i): + return self.xs[i] + + plain = Swapped.__getitem__ + for _ in range(ROUNDS): + it = iter(Swapped()) + got = [next(it), next(it)] + Swapped.__getitem__ = lambda self, i: -self.xs[i] + got.append(next(it)) + Swapped.__getitem__ = plain + self.assertEqual(got + list(it), [1, 2, -3, 4, 5, 6]) + + def test_the_frame_lets_go_of_an_item_as_it_takes_the_next(self): + log = [] + + class Item: + def __init__(self, k): + self.k = k + + def __del__(self): + log.append(self.k) + + for _ in range(ROUNDS): + del log[:] + q = Wraps([Item(i) for i in range(4)]) + it = iter(q) + x = next(it) + x = next(it) + del q.xs[0] + log.append("a") + x = next(it) + log.append("b") + del x, it, q + self.assertEqual(log, [0, "a", "b", 3, 2, 1]) + + +class HandWrittenWalks(unittest.TestCase): + def test_the_same_loop_in_a_plain_function(self): + ns = {} + exec(WALK, ns) + walk = ns["walk"] + for _ in range(ROUNDS): + self.assertEqual(list(walk(Plain([1, 2, 3]))), [1, 2, 3]) + self.assertEqual([v for v in walk(Plain((4, 5)))], [4, 5]) + self.assertEqual(list(walk(Plain([]))), []) + # A receiver that is no instance at all. + self.assertEqual(list(walk([7, 8])), [7, 8]) + + def test_a_handler_that_names_another_class(self): + ns = {"IndexError": KeyError} + exec(WALK, ns) + walk = ns["walk"] + for _ in range(ROUNDS): + for drain in (list, lambda g: [v for v in g]): + self.assertEqual( + outcome(lambda: drain(walk(Plain([1, 2])))), + ("IndexError", "list index out of range"), + ) + + +class Dicts: + __slots__ = ("d",) + + def __init__(self): + self.d = {"a": 1, 2: "two", (1, 2): "pair"} + + def __getitem__(self, k): + return self.d[k] + + +class Tuples: + def __init__(self): + self.t = (10, 20, 30) + + def __getitem__(self, i): + return self.t[i] + + +class OnTheClass: + xs = [7, 8, 9] + + def __getitem__(self, i): + return self.xs[i] + + +class ThroughAProperty: + def __init__(self): + self._xs = [1, 2, 3] + self.reads = 0 + + @property + def xs(self): + self.reads += 1 + return self._xs + + def __getitem__(self, i): + return self.xs[i] + + +class Watched: + log = [] + + def __init__(self): + self.xs = [1, 2, 3] + + def __getattribute__(self, name): + if name == "xs": + Watched.log.append(name) + return object.__getattribute__(self, name) + + def __getitem__(self, i): + return self.xs[i] + + +class IntSub(int): + pass + + +def probe(o, keys): + got = [] + for k in keys: + try: + got.append(o[k]) + except Exception as e: + got.append(type(e).__name__) + return got + + +class DelegatingSubscripts(unittest.TestCase): + def test_a_dict_field(self): + for _ in range(ROUNDS): + self.assertEqual( + probe(Dicts(), ["a", 2, (1, 2), "zz", 3, 2.0, True, None, [1]]), + [1, "two", "pair", "KeyError", "KeyError", "two", "KeyError", "KeyError", "TypeError"], + ) + + def test_a_tuple_field(self): + keys = [0, -1, 2, 3, -4, True, 1.0, "a", slice(0, 2), IntSub(1), 10**30] + for _ in range(ROUNDS): + t = Tuples() + self.assertEqual( + probe(t, keys), + [10, 30, 30, "IndexError", "IndexError", 20, "TypeError", "TypeError", (10, 20), 20, "IndexError"], + ) + self.assertEqual(list(t), [10, 20, 30]) + + def test_a_class_attribute_and_its_instance_shadow(self): + for _ in range(ROUNDS): + c = OnTheClass() + self.assertEqual(probe(c, [0, 2, -3, 5]), [7, 9, 7, "IndexError"]) + self.assertEqual(list(c), [7, 8, 9]) + c.xs = "abc" + self.assertEqual(probe(c, [0, 2, 3]), ["a", "c", "IndexError"]) + self.assertEqual(list(c), ["a", "b", "c"]) + + def test_a_property_runs_at_every_read(self): + for _ in range(ROUNDS): + p = ThroughAProperty() + self.assertEqual(probe(p, [0, 1, 2, 9]), [1, 2, 3, "IndexError"]) + self.assertEqual(p.reads, 4) + self.assertEqual(list(p), [1, 2, 3]) + self.assertEqual(p.reads, 8) + + def test_a_class_getattribute_runs_at_every_read(self): + for _ in range(ROUNDS): + del Watched.log[:] + w = Watched() + self.assertEqual(probe(w, [0, 1, 7]), [1, 2, "IndexError"]) + self.assertEqual(list(w), [1, 2, 3]) + self.assertEqual(len(Watched.log), 7) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_set_add_leaf_hash.py b/tests/regrtest/test_set_add_leaf_hash.py new file mode 100644 index 000000000..f6e25d1ea --- /dev/null +++ b/tests/regrtest/test_set_add_leaf_hash.py @@ -0,0 +1,147 @@ +"""Compiled `set.add` and `dict.get` of an object whose Python `__hash__` +evaluates frameless hash it in place; the members, equal-but-distinct objects +(their `__eq__` decides), hash collisions, `__hash__` returning big or +negative values, and lookups through the general paths afterwards match +the general call.""" + +import unittest + + +class K: + def __init__(self, a, b): + self.a = a + self.b = b + self.eqs = 0 + + def key(self): + return (self.a, self.b) + + def __hash__(self): + return hash(self.key()) + + def __eq__(self, o): + self.eqs += 1 + return isinstance(o, K) and self.key() == o.key() + + +class Collide: + def __init__(self, v): + self.v = v + + def __hash__(self): + return 7 + + def __eq__(self, o): + return isinstance(o, Collide) and self.v == o.v + + +class Big: + def __init__(self, v): + self.v = v + + def __hash__(self): + return self.v + + def __eq__(self, o): + return isinstance(o, Big) and self.v == o.v + + +class SetAddLeafHash(unittest.TestCase): + def test_same_objects(self): + ks = [K(i, -i) for i in range(50)] + s = set() + for _ in range(100): + for k in ks: + s.add(k) + self.assertEqual(len(s), 50) + for k in ks: + self.assertIn(k, s) + self.assertIn(K(3, -3), s) + + def test_equal_distinct_objects(self): + s = set() + for i in range(3000): + s.add(K(i % 10, 0)) + self.assertEqual(len(s), 10) + self.assertEqual(sorted(k.a for k in s), list(range(10))) + + def test_collisions(self): + s = set() + for i in range(3000): + s.add(Collide(i % 5)) + self.assertEqual(len(s), 5) + self.assertEqual(sorted(c.v for c in s), [0, 1, 2, 3, 4]) + + def test_hash_values(self): + s = set() + vals = [0, -1, -2, 2**61 - 1, 2**61, -(2**70), 2**100 + 3] + for _ in range(500): + for v in vals: + s.add(Big(v)) + self.assertEqual(len(s), len(vals)) + for v in vals: + self.assertIn(Big(v), s) + self.assertEqual(hash(Big(-1)), -2) + d = {Big(v): v for v in vals} + for b in s: + self.assertEqual(d[b], b.v) + + def test_mixed_with_natives(self): + s = set() + for i in range(1000): + s.add(i % 3) + s.add(K(i % 3, 1)) + s.add("x") + self.assertEqual(len(s), 7) + s.discard(K(0, 1)) + self.assertEqual(len(s), 6) + self.assertNotIn(K(0, 1), s) + + def test_frozen_and_subclass_sets(self): + class S(set): + pass + + t = S() + for i in range(1000): + t.add(K(i % 4, 2)) + self.assertEqual(len(t), 4) + self.assertEqual(frozenset(t), frozenset(K(i, 2) for i in range(4))) + + +class DictGetLeafHash(unittest.TestCase): + def test_get(self): + ks = [K(i, 0) for i in range(20)] + d = {k: k.a for k in ks} + for _ in range(200): + for k in ks: + self.assertEqual(d.get(k), k.a) + self.assertEqual(d.get(k, -1), k.a) + missing = K(99, 0) + for _ in range(500): + self.assertIsNone(d.get(missing)) + self.assertEqual(d.get(missing, "dflt"), "dflt") + # An equal but distinct key: its `__eq__` decides. + for _ in range(500): + self.assertEqual(d.get(K(3, 0)), 3) + + def test_collisions_and_mixed(self): + d = {Collide(i): i for i in range(5)} + d[7] = "seven" + for _ in range(500): + self.assertEqual(d.get(Collide(2)), 2) + self.assertIsNone(d.get(Collide(9))) + self.assertEqual(d.get(7), "seven") + + def test_dict_subclass(self): + class D(dict): + pass + + k = K(1, 1) + d = D({k: "v"}) + for _ in range(500): + self.assertEqual(d.get(k), "v") + self.assertIsNone(d.get(K(2, 2))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_set_algebra_compiled.py b/tests/regrtest/test_set_algebra_compiled.py new file mode 100644 index 000000000..e5667b00f --- /dev/null +++ b/tests/regrtest/test_set_algebra_compiled.py @@ -0,0 +1,40 @@ +"""Set union, intersection, difference and symmetric difference in +compiled code. + +Plain keys are combined in place with the result kind following the left +operand; keys with a Python `__eq__` take the full path; in-place +operators mutate the left set. Items are heap objects too. Run it past +the compile threshold. +""" + + +class E: + eqs = 0 + + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + E.eqs += 1 + return isinstance(other, E) and self.v == other.v + + +s100 = set(range(100)) +words = {"a", "b", "c"} +for i in range(3000): + assert s100 & {1, 2, 300} == {1, 2} + assert {1, 2} | {2, 3} == {1, 2, 3} and {1, 2} - {2} == {1} and {1, 2} ^ {2, 3} == {1, 3} + r = frozenset({1, 2}) & {2, 3} + assert r == {2} and type(r) is frozenset + assert type({1} | frozenset({2})) is set + assert words & {"b", "z"} == {"b"} + E.eqs = 0 + assert {E(1), E(2)} & {E(2), E(3)} == {E(2)} + assert E.eqs > 0 + x = {1, 2} + y = x + x &= {2} + assert y is x and x == {2} diff --git a/tests/regrtest/test_set_algebra_on_large_and_small.py b/tests/regrtest/test_set_algebra_on_large_and_small.py new file mode 100644 index 000000000..d107af103 --- /dev/null +++ b/tests/regrtest/test_set_algebra_on_large_and_small.py @@ -0,0 +1,375 @@ +"""Set algebra between a large operand and a small one, and between kinds. + +Every operator, comparison and method of `set` and `frozenset`, and the +set operators of a dict's keys view, must give what a plain model gives +(lists searched with `==`), keep the elements CPython keeps where equal +keys differ (`1` and `1.0`), give the result its type, change the +receiver itself for the in-place forms, and take time that depends on the +operand it has to walk, not on the larger one: `small <= big`, +`big -= small`, `big.intersection(small)` and `small & d.keys()` cost the +same against a set of a thousand keys as against one of a hundred +thousand. +""" + +import time +import unittest + + +def model(keys): + out = [] + for k in keys: + if not any(k == x for x in out): + out.append(k) + return out + + +def same(test, got, want, kind=None): + want = model(want) + test.assertEqual(len(got), len(want), (got, want)) + for k in want: + test.assertIn(k, got) + if kind is not None: + test.assertIs(type(got), kind) + + +POOLS = ( + [1, 2, 3, 4, 5, 6, 7, 8], + [2.0, 4.0, 9.5, "a"], + [True, 0, "a", "b", (1, 2)], + [], + list(range(40)), + ["k%d" % i for i in range(30)] + [3, 4.0], + [(i, str(i)) for i in range(12)] + [None], +) + + +class Odd: + """A key that compares through Python (equal to others of its value).""" + + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) & 7 + + def __eq__(self, other): + return isinstance(other, Odd) and self.v == other.v + + def __repr__(self): + return "Odd(%r)" % (self.v,) + + +ODD_POOLS = ([Odd(i) for i in range(12)], [Odd(i) for i in range(6, 20)] + [1, "a"], [Odd(3)]) + + +class AlgebraTests(unittest.TestCase): + def check_pair(self, xs, ys): + for make_a in (set, frozenset): + for make_b in (set, frozenset): + a, b = make_a(xs), make_b(ys) + in_b = lambda k: any(k == y for y in ys) + in_a = lambda k: any(k == x for x in xs) + same(self, a & b, [k for k in xs if in_b(k)], make_a) + same(self, a | b, list(xs) + list(ys), make_a) + same(self, a - b, [k for k in xs if not in_b(k)], make_a) + same(self, a ^ b, [k for k in xs if not in_b(k)] + [k for k in ys if not in_a(k)], make_a) + same(self, a.intersection(b), [k for k in xs if in_b(k)], make_a) + same(self, a.union(b), list(xs) + list(ys), make_a) + same(self, a.difference(b), [k for k in xs if not in_b(k)], make_a) + same(self, a.symmetric_difference(b), (a - b) | (b - a), make_a) + same(self, a.intersection(list(ys)), [k for k in xs if in_b(k)], make_a) + same(self, a.difference(tuple(ys)), [k for k in xs if not in_b(k)], make_a) + sub = all(in_b(k) for k in model(xs)) + sup = all(in_a(k) for k in model(ys)) + self.assertEqual(a <= b, sub) + self.assertEqual(a >= b, sup) + self.assertEqual(a < b, sub and len(a) < len(b)) + self.assertEqual(a > b, sup and len(a) > len(b)) + self.assertEqual(a == b, sub and sup) + self.assertEqual(a != b, not (sub and sup)) + self.assertEqual(a.issubset(b), sub) + self.assertEqual(a.issuperset(b), sup) + self.assertEqual(a.issubset(list(ys)), sub) + self.assertEqual(a.issuperset(list(ys)), sup) + self.assertEqual(a.isdisjoint(b), not any(in_b(k) for k in xs)) + self.assertEqual(len(a), len(model(xs))) + self.assertEqual(len(b), len(model(ys))) + + def test_every_pair_of_pools(self): + for xs in POOLS: + for ys in POOLS: + self.check_pair(xs, ys) + + def test_keys_compared_through_python(self): + for xs in ODD_POOLS: + for ys in ODD_POOLS: + self.check_pair(xs, ys) + + def test_in_place_forms_change_the_receiver(self): + for xs in POOLS + ODD_POOLS: + for ys in POOLS + ODD_POOLS: + for make_b in (set, frozenset, list, tuple): + ops = ( + ("difference_update", lambda a, b: a - set(b)), + ("intersection_update", lambda a, b: a & set(b)), + ("symmetric_difference_update", lambda a, b: a ^ set(b)), + ("update", lambda a, b: a | set(b)), + ) + for name, ref in ops: + a = set(xs) + alias = a + want = ref(set(xs), make_b(ys)) + self.assertIsNone(getattr(a, name)(make_b(ys))) + self.assertIs(a, alias) + self.assertEqual(a, want, (name, xs, ys)) + for make_b in (set, frozenset): + a = set(xs) + alias = a + a -= make_b(ys) + self.assertIs(a, alias) + self.assertEqual(a, set(xs) - set(ys)) + a = set(xs) + alias = a + a &= make_b(ys) + self.assertIs(a, alias) + self.assertEqual(a, set(xs) & set(ys)) + a = set(xs) + alias = a + a ^= make_b(ys) + self.assertIs(a, alias) + self.assertEqual(a, set(xs) ^ set(ys)) + a = set(xs) + alias = a + a |= make_b(ys) + self.assertIs(a, alias) + self.assertEqual(a, set(xs) | set(ys)) + + def test_a_set_with_itself(self): + for xs in POOLS + ODD_POOLS: + a = set(xs) + self.assertEqual(a & a, a) + self.assertEqual(a | a, a) + self.assertEqual(a - a, set()) + self.assertEqual(a ^ a, set()) + self.assertTrue(a <= a and a >= a and a == a and not a < a) + b = set(xs) + b |= b + b &= b + self.assertEqual(b, a) + b.intersection_update(b) + b.update(b) + self.assertEqual(b, a) + b ^= b + self.assertEqual(b, set()) + b = set(xs) + b -= b + self.assertEqual(b, set()) + b = set(xs) + b.difference_update(b) + self.assertEqual(b, set()) + b = set(xs) + b.symmetric_difference_update(b) + self.assertEqual(b, set()) + + def test_which_equal_element_is_kept(self): + kinds = lambda s: sorted(type(k).__name__ for k in s) + self.assertEqual(kinds({1, 2} & {1.0, 2.0, 3}), ["int", "int"]) + self.assertEqual(kinds({1.0, 2.0, 3} & {1, 2}), ["int", "int"]) + self.assertEqual(kinds({1, 2} & {1.0, 2.0}), ["float", "float"]) + self.assertEqual(kinds({1, 2}.intersection({1.0, 2.0})), ["float", "float"]) + self.assertEqual(kinds({1.0, 2.0}.intersection({1, 2})), ["int", "int"]) + self.assertEqual(kinds({1, 2}.intersection([1.0, 2.0, 2.0])), ["float", "float"]) + self.assertEqual(kinds({1, 2} | {1.0, 5}), ["int", "int", "int"]) + self.assertEqual(kinds({1, 2, 3} - {2.0}), ["int", "int"]) + self.assertEqual(kinds({1, 2} ^ {2.0, 3.5}), ["float", "int"]) + s = {1, 2} + s |= {1.0, 2.0} + self.assertEqual(kinds(s), ["int", "int"]) + s &= {1.0, 2.0} + self.assertEqual(kinds(s), ["float", "float"]) + s = {1, 2, 3} + s.intersection_update({1.0, 2.0}) + self.assertEqual(kinds(s), ["float", "float"]) + s = {1, 2} + s.intersection_update({1.0, 2.0, 5}) + self.assertEqual(kinds(s), ["int", "int"]) + s = {1, 2} + s ^= {2.0, 7} + self.assertEqual(kinds(s), ["int", "int"]) + s -= {1.0} + self.assertEqual(kinds(s), ["int"]) + + def test_changes_from_inside_a_comparison(self): + class Meddler: + def __init__(self, target): + self.target = target + + def __hash__(self): + return hash(1) + + def __eq__(self, other): + self.target.clear() + return False + + for op in ( + lambda a, b: a & b, + lambda a, b: a | b, + lambda a, b: a - b, + lambda a, b: a ^ b, + lambda a, b: a <= b, + lambda a, b: a == b, + lambda a, b: a.isdisjoint(b), + lambda a, b: a.issubset(b), + lambda a, b: a.intersection(b), + ): + a = {1, 2, 3} + b = {Meddler(a), 5} + try: + op(a, b) + except RuntimeError: + pass + a = {1, 2, 3} + b = {Meddler(a), 5} + try: + op(b, a) + except RuntimeError: + pass + + def test_errors(self): + with self.assertRaises(TypeError): + {1} & [1] + with self.assertRaises(TypeError): + {1} <= [1] + with self.assertRaises(TypeError): + {1}.issubset(5) + with self.assertRaises(TypeError): + {1}.intersection([[]]) + with self.assertRaises(AttributeError): + frozenset([1]).difference_update({1}) + f = frozenset([1, 2]) + g = f + g -= {1} + self.assertEqual(f, frozenset([1, 2])) + self.assertEqual(g, frozenset([2])) + + +class KeysViewTests(unittest.TestCase): + def test_against_sets_views_and_iterables(self): + for xs in POOLS: + for ys in POOLS: + d = dict.fromkeys(xs) + e = dict.fromkeys(ys) + in_y = lambda k: any(k == y for y in ys) + in_x = lambda k: any(k == x for x in xs) + for other in (set(ys), frozenset(ys), e.keys(), list(ys)): + same(self, d.keys() & other, [k for k in xs if in_y(k)], set) + same(self, d.keys() | other, list(xs) + list(ys), set) + same(self, d.keys() - other, [k for k in xs if not in_y(k)], set) + same(self, d.keys() ^ other, [k for k in xs if not in_y(k)] + [k for k in ys if not in_x(k)], set) + for other in (set(ys), frozenset(ys)): + same(self, other & d.keys(), [k for k in xs if in_y(k)], set) + same(self, other | d.keys(), list(xs) + list(ys), set) + same(self, other - d.keys(), [k for k in ys if not in_x(k)], set) + same(self, other ^ d.keys(), [k for k in xs if not in_y(k)] + [k for k in ys if not in_x(k)], set) + self.assertEqual(len(d), len(model(xs))) + + def test_which_equal_key_is_kept(self): + kinds = lambda s: sorted(type(k).__name__ for k in s) + d = {1: 0, 2: 0, 3.0: 0} + self.assertEqual(kinds(d.keys() & {1.0, 2.0, 3, 9}), ["float", "int", "int"]) + self.assertEqual(kinds(d.keys() & {1.0, 2.0}), ["float", "float"]) + self.assertEqual(kinds(d.keys() & frozenset([1.0, 2.0, 3, 9, 10])), ["float", "float", "int"]) + self.assertEqual(kinds({1.0, 2.0, 3, 9} & d.keys()), ["float", "int", "int"]) + self.assertEqual(kinds({1.0} & d.keys()), ["float"]) + self.assertEqual(kinds(d.keys() & {1.0: 0, 2.0: 0}.keys()), ["float", "float"]) + self.assertEqual(kinds({1.0: 0, 2.0: 0, 3: 0}.keys() & d.keys()), ["float", "int", "int"]) + self.assertEqual(kinds(d.keys() | {1.0, 4}), ["float", "int", "int", "int"]) + self.assertEqual(kinds({1.0, 4} | d.keys()), ["float", "float", "int", "int"]) + + +class CostTests(unittest.TestCase): + """What an operation costs follows the operand it must walk.""" + + def per_call(self, fn, reps=400): + best = None + for _ in range(5): + t0 = time.perf_counter() + for _ in range(reps): + fn() + dt = (time.perf_counter() - t0) / reps + best = dt if best is None else min(best, dt) + return best + + def flat(self, make): + # (A hundred times the keys cost a hundred times as much when the + # large operand was copied or walked. Allow eight, far past noise.) + for fn in make(1000): + fn() + small = [self.per_call(fn) for fn in make(1000)] + large = [self.per_call(fn) for fn in make(100_000)] + for i, (s, l) in enumerate(zip(small, large)): + self.assertLess(l, 8 * s + 4e-6, (i, s, l)) + + def test_small_against_large_sets(self): + def make(n): + big = set(range(n)) + froze = frozenset(big) + small = {1, 2, n + 5} + few = [1, 2, 3] + + def restore(): + big.update(small) + big.discard(n + 5) + + def in_place(): + big.difference_update(small) + big.symmetric_difference_update(small) + big.symmetric_difference_update(small) + big.update(small) + big.discard(n + 5) + x = big + x -= small + x |= small + x.discard(n + 5) + + return ( + lambda: small <= big, + lambda: big >= small, + lambda: small < froze, + lambda: small == big, + lambda: big != small, + lambda: big & small, + lambda: small & big, + lambda: small - big, + lambda: big.intersection(small), + lambda: small.intersection(big), + lambda: small.issubset(big), + lambda: big.issuperset(small), + lambda: big.issuperset(few), + lambda: big.isdisjoint(small), + lambda: small.isdisjoint(froze), + lambda: big.intersection(few), + lambda: big.difference_update(few) or big.update(few), + in_place, + restore, + ) + + self.flat(make) + + def test_small_set_against_a_large_dicts_keys(self): + def make(n): + d = dict.fromkeys(range(n)) + small = {1, 2, n + 5} + return ( + lambda: d.keys() & small, + lambda: small & d.keys(), + lambda: d.keys() >= small, + lambda: small <= d.keys(), + lambda: d.keys().isdisjoint(small), + ) + + self.flat(make) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_set_deferred_ops.py b/tests/regrtest/test_set_deferred_ops.py new file mode 100644 index 000000000..eafcd8421 --- /dev/null +++ b/tests/regrtest/test_set_deferred_ops.py @@ -0,0 +1,55 @@ +"""A set mutated from an element's `__eq__` while another operation holds it. + +The mutation waits for the set's next in-place change, which applies it +first. It never reaches another set: a set that dies with a mutation +pending drops it, so a new set at the same address keeps everything added +to it. +""" + +armed = False + + +class Bad: + def __hash__(self): + return 1 + + def __eq__(self, other): + if armed: + victim.clear() + return True + + +class K: + def __init__(self, v): + self.v = v + + def __hash__(self): + return self.v + + +def defer_clear(): + global armed, victim + armed = False + victim = {Bad(), Bad()} + armed = True + try: + Bad() in victim + finally: + armed = False + + +for _ in range(200): + defer_clear() + k = K(7) + victim.add(k) + assert victim == {k}, victim + +for _ in range(200): + defer_clear() + victim = None + for j in range(50): + f = set() + f.add(K(j)) + f.add(K(-j - 1)) + assert len(f) == 2, f +print("ok") diff --git a/tests/regrtest/test_set_discard_and_remove_keys.py b/tests/regrtest/test_set_discard_and_remove_keys.py new file mode 100644 index 000000000..cd3bbc867 --- /dev/null +++ b/tests/regrtest/test_set_discard_and_remove_keys.py @@ -0,0 +1,151 @@ +"""`set.discard` and `set.remove` by the kinds of key programs use. + +A `str`, an `int` or a `float` that only meets stored keys of its own kind +is found and removed with one probe; anything else (a `bool` beside an +`int`, an `int` beside an equal `float`, a key with its own `__eq__`, a +set being changed from inside a comparison) takes the general path. Both +must leave the same set and raise the same errors, which a model kept in +a dict checks through a long mixed run. +""" + +import unittest + +ROUNDS = 40_000 + + +class Rng: + def __init__(self, seed): + self.state = seed + + def below(self, n): + self.state = (self.state * 6364136223846793005 + 1442695040888963407) % (1 << 64) + return (self.state >> 33) % n + + +class Key: + """Equal to the int it wraps, through Python.""" + + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return (other.v if isinstance(other, Key) else other) == self.v + + +def keys_for(i): + return (i & 127, str(i & 63), (i & 31) + 0.5, float(i & 15), bool(i & 1), (i & 7, "t")) + + +class SetRemovalTests(unittest.TestCase): + def test_mixed_keys_against_a_model(self): + rng = Rng(11) + s = set() + model = {} + misses = 0 + for i in range(ROUNDS): + pool = keys_for(rng.below(1 << 20)) + k = pool[rng.below(len(pool))] + roll = rng.below(4) + if roll < 2: + s.add(k) + model.setdefault(k, None) + elif roll == 2: + s.discard(k) + model.pop(k, None) + else: + try: + s.remove(k) + removed = True + except KeyError as e: + removed = False + self.assertIs(e.args[0], k) + misses += 1 + self.assertEqual(removed, k in model) + model.pop(k, None) + if i % 997 == 0: + self.assertEqual(len(s), len(model)) + self.assertEqual(s, set(model)) + self.assertEqual(s, set(model)) + self.assertGreater(misses, 100) + + def test_equal_keys_of_other_kinds(self): + for stored, probe in ((1, True), (True, 1), (1, 1.0), (2.0, 2), (0, False), (0.0, 0), (3, Key(3))): + s = {stored, "other"} + s.discard(probe) + self.assertEqual(s, {"other"}, (stored, probe)) + s = {stored, "other"} + s.remove(probe) + self.assertEqual(s, {"other"}, (stored, probe)) + s = {Key(5), Key(6), 7} + for i in range(ROUNDS // 100): + s.discard(5) + self.assertEqual(len(s), 2) + s.add(Key(5)) + s.discard(7) + self.assertEqual(len(s), 2) + + def test_hot_loop_of_ints_and_strs(self): + s = set(range(64)) + names = {"n%d" % i for i in range(64)} + for i in range(ROUNDS): + s.discard(i & 127) + s.add((i * 7) & 127) + names.discard("n%d" % (i & 127)) + names.add("n%d" % ((i * 5) & 63)) + want = set(range(64)) + want_names = {"n%d" % i for i in range(64)} + for i in range(ROUNDS): + want -= {i & 127} + want |= {(i * 7) & 127} + want_names -= {"n%d" % (i & 127)} + want_names |= {"n%d" % ((i * 5) & 63)} + self.assertEqual(s, want) + self.assertEqual(names, want_names) + + def test_errors(self): + s = {1, 2} + with self.assertRaises(TypeError): + s.discard([1]) + with self.assertRaises(TypeError): + s.remove({}) + with self.assertRaises(KeyError): + s.remove(3) + with self.assertRaises(TypeError): + s.discard() + self.assertEqual(s, {1, 2}) + f = frozenset(s) + self.assertFalse(hasattr(f, "discard")) + + def test_discard_during_iteration_is_noticed(self): + s = set(range(100)) + with self.assertRaises(RuntimeError): + for x in s: + s.discard(x) + s = set(range(100)) + for x in s: + s.discard(1000 + x) + self.assertEqual(len(s), 100) + + def test_change_from_inside_a_comparison(self): + class Meddler: + def __init__(self, target): + self.target = target + + def __hash__(self): + return hash(1) + + def __eq__(self, other): + self.target.discard(2) + self.target.add(99) + return False + + s = {1, 2, 3} + s.discard(Meddler(s)) + self.assertEqual(s, {1, 3, 99}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_set_method_leaf_halves.py b/tests/regrtest/test_set_method_leaf_halves.py new file mode 100644 index 000000000..8a549eada --- /dev/null +++ b/tests/regrtest/test_set_method_leaf_halves.py @@ -0,0 +1,183 @@ +"""Set methods with set and frozenset arguments run in place from compiled +loops (issubset, issuperset, isdisjoint, union of several sets, +intersection, difference, symmetric_difference), and enumerate over a str +or bytes leaves compiled code only at the end: results, kinds and orders +matching CPython, keys whose __eq__ runs Python, subclass receivers, +non-set arguments, and an argument changed while the loop runs. Also +list(map(f, xs, ys)) of a builtin over two cursors, and min/max of two +ints or floats.""" + +import unittest + +S1 = set(range(10)) +S2 = set(range(5, 15)) +F1 = frozenset(range(3)) + + +def tests(n, a, b): + out = None + for i in range(n): + out = (a.issubset(b), a.issuperset(b), a.isdisjoint(b)) + return out + + +def algebra(n, a, *others): + out = None + for i in range(n): + out = ( + a.union(*others), + a.intersection(others[0]), + a.difference(others[0]), + a.symmetric_difference(others[0]), + ) + return out + + +class Key: + calls = 0 + + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + Key.calls += 1 + return isinstance(other, Key) and self.v == other.v + + +def enum_pairs(n, s, start): + out = [] + for i in range(n): + out = [(j, c) for j, c in enumerate(s, start)] + for j, c in enumerate(s, start): + pass + return out + + +class SetLeafTests(unittest.TestCase): + def test_tests(self): + for n in (1, 300): + self.assertEqual(tests(n, {1, 2}, S1), (True, False, False)) + self.assertEqual(tests(n, S1, {1, 2}), (False, True, False)) + self.assertEqual(tests(n, F1, frozenset({7})), (False, False, True)) + self.assertEqual(tests(n, set(), S1), (True, False, True)) + self.assertEqual(tests(n, {1, 2}, [1, 2, 3]), (True, False, False)) + + def test_algebra(self): + for n in (1, 300): + u, i, d, x = algebra(n, S1, S2, {99}) + self.assertEqual(u, set(range(15)) | {99}) + self.assertEqual(list(u)[:10], list(S1)) + self.assertEqual(i, set(range(5, 10))) + self.assertEqual(d, set(range(5))) + self.assertEqual(x, set(range(5)) | set(range(10, 15))) + self.assertIs(type(u), set) + fu, fi, fd, fx = algebra(n, F1, {2, 3}, frozenset({4})) + self.assertEqual(fu, frozenset({0, 1, 2, 3, 4})) + self.assertEqual((fi, fd, fx), ({2}, {0, 1}, {0, 1, 3})) + for r in (fu, fi, fd, fx): + self.assertIs(type(r), frozenset) + lu = algebra(n, {1}, [2, 3], (4,))[0] + self.assertEqual(lu, {1, 2, 3, 4}) + + def test_python_keys(self): + a = {Key(1), Key(2)} + b = {Key(1), Key(2), Key(3)} + Key.calls = 0 + self.assertEqual(tests(300, a, b), (True, False, False)) + self.assertGreater(Key.calls, 0) + u = algebra(300, a, b, {Key(4)})[0] + self.assertEqual(sorted(k.v for k in u), [1, 2, 3, 4]) + + def test_subclass_receiver(self): + class S(set): + pass + + u = algebra(300, S({1, 2}), {3}, {4})[0] + self.assertEqual(u, {1, 2, 3, 4}) + self.assertIs(type(u), set) + self.assertEqual(tests(300, S({1}), {1, 2}), (True, False, False)) + + def test_argument_changes(self): + a = {1, 2} + b = {1} + seen = [] + for i in range(300): + seen.append(a.issubset(b)) + if i == 150: + b.add(2) + self.assertEqual(seen, [False] * 151 + [True] * 149) + + def test_set_copies(self): + f = frozenset({1, 2}) + k = {Key(1), Key(2)} + for i in range(300): + a = set(S1) + b = frozenset(S1) + c = frozenset(f) + d = set(f) + e = set(k) + self.assertEqual(a, S1) + self.assertIsNot(a, S1) + self.assertEqual(list(a), list(S1)) + self.assertIs(type(b), frozenset) + self.assertEqual(b, S1) + self.assertIs(c, f) + self.assertIs(type(d), set) + self.assertEqual(d, {1, 2}) + self.assertEqual(len(e), 2) + a.add(99) + self.assertNotIn(99, S1) + + def test_map_two_sources(self): + a = [1, 5, 3] + b = [4, 2, 6, 9] + for i in range(300): + r = list(map(max, a, b)) + m = list(map(min, b, a)) + self.assertEqual(r, [4, 5, 6]) + self.assertEqual(m, [1, 2, 3]) + x, y = iter(b), iter(a) + self.assertEqual(list(map(max, x, y)), [4, 5, 6]) + self.assertEqual(list(x), []) + x, y = iter(a), iter(b) + self.assertEqual(list(map(max, x, y)), [4, 5, 6]) + self.assertEqual(list(y), [9]) + with self.assertRaises(ValueError): + list(map(max, a, b, strict=True)) + with self.assertRaises(TypeError): + list(map(max, [1, "a"], [2, 3])) + self.assertEqual(list(map(pow, [2, 3], (3, 2))), [8, 9]) + self.assertEqual(list(map(max, ["b", "a"], ["a", "c"])), ["b", "c"]) + + def test_min_max_pairs(self): + nan = float("nan") + for i in range(300): + r = (max(1, 2), min(1, 2), max(2.5, 1.5), min(-0.0, 0.0), max(0.0, -0.0)) + s = (max(nan, 1.0), max(1.0, nan), min(nan, 1.0), max(True, 1), max(1, True)) + self.assertEqual(r[:3], (2, 1, 2.5)) + self.assertEqual(str(r[3]), "-0.0") + self.assertEqual(str(r[4]), "0.0") + self.assertTrue(s[0] != s[0]) + self.assertEqual(s[1], 1.0) + self.assertTrue(s[2] != s[2]) + self.assertIs(s[3], True) + self.assertEqual(s[4], 1) + self.assertIsNot(s[4], True) + + def test_enumerate_str_and_bytes(self): + for n in (1, 300): + self.assertEqual(enum_pairs(n, "abc", 1), [(1, "a"), (2, "b"), (3, "c")]) + self.assertEqual(enum_pairs(n, "", 0), []) + self.assertEqual(enum_pairs(n, b"xy", 5), [(5, 120), (6, 121)]) + self.assertEqual(enum_pairs(n, "hé\U0001f600", 0), [(0, "h"), (1, "é"), (2, "\U0001f600")]) + it = iter("abcd") + next(it) + self.assertEqual(list(enumerate(it)), [(0, "b"), (1, "c"), (2, "d")]) + self.assertEqual(list(it), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_set_unpacking_and_truth_tests.py b/tests/regrtest/test_set_unpacking_and_truth_tests.py new file mode 100644 index 000000000..6eb9aa0c4 --- /dev/null +++ b/tests/regrtest/test_set_unpacking_and_truth_tests.py @@ -0,0 +1,220 @@ +"""Set displays that unpack a sequence, and truth tests through `__bool__`. + +`{*xs, x}` inserts a list's or tuple's items in compiled code when they +hash natively, and `any`, `all`, `filter(None, ...)` and `bool()` evaluate +a plain class's small `__bool__` in place. These tests pin the results for +every kind of source and item, the errors, and what a `__bool__` may do +that the shortcut must leave to the full protocol. +""" + +import unittest + +N = 3000 + + +class Key: + calls = [] + + def __init__(self, v): + self.v = v + + def __hash__(self): + Key.calls.append(("hash", self.v)) + return hash(self.v) + + def __eq__(self, other): + Key.calls.append(("eq", self.v)) + return isinstance(other, Key) and self.v == other.v + + +def members(s): + return sorted(s, key=repr) + + +class SetDisplays(unittest.TestCase): + def test_lists_and_tuples(self): + xs = [1, 2, 3, 2, "a", (1, 2), None, 2.5, b"b"] + t = (4, 5, 4) + for i in range(N): + a = {*xs, i} + b = {i, *xs} + c = {*xs, *t, i} + d = {*xs} + e = {*t, *xs, *t} + want = set(xs) + self.assertEqual(a, want | {N - 1}) + self.assertEqual(b, want | {N - 1}) + self.assertEqual(c, want | {4, 5, N - 1}) + self.assertEqual(d, want) + self.assertEqual(e, want | {4, 5}) + self.assertEqual(len(d), 8) + self.assertIs(type(a), set) + + def test_first_of_equal_keys_stays(self): + for _ in range(200): + s = {*[1, 1.0, True], *(0, 0.0, False)} + self.assertEqual(members(s), [0, 1]) + self.assertEqual([type(x) for x in members(s)], [int, int]) + s = {*[True, 1], 1.0} + self.assertEqual([type(x) for x in s], [bool]) + s = {*("ab", "ab"), "".join(["a", "b"])} + self.assertEqual(s, {"ab"}) + + def test_other_sources(self): + def gen(): + yield 1 + yield 2 + + d = {"k": 1, "j": 2} + for i in range(300): + s = {*{1, 2}, *frozenset((3,)), *gen(), *d, *"xy", *range(3), *d.values(), i} + self.assertEqual(s, {1, 2, 3, "k", "j", "x", "y", 0, 299}) + self.assertEqual({*[], *()}, set()) + self.assertEqual({*[[]][:0]}, set()) + + def test_items_that_run_code_or_fail(self): + keys = [Key(1), Key(2), Key(1)] + for _ in range(50): + Key.calls.clear() + s = {*keys, Key(2)} + self.assertEqual(len(s), 2) + self.assertEqual([c for c in Key.calls if c[0] == "hash"], [("hash", 1), ("hash", 2), ("hash", 1), ("hash", 2)]) + for bad in ([[1]], [1, {}], ([], 2), [(1, [2])]): + with self.assertRaises(TypeError): + {*bad, 0} + with self.assertRaises(TypeError): + {*5} + nan = float("nan") + s = {*[nan, nan], float("nan")} + self.assertEqual(len(s), 2) + + def test_source_is_left_alone(self): + xs = [3, 1, 2] + for i in range(300): + s = {*xs, i} + s.add("extra") + self.assertEqual(xs, [3, 1, 2]) + ys = [1] + s = {*ys, *ys, *ys} + ys.append(2) + self.assertEqual(s, {1}) + + +class Flag: + def __init__(self, on): + self.on = on + + def __bool__(self): + return self.on + + +class Sized: + def __init__(self, n): + self.n = n + + def __len__(self): + return self.n + + +class Counted: + seen = 0 + + def __init__(self, on): + self.on = on + + def __bool__(self): + Counted.seen += 1 + return self.on + + +class TruthTests(unittest.TestCase): + def test_native_consumers(self): + flags = [Flag(i % 3 == 0) for i in range(60)] + for _ in range(200): + self.assertTrue(any(flags)) + self.assertFalse(all(flags)) + self.assertEqual(len(list(filter(None, flags))), 20) + self.assertEqual(sum(map(bool, flags)), 20) + self.assertEqual([bool(f) for f in flags[:4]], [True, False, False, True]) + self.assertEqual(sum(1 for f in flags if f), 20) + self.assertEqual(sum(1 for f in flags if not f), 40) + self.assertFalse(any([Flag(False)] * 5)) + self.assertTrue(all([Flag(True)] * 5)) + + def test_every_call_is_made_once(self): + items = [Counted(False)] * 10 + [Counted(True)] + [Counted(False)] * 10 + for _ in range(300): + Counted.seen = 0 + self.assertTrue(any(items)) + self.assertEqual(Counted.seen, 11) + Counted.seen = 0 + self.assertEqual(len(list(filter(None, items))), 1) + self.assertEqual(Counted.seen, 21) + + def test_answers_that_are_not_bools(self): + class Wrong: + def __init__(self, v): + self.v = v + + def __bool__(self): + return self.v + + for _ in range(100): + self.assertTrue(any([Wrong(True)])) + for bad in (1, 0, "x", None, 1.0): + with self.assertRaises(TypeError): + bool(Wrong(bad)) + with self.assertRaises(TypeError): + any([Wrong(bad)]) + + def test_protocol_cases(self): + class Raises: + def __bool__(self): + raise KeyError("no") + + class Blocked: + __bool__ = None + + class Both: + def __bool__(self): + return False + + def __len__(self): + return 5 + + class IntFlag(int): + def __bool__(self): + return False + + class Plain: + pass + + shadowed = Flag(False) + shadowed.__bool__ = lambda: True + for _ in range(100): + with self.assertRaises(KeyError): + any([Raises()]) + with self.assertRaises(TypeError): + bool(Blocked()) + self.assertFalse(any([Both(), Sized(0), IntFlag(7), shadowed, Flag(False)])) + self.assertTrue(all([Sized(2), Plain(), Flag(True), object()])) + self.assertEqual(list(filter(None, [Sized(0), Sized(1)]))[0].n, 1) + + def test_class_changes_between_tests(self): + class Shifty: + def __bool__(self): + return True + + items = [Shifty() for _ in range(20)] + for _ in range(100): + self.assertTrue(all(items)) + Shifty.__bool__ = lambda self: False + self.assertFalse(any(items)) + del Shifty.__bool__ + self.assertTrue(all(items)) + Shifty.__len__ = lambda self: 0 + self.assertFalse(any(items)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_set_update_leaf.py b/tests/regrtest/test_set_update_leaf.py new file mode 100644 index 000000000..c05e51a4e --- /dev/null +++ b/tests/regrtest/test_set_update_leaf.py @@ -0,0 +1,85 @@ +"""`s.add(x)` and `s.update(...)` of plain sets in compiled code. + +Values that hash and compare natively go straight in: `True` against `1`, +a NaN, strings and bytes, from tuples, lists, sets and frozensets, keep +CPython's results. Values with a Python `__eq__`, `s.update(s)`, other +iterables, a live iterator over the set, and a mutation another operation +deferred behave as in CPython. Run it past the compile threshold. +""" + +import math + + +class K: + def __init__(self, v): + self.v = v + + def __hash__(self): + return 1 + + def __eq__(self, other): + return isinstance(other, K) and self.v == other.v + + +def grow(s, *srcs): + s.update(*srcs) + return s + + +def add_all(s, xs): + for x in xs: + s.add(x) + return s + + +N = 3000 +nan = float("nan") +for i in range(N): + s = grow(set(), (1, 2), [2, "a"], {b"x"}, frozenset({3.5, None})) + assert s == {1, 2, "a", b"x", 3.5, None} + t = grow({1}, (True, 1.0)) + assert t == {1} and type(next(iter(t))) is int + assert len(grow(set(), (nan, nan))) == 1 + assert grow({1}, {1, 2}, ()) == {1, 2} + same = {1, 2} + assert grow(same, same) == {1, 2} + assert len(grow(set(), [K(1), K(1), K(2)])) == 2 + assert grow(set(), range(3), "ab") == {0, 1, 2, "a", "b"} + assert add_all(set(), [True, 1, "x", "x", None]) == {True, "x", None} +s = {1, 2} +it = iter(s) +next(it) +grow(s, (3,)) +try: + next(it) +except RuntimeError: + pass +else: + raise AssertionError("set grew during iteration") +try: + grow(set(), [[1]]) +except TypeError: + pass +else: + raise AssertionError("unhashable") + +armed = False + + +class Bad: + def __hash__(self): + return 1 + + def __eq__(self, other): + if armed: + victim.clear() + return True + + +victim = {Bad()} +armed = True +Bad() in victim +armed = False +grow(victim, (7,)) +assert victim == {7}, victim +print("ok") diff --git a/tests/regrtest/test_setattr_builtin_replace.py b/tests/regrtest/test_setattr_builtin_replace.py new file mode 100644 index 000000000..950bd8106 --- /dev/null +++ b/tests/regrtest/test_setattr_builtin_replace.py @@ -0,0 +1,68 @@ +"""`setattr(obj, name, value)` replacing an attribute already there. + +The builtin replaces an existing instance attribute at its position; +new attributes, re-added ones, `__dict__` order, finalizers of replaced +values, and descriptors behave as before. +""" + +import unittest + +N = 3000 + + +class O: + def __init__(self): + self.x = 1 + self.y = 2 + + +class Dying: + deaths = 0 + + def __del__(self): + Dying.deaths += 1 + + +class P: + @property + def v(self): + return self._v + + @v.setter + def v(self, value): + self._v = value * 2 + + +class SetattrReplaceTests(unittest.TestCase): + def test_replace_and_add(self): + o = O() + for i in range(N): + setattr(o, "x", i) + self.assertEqual((o.x, o.y), (N - 1, 2)) + setattr(o, "z", 3) + self.assertEqual(list(o.__dict__), ["x", "y", "z"]) + del o.x + setattr(o, "x", 9) + self.assertEqual(list(o.__dict__), ["y", "z", "x"]) + name = "".join(["y"]) + setattr(o, name, 5) + self.assertEqual(o.y, 5) + + def test_replaced_value_finalizes(self): + o = O() + Dying.deaths = 0 + for i in range(N // 10): + setattr(o, "x", Dying()) + self.assertEqual(Dying.deaths, i) + o.x = None + self.assertEqual(Dying.deaths, N // 10) + + def test_descriptor(self): + p = P() + for i in range(N // 10): + setattr(p, "v", i) + self.assertEqual(p.v, 2 * (N // 10 - 1)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_setattr_hook_changes.py b/tests/regrtest/test_setattr_hook_changes.py new file mode 100644 index 000000000..5e896b06d --- /dev/null +++ b/tests/regrtest/test_setattr_hook_changes.py @@ -0,0 +1,88 @@ +"""A class's own `__setattr__`, found once per class version. + +The inline store finds a class's Python `__setattr__` (and a native one) +through a cache the class's version guards: replacing the hook on the +class, or on a base the class inherits it from, or deleting it, takes +effect at the next store. +""" + +import threading +import unittest + + +class SetattrHookTests(unittest.TestCase): + def test_replaced_on_class(self): + log = [] + + class A: + def __setattr__(self, k, v): + log.append(("one", k)) + object.__setattr__(self, k, v) + + a = A() + for i in range(300): + a.x = i + self.assertEqual(len(log), 300) + + def two(self, k, v): + log.append(("two", k)) + object.__setattr__(self, k, v * 2) + + A.__setattr__ = two + for i in range(300): + a.y = i + self.assertEqual(log[-1], ("two", "y")) + self.assertEqual(a.y, 598) + del A.__setattr__ + a.z = 5 + self.assertEqual(log[-1], ("two", "y")) + self.assertEqual(a.z, 5) + + def test_replaced_on_base(self): + class Base: + def __setattr__(self, k, v): + self.__dict__[k] = ("base", v) + + class Sub(Base): + pass + + s = Sub() + for i in range(300): + s.v = i + self.assertEqual(s.v, ("base", 299)) + + def other(self, k, v): + self.__dict__[k] = ("other", v) + + Base.__setattr__ = other + for i in range(300): + s.v = i + self.assertEqual(s.v, ("other", 299)) + + def test_native_hook(self): + loc = threading.local() + for i in range(300): + loc.n = i + self.assertEqual(loc.n, 299) + + class L(threading.local): + pass + + l = L() + for i in range(300): + l.n = i + self.assertEqual(l.n, 299) + + def test_raising_hook(self): + class Frozen: + def __setattr__(self, k, v): + raise AttributeError(k) + + f = Frozen() + for i in range(300): + with self.assertRaises(AttributeError): + f.x = i + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_setattr_hook_direct.py b/tests/regrtest/test_setattr_hook_direct.py new file mode 100644 index 000000000..d2dcbc16f --- /dev/null +++ b/tests/regrtest/test_setattr_hook_direct.py @@ -0,0 +1,206 @@ +"""Compiled attribute stores call a class's Python `__setattr__` or a +property's Python setter directly; the values stored, the name passed, +a setter's ignored result, raises (caught in the storing frame or +past it), stores in loops and from `self.x = v`, the receiver's and +value's lifetimes, and a hook replaced later match the general store.""" + +import gc +import sys +import unittest +import weakref + + +class Log: + def __init__(self): + object.__setattr__(self, "log", []) + + def __setattr__(self, k, v): + self.log.append((k, v)) + object.__setattr__(self, k, v) + + +class ViaDict: + def __setattr__(self, k, v): + self.__dict__[k] = v * 2 + + +class ViaSuper: + def __setattr__(self, k, v): + if k.startswith("_"): + raise AttributeError(k) + super().__setattr__(k, v) + return "ignored" + + +class Frozen: + __slots__ = ("a",) + + def __init__(self, a): + object.__setattr__(self, "a", a) + + def __setattr__(self, k, v): + raise AttributeError(f"frozen: {k}") + + +class Prop: + def __init__(self): + self._x = 0 + self.calls = 0 + + @property + def x(self): + return self._x + + @x.setter + def x(self, v): + # Not a frameless leaf: it calls and stores twice. + self.calls = self.calls + 1 + self._x = abs(v) + + +class InitStores: + def __init__(self, a, b): + self.a = a + self.b = b + + def __setattr__(self, k, v): + object.__setattr__(self, k, (k, v)) + + +class Tracked: + deleted = 0 + + def __del__(self): + Tracked.deleted += 1 + + +class Hold: + def __setattr__(self, k, v): + object.__setattr__(self, k, v) + + +class SetattrHookDirect(unittest.TestCase): + def test_log_hook(self): + o = Log() + for i in range(2000): + o.x = i + self.assertEqual(o.x, 1999) + self.assertEqual(len(o.log), 2000) + self.assertEqual(o.log[0], ("x", 0)) + self.assertEqual(o.log[-1], ("x", 1999)) + + def test_dict_hook_and_names(self): + o = ViaDict() + for i in range(2000): + o.a = i + o.b = -i + self.assertEqual((o.a, o.b), (3998, -3998)) + self.assertEqual(sorted(o.__dict__), ["a", "b"]) + + def test_super_hook_result_ignored(self): + o = ViaSuper() + for i in range(2000): + o.v = i + self.assertEqual(o.v, 1999) + self.assertNotIn("_p", o.__dict__) + + def test_raise_caught_here(self): + o = ViaSuper() + n = 0 + for i in range(2000): + try: + o._p = i + except AttributeError as e: + n += 1 + self.assertEqual(e.args, ("_p",)) + self.assertEqual(n, 2000) + + def test_raise_past_frame(self): + def store(o, v): + o.a = v + + for i in range(1000): + f = Frozen(i) + with self.assertRaises(AttributeError): + store(f, i + 1) + self.assertEqual(f.a, i) + + def test_property_setter(self): + p = Prop() + for i in range(2000): + p.x = -i + self.assertEqual(p.x, 1999) + self.assertEqual(p.calls, 2000) + + def test_self_stores_in_init(self): + for i in range(2000): + o = InitStores(i, "b") + self.assertEqual(o.a, ("a", i)) + self.assertEqual(o.b, ("b", "b")) + + def test_lifetimes(self): + h = Hold() + for _ in range(500): + h.t = Tracked() + before = Tracked.deleted + t = Tracked() + r = weakref.ref(t) + h.t = t + del t + self.assertIsNotNone(r()) + h.t = None + self.assertIsNone(r()) + self.assertEqual(Tracked.deleted, before + 2) + # The receiver's references are what they were. + n = sys.getrefcount(h) + for i in range(1000): + h.u = i + self.assertEqual(sys.getrefcount(h), n) + + def test_hook_replaced(self): + class C: + def __setattr__(self, k, v): + object.__setattr__(self, k, v + 1) + + c = C() + for i in range(1000): + c.x = i + self.assertEqual(c.x, 1000) + + def other(self, k, v): + object.__setattr__(self, k, -v) + + C.__setattr__ = other + for i in range(1000): + c.x = i + self.assertEqual(c.x, -999) + del C.__setattr__ + for i in range(1000): + c.x = i + self.assertEqual(c.x, 999) + + def test_hook_with_generator_caller(self): + o = Log() + + def g(): + for i in range(300): + o.y = i + yield i + + self.assertEqual(sum(g()), sum(range(300))) + self.assertEqual(o.y, 299) + + def test_collect_during(self): + class Cyc: + def __setattr__(self, k, v): + gc.collect() if v % 500 == 0 else None + object.__setattr__(self, k, v) + + c = Cyc() + for i in range(1500): + c.z = i + self.assertEqual(c.z, 1499) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_setcomp_set_add.py b/tests/regrtest/test_setcomp_set_add.py new file mode 100644 index 000000000..f245dd99c --- /dev/null +++ b/tests/regrtest/test_setcomp_set_add.py @@ -0,0 +1,61 @@ +"""Set comprehensions in compiled code (`SET_ADD`). + +A value the native probe settles is added in place; an equal element +keeps the first object; unhashable values raise; values with a Python +`__eq__` or `__hash__`, `True` against `1`, and a discarded duplicate's +finalizer behave as in CPython. Run it past the compile threshold. +""" + + +class K: + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + return isinstance(other, K) and self.v == other.v + + +class D: + log = [] + + def __init__(self, n): + self.n = n + + def __hash__(self): + return 7 + + def __eq__(self, other): + return isinstance(other, D) + + def __del__(self): + D.log.append(self.n) + + +def run(n): + xs = (1, 2, 3, 2, 1) + for i in range(n): + s = {x + i % 2 for x in xs} + assert s == {1 + i % 2, 2 + i % 2, 3 + i % 2} + t = {v for v in (1, True, 1.0, "a", "a", None, None)} + assert t == {1, "a", None} and [type(v) for v in t if v == 1] == [int] + k = {K(x) for x in xs} + assert len(k) == 3 + try: + {[x] for x in xs} + except TypeError: + pass + else: + raise AssertionError("unhashable") + D.log.clear() + d = {D(j) for j in (1, 2)} + assert D.log == [2] and next(iter(d)).n == 1, D.log + del d + D.log.clear() + assert {c for c in "hello"} == set("helo") + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_setitem_delegate_stores.py b/tests/regrtest/test_setitem_delegate_stores.py new file mode 100644 index 000000000..3fb7ecda6 --- /dev/null +++ b/tests/regrtest/test_setitem_delegate_stores.py @@ -0,0 +1,107 @@ +"""Item stores into instances whose __setitem__ is exactly +self.[key] = value (a UserDict, a wrapper), or self.maps[0][key] = value (a ChainMap), from compiled loops: the +target dict updated and read back, an unhashable key's TypeError, a key +whose __hash__/__eq__ is Python, a target that isn't a dict (a list, a +dict subclass with its own __setitem__), the attribute rebound partway, a +class whose __setitem__ changes, and the value's old reference released, +each matching CPython.""" + +import collections +import unittest + +log = [] + + +class Wrap: + def __init__(self, target): + self.data = target + + def __setitem__(self, key, value): + self.data[key] = value + + +class Loud(dict): + def __setitem__(self, k, v): + log.append(k) + super().__setitem__(k, v) + + +class K: + def __init__(self, k): + self.k = k + + def __hash__(self): + return hash(self.k) + + def __eq__(self, other): + return isinstance(other, K) and self.k == other.k + + +class Gone: + def __init__(self, n): + self.n = n + + def __del__(self): + log.append(("del", self.n)) + + +def store(n, c, key="a"): + for i in range(n): + c[key] = i + return c + + +class DelegateTests(unittest.TestCase): + def test_dicts(self): + for n in (1, 400): + self.assertEqual(store(n, Wrap({})).data, {"a": n - 1}) + self.assertEqual(dict(store(n, collections.UserDict())), {"a": n - 1}) + self.assertEqual(store(n, Wrap({}), 5).data, {5: n - 1}) + self.assertEqual(store(n, Wrap({}), K(1)).data, {K(1): n - 1}) + cm = store(n, collections.ChainMap({}, {"b": 1})) + self.assertEqual(cm.maps, [{"a": n - 1}, {"b": 1}]) + + def test_other_targets(self): + self.assertEqual(store(400, Wrap([0]), 0).data, [399]) + del log[:] + w = store(400, Wrap(Loud())) + self.assertEqual(len(log), 400) + self.assertEqual(dict(w.data), {"a": 399}) + with self.assertRaises(TypeError): + store(400, Wrap({}), []) + + def test_chainmap_edges(self): + cm = collections.ChainMap() + cm.maps = [] + with self.assertRaises(IndexError): + store(400, cm) + cm = collections.ChainMap(collections.UserDict()) + self.assertEqual(dict(store(400, cm).maps[0]), {"a": 399}) + + def test_rebound_and_changed(self): + w = Wrap({}) + store(400, w) + first = w.data + w.data = {} + store(300, w) + self.assertEqual((first, w.data), ({"a": 399}, {"a": 299})) + + class W(Wrap): + pass + + x = W({}) + store(400, x) + W.__setitem__ = lambda self, k, v: self.data.__setitem__(k, -v) + self.assertEqual(store(300, x).data, {"a": -299}) + + def test_release(self): + del log[:] + w = Wrap({}) + for i in range(300): + w["x"] = Gone(i) + self.assertEqual(len(log), 299) + self.assertEqual(log[-1], ("del", 298)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_setitem_dunder_direct.py b/tests/regrtest/test_setitem_dunder_direct.py new file mode 100644 index 000000000..f0c9bd284 --- /dev/null +++ b/tests/regrtest/test_setitem_dunder_direct.py @@ -0,0 +1,169 @@ +"""Compiled item stores call a class's Python `__setitem__` directly; the +items stored, the method's ignored result, raises (caught in the storing +frame or past it), stores from inside methods and generators, the +operands' lifetimes, and a method replaced later match the general +store.""" + +import collections +import sys +import unittest +import weakref + + +class Logged: + def __init__(self): + self.data = {} + self.calls = 0 + + def __setitem__(self, k, v): + # More than a dict delegate: a count and a store. + self.calls = self.calls + 1 + self.data[k] = v + return "ignored" + + +class Checked(dict): + def __setitem__(self, k, v): + if not isinstance(k, str): + raise TypeError("keys are str") + super().__setitem__(k, v * 2) + + +class Tracked: + deleted = 0 + + def __del__(self): + Tracked.deleted += 1 + + +class Holder: + def __init__(self): + self.d = {} + + def __setitem__(self, k, v): + self.d[k] = v + self.last = k + + def fill(self, n): + for i in range(n): + self[i] = i * i + + +class SetitemDunderDirect(unittest.TestCase): + def test_logged(self): + o = Logged() + for i in range(3000): + o[i % 7] = i + self.assertEqual(o.calls, 3000) + self.assertEqual(o.data[2999 % 7], 2999) + self.assertEqual(len(o.data), 7) + + def test_dict_subclass(self): + c = Checked() + for i in range(3000): + c["k%d" % (i % 5)] = i + self.assertEqual(c["k4"], 2 * 2999) + self.assertEqual(len(c), 5) + + def test_raise_caught_here(self): + c = Checked() + n = 0 + for i in range(2000): + try: + c[i] = i + except TypeError as e: + n += 1 + self.assertEqual(str(e), "keys are str") + self.assertEqual(n, 2000) + self.assertEqual(len(c), 0) + + def test_raise_past_frame(self): + def store(c, k, v): + c[k] = v + return "after" + + c = Checked() + for i in range(2000): + with self.assertRaises(TypeError): + store(c, i, i) + self.assertEqual(store(c, "a", i), "after") + self.assertEqual(c["a"], 2 * 1999) + + def test_self_stores(self): + h = Holder() + for _ in range(300): + h.fill(20) + self.assertEqual(h.d[19], 361) + self.assertEqual(h.last, 19) + + def test_generator_caller(self): + o = Logged() + + def g(): + for i in range(500): + o[i] = -i + yield i + + self.assertEqual(sum(g()), sum(range(500))) + self.assertEqual(o.data[499], -499) + + def test_ordered_dict_and_chainmap(self): + for _ in range(300): + od = collections.OrderedDict() + od["a"] = 1 + od["b"] = 2 + od["a"] = 3 + self.assertEqual(list(od.items()), [("a", 3), ("b", 2)]) + cm = collections.ChainMap({}, {"x": 1}) + cm["y"] = 2 + cm["x"] = 5 + self.assertEqual(cm.maps[0], {"y": 2, "x": 5}) + ud = collections.UserDict() + ud["q"] = 1 + self.assertEqual(ud.data, {"q": 1}) + + def test_lifetimes(self): + h = Holder() + for i in range(500): + h["t"] = Tracked() + before = Tracked.deleted + t = Tracked() + r = weakref.ref(t) + h["t"] = t + del t + self.assertIsNotNone(r()) + h["t"] = None + self.assertIsNone(r()) + self.assertEqual(Tracked.deleted, before + 2) + n = sys.getrefcount(h) + for i in range(1000): + h["key"] = i + self.assertEqual(sys.getrefcount(h), n) + + def test_method_replaced(self): + class C: + def __init__(self): + self.d = {} + + def __setitem__(self, k, v): + self.d[k] = v + 1 + + c = C() + for i in range(1000): + c[0] = i + self.assertEqual(c.d[0], 1000) + + def other(self, k, v): + self.d[k] = -v + + C.__setitem__ = other + for i in range(1000): + c[0] = i + self.assertEqual(c.d[0], -999) + del C.__setitem__ + with self.assertRaises(TypeError): + c[0] = 1 + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_setter_site_cache.py b/tests/regrtest/test_setter_site_cache.py new file mode 100644 index 000000000..46592e35d --- /dev/null +++ b/tests/regrtest/test_setter_site_cache.py @@ -0,0 +1,213 @@ +"""A `STORE_ATTR` site that stores through a property's Python setter +remembers that setter under the receiver's class version: replacing the +property, re-initializing it with another setter, a class or base that +gains `__setattr__`, a receiver of another class, and a setter removed +all take the new behavior, for a local receiver and a global one.""" + +import unittest + + +class C: + def __init__(self): + self._v = 0 + + @property + def v(self): + return self._v + + @v.setter + def v(self, n): + self._v = n + + +class S: + __slots__ = ("_v",) + + def __init__(self): + self._v = 0 + + @property + def v(self): + return self._v + + @v.setter + def v(self, n): + self._v = n + + +def store_local(o, n): + for i in range(n): + o.v = i + return o + + +g = None + + +def store_global(n): + for i in range(n): + g.v = i + + +N = 3000 + + +class SetterSiteCacheTests(unittest.TestCase): + def test_local_and_global_receivers(self): + global g + self.assertEqual(store_local(C(), N)._v, N - 1) + self.assertEqual(store_local(S(), N)._v, N - 1) + g = C() + store_global(N) + self.assertEqual(g._v, N - 1) + + def test_property_replaced(self): + class K(C): + pass + + o = store_local(K(), N) + self.assertEqual(o._v, N - 1) + + def doubled(self, n): + self._v = 2 * n + + K.v = property(C.v.fget, doubled) + store_local(o, N) + self.assertEqual(o._v, 2 * (N - 1)) + + def test_base_property_replaced(self): + class B: + @property + def v(self): + return self._v + + @v.setter + def v(self, n): + self._v = n + + class K(B): + pass + + o = store_local(K(), N) + self.assertEqual(o._v, N - 1) + + def neg(self, n): + self._v = -n + + B.v = property(B.v.fget, neg) + store_local(o, N) + self.assertEqual(o._v, -(N - 1)) + + def test_property_reinitialized(self): + def plain(self, n): + self._v = n + + def tripled(self, n): + self._v = 3 * n + + p = property(lambda self: self._v, plain) + + class K: + v = p + + o = store_local(K(), N) + self.assertEqual(o._v, N - 1) + p.__init__(lambda self: self._v, tripled) + store_local(o, N) + self.assertEqual(o._v, 3 * (N - 1)) + + def test_class_gains_setattr(self): + class K(C): + pass + + o = store_local(K(), N) + seen = [] + + def setattr_(self, name, value): + seen.append(name) + object.__setattr__(self, name, value) + + K.__setattr__ = setattr_ + store_local(o, 5) + self.assertEqual(o._v, 4) + self.assertEqual(seen.count("v"), 5) + + def test_setter_removed(self): + class K(C): + pass + + o = store_local(K(), N) + K.v = property(C.v.fget) + with self.assertRaises(AttributeError): + store_local(o, 1) + self.assertEqual(o._v, N - 1) + + def test_receivers_of_several_classes(self): + class D: + def __init__(self): + self.log = [] + + @property + def v(self): + return self.log + + @v.setter + def v(self, n): + self.log.append(n) + + class Plain: + pass + + objs = [C(), D(), S(), Plain()] + for _ in range(N // 10): + for o in objs: + o.v = 7 + self.assertEqual(objs[0]._v, 7) + self.assertEqual(objs[1].log, [7] * (N // 10)) + self.assertEqual(objs[2]._v, 7) + self.assertEqual(objs[3].v, 7) + + def test_class_assignment(self): + class A: + @property + def v(self): + return self._v + + @v.setter + def v(self, n): + self._v = n + + class B: + @property + def v(self): + return self._v + + @v.setter + def v(self, n): + self._v = n + 100 + + o = store_local(A(), N) + o.__class__ = B + store_local(o, 2) + self.assertEqual(o._v, 101) + + def test_setter_raises(self): + class K: + @property + def v(self): + return self._v + + @v.setter + def v(self, n): + if n < 0: + raise ValueError(n) + self._v = n + + o = store_local(K(), N) + with self.assertRaises(ValueError): + o.v = -1 + self.assertEqual(o._v, N - 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_shared_setter_slot_stores.py b/tests/regrtest/test_shared_setter_slot_stores.py new file mode 100644 index 000000000..eb5a1628d --- /dev/null +++ b/tests/regrtest/test_shared_setter_slot_stores.py @@ -0,0 +1,94 @@ +"""A property setter shared by several classes, storing into `__slots__`. + +A base class's `@p.setter` that does `self._p = v` runs frameless for +each subclass whose instances keep `_p` in a `__slots__` member (with or +without an instance `__dict__` beside it), and for plain subclasses, one +after another at one site. The stores must land where the full +`__setattr__` puts them: a later read, `__dict__`, a readonly or +defaulted member left alone, a class whose `__setattr__` is its own, and +a member shadowed by a class attribute. +""" + +import unittest + + +class Base: + @property + def p(self): + return self._p + + @p.setter + def p(self, v): + self._p = v + + +class A(Base): + __slots__ = ("_p",) + + +class B(Base): + __slots__ = ("x", "_p") + + +class C(Base): + pass + + +class Strict(Base): + __slots__ = ("_p",) + + def __setattr__(self, name, value): + object.__setattr__(self, name, value * 10) + + +class Shadow(Base): + _p = property(lambda self: "shadow", lambda self, v: None) + + +def store_all(cls, n): + out = [] + for i in range(n): + o = cls() + o.p = i + out.append(o) + return out + + +class SharedSetterTests(unittest.TestCase): + def test_sequence_of_classes(self): + for cls in (A, B, C, A, B, C): + objs = store_all(cls, 400) + self.assertEqual([o.p for o in objs], list(range(400))) + self.assertEqual([o._p for o in objs[:3]], [0, 1, 2]) + + def test_slots_beside_dict(self): + objs = store_all(B, 300) + o = objs[-1] + self.assertEqual(o.p, 299) + self.assertNotIn("_p", o.__dict__) + o.extra = 1 + self.assertEqual(o.__dict__, {"extra": 1}) + c = store_all(C, 300)[-1] + self.assertEqual(c.__dict__, {"_p": 299}) + + def test_own_setattr_and_shadowing(self): + store_all(A, 300) + s = store_all(Strict, 300) + self.assertEqual([o.p for o in s[:3]], [0, 100, 200]) + sh = store_all(Shadow, 300) + self.assertEqual(sh[5].p, "shadow") + + def test_heap_values(self): + for cls in (A, B): + objs = [] + for i in range(300): + o = cls() + o.p = [i] + objs.append(o) + self.assertEqual(objs[7].p, [7]) + objs[7].p = objs[8] + self.assertIs(objs[7].p, objs[8]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_single_op_paths_3.py b/tests/regrtest/test_single_op_paths_3.py new file mode 100644 index 000000000..a41885ccb --- /dev/null +++ b/tests/regrtest/test_single_op_paths_3.py @@ -0,0 +1,203 @@ +"""Results of operations given in-place fast paths. + +Complex arithmetic in compiled code, `setattr` on plain instances, +`str.center`/`ljust`/`rjust`/`zfill`, `struct.unpack` of `bytes`, +`sorted` of a dict, a dict display or keyword splat into an empty dict, +`functools.reduce` run in place, and `bytes.join` of `bytes` parts. Each +loop runs long enough for the compiled paths to take over. +""" + +import functools +import operator +import struct +import sys +import unittest + +N = 3000 + + +class ComplexTests(unittest.TestCase): + def test_arithmetic(self): + c = complex(1, 2) + for _ in range(N): + r = (c * c, c + 1.5, 2 * c, c / 2, c - c, 1.5 / c, c * 3, 4 - c) + self.assertEqual(r, ((-3 + 4j), (2.5 + 2j), (2 + 4j), (0.5 + 1j), 0j, + (0.3 - 0.6j), (3 + 6j), (3 - 2j))) + + def test_errors_and_specials(self): + c = complex(1, 2) + for divisor in (0, 0.0, 0j): + with self.assertRaises(ZeroDivisionError): + for _ in range(N): + c / divisor + big = complex(1e308, 1e308) + for _ in range(N): + r = big * 2 + self.assertEqual(r, complex(float("inf"), float("inf"))) + with self.assertRaises(TypeError): + for _ in range(N): + c | 1 + + def test_subclass_and_bool(self): + class C(complex): + def __mul__(self, other): + return "mul" + + x = C(1, 1) + for _ in range(N): + r = (x * 2, complex(1, 1) * True) + self.assertEqual(r, ("mul", (1 + 1j))) + + +class SetattrTests(unittest.TestCase): + def test_plain_and_protocols(self): + class O: + pass + + class P: + @property + def x(self): + return self._x + + @x.setter + def x(self, v): + self._x = v * 2 + + class S: + def __setattr__(self, k, v): + object.__setattr__(self, k, (k, v)) + + class SL: + __slots__ = ("a",) + + o, p, s, sl = O(), P(), S(), SL() + for i in range(N): + setattr(o, "x", i) + setattr(o, "y" + str(i % 3), i) + setattr(p, "x", i) + setattr(s, "q", i) + setattr(sl, "a", i) + self.assertEqual((o.x, o.y0, o.y1, o.y2), (N - 1, N - 3, N - 2, N - 1)) + self.assertEqual((p.x, s.q, sl.a), (2 * (N - 1), ("q", N - 1), N - 1)) + with self.assertRaises(AttributeError): + setattr(sl, "b", 1) + with self.assertRaises(TypeError): + setattr(o, 1, 1) + + def test_interned_key_and_finalizer_order(self): + class O: + pass + + events = [] + + class D: + def __init__(self, n): + self.n = n + + def __del__(self): + events.append(self.n) + + o = O() + name = "".join(["z", "z"]) + for _ in range(N): + setattr(o, name, 5) + self.assertIs([k for k in vars(o) if k == "zz"][0], sys.intern("zz")) + for i in range(N): + setattr(o, "d", D(i)) + events.clear() + setattr(o, "d", None) + self.assertEqual(events, [N - 1]) + + +class PaddingTests(unittest.TestCase): + def test_center_just_zfill(self): + for _ in range(N): + r = ("ab".center(7), "ab".center(6, "*"), "Monday".center(9), + "x".ljust(4, "é"), "x".rjust(3), "-42".zfill(6), "+7".zfill(4), + "abc".center(2), "7".zfill(-1)) + self.assertEqual(r, (" ab ", "**ab**", " Monday ", "xééé", " x", + "-00042", "+007", "abc", "7")) + + def test_identity_when_wide_enough(self): + s = "hello" + for _ in range(N): + r = (s.center(3), s.ljust(5), s.rjust(0), s.zfill(2)) + for x in r: + self.assertIs(x, s) + + +class StructTests(unittest.TestCase): + def test_unpack_bytes_and_buffers(self): + packed = struct.pack("4"), format(F(), "x"), + format(True), format(2.0), format(3, "b")) + self.assertEqual(r, ("1.5", "10", " ab", "Fx", "True", "2.0", "11")) + for bad, name in ((5, "int"), (None, "None")): + with self.assertRaises(TypeError) as cm: + format(1.5, bad) + self.assertEqual(str(cm.exception), "format() argument 2 must be str, not " + name) + + +class NativeShortcutTests(unittest.TestCase): + def test_fsum_and_dist(self): + import math + for _ in range(N): + r = (math.fsum([0.1] * 10), math.fsum((1, 2**62, -2**62, 0.5)), + math.fsum([True, 1.5]), math.dist((1, 2), (4, 6)), + math.fsum(x / 10 for x in range(3))) + self.assertEqual(r, (1.0, 1.5, 2.5, 5.0, 0.30000000000000004)) + with self.assertRaises(TypeError) as cm: + math.fsum([1, "a"]) + self.assertEqual(str(cm.exception), "must be real number, not str") + with self.assertRaises(OverflowError): + math.fsum([1e308, 1e308]) + + def test_tuple_of_list(self): + for _ in range(N): + r = (tuple([1, "a"]), tuple([]), tuple((2,))) + self.assertEqual(r, ((1, "a"), (), (2,))) + self.assertIs(tuple([]), ()) + + def test_date_fromisoformat(self): + import datetime + + class D(datetime.date): + pass + + for _ in range(N): + r = (datetime.date.fromisoformat("2024-01-02"), + datetime.date.fromisoformat("20240102"), + datetime.date.fromisoformat("2024-02-29"), + datetime.date.fromisoformat("9999-12-31"), + datetime.date.fromisoformat("2024-W01-1"), + type(D.fromisoformat("2024-05-06"))) + self.assertEqual(r[:5], (datetime.date(2024, 1, 2), datetime.date(2024, 1, 2), + datetime.date(2024, 2, 29), datetime.date(9999, 12, 31), + datetime.date(2024, 1, 1))) + self.assertIs(r[5], D) + for bad in ("2024-02-30", "2023-02-29", "2024-1-02", "0000-01-01", "2024-13-01", "2024-01"): + with self.assertRaises(ValueError): + datetime.date.fromisoformat(bad) + with self.assertRaises(TypeError): + datetime.date.fromisoformat(20240102) + + def test_maketrans(self): + for _ in range(N): + r = (str.maketrans("ab", "cd"), str.maketrans({"a": "b"}), + bytes.maketrans(b"a", b"b")[97], "abc".translate(str.maketrans("ab", "xy", "c"))) + self.assertEqual(r, ({97: 99, 98: 100}, {97: "b"}, 98, "xy")) + with self.assertRaises(ValueError): + str.maketrans("ab", "c") + + +class ReversedSumTests(unittest.TestCase): + def test_sum_reversed(self): + for _ in range(N): + r = reversed([1, 2, 3]) + a = sum(r) + b = list(r) + c = sum(reversed([1.5, 2, 1e16, -1e16])) + d = sum(reversed([2**62, 2**62, 2**62])) + e = sum(reversed([]), 5) + r2 = reversed([1, 2, 3]) + next(r2) + f = sum(r2) + self.assertEqual((a, b, c, d, e, f), (6, [], 3.5, 3 * 2**62, 5, 3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_slot_getattr_fast.py b/tests/regrtest/test_slot_getattr_fast.py new file mode 100644 index 000000000..1a6037798 --- /dev/null +++ b/tests/regrtest/test_slot_getattr_fast.py @@ -0,0 +1,112 @@ +"""getattr, hasattr and attrgetter read a `__slots__` member directly; an +unset member gives the default, a `__getattr__`'s answer, or the +AttributeError, as the full lookup does.""" + +import operator +import unittest + + +class S: + __slots__ = ("a", "b") + + def __init__(self, a): + self.a = a + + +class G(S): + __slots__ = () + + def __getattr__(self, name): + return "fallback:" + name + + +class Sub(S): + pass + + +class Prop: + __slots__ = ("_x",) + + def __init__(self): + self._x = 3 + + @property + def x(self): + return self._x * 2 + + +class SlotGetattr(unittest.TestCase): + def test_reads(self): + s, g, sub = S(1), G(2), Sub(3) + sub.c = 9 + get_a = operator.attrgetter("a") + for _ in range(500): + self.assertEqual(getattr(s, "a"), 1) + self.assertEqual(getattr(s, "a", None), 1) + self.assertIsNone(getattr(s, "b", None)) + self.assertEqual(getattr(s, "b", 5), 5) + self.assertTrue(hasattr(s, "a")) + self.assertFalse(hasattr(s, "b")) + self.assertEqual(getattr(g, "b", None), "fallback:b") + self.assertTrue(hasattr(g, "b")) + self.assertEqual(getattr(sub, "a"), 3) + self.assertEqual(getattr(sub, "c"), 9) + self.assertEqual(get_a(s), 1) + self.assertEqual(list(map(get_a, [s, sub])), [1, 3]) + self.assertEqual(getattr(Prop(), "x"), 6) + with self.assertRaises(AttributeError): + getattr(s, "b") + + def test_set_and_delete(self): + s = S(1) + for i in range(300): + s.b = i + self.assertEqual(getattr(s, "b", None), i) + del s.b + self.assertIsNone(getattr(s, "b", None)) + self.assertFalse(hasattr(s, "b")) + + def test_class_change(self): + s = S(1) + for _ in range(300): + getattr(s, "a") + S.a_alias = 1 + self.assertEqual(getattr(s, "a"), 1) + del S.a_alias + + def test_class_gains_attribute_after_misses(self): + class P: + pass + + class Q(P): + pass + + q = Q() + for _ in range(300): + self.assertEqual(getattr(q, "z", 1), 1) + self.assertFalse(hasattr(q, "z")) + P.z = 7 + self.assertEqual(getattr(q, "z", 1), 7) + P.z = property(lambda self: 8) + self.assertEqual(getattr(q, "z", 1), 8) + q.__dict__["z"] = 9 + self.assertEqual(getattr(q, "z", 1), 8) + del P.z + self.assertEqual(getattr(q, "z", 1), 9) + P.__getattr__ = lambda self, name: "ga" + self.assertEqual(getattr(q, "w", 1), "ga") + + def test_slot_replaced_on_class(self): + class T: + __slots__ = ("v",) + + t = T() + t.v = 1 + for _ in range(300): + self.assertEqual(getattr(t, "v", None), 1) + T.v = 5 + self.assertEqual(getattr(t, "v", None), 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_slot_member_update_methods.py b/tests/regrtest/test_slot_member_update_methods.py new file mode 100644 index 000000000..8fa61d887 --- /dev/null +++ b/tests/regrtest/test_slot_member_update_methods.py @@ -0,0 +1,228 @@ +"""Methods that add to a `__slots__` member keep their meaning in hot loops. + +A method whose body is `self.x += k; return self.x` runs in line in a +compiled loop once it has run a few times, for a field in an instance +dictionary and for a `__slots__` member alike. Whatever the loop meets +afterwards (another class, an unset or non-int member, an overflow, a +replaced method or code object, a subclass whose instances can shadow +the method) gives the result the plain call gives. +""" + +import unittest + +N = 6000 + + +class Slotted: + __slots__ = ("a", "b", "c") + + def __init__(self): + self.a = 1 + self.b = 2.0 + self.c = "x" + + def tick(self): + self.a += 1 + return self.a + + def bump(self, n): + self.a += n + return self.a + + +class Plain: + def __init__(self): + self.a = 1 + + def tick(self): + self.a += 1 + return self.a + + +def ticks(obj, n): + total = 0 + for _ in range(n): + total += obj.tick() + return total + + +def bumps(obj, n, by): + total = 0 + for _ in range(n): + total += obj.bump(by) + return total + + +def expected_ticks(start, n): + # start+1 + start+2 + ... + start+n + return n * start + n * (n + 1) // 2 + + +class SlotUpdateTests(unittest.TestCase): + def test_tick_and_bump(self): + s = Slotted() + self.assertEqual(ticks(s, N), expected_ticks(1, N)) + self.assertEqual(s.a, 1 + N) + s2 = Slotted() + self.assertEqual(bumps(s2, N, 3), sum(1 + 3 * k for k in range(1, N + 1))) + self.assertEqual(s2.a, 1 + 3 * N) + self.assertEqual((s2.b, s2.c), (2.0, "x")) + + def test_both_kinds_of_class_in_one_loop(self): + objs = [Slotted(), Plain(), Slotted(), Plain()] + total = 0 + for i in range(N): + total += objs[i % 4].tick() + per = N // 4 + self.assertEqual(total, 4 * expected_ticks(1, per)) + self.assertTrue(all(o.a == 1 + per for o in objs)) + + def test_overflow_into_a_big_int(self): + s = Slotted() + ticks(s, N) + s.a = 2**63 - 3 + got = [s.tick() for _ in range(6)] + self.assertEqual(got, [2**63 - 2 + k for k in range(6)]) + self.assertEqual(ticks(s, 10), sum(2**63 + 3 + k for k in range(1, 11))) + s.a = -(2**63) + 1 + self.assertEqual(bumps(s, 3, -1), sum(-(2**63) + 1 - k for k in range(1, 4))) + + def test_member_of_another_type(self): + s = Slotted() + ticks(s, N) + s.a = 1.5 + self.assertEqual(ticks(s, 4), 2.5 + 3.5 + 4.5 + 5.5) + s.a = True + self.assertEqual(s.tick(), 2) + s.a = "ab" + with self.assertRaises(TypeError): + ticks(s, 3) + self.assertEqual(s.a, "ab") + + def test_unset_member(self): + s = Slotted() + ticks(s, N) + del s.a + with self.assertRaises(AttributeError): + ticks(s, 3) + s.a = 10 + self.assertEqual(ticks(s, 3), 11 + 12 + 13) + + def test_method_replaced_on_the_class(self): + class C: + __slots__ = ("a",) + + def __init__(self): + self.a = 0 + + def tick(self): + self.a += 1 + return self.a + + c = C() + self.assertEqual(ticks(c, N), expected_ticks(0, N)) + C.tick = lambda self: -1 + self.assertEqual(ticks(c, 50), -50) + self.assertEqual(c.a, N) + + def test_code_object_swapped(self): + class C: + __slots__ = ("a",) + + def __init__(self): + self.a = 0 + + def tick(self): + self.a += 1 + return self.a + + def other(self): + self.a += 100 + return self.a + + c = C() + ticks(c, N) + C.tick.__code__ = other.__code__ + self.assertEqual(c.tick(), N + 100) + self.assertEqual(ticks(c, 10), sum(N + 100 + 100 * k for k in range(1, 11))) + + def test_subclass_instances_can_shadow_the_method(self): + class Sub(Slotted): + pass # no __slots__: its instances have a dictionary + + s = Sub() + self.assertEqual(ticks(s, N), expected_ticks(1, N)) + s.tick = lambda: -7 + self.assertEqual(ticks(s, 20), -140) + del s.tick + self.assertEqual(s.tick(), N + 2) + base = Slotted() + self.assertEqual(ticks(base, N), expected_ticks(1, N)) + + def test_subclass_with_more_slots(self): + class More(Slotted): + __slots__ = ("d",) + + def __init__(self): + super().__init__() + self.d = 9 + + m = More() + b = Slotted() + total = 0 + for i in range(N): + total += (m if i % 2 else b).tick() + self.assertEqual(total, 2 * expected_ticks(1, N // 2)) + self.assertEqual((m.a, m.d, b.a), (1 + N // 2, 9, 1 + N // 2)) + + def test_descriptor_installed_over_the_member(self): + class C: + __slots__ = ("a",) + + def __init__(self): + self.a = 0 + + def tick(self): + self.a += 1 + return self.a + + c = C() + ticks(c, N) + seen = [] + member = C.__dict__["a"] + + class Watch: + def __get__(self, obj, cls): + seen.append("get") + return member.__get__(obj, cls) + + def __set__(self, obj, value): + seen.append("set") + member.__set__(obj, value) + + C.a = Watch() + self.assertEqual(c.tick(), N + 1) + self.assertEqual(seen, ["get", "set", "get"]) + self.assertEqual(ticks(c, 5), sum(N + 1 + k for k in range(1, 6))) + + def test_fixture_shape(self): + # Reads, float stores, both ticks and a string compare in one loop. + p, s = Plain(), Slotted() + p.b, p.c = 2.0, "x" + total = 0 + for _ in range(N): + total += p.a + s.a + p.b = p.b + 0.5 + s.b = s.b + 0.5 + total += p.tick() + s.tick() + if p.c == s.c: + total += 1 + self.assertEqual(p.a, 1 + N) + self.assertEqual(s.a, 1 + N) + self.assertEqual(p.b, 2.0 + N * 0.5) + self.assertEqual(s.b, 2.0 + N * 0.5) + self.assertEqual(total, 2 * sum(range(1, N + 1)) + 2 * expected_ticks(1, N) + N) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_slot_property_reads.py b/tests/regrtest/test_slot_property_reads.py new file mode 100644 index 000000000..9c4a1bc5d --- /dev/null +++ b/tests/regrtest/test_slot_property_reads.py @@ -0,0 +1,442 @@ +"""Property reads and unset `__slots__` members of slotted classes (as +`pathlib.PurePath` reads `self._tail` and `self._tail_cached`), and +functions that catch an exception and return, with their callers: getters +that run as calls, an unset member's `AttributeError` (with a `__getattr__`, +after the class changes, over subclasses' layouts), and frames a kept +traceback or `sys._getframe` reaches after the return; and modules a +class holds, read through the class (`cls.parser`).""" + +import sys +import unittest + + +class Cached: + __slots__ = ("raw", "a", "b", "c") + + def __init__(self, raw): + self.raw = raw + + @property + def tail(self): + try: + return self.c + except AttributeError: + self.a, self.b, self.c = self._parse(self.raw) + return self.c + + @classmethod + def _parse(cls, raw): + parts = [x for x in raw.split("/") if x] + return "", "/", parts + + @property + def name(self): + tail = self.tail + if not tail: + return "" + return tail[-1] + + +class SlotPropertyReads(unittest.TestCase): + def test_property_over_property(self): + for i in range(3000): + p = Cached("/usr/lib/f%d.txt" % (i % 7)) + self.assertEqual(p.name, "f%d.txt" % (i % 7)) + self.assertEqual(p.name, "f%d.txt" % (i % 7)) + self.assertEqual(p.tail, ["usr", "lib", "f%d.txt" % (i % 7)]) + self.assertEqual(Cached("/").name, "") + + def test_getter_replaced(self): + class P: + __slots__ = ("x",) + + def __init__(self): + self.x = 3 + + @property + def v(self): + total = 0 + for i in range(self.x): + total += i + return total + + def read(objs): + return [o.v for o in objs] + + objs = [P() for _ in range(50)] + for _ in range(100): + self.assertEqual(read(objs), [3] * 50) + P.v = property(lambda self: [self.x]) + self.assertEqual(read(objs)[:2], [[3], [3]]) + P.v = 7 + self.assertEqual(read(objs)[:2], [7, 7]) + del P.v + with self.assertRaises(AttributeError): + read(objs) + + def test_getter_raising_attribute_error_reaches_getattr(self): + class G: + __slots__ = ("n",) + + def __init__(self, n): + self.n = n + + @property + def v(self): + for _ in range(2): + pass + if self.n % 2: + raise AttributeError("odd") + return self.n + + def __getattr__(self, name): + return ("fallback", name) + + for i in range(2000): + got = G(i).v + self.assertEqual(got, ("fallback", "v") if i % 2 else i) + + def test_custom_getattribute_wins(self): + class H: + __slots__ = () + + @property + def v(self): + for _ in range(2): + pass + return "property" + + class K(H): + __slots__ = () + + def __getattribute__(self, name): + if name == "v": + return "hook" + return object.__getattribute__(self, name) + + def read(o): + return o.v + + for i in range(2000): + self.assertEqual(read(H()), "property") + self.assertEqual(read(K()), "hook") + + +class UnsetSlotMisses(unittest.TestCase): + def test_miss_then_set(self): + class T: + __slots__ = ("a",) + + for i in range(3000): + t = T() + try: + t.a + except AttributeError as e: + self.assertIn("'a'", str(e)) + t.a = i + self.assertEqual(t.a, i) + + def test_message_and_name(self): + class T: + __slots__ = ("member",) + + for _ in range(500): + try: + T().member + except AttributeError as e: + self.assertEqual(e.name, "member") + self.assertIsInstance(e.obj, T) + self.assertIn("member", str(e)) + else: + self.fail("no AttributeError") + + def test_getattr_answers_unset_member(self): + class T: + __slots__ = ("a",) + + def read(t): + try: + return t.a + except AttributeError: + return "missing" + + for _ in range(1000): + self.assertEqual(read(T()), "missing") + T.__getattr__ = lambda self, name: "hook:" + name + self.assertEqual(read(T()), "hook:a") + del T.__getattr__ + self.assertEqual(read(T()), "missing") + + def test_member_replaced_by_class_attribute(self): + class T: + __slots__ = ("a",) + + member = T.__dict__["a"] + + def read(t): + try: + return t.a + except AttributeError: + return "missing" + + for _ in range(1000): + self.assertEqual(read(T()), "missing") + T.a = "class value" + self.assertEqual(read(T()), "class value") + T.a = member + self.assertEqual(read(T()), "missing") + t = T() + t.a = 5 + self.assertEqual(read(t), 5) + + def test_subclass_layouts(self): + class A: + __slots__ = ("x",) + + class B(A): + __slots__ = ("y",) + + class C(A): + __slots__ = ("z", "y") + + def read_y(o): + try: + return o.y + except AttributeError: + return None + + for i in range(1500): + b, c = B(), C() + self.assertIsNone(read_y(b)) + self.assertIsNone(read_y(c)) + if i % 3 == 0: + b.y = i + c.y = -i + self.assertEqual(read_y(b), i) + self.assertEqual(read_y(c), -i) + self.assertIsNone(read_y(A())) + + def test_deleted_member(self): + class T: + __slots__ = ("a",) + + def read(t): + try: + return t.a + except AttributeError: + return "missing" + + t = T() + for i in range(1000): + t.a = i + self.assertEqual(read(t), i) + del t.a + self.assertEqual(read(t), "missing") + + def test_stack_receiver(self): + class T: + __slots__ = ("a",) + + hits = 0 + for i in range(2000): + try: + T().a + except AttributeError: + hits += 1 + self.assertEqual(hits, 2000) + + +kept = [] + + +class Catcher: + __slots__ = ("v",) + + def inner(self, keep): + marker = "inner local" + try: + return self.v + except AttributeError as e: + if keep: + kept.append(e) + self.v = len(marker) + return -1 + + def outer(self, keep): + outer_marker = "outer local" + r = self.inner(keep) + return r, outer_marker + + +class CatchAndReturn(unittest.TestCase): + def test_returns(self): + for i in range(3000): + c = Catcher() + self.assertEqual(c.outer(False), (-1, "outer local")) + self.assertEqual(c.outer(False), (11, "outer local")) + + def test_kept_traceback_after_return(self): + kept.clear() + for i in range(500): + c = Catcher() + self.assertEqual(c.outer(i % 100 == 0), (-1, "outer local")) + self.assertEqual(len(kept), 5) + for e in kept: + tb = e.__traceback__ + frame = tb.tb_frame + self.assertEqual(frame.f_code.co_name, "inner") + self.assertEqual(frame.f_locals["marker"], "inner local") + self.assertIsNone(tb.tb_next) + kept.clear() + + def test_frame_seen_in_handler(self): + seen = [] + + class F: + __slots__ = ("v",) + + def inner(self): + try: + return self.v + except AttributeError: + f = sys._getframe() + seen.append((f.f_code.co_name, f.f_back.f_code.co_name)) + return 0 + + def outer(self): + return self.inner() + 1 + + for i in range(1000): + self.assertEqual(F().outer(), 1) + self.assertEqual(len(seen), 1000) + self.assertEqual(seen[-1], ("inner", "outer")) + + def test_exception_context_in_handler(self): + class E: + __slots__ = ("v",) + + def inner(self): + try: + return self.v + except AttributeError: + try: + raise KeyError("k") + except KeyError as k: + return type(k.__context__).__name__ + + def outer(self): + return self.inner() + + for _ in range(1000): + self.assertEqual(E().outer(), "AttributeError") + self.assertIsNone(sys.exception()) + + +class PropertySitesBeforeCompiling(unittest.TestCase): + """A local receiver's property read at a site that cached the getter, + in loops short enough to stay interpreted.""" + + def test_instance_dict_entry_of_the_same_name(self): + class P: + @property + def v(self): + return "property" + + p = P() + p.__dict__["v"] = "instance" + for _ in range(300): + self.assertEqual(p.v, "property") + del P.v + self.assertEqual(p.v, "instance") + + def test_property_replaced_and_restored(self): + class P: + @property + def v(self): + return 1 + + prop = P.__dict__["v"] + p = P() + got = [] + for i in range(300): + if i == 100: + P.v = 2 + elif i == 200: + P.v = prop + got.append(p.v) + self.assertEqual(got, [1] * 100 + [2] * 100 + [1] * 100) + + def test_two_classes_at_one_site(self): + class A: + @property + def v(self): + return "a" + + class B: + def __init__(self): + self.v = "b field" + + class C: + @property + def v(self): + return "c" + + a, b, c = A(), B(), C() + for _ in range(200): + for o, want in ((a, "a"), (b, "b field"), (c, "c")): + self.assertEqual(o.v, want) + + def test_getattribute_subclass(self): + class P: + @property + def v(self): + return "property" + + class Q(P): + def __getattribute__(self, name): + return "hook" if name == "v" else object.__getattribute__(self, name) + + p, q = P(), Q() + for _ in range(300): + self.assertEqual(p.v, "property") + self.assertEqual(q.v, "hook") + + def test_getter_raises(self): + class P: + @property + def v(self): + raise KeyError("k") + + p = P() + for _ in range(300): + with self.assertRaises(KeyError): + p.v + + +class ClassHeldModules(unittest.TestCase): + def test_module_attribute_through_class(self): + import posixpath + import ntpath + + class Flavour: + parser = posixpath + + @classmethod + def seps(cls): + return cls.parser.sep, cls.parser.altsep + + for _ in range(2000): + self.assertEqual(Flavour.seps(), ("/", None)) + Flavour.parser = ntpath + self.assertEqual(Flavour.seps(), ("\\", "/")) + + class Sub(Flavour): + parser = posixpath + + for _ in range(500): + self.assertEqual(Sub.seps(), ("/", None)) + self.assertEqual(Flavour.seps(), ("\\", "/")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_sort_attrgetter_filter_leaf.py b/tests/regrtest/test_sort_attrgetter_filter_leaf.py new file mode 100644 index 000000000..e6e438804 --- /dev/null +++ b/tests/regrtest/test_sort_attrgetter_filter_leaf.py @@ -0,0 +1,162 @@ +"""`sorted` with an `attrgetter` key over `__slots__` instances, plain +instances, mixed classes, a missing slot and a dotted name; `filter` with +a leaf builtin predicate (its result's full truth test, a raise, a shared +iterator); and the ASCII paths of `str.isalpha`, `isalnum`, `isspace`, +`isdigit`, `isdecimal` and `isnumeric` against the Unicode ones.""" + +import unittest +from operator import attrgetter + +N = 300 + + +class S: + __slots__ = ("name", "age") + + def __init__(self, name, age): + self.name = name + self.age = age + + +class T: + __slots__ = ("age", "name") + + def __init__(self, name, age): + self.name = name + self.age = age + + +class D: + def __init__(self, name, age): + self.name = name + self.age = age + + +class Prop: + __slots__ = ("_age",) + + def __init__(self, age): + self._age = age + + @property + def age(self): + return -self._age + + +class Inner: + def __init__(self, v): + self.v = v + + +class Outer: + def __init__(self, v): + self.inner = Inner(v) + + +class SortAttrgetterTests(unittest.TestCase): + def test_slots(self): + rs = [S(str(i), (i * 7) % 13) for i in range(20)] + for _ in range(N): + out = sorted(rs, key=attrgetter("age")) + self.assertEqual([r.age for r in out], sorted(r.age for r in rs)) + self.assertEqual(sorted(rs, key=attrgetter("name"))[0].name, "0") + + def test_mixed_classes(self): + rs = [] + for i in range(30): + cls = (S, T, D)[i % 3] + rs.append(cls(str(i), (i * 5) % 11)) + rs.append(Prop(3)) + for _ in range(N): + out = sorted(rs, key=attrgetter("age")) + self.assertEqual([r.age for r in out], sorted(r.age for r in rs)) + + def test_unset_slot(self): + rs = [S("a", 1), S("b", 2)] + u = S.__new__(S) + u.name = "u" + for _ in range(N // 10): + with self.assertRaises(AttributeError): + sorted(rs + [u], key=attrgetter("age")) + + def test_dotted_and_missing(self): + os_ = [Outer(v) for v in (3, 1, 2)] + self.assertEqual([o.inner.v for o in sorted(os_, key=attrgetter("inner.v"))], [1, 2, 3]) + with self.assertRaises(AttributeError): + sorted([D("a", 1), D("b", 2)], key=attrgetter("missing")) + + def test_class_changed_between_sorts(self): + rs = [S(str(i), 10 - i) for i in range(10)] + self.assertEqual(sorted(rs, key=attrgetter("age"))[0].age, 1) + S.age2 = property(lambda self: -self.age) + try: + self.assertEqual(sorted(rs, key=attrgetter("age2"))[0].age, 10) + finally: + del S.age2 + + +class Weird: + def __init__(self, v): + self.v = v + + def __bool__(self): + return self.v + + +class FilterLeafTests(unittest.TestCase): + def test_predicates(self): + ws = "alpha b3ta gamma 42 de-lta eps".split() + for _ in range(N): + self.assertEqual(list(filter(str.isalpha, ws)), ["alpha", "gamma", "eps"]) + self.assertEqual(list(filter(str.isdigit, ws)), ["42"]) + self.assertEqual(list(filter(str.isalnum, ws)), ["alpha", "b3ta", "gamma", "42", "eps"]) + self.assertEqual(list(filter(len, ["", "a", ""])), ["a"]) + self.assertEqual(list(filter(abs, [0, -1, 0, 2])), [-1, 2]) + + def test_full_truth(self): + for _ in range(N // 10): + self.assertEqual(list(filter(tuple, [[], [1], (), "x"])), [[1], "x"]) + self.assertEqual(len(list(filter(Weird, [True, False, True]))), 2) + + def test_raise_and_consumption(self): + it = iter(["a", 1, "b"]) + with self.assertRaises(TypeError): + list(filter(str.isalpha, it)) + self.assertEqual(list(it), ["b"]) + f = filter(str.isalpha, ["a", "1", "b"]) + self.assertEqual(next(f), "a") + self.assertEqual(list(f), ["b"]) + + +class AsciiPredicateTests(unittest.TestCase): + def test_against_unicode(self): + cases = ["", "abc", "ABC", "a1", "12", "1.5", " ", "\t\n", "\x0b\x0c\r", "\x1c\x1d\x1e\x1f", + "a b", "_", "é", "aé", "é1", "١٢", "²", "½", " ", "a ", " \x85", "Ⅻ", + "x" * 40, "7" * 40, "\x00", "\x7f"] + want = { + "isalpha": [False, True, True, False, False, False, False, False, False, False, + False, False, True, True, False, False, False, False, False, False, + False, False, True, False, False, False], + "isalnum": [False, True, True, True, True, False, False, False, False, False, + False, False, True, True, True, True, True, True, False, False, + False, True, True, True, False, False], + "isspace": [False, False, False, False, False, False, True, True, True, True, + False, False, False, False, False, False, False, False, True, False, + True, False, False, False, False, False], + "isdigit": [False, False, False, False, True, False, False, False, False, False, + False, False, False, False, False, True, True, False, False, False, + False, False, False, True, False, False], + "isdecimal": [False, False, False, False, True, False, False, False, False, False, + False, False, False, False, False, True, False, False, False, False, + False, False, False, True, False, False], + "isnumeric": [False, False, False, False, True, False, False, False, False, False, + False, False, False, False, False, True, True, True, False, False, + False, True, False, True, False, False], + } + for _ in range(N // 30): + for name, expected in want.items(): + self.assertEqual([getattr(c, name)() for c in cases], expected, name) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_sort_floats_in_place.py b/tests/regrtest/test_sort_floats_in_place.py new file mode 100644 index 000000000..8aa0647b9 --- /dev/null +++ b/tests/regrtest/test_sort_floats_in_place.py @@ -0,0 +1,103 @@ +"""`list.sort()` and `sorted()` of floats order them as `<` does. + +Lists of only floats sort stably, forward and in reverse, with infinities, +signed zeros and NaNs placed as CPython's merge sort places them (a NaN +compares false both ways, so where it lands depends on the comparisons +made). Mixed int and float lists still compare exactly. +""" + +import math +import random +import unittest + + +def reference_sort(items, reverse=False): + """A plain stable merge sort that compares only with `<`.""" + items = list(items) + if reverse: + items.reverse() + def merge(a, b): + out = [] + i = j = 0 + while i < len(a) and j < len(b): + if b[j] < a[i]: + out.append(b[j]); j += 1 + else: + out.append(a[i]); i += 1 + return out + a[i:] + b[j:] + def sort(xs): + if len(xs) <= 1: + return xs + mid = len(xs) // 2 + return merge(sort(xs[:mid]), sort(xs[mid:])) + result = sort(items) + if reverse: + result.reverse() + return result + + +class FloatSortTests(unittest.TestCase): + def test_random(self): + rnd = random.Random(5) + for n in (0, 1, 2, 10, 100, 1000, 5000): + xs = [rnd.random() * 100 - 50 for _ in range(n)] + expected = reference_sort(xs) + l = xs[:] + l.sort() + self.assertEqual(l, expected) + self.assertEqual(sorted(xs), expected) + l = xs[:] + l.sort(reverse=True) + self.assertEqual(l, expected[::-1]) + self.assertEqual(sorted(xs, reverse=True), expected[::-1]) + + def test_specials(self): + xs = [3.0, -0.0, 0.0, math.inf, -math.inf, 1e-300, -1e300, 2.0, 0.0, -0.0] + l = xs[:] + l.sort() + self.assertEqual([math.copysign(1, x) if x == 0 else x for x in l], + [math.copysign(1, x) if x == 0 else x for x in reference_sort(xs)]) + # Zeros keep their order (equal values are stable). + zeros = [x for x in l if x == 0] + self.assertEqual([math.copysign(1, z) for z in zeros], [-1.0, 1.0, 1.0, -1.0]) + l = xs[:] + l.sort(reverse=True) + zeros = [x for x in l if x == 0] + self.assertEqual([math.copysign(1, z) for z in zeros], [-1.0, 1.0, 1.0, -1.0]) + + def test_stable_identity(self): + a, b, c = 1.5, 1.5, 0.5 + # Distinct objects with equal values keep their order. + a = float("1.5"); b = float("1.5") + l = [a, c, b] + l.sort() + self.assertIs(l[1], a) + self.assertIs(l[2], b) + l = [a, c, b] + l.sort(reverse=True) + self.assertIs(l[0], a) + self.assertIs(l[1], b) + + def test_nan(self): + nan = float("nan") + xs = [3.0, nan, 1.0, 2.0, nan, 0.5] + l = xs[:] + l.sort() + got = ["nan" if x != x else x for x in l] + want = ["nan" if x != x else x for x in reference_sort(xs)] + self.assertEqual(len(got), len(want)) + self.assertEqual(sorted(x for x in got if x != "nan"), + sorted(x for x in want if x != "nan")) + self.assertEqual(got.count("nan"), 2) + + def test_mixed_numbers(self): + xs = [2**53 + 1, float(2**53), 1, 0.5, True, -3, -2.5] + l = xs[:] + l.sort() + self.assertEqual(l, [-3, -2.5, 0.5, 1, True, float(2**53), 2**53 + 1]) + self.assertIs(type(l[3]), int) + self.assertIs(type(l[4]), bool) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_sort_keyword_calls.py b/tests/regrtest/test_sort_keyword_calls.py new file mode 100644 index 000000000..4249fa5fb --- /dev/null +++ b/tests/regrtest/test_sort_keyword_calls.py @@ -0,0 +1,156 @@ +"""`list.sort` and `sorted` called with keywords. + +`xs.sort(reverse=True)`, `xs.sort(key=None)` and `sorted(xs, key=None, +reverse=...)` of plain numbers or strings sort in place of the full call, +with CPython's stability: a reverse sort keeps equal items in their +original order. Any other key, item or argument shape takes the full call +and its errors, including a positional argument to `list.sort` and +`sorted`'s positional-only iterable passed by keyword. +""" + +import unittest + + +class SortKeywordTests(unittest.TestCase): + def test_reverse_and_none_key(self): + for _ in range(300): + xs = [3, 1, 2] + xs.sort(reverse=True) + self.assertEqual(xs, [3, 2, 1]) + xs.sort(key=None) + self.assertEqual(xs, [1, 2, 3]) + xs.sort(key=None, reverse=1) + self.assertEqual(xs, [3, 2, 1]) + xs.sort(reverse=False) + self.assertEqual(xs, [1, 2, 3]) + ws = ["b", "a", "é", "c"] + ws.sort(reverse=True) + self.assertEqual(ws, ["é", "c", "b", "a"]) + self.assertEqual(sorted((2.5, 1, True), reverse=True), [2.5, 1, True]) + self.assertEqual(sorted([3, 1, 2], key=None), [1, 2, 3]) + self.assertEqual(sorted([], reverse=True), []) + + def test_stability(self): + for _ in range(200): + xs = [1, True, 1.0, 0, False] + xs.sort(reverse=True) + self.assertEqual([type(x) for x in xs], [int, bool, float, int, bool]) + ys = sorted([1.0, 1, True, 0.0, 0], reverse=True) + self.assertEqual([type(y) for y in ys], [float, int, bool, float, int]) + src = (True, 1, 1.0) + out = sorted(src, key=None) + self.assertEqual([type(v) for v in out], [bool, int, float]) + + def test_other_shapes(self): + xs = ["bb", "a", "ccc"] + for _ in range(200): + xs.sort(key=len) + self.assertEqual(xs, ["a", "bb", "ccc"]) + xs.sort(key=len, reverse=True) + self.assertEqual(xs, ["ccc", "bb", "a"]) + self.assertEqual(sorted(iter([2, 1]), reverse=True), [2, 1]) + self.assertEqual(sorted({3, 1}, reverse=True), [3, 1]) + with self.assertRaises(TypeError): + [1, "a"].sort(reverse=True) + with self.assertRaises(TypeError): + sorted([1, "a"], reverse=True) + with self.assertRaises(TypeError): + [1].sort(None) + with self.assertRaises(TypeError): + [1].sort(None, reverse=True) + with self.assertRaises(TypeError): + [1].sort(nope=True) + with self.assertRaises(TypeError): + sorted(iterable=[1]) + with self.assertRaises(TypeError): + sorted([1], nope=1) + ys = [2, 1] + ys.sort(reverse="yes") + self.assertEqual(ys, [2, 1]) + + class L(list): + pass + + z = L([2, 3, 1]) + z.sort(reverse=True) + self.assertEqual(z, [3, 2, 1]) + + def test_tuples(self): + for _ in range(200): + ps = [(2, "b"), (1, "z"), (2, "a"), (1, "a", 0), (1, "a")] + ps.sort() + self.assertEqual(ps, [(1, "a"), (1, "a", 0), (1, "z"), (2, "a"), (2, "b")]) + ps.sort(reverse=True) + self.assertEqual(ps, [(2, "b"), (2, "a"), (1, "z"), (1, "a", 0), (1, "a")]) + self.assertEqual(sorted([(1, True), (1, 0), ()]), [(), (1, 0), (1, True)]) + same = [(1, True), (1, 1)] + same.sort(reverse=True) + self.assertEqual([type(t[1]) for t in same], [bool, int]) + with self.assertRaises(TypeError) as cm: + [(1, "a"), (1, 2)].sort() + self.assertIn("'<' not supported", str(cm.exception)) + nested = [(1, (2,)), (1, (1,))] + nested.sort() + self.assertEqual(nested, [(1, (1,)), (1, (2,))]) + + def test_native_keys(self): + import collections + import operator + + words = ["ccc", "a", "bb", "dd", "e"] + items = [("x", 3), ("y", 1), ("z", 2), ("w", 1)] + + class P: + def __init__(self, n): + self.n = n + + ps = [P(3), P(1), P(2)] + for _ in range(200): + self.assertEqual(sorted(words, key=len), ["a", "e", "bb", "dd", "ccc"]) + self.assertEqual(sorted(words, key=len, reverse=True), ["ccc", "bb", "dd", "a", "e"]) + self.assertEqual(sorted(items, key=operator.itemgetter(1)), [("y", 1), ("w", 1), ("z", 2), ("x", 3)]) + self.assertEqual(sorted(items, key=operator.itemgetter(1), reverse=True), [("x", 3), ("z", 2), ("y", 1), ("w", 1)]) + self.assertEqual([p.n for p in sorted(ps, key=operator.attrgetter("n"))], [1, 2, 3]) + ws = list(words) + ws.sort(key=len) + self.assertEqual(ws, ["a", "e", "bb", "dd", "ccc"]) + self.assertEqual(sorted(items, key=operator.itemgetter(1, 0)), [("w", 1), ("y", 1), ("z", 2), ("x", 3)]) + c = collections.Counter("abracadabra") + self.assertEqual(c.most_common(3), [("a", 5), ("b", 2), ("r", 2)]) + with self.assertRaises(TypeError): + sorted([1, 2], key=len) + with self.assertRaises(TypeError): + sorted([("a", 1), ("b", "x")], key=operator.itemgetter(1)) + with self.assertRaises(IndexError): + sorted([(1,), ()], key=operator.itemgetter(0)) + self.assertEqual(sorted([[1, 2], [1], []], key=len), [[], [1], [1, 2]]) + + def test_dicts_and_views(self): + import collections + import operator + + d = {"b": 2, "a": 3, "c": 1} + for _ in range(200): + self.assertEqual(sorted(d.items(), key=operator.itemgetter(1)), [("c", 1), ("b", 2), ("a", 3)]) + self.assertEqual(sorted(d.items(), key=operator.itemgetter(1), reverse=True), [("a", 3), ("b", 2), ("c", 1)]) + self.assertEqual(sorted(d, reverse=True), ["c", "b", "a"]) + self.assertEqual(sorted(d.keys(), key=None), ["a", "b", "c"]) + self.assertEqual(sorted(d.values(), reverse=True), [3, 2, 1]) + self.assertEqual(sorted(d.items(), reverse=True), [("c", 1), ("b", 2), ("a", 3)]) + c = collections.Counter("aabbbc") + self.assertEqual(sorted(c.items(), key=operator.itemgetter(1), reverse=True), [("b", 3), ("a", 2), ("c", 1)]) + self.assertEqual(sorted({}.items(), reverse=True), []) + with self.assertRaises(TypeError): + sorted({1: "a", "x": "b"}, reverse=True) + + def test_sorted_returns_new_list(self): + src = [3, 1, 2] + out = sorted(src, reverse=True) + self.assertEqual(src, [3, 1, 2]) + self.assertIsNot(out, src) + out.append(0) + self.assertEqual(src, [3, 1, 2]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_sort_lambda_part_keys.py b/tests/regrtest/test_sort_lambda_part_keys.py new file mode 100644 index 000000000..ea1adecca --- /dev/null +++ b/tests/regrtest/test_sort_lambda_part_keys.py @@ -0,0 +1,93 @@ +"""`sorted`/`list.sort` with a key lambda that reads one part of each item +(`lambda kv: kv[1]`, `lambda r: r["age"]`, `lambda p: p.x`): the order, +stability and `reverse` match the general call, items the shortcut doesn't +serve (strings, other mappings, misses) take the full call and raise +what it raises, and a trace hook still sees every call.""" + +import sys +import unittest +from collections import OrderedDict + +N = 300 + + +class P: + __slots__ = ("x", "y") + + def __init__(self, x, y): + self.x = x + self.y = y + + +class Q: + def __init__(self, x): + self.x = x + + +class SortLambdaKeyTests(unittest.TestCase): + def test_index(self): + d = {"k%d" % i: (i * 7) % 11 for i in range(30)} + want = sorted(d.items(), key=lambda kv: (kv[1],)) + for _ in range(N): + self.assertEqual(sorted(d.items(), key=lambda kv: kv[1]), want) + self.assertEqual( + sorted(d.items(), key=lambda kv: kv[1], reverse=True), + sorted(d.items(), key=lambda kv: (kv[1],), reverse=True), + ) + rows = [[i, -i, i % 3] for i in range(12)] + self.assertEqual(sorted(rows, key=lambda r: r[-1]), sorted(rows, key=lambda r: (r[2],))) + + def test_str_key(self): + rows = [{"name": "n%d" % i, "age": (i * 5) % 7} for i in range(20)] + for _ in range(N): + out = sorted(rows, key=lambda r: r["age"]) + self.assertEqual([r["age"] for r in out], sorted(r["age"] for r in rows)) + # Stable: equal ages keep their order. + self.assertEqual(out, sorted(rows, key=lambda r: (r["age"],))) + with self.assertRaises(KeyError): + sorted(rows + [{"name": "x"}], key=lambda r: r["age"]) + od = [OrderedDict(age=3), OrderedDict(age=1)] + self.assertEqual([r["age"] for r in sorted(od, key=lambda r: r["age"])], [1, 3]) + + def test_attr(self): + ps = [P(i % 4, i) for i in range(16)] + [Q(2)] + for _ in range(N): + out = sorted(ps, key=lambda p: p.x) + self.assertEqual([p.x for p in out], sorted(p.x for p in ps)) + with self.assertRaises(AttributeError): + sorted([P(1, 2), object()], key=lambda p: p.x) + + def test_fallbacks(self): + ws = ["pear", "fig", "apple", "kiwi"] + for _ in range(N // 10): + self.assertEqual(sorted(ws, key=lambda w: w[-1]), ["apple", "fig", "kiwi", "pear"]) + n = 1 + self.assertEqual(sorted([(1, 2), (0, 3)], key=lambda t: t[n]), [(1, 2), (0, 3)]) + self.assertEqual( + sorted([(1, 2), (0, 3)], key=lambda t, i=0: t[i]), [(0, 3), (1, 2)] + ) + with self.assertRaises(IndexError): + sorted([(1,), (2, 3)], key=lambda t: t[1]) + xs = [(3, "c"), (1, "a"), (2, "b")] + xs.sort(key=lambda t: t[0]) + self.assertEqual(xs, [(1, "a"), (2, "b"), (3, "c")]) + + def test_trace_sees_calls(self): + calls = [] + + def tracer(frame, event, arg): + if event == "call" and frame.f_code.co_name == "": + calls.append(1) + return None + + items = [(i, -i) for i in range(5)] + sys.settrace(tracer) + try: + sorted(items, key=lambda t: t[1]) + finally: + sys.settrace(None) + self.assertEqual(len(calls), 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_sort_tuple_keys_plain.py b/tests/regrtest/test_sort_tuple_keys_plain.py new file mode 100644 index 000000000..4e189b001 --- /dev/null +++ b/tests/regrtest/test_sort_tuple_keys_plain.py @@ -0,0 +1,51 @@ +"""Sorting tuples of ints, bools and strings (the items themselves or keys +from `itemgetter(1, 0)`), whose elements compare natively, keeps CPython's +order and errors: ties broken by later fields, shorter tuples first, bools +as ints, strings in code-point order, stability, reverse, and a string +against an int raising `TypeError`.""" + +import operator +import random +import unittest + +N = 300 + + +class SortTupleKeysTests(unittest.TestCase): + def test_against_reference(self): + r = random.Random(3) + words = ["b", "a", "ab", "", "\xe9", "z", "\U0001f600", "Z", "aa"] + for _ in range(N): + items = [(r.choice(words), r.randrange(-3, 4), r.choice((True, False, 0, 1))) + for _ in range(r.randrange(0, 12))] + key = operator.itemgetter(1, 0) + got = sorted(items, key=key) + want = sorted(items, key=lambda t: (t[1], t[0])) + self.assertEqual(got, want) + self.assertEqual(sorted(items), sorted(items, key=lambda t: t)) + self.assertEqual(sorted(items, reverse=True), sorted(items, key=lambda t: t, reverse=True)) + self.assertEqual(sorted(items, key=operator.itemgetter(2, 1, 0)), + sorted(items, key=lambda t: (t[2], t[1], t[0]))) + + def test_order_details(self): + for _ in range(N): + self.assertEqual(sorted([(1, "b"), (1,), (0, "z"), (1, "a")]), + [(0, "z"), (1,), (1, "a"), (1, "b")]) + self.assertEqual(sorted([("\U0001f600",), ("￿",), ("\xe9",), ("e",)]), + [("e",), ("\xe9",), ("￿",), ("\U0001f600",)]) + self.assertEqual(sorted([(True, 2), (0, 1), (1, 1), (False, 0)]), + [(False, 0), (0, 1), (1, 1), (True, 2)]) + pairs = [("x", 1), ("y", 1), ("z", 0)] + self.assertEqual(sorted(pairs, key=operator.itemgetter(1, 1)), + [("z", 0), ("x", 1), ("y", 1)]) + + def test_mixed_raises(self): + with self.assertRaises(TypeError): + sorted([(1, "a"), ("a", 1)]) + with self.assertRaises(TypeError): + sorted([(1, "a"), (1, 2)]) + self.assertEqual(sorted([(1, "a"), (2, 2)]), [(1, "a"), (2, 2)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_sorted_dict_value_keys.py b/tests/regrtest/test_sorted_dict_value_keys.py new file mode 100644 index 000000000..76aa69192 --- /dev/null +++ b/tests/regrtest/test_sorted_dict_value_keys.py @@ -0,0 +1,69 @@ +"""`sorted(xs, key=d.__getitem__)` and `key=d.get` of an exact dict, whose +keys are read under one view of the table, keep CPython's results: ties in +order, `get` misses as `None`, `__getitem__` misses raising `KeyError`, +keys whose lookup runs `__eq__`, and subclasses.""" + +import unittest + +N = 2000 + + +class Key: + calls = 0 + + def __init__(self, v): + self.v = v + + def __hash__(self): + return hash(self.v) + + def __eq__(self, other): + Key.calls += 1 + return isinstance(other, Key) and self.v == other.v + + +class Missing(dict): + def __missing__(self, key): + return -1 + + +class SortedDictValueKeysTests(unittest.TestCase): + def test_getitem_and_get(self): + d = {"pear": 3, "fig": 1, "apple": 3, "kiwi": 2, 7: 0} + for _ in range(N): + self.assertEqual(sorted(d, key=d.__getitem__), [7, "fig", "kiwi", "pear", "apple"]) + self.assertEqual(sorted(d, key=d.get, reverse=True), ["pear", "apple", "kiwi", "fig", 7]) + self.assertEqual(max(d, key=d.get), "pear") + self.assertEqual(sorted(["kiwi", "fig"], key=d.get), ["fig", "kiwi"]) + self.assertEqual([*d], ["pear", "fig", "apple", "kiwi", 7]) + + def test_misses(self): + d = {"a": 2, "b": 1} + for _ in range(N // 10): + with self.assertRaises(TypeError): + # (`None` from a miss doesn't order against ints.) + sorted(["a", "zz", "b"], key=d.get) + self.assertEqual(sorted(["zz"], key=d.get), ["zz"]) + with self.assertRaises(KeyError) as cm: + sorted(["a", "zz"], key=d.__getitem__) + self.assertEqual(cm.exception.args, ("zz",)) + with self.assertRaises(TypeError): + sorted([[1]], key=d.get) + + def test_other_keys_and_subclasses(self): + k1, k2 = Key(1), Key(2) + d = {k1: 5, k2: 4} + Key.calls = 0 + for _ in range(N // 10): + self.assertEqual(sorted([Key(1), Key(2)], key=d.__getitem__)[0].v, 2) + self.assertGreater(Key.calls, 0) + m = Missing(a=1, b=0) + for _ in range(N // 10): + self.assertEqual(sorted(["a", "b", "c"], key=m.__getitem__), ["c", "b", "a"]) + f = {1.0: 1, 2: 0, (1, 2): 2} + for _ in range(N // 10): + self.assertEqual(sorted([1, 2, (1, 2)], key=f.__getitem__), [2, 1, (1, 2)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_split_attr_hashed_lookups.py b/tests/regrtest/test_split_attr_hashed_lookups.py new file mode 100644 index 000000000..fd0e16b54 --- /dev/null +++ b/tests/regrtest/test_split_attr_hashed_lookups.py @@ -0,0 +1,80 @@ +"""Instance attributes found by name hash: getattr, setattr and attribute +reads over instances with many attributes, with names built at run time +(not interned) as well as literal ones, and names that collide with a +method on the class.""" + +import unittest + + +def make_class(n): + names = ["a%d" % i for i in range(n)] + + class Many: + def __init__(self): + for i, name in enumerate(names): + setattr(self, name, i) + + def method(self): + return "method" + + def get(self, k): + return getattr(self, k) + + return Many, names + + +class SplitAttrHashedLookups(unittest.TestCase): + def test_getattr_hits_and_misses(self): + Many, names = make_class(30) + for _ in range(300): + m = Many() + for i, name in enumerate(names): + # A fresh, non-interned string with the same text. + built = "".join(["a", str(i)]) + self.assertEqual(getattr(m, built), i) + self.assertEqual(getattr(m, name), i) + self.assertEqual(getattr(m, "missing", "dflt"), "dflt") + self.assertEqual(getattr(m, "".join(["miss", "ing"]), 7), 7) + self.assertFalse(hasattr(m, "a30")) + self.assertTrue(hasattr(m, "a29")) + self.assertEqual(getattr(m, "method")(), "method") + + def test_instance_value_shadows_method(self): + Many, names = make_class(20) + for _ in range(300): + m = Many() + self.assertEqual(m.method(), "method") + m.method = lambda: "own" + self.assertEqual(m.method(), "own") + self.assertEqual(getattr(m, "".join(["met", "hod"]))(), "own") + del m.method + self.assertEqual(m.method(), "method") + + def test_setattr_replaces_in_place(self): + Many, names = make_class(25) + for _ in range(300): + m = Many() + for i in range(25): + setattr(m, "".join(["a", str(i)]), i * 2) + self.assertEqual([getattr(m, n) for n in names], [i * 2 for i in range(25)]) + setattr(m, "".join(["extra", "_x"]), 5) + self.assertEqual(m.extra_x, 5) + self.assertEqual(list(vars(m))[-1], "extra_x") + self.assertEqual(len(vars(m)), 26) + + def test_attribute_reads_after_class_change(self): + Many, names = make_class(18) + out = [] + for j in range(400): + m = Many() + if j == 200: + Many.extra = "cls" + out.append((m.a3, getattr(m, "extra", None))) + self.assertEqual(out[0], (3, None)) + self.assertEqual(out[199], (3, None)) + self.assertEqual(out[200], (3, "cls")) + self.assertEqual(out[-1], (3, "cls")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_splitlines_bytearray_del_lanes.py b/tests/regrtest/test_splitlines_bytearray_del_lanes.py new file mode 100644 index 000000000..e00e558e3 --- /dev/null +++ b/tests/regrtest/test_splitlines_bytearray_del_lanes.py @@ -0,0 +1,113 @@ +"""`str.splitlines` over ASCII text read a word at a time (every break +kind, `keepends`, breaks at and across word edges, a line with no break +giving the string itself), and `del buf[i]` of a bytearray in compiled +code (negative and out-of-range indexes, a live memoryview's export).""" + +import unittest + +N = 2000 + +BREAKS = ["\n", "\r", "\r\n", "\x0b", "\x0c", "\x1c", "\x1d", "\x1e"] + + +def reference(s, keepends=False): + out, start, i = [], 0, 0 + while i < len(s): + c = s[i] + if c in "\n\r\x0b\x0c\x1c\x1d\x1e\x85

": + end = i + 1 + if c == "\r" and s[i + 1 : i + 2] == "\n": + end = i + 2 + out.append(s[start : end if keepends else i]) + start = i = end + else: + i += 1 + if start < len(s): + out.append(s[start:]) + return out + + +class SplitlinesTests(unittest.TestCase): + def test_every_break_at_every_offset(self): + for br in BREAKS: + for k in range(0, 20): + for tail in ("", "z", "tail text!"): + s = "x" * k + br + tail + self.assertEqual(s.splitlines(), reference(s), repr(s)) + self.assertEqual(s.splitlines(True), reference(s, True), repr(s)) + + def test_mixed_and_controls(self): + cases = [ + "", + "\n", + "\n\n", + "a\r\n\r\nb", + "tab\there\x07bell\x1fus", + "\x00nul\x01\x1b[0m", + "line one\nline two\rline three\r\n", + "x" * 64 + "\n" + "y" * 63, + "\x1f\x1c" * 9, + ] + for _ in range(N // 100): + for s in cases: + self.assertEqual(s.splitlines(), reference(s), repr(s)) + self.assertEqual(s.splitlines(keepends=True), reference(s, True), repr(s)) + + def test_one_line_is_the_string(self): + s = "a single line of plain ascii text" + for _ in range(N): + parts = s.splitlines() + self.assertEqual(parts, [s]) + self.assertIs(s.splitlines()[0], s) + self.assertEqual("".splitlines(), []) + + def test_non_ascii(self): + for s in ("é\nü", "a\x85b", "a
b
c", "日本\r\n語"): + self.assertEqual(s.splitlines(), reference(s)) + self.assertEqual(s.splitlines(True), reference(s, True)) + + def test_subclass(self): + class S(str): + pass + + parts = S("ab\ncd").splitlines() + self.assertEqual(parts, ["ab", "cd"]) + self.assertIs(type(S("one").splitlines()[0]), str) + + +class BytearrayDelTests(unittest.TestCase): + def test_del_index(self): + ba = bytearray(b"abcdef") + for _ in range(N): + ba.extend(b"x") + del ba[-1] + self.assertEqual(ba, bytearray(b"abcdef")) + for _ in range(N // 100): + b2 = bytearray(b"012345") + del b2[0] + del b2[-2] + del b2[2] + self.assertEqual(b2, bytearray(b"125")) + + def test_out_of_range(self): + ba = bytearray(b"ab") + for _ in range(N // 100): + with self.assertRaises(IndexError): + del ba[5] + with self.assertRaises(IndexError): + del ba[-3] + self.assertEqual(ba, bytearray(b"ab")) + + def test_export(self): + ba = bytearray(b"abc") + for _ in range(N // 100): + m = memoryview(ba) + with self.assertRaises(BufferError): + del ba[0] + m.release() + del ba[0] + self.assertEqual(ba, bytearray(b"bc")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_spread_args_tuple.py b/tests/regrtest/test_spread_args_tuple.py new file mode 100644 index 000000000..c20505769 --- /dev/null +++ b/tests/regrtest/test_spread_args_tuple.py @@ -0,0 +1,64 @@ +"""A call's spread arguments (`f(a, *rest)`) and a starred tuple display +(`(a, *rest)`) build their tuple straight from the leading items and an +exact tuple or list; other sources take the general steps.""" + +import gc +import unittest + +G = (7, 8) + + +def args(*a): + return a + + +class Seq: + def __iter__(self): + return iter([5, 6]) + + +class SpreadTests(unittest.TestCase): + def test_sources(self): + t, l, s = (1, 2), [3, 4], Seq() + for _ in range(300): + self.assertEqual(args(0, *t), (0, 1, 2)) + self.assertEqual(args(0, 9, *l), (0, 9, 3, 4)) + self.assertEqual(args(0, *s), (0, 5, 6)) + self.assertEqual(args(0, *"ab"), (0, "a", "b")) + self.assertEqual(args(0, *(x for x in (1, 2))), (0, 1, 2)) + self.assertEqual(args(0, *G), (0, 7, 8)) + self.assertEqual(args(0, *()), (0,)) + self.assertEqual(args(0, *[]), (0,)) + self.assertEqual((0, *t), (0, 1, 2)) + self.assertEqual((*l,), (3, 4)) + + def test_source_unchanged_and_items_shared(self): + l = [object(), object()] + for _ in range(200): + r = args(1, *l) + self.assertEqual(len(l), 2) + self.assertIs(r[1], l[0]) + self.assertIs(r[2], l[1]) + self.assertIsInstance(r, tuple) + + def test_errors(self): + def bad(x): + return args(1, *x) + for _ in range(200): + with self.assertRaises(TypeError): + bad(5) + self.assertEqual(bad([2]), (1, 2)) + + def test_cycles_still_collected(self): + class Node: + pass + for _ in range(300): + n = Node() + n.me = args(n, *[n]) + del n + gc.collect() + self.assertFalse([o for o in gc.get_objects() if type(o) is Node]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_spread_leaf_call.py b/tests/regrtest/test_spread_leaf_call.py new file mode 100644 index 000000000..e91d84b3e --- /dev/null +++ b/tests/regrtest/test_spread_leaf_call.py @@ -0,0 +1,105 @@ +"""`f(*args)` in compiled code where `f` is a warm leaf the tuple's items +fill exactly: results, bound methods, keyword-only defaults, an empty +`**` mapping, an effect leaf (an attribute store), a raising body, +shapes the lane leaves to the general call (too few items, a list, +keywords, varargs), and a function whose code is replaced.""" + +import unittest + +N = 3000 + + +def add(a, b): + return a + b + + +def kwdef(a, b, *, c=10): + return a + b + c + + +def withdef(a, b=5): + return a * b + + +def div(a, b): + return a // b + + +def va(*xs): + return len(xs) + + +class Box: + def __init__(self): + self.v = 0 + + def m(self, a, b): + return a - b + + def put(self, a, b): + self.v = a + b + + +class SpreadLeafTests(unittest.TestCase): + def test_exact(self): + args = (3, 4) + t = 0 + for _ in range(N): + t += add(*args) + self.assertEqual(t, 7 * N) + for _ in range(N): + self.assertEqual(kwdef(*args), 17) + self.assertEqual(add(*args, **{}), 7) + + def test_bound_and_effect(self): + b = Box() + args = (9, 2) + for _ in range(N): + self.assertEqual(b.m(*args), 7) + b.put(*args) + self.assertEqual(b.v, 11) + + def test_other_shapes(self): + for _ in range(N // 10): + self.assertEqual(withdef(*(3,)), 15) + self.assertEqual(add(*[1, 2]), 3) + self.assertEqual(add(*(1,), b=5), 6) + self.assertEqual(va(*(1, 2, 3)), 3) + with self.assertRaises(TypeError): + add(*(1, 2, 3)) + + def test_raising(self): + args = (1, 0) + for _ in range(N // 10): + with self.assertRaises(ZeroDivisionError): + div(*args) + + def test_code_replaced(self): + def f(a, b): + return a + b + + def g(a, b): + return a * b + + args = (3, 4) + for _ in range(N): + self.assertEqual(f(*args), 7) + f.__code__ = g.__code__ + for _ in range(N): + self.assertEqual(f(*args), 12) + + def test_forwarder(self): + def deco(fn): + def w(*a, **k): + return fn(*a, **k) + + return w + + wadd = deco(add) + for _ in range(N): + self.assertEqual(wadd(1, 2), 3) + self.assertEqual(wadd(1, b=2), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_spread_native_classes.py b/tests/regrtest/test_spread_native_classes.py new file mode 100644 index 000000000..d07b8f9f5 --- /dev/null +++ b/tests/regrtest/test_spread_native_classes.py @@ -0,0 +1,107 @@ +"""`cls(*args)` of a natively served class (as `_strptime` builds its +result with `cls(*args)`) and of classes with a native constructor of +their own: the values, a subclass, bad arguments' errors, list spreads, +and a callee that changes between calls at one site.""" + +import collections +import datetime +import decimal +import itertools +import unittest + + +def build(cls, args): + return cls(*args) + + +class SpreadNativeClasses(unittest.TestCase): + def test_datetime(self): + for i in range(3000): + args = (2024, 1 + i % 12, 1 + i % 28, i % 24, i % 60, i % 60, i) + got = build(datetime.datetime, args) + self.assertEqual(got, datetime.datetime(*args)) + self.assertEqual(got.microsecond, i) + self.assertEqual(build(datetime.date, [2020, 2, 29]), datetime.date(2020, 2, 29)) + self.assertEqual(build(datetime.time, ()), datetime.time()) + self.assertEqual( + build(datetime.timedelta, (1, 2, 3)), datetime.timedelta(days=1, seconds=2, microseconds=3) + ) + + def test_subclass(self): + class Stamp(datetime.datetime): + def label(self): + return "stamp %d" % self.year + + class Made(datetime.date): + def __new__(cls, *args): + self = super().__new__(cls, *args) + self.extra = "made" + return self + + for i in range(1500): + s = build(Stamp, (2000 + i % 30, 1, 2)) + self.assertIs(type(s), Stamp) + self.assertEqual(s.label(), "stamp %d" % (2000 + i % 30)) + m = build(Made, (2001, 2, 3)) + self.assertIs(type(m), Made) + self.assertEqual(m.extra, "made") + + def test_errors(self): + for i in range(1000): + with self.assertRaises(ValueError): + build(datetime.datetime, (2024, 13, 1)) + with self.assertRaises(TypeError): + build(datetime.datetime, ("2024", 1, 1)) + with self.assertRaises(TypeError): + build(datetime.date, (2024,)) + self.assertEqual(build(datetime.date, (2024, 5, 6)).day, 6) + + def test_other_native_classes(self): + for i in range(1000): + self.assertEqual(build(decimal.Decimal, ("1.%d" % i,)), decimal.Decimal("1.%d" % i)) + d = build(collections.defaultdict, (list,)) + d["k"].append(i) + self.assertEqual(d, {"k": [i]}) + self.assertEqual(list(build(itertools.chain, ([1], (2,), "a"))), [1, 2, "a"]) + self.assertEqual( + list(build(itertools.product, [[0, 1], "ab"])), + [(0, "a"), (0, "b"), (1, "a"), (1, "b")], + ) + self.assertEqual(list(build(itertools.repeat, ("x", 2))), ["x", "x"]) + + def test_callee_changes_at_site(self): + classes = [datetime.date, collections.OrderedDict, decimal.Decimal, tuple, dict] + argsets = [(2024, 1, 2), ([("a", 1)],), ("2.5",), ([1, 2],), ([("b", 2)],)] + want = [ + datetime.date(2024, 1, 2), + collections.OrderedDict(a=1), + decimal.Decimal("2.5"), + (1, 2), + {"b": 2}, + ] + for i in range(2500): + k = i % 5 + self.assertEqual(build(classes[k], argsets[k]), want[k]) + + def test_items_released(self): + import gc + import weakref + + class Tz(datetime.tzinfo): + def utcoffset(self, dt): + return datetime.timedelta(0) + + for _ in range(300): + tz = Tz() + r = weakref.ref(tz) + dt = build(datetime.datetime, (2024, 1, 1, 0, 0, 0, 0, tz)) + self.assertIs(dt.tzinfo, tz) + del tz + self.assertIsNotNone(r()) + del dt + gc.collect() + self.assertIsNone(r()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_stack_receiver_reads_with_threads.py b/tests/regrtest/test_stack_receiver_reads_with_threads.py new file mode 100644 index 000000000..7620e7702 --- /dev/null +++ b/tests/regrtest/test_stack_receiver_reads_with_threads.py @@ -0,0 +1,159 @@ +"""Attribute reads off temporaries while a second thread is alive. + +A compiled read whose receiver is a temporary (`self._lock.__exit__`, +`make().field`) replaces the receiver with the value in its stack slot. +Once another thread exists, reference counts are shared and the cheap +release no longer applies; the read must still answer from the site's +memos, release the receiver on time, and give the same values as with +one thread. +""" + +import collections +import sys +import threading +import unittest +import weakref + +ROUNDS = 3000 + +Point = collections.namedtuple("Point", "x y") + + +class Guarded: + kind = "guarded" + limit = 10 + + def __init__(self): + self._lock = threading.Lock() + self.entered = 0 + + def __enter__(self): + self.entered += 1 + return self._lock.__enter__() + + def __exit__(self, *args): + # A native method read off a temporary, called with `*args`. + return self._lock.__exit__(*args) + + +class Node: + label = "node" + + def __init__(self, n): + self.value = n + self.child = None + + def __del__(self): + Node.dropped += 1 + + +Node.dropped = 0 + + +def make_node(n): + return Node(n) + + +def make_point(n): + return Point(n, n + 1) + + +def frame_name(): + return sys._getframe().f_code.co_name + + +class Holder: + def __init__(self): + self.node = Node(0) + self.point = Point(1, 2) + self.guard = Guarded() + + def chain(self): + return self.node.value + self.point.y + self.guard.limit + + def kinds(self): + return self.node.label + "/" + self.guard.kind + + def namespace(self): + return self.node.__dict__["value"] + + +def exercise(test): + g = Guarded() + h = Holder() + for i in range(ROUNDS): + with g: + test.assertTrue(g._lock.locked()) + test.assertFalse(g._lock.locked()) + test.assertEqual(make_point(i).y, i + 1) + test.assertEqual(make_node(i).value, i) + test.assertEqual(make_node(i).label, "node") + test.assertEqual(h.chain(), 0 + 2 + 10) + test.assertEqual(h.kinds(), "node/guarded") + test.assertEqual(h.namespace(), 0) + test.assertEqual(frame_name(), "frame_name") + test.assertEqual(type(h.node).label, "node") + test.assertEqual(g.entered, ROUNDS) + + +class StackReceiverTests(unittest.TestCase): + def test_single_thread(self): + Node.dropped = 0 + exercise(self) + self.assertEqual(Node.dropped, 2 * ROUNDS + 1) + + def test_with_an_idle_thread(self): + stop = threading.Event() + t = threading.Thread(target=stop.wait) + t.start() + try: + Node.dropped = 0 + exercise(self) + self.assertEqual(Node.dropped, 2 * ROUNDS + 1) + finally: + stop.set() + t.join() + + def test_temporaries_die_at_the_read(self): + stop = threading.Event() + t = threading.Thread(target=stop.wait) + t.start() + try: + refs = [] + + def read(n): + node = Node(n) + refs.append(weakref.ref(node)) + return node + + for i in range(500): + self.assertEqual(read(i).value, i) + self.assertIsNone(refs[-1]()) + finally: + stop.set() + t.join() + + def test_two_threads_reading(self): + errors = [] + + def work(): + try: + g = Guarded() + for i in range(ROUNDS): + with g: + pass + if make_point(i).x != i or make_node(i).value != i: + errors.append(i) + except Exception as e: # pragma: no cover + errors.append(e) + + ts = [threading.Thread(target=work) for _ in range(3)] + for t in ts: + t.start() + for t in ts: + t.join() + self.assertEqual(errors, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_starmap_pure_steps.py b/tests/regrtest/test_starmap_pure_steps.py new file mode 100644 index 000000000..f58b074f4 --- /dev/null +++ b/tests/regrtest/test_starmap_pure_steps.py @@ -0,0 +1,59 @@ +"""`itertools.starmap` steps in place over a list or tuple of tuples. + +With a callback that runs as a pure leaf (`operator.add`, `max`, a short +Python function), each tuple's fields are its arguments without the +general step; other items and callbacks keep the general step, and the +results and errors match it. +""" + +import itertools +import operator +import unittest + +N = 3000 + + +def addmul(a, b, c=2): + return (a + b) * c + + +class StarmapPureStepTests(unittest.TestCase): + def test_native_and_python_callbacks(self): + P = [(1, 2), (3, 4)] + for _ in range(N): + a = list(itertools.starmap(operator.add, P)) + b = list(itertools.starmap(max, ((1, 5, 2), (7, 0)))) + c = list(itertools.starmap(addmul, [(1, 2), (3, 4, 5)])) + self.assertEqual(a, [3, 7]) + self.assertEqual(b, [5, 7]) + self.assertEqual(c, [6, 35]) + + def test_non_tuple_items(self): + for _ in range(N): + r = list(itertools.starmap(operator.add, [(1, 2), [3, 4], "ab"])) + self.assertEqual(r, [3, 7, "ab"]) + + def test_errors_and_partial_reads(self): + for _ in range(N): + it = itertools.starmap(operator.truediv, [(1, 2), (1, 0), (3, 4)]) + first = next(it) + with self.assertRaises(ZeroDivisionError): + next(it) + rest = list(it) + self.assertEqual((first, rest), (0.5, [0.75])) + with self.assertRaises(TypeError): + list(itertools.starmap(operator.add, [(1,)])) + + def test_side_effects_in_order(self): + seen = [] + + def note(x, y): + seen.append((x, y)) + return x + + list(itertools.starmap(note, [(1, 2), (3, 4)])) + self.assertEqual(seen, [(1, 2), (3, 4)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_stdlib_leaf_calls.py b/tests/regrtest/test_stdlib_leaf_calls.py new file mode 100644 index 000000000..81b488e2d --- /dev/null +++ b/tests/regrtest/test_stdlib_leaf_calls.py @@ -0,0 +1,84 @@ +"""Calls compiled code runs in place: math.prod and math.fsum of lists +and tuples of plain numbers (int overflow, floats mixed in, bools, a +start value), unicodedata lookups and their argument errors, +csv.reader construction with default and given dialects, and stores +into a SimpleNamespace (a dunder name, attributes read back), each +matching CPython.""" + +import csv +import math +import types +import unicodedata +import unittest + + +def run(n, f, *args, **kw): + out = None + for i in range(n): + out = f(*args, **kw) + return out + + +class LeafCallTests(unittest.TestCase): + def test_prod_fsum(self): + for n in (1, 300): + self.assertEqual(run(n, math.prod, [2, 3, 4]), 24) + self.assertEqual(run(n, math.prod, (2, 3.5, 4)), 28.0) + self.assertEqual(run(n, math.prod, [10**10] * 3), 10**30) + self.assertEqual(run(n, math.prod, [2**62, 4]), 2**64) + self.assertEqual(run(n, math.prod, []), 1) + self.assertEqual(run(n, math.prod, [2, True]), 2) + self.assertEqual(run(n, math.prod, [1.5], start=2), 3.0) + self.assertEqual(run(n, math.fsum, [0.1] * 10), 1.0) + self.assertEqual(run(n, math.fsum, (1, 2.5)), 3.5) + with self.assertRaises(TypeError): + run(300, math.prod, [[1], 2.5]) + + def test_unicodedata(self): + for n in (1, 300): + self.assertEqual(run(n, unicodedata.category, "A"), "Lu") + self.assertEqual(run(n, unicodedata.name, "a"), "LATIN SMALL LETTER A") + self.assertEqual(run(n, unicodedata.decimal, "x", None), None) + for f, arg in ((unicodedata.category, "argument"), (unicodedata.name, "argument 1")): + with self.assertRaises(TypeError) as cm: + f("ab") + self.assertEqual( + str(cm.exception), + f"{f.__name__}(): {arg} must be a unicode character, not a string of length 2", + ) + with self.assertRaises(TypeError) as cm: + f(5) + self.assertEqual( + str(cm.exception), f"{f.__name__}() {arg} must be a unicode character, not int" + ) + + def test_csv(self): + lines = ["a,b", '"c,d",e'] + for n in (1, 300): + self.assertEqual(run(n, lambda: list(csv.reader(lines))), [["a", "b"], ["c,d", "e"]]) + self.assertEqual(run(n, lambda: list(csv.reader(["a;b"], delimiter=";"))), [["a", "b"]]) + r = run(n, csv.reader, lines, "excel-tab") + self.assertEqual((r.dialect.delimiter, r.dialect.quotechar), ("\t", '"')) + d = csv.reader([]).dialect + self.assertEqual((d.delimiter, d.lineterminator, d.quoting, d.strict), (",", "\r\n", 0, False)) + + def test_namespace_store(self): + def store(n): + s = types.SimpleNamespace(a=0) + for i in range(n): + s.b = i + s.a += 1 + return s + + for n in (1, 400): + s = store(n) + self.assertEqual((s.a, s.b), (n, n - 1)) + self.assertEqual(vars(s), {"a": n, "b": n - 1}) + s = types.SimpleNamespace() + for i in range(300): + s.__doc__ = "d" + self.assertEqual(s.__doc__, "d") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_str_affix_tuple.py b/tests/regrtest/test_str_affix_tuple.py new file mode 100644 index 000000000..197b791de --- /dev/null +++ b/tests/regrtest/test_str_affix_tuple.py @@ -0,0 +1,39 @@ +"""`str.startswith` and `str.endswith` of a tuple of prefixes in compiled code. + +Any matching prefix or suffix answers, non-ASCII text matches by +characters, an empty tuple never matches, an empty string always does, +and a start position, a non-`str` item or a subclass's receiver take the +full path, whose errors read as CPython's (a matching prefix ahead of a +bad item answers first, as there). Run it past the compile threshold. +""" + + +class S(str): + pass + + +def run(n): + for i in range(n): + s = "héllo wörld" + assert s.startswith(("x", "hé")) and not s.startswith(("x", "y")) + assert s.endswith(("ld", "z")) and not s.endswith(()) + assert s.startswith(("",)) and s.endswith(("rld",)) + assert s.startswith(("wö", "zz"), 6) and not s.startswith(("h",), 1) + assert S("abc").startswith(("a",)) and "abc".endswith(("bc", "x")) + assert s.startswith(("h", 1)) + try: + s.startswith(("x", 1)) + except TypeError as e: + assert str(e) == "tuple for startswith must only contain str, not int", e + else: + raise AssertionError("int in the prefix tuple") + try: + s.endswith(2.5) + except TypeError as e: + assert str(e) == "endswith first arg must be str or a tuple of str, not float", e + else: + raise AssertionError("float suffix") + + +run(3000) +print("ok") diff --git a/tests/regrtest/test_str_case_unchanged_ascii.py b/tests/regrtest/test_str_case_unchanged_ascii.py new file mode 100644 index 000000000..88302fa10 --- /dev/null +++ b/tests/regrtest/test_str_case_unchanged_ascii.py @@ -0,0 +1,45 @@ +"""`str.lower()` and `str.upper()` of ASCII text already in that case. + +An exact `str` may come back as itself; a subclass's instance must still +give a new exact `str`, and text that changes, or isn't ASCII, must map +as always. +""" + +import unittest + + +class S(str): + pass + + +class CaseTests(unittest.TestCase): + def test_values(self): + cases = ["", "abc", "ABC", "aBc", "hello world 123!", "ALL CAPS?", "x", "Z", "été", "ÉTÉ"] + for _ in range(200): + for s in cases: + self.assertEqual(s.lower(), "".join(c.lower() for c in s)) + self.assertEqual(s.upper(), "".join(c.upper() for c in s)) + self.assertIs(type(s.lower()), str) + self.assertEqual("straße".upper(), "STRASSE") + self.assertEqual("İ".lower(), "i̇") + self.assertEqual(sorted(["b", "A", "c"], key=str.lower), ["A", "b", "c"]) + + def test_subclass(self): + for s in ("abc", "ABC", "aBc", ""): + t = S(s) + for r in (t.lower(), t.upper(), str.lower(t), str.upper(t)): + self.assertIs(type(r), str) + self.assertIsNot(r, t) + self.assertEqual(t.lower(), s.lower()) + self.assertEqual(t.upper(), s.upper()) + + def test_other_cases_unchanged(self): + self.assertEqual("hello".title(), "Hello") + self.assertEqual("hello".capitalize(), "Hello") + self.assertEqual("hello".swapcase(), "HELLO") + self.assertEqual("123".swapcase(), "123") + self.assertEqual("abc".casefold(), "abc") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_str_dunder_direct.py b/tests/regrtest/test_str_dunder_direct.py new file mode 100644 index 000000000..4a13c859e --- /dev/null +++ b/tests/regrtest/test_str_dunder_direct.py @@ -0,0 +1,125 @@ +"""Compiled `str(obj)` calls a class's Python `__str__` directly; the +text, a `str` subclass result (kept as it is), a non-string result's +TypeError, raises (caught in the frame or past it), objects without +their own `__str__`, `str` shadowed, and methods replaced later match the +general call.""" + +import builtins +import unittest + + +class K: + def __init__(self, a): + self.a = a + self.calls = 0 + + def fmt(self): + return "K<%r>" % (self.a,) + + def __str__(self): + self.calls += 1 + return self.fmt() + + +class S(str): + pass + + +class SubResult: + def __str__(self): + return S("sub") + + +class Bad: + def __str__(self): + return 5 + + +class Raiser: + def __str__(self): + raise KeyError("str") + + +class OnlyRepr: + def __repr__(self): + return "R" + + +class StrDunderDirect(unittest.TestCase): + def test_text(self): + k = K("x") + for i in range(3000): + self.assertEqual(str(k), "K<'x'>") + self.assertEqual(k.calls, 3000) + + def test_subclass_result(self): + o = SubResult() + for i in range(1000): + r = str(o) + self.assertEqual(r, "sub") + self.assertIs(type(r), S) + + def test_bad_result(self): + b = Bad() + for i in range(500): + with self.assertRaises(TypeError) as cm: + str(b) + self.assertEqual(str(cm.exception), "__str__ returned non-string (type int)") + + def test_raises(self): + r = Raiser() + n = 0 + for i in range(1000): + try: + str(r) + except KeyError: + n += 1 + self.assertEqual(n, 1000) + + def show(o): + return str(o) + "!" + + for i in range(1000): + with self.assertRaises(KeyError): + show(r) + self.assertEqual(show(K(i)), "K<%d>!" % i) + + def test_other_objects(self): + o = OnlyRepr() + for i in range(1000): + self.assertEqual(str(o), "R") + self.assertEqual(str(i), "%d" % i) + self.assertEqual(str(S("s")), "s") + + def test_str_shadowed(self): + k = K(1) + real = builtins.str + try: + for i in range(500): + self.assertEqual(str(k), "K<1>") + builtins.str = lambda o: "shadow" + got = str(k) + finally: + builtins.str = real + self.assertEqual(got, "shadow") + self.assertEqual(str(k), "K<1>") + + def test_replaced(self): + class C: + def __str__(self): + return "a" + + c = C() + out = [] + for i in range(1000): + out.append(str(c)) + C.__str__ = lambda self: "b" + for i in range(1000): + out.append(str(c)) + del C.__str__ + self.assertTrue(str(c).startswith("<")) + self.assertEqual((out.count("a"), out.count("b")), (1000, 1000)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_str_encode_keywords.py b/tests/regrtest/test_str_encode_keywords.py new file mode 100644 index 000000000..f1b94decb --- /dev/null +++ b/tests/regrtest/test_str_encode_keywords.py @@ -0,0 +1,37 @@ +"""`str.encode` with its arguments by keyword, in compiled code. + +UTF-8 with a builtin error handler, by position or keyword, gives the +text's bytes; other codecs take the full path. An unknown keyword, a name +given twice, and a non-`str` encoding raise as CPython's do. Run it past +the compile threshold. +""" + + +def enc(s): + return ( + s.encode(encoding="utf-8"), + s.encode(errors="strict"), + s.encode("utf-8", errors="ignore"), + s.encode(encoding="latin-1", errors="strict"), + ) + + +def bad(s, **kw): + try: + s.encode(**kw) + except TypeError as e: + return str(e) + return None + + +for _ in range(3000): + assert enc("héllo") == (b"h\xc3\xa9llo",) * 3 + (b"h\xe9llo",) + assert bad("x", foo=1) == "encode() got an unexpected keyword argument 'foo'" + assert bad("x", encoding=1) == "encode() argument 'encoding' must be str, not int" + try: + "x".encode("utf-8", encoding="utf-8") + except TypeError as e: + assert "given by name ('encoding') and position (1)" in str(e) + else: + raise AssertionError("no raise") + assert "a€".encode(encoding="utf8") == b"a\xe2\x82\xac" diff --git a/tests/regrtest/test_str_encode_wide_codecs.py b/tests/regrtest/test_str_encode_wide_codecs.py new file mode 100644 index 000000000..d88cbbdc4 --- /dev/null +++ b/tests/regrtest/test_str_encode_wide_codecs.py @@ -0,0 +1,70 @@ +"""`s.encode()` to UTF-16 and UTF-32 by their common spellings, in hot +loops. + +Every spelling and byte order must give what the codec module gives, +for ASCII, BMP, and astral text; error handlers must be accepted as +CPython accepts them; a lone surrogate must still raise or pass as the +handler says. +""" + +import codecs +import unittest + +TEXTS = ["", "hello", "héllo", "日本語", "a\U0001f600b", "x" * 40 + "é"] +NAMES = { + "utf-16": "utf_16", + "utf_16": "utf_16", + "utf16": "utf_16", + "utf-16-le": "utf_16_le", + "utf-16le": "utf_16_le", + "utf_16_le": "utf_16_le", + "utf-16-be": "utf_16_be", + "utf-16be": "utf_16_be", + "utf_16_be": "utf_16_be", + "utf-32": "utf_32", + "utf_32": "utf_32", + "utf32": "utf_32", + "utf-32-le": "utf_32_le", + "utf-32le": "utf_32_le", + "utf_32_le": "utf_32_le", + "utf-32-be": "utf_32_be", + "utf-32be": "utf_32_be", + "utf_32_be": "utf_32_be", + "UTF-16": "utf_16", + "Utf-32-LE": "utf_32_le", +} + + +class StrEncodeWideCodecs(unittest.TestCase): + def test_spellings(self): + for spelling, name in NAMES.items(): + for t in TEXTS: + want = codecs.encode(t, name) + for _ in range(100): + self.assertEqual(t.encode(spelling), want) + self.assertEqual(t.encode(spelling).decode(spelling), t) + + def test_loop(self): + for i in range(5000): + s = "héllo" + str(i) + self.assertEqual(s.encode("utf-16"), codecs.BOM_UTF16_LE + s.encode("utf-16-le")) + + def test_handlers(self): + for _ in range(200): + self.assertEqual("é".encode("utf-16", "strict"), codecs.encode("é", "utf_16")) + self.assertEqual("é".encode("utf-32-be", errors="ignore"), b"\x00\x00\x00\xe9") + self.assertEqual("é".encode("utf-16-le", "no-such-handler"), b"\xe9\x00") + + def test_lone_surrogate(self): + s = "a\udc80b" + for _ in range(200): + with self.assertRaises(UnicodeEncodeError): + s.encode("utf-16") + with self.assertRaises(UnicodeEncodeError): + s.encode("utf-32-le") + self.assertEqual(s.encode("utf-16-le", "surrogatepass"), b"a\x00\x80\xdcb\x00") + self.assertEqual(s.encode("utf-16-le", "ignore"), b"a\x00b\x00") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_str_join_native_iterators.py b/tests/regrtest/test_str_join_native_iterators.py new file mode 100644 index 000000000..72144676e --- /dev/null +++ b/tests/regrtest/test_str_join_native_iterators.py @@ -0,0 +1,48 @@ +"""`str.join` and `bytes.join` of native iterators and with an empty +separator, in hot loops. + +The parts must come out as CPython joins them, a bad part must raise +the same TypeError, and the iterator must be left exhausted. +""" + +import unittest + + +class S(str): + pass + + +class StrJoinNativeIterators(unittest.TestCase): + def test_reversed_and_iter(self): + L = ["ab", "c", "", "déf"] + for i in range(3000): + self.assertEqual("".join(reversed("abcdef")), "fedcba") + self.assertEqual("-".join(iter(L)), "ab-c--déf") + self.assertEqual("".join(iter(L)), "abcdéf") + self.assertEqual(", ".join(reversed(L)), "déf, , c, ab") + self.assertEqual(b"".join(iter([b"x", b"yz"])), b"xyz") + self.assertEqual("".join(iter(())), "") + self.assertEqual("".join(reversed([S("q"), "r"])), "rq") + it = iter(L) + next(it) + self.assertEqual("".join(it), "cdéf") + self.assertEqual(list(it), []) + + def test_empty_separator(self): + parts = [str(i) for i in range(10)] + for _ in range(3000): + self.assertEqual("".join(parts), "0123456789") + self.assertEqual("".join(("é", "a", "€")), "éa€") + + def test_bad_part(self): + for _ in range(500): + with self.assertRaises(TypeError) as cm: + "".join(iter(["a", 1])) + self.assertIn("sequence item 1: expected str instance, int found", + str(cm.exception)) + with self.assertRaises(TypeError): + b"".join(iter([b"a", "b"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_str_partition_lines.py b/tests/regrtest/test_str_partition_lines.py new file mode 100644 index 000000000..f831dc17c --- /dev/null +++ b/tests/regrtest/test_str_partition_lines.py @@ -0,0 +1,73 @@ +"""`str.partition`, `rpartition`, `split`, `rsplit` and `splitlines` on exact strings. + +The pieces, the separator object returned as the middle item, the string +itself when the separator isn't found, every line boundary (`\\r\\n` +together, the ASCII controls, and the non-ASCII ones), `keepends`, and a +`str` subclass's results behave as in CPython. +""" + + +class S(str): + pass + + +def list_split(text, m): + out, start, i = [], 0, 0 + while i < len(text): + if text[i] == "," and (m < 0 or len(out) < m): + out.append(text[start:i]) + start = i + 1 + i += 1 + return out + [text[start:]] + + +def list_rsplit(text, m): + out, end, i = [], len(text), len(text) + while i > 0: + i -= 1 + if text[i] == "," and (m < 0 or len(out) < m): + out.append(text[i + 1:end]) + end = i + return [text[:end]] + out[::-1] + + +def run(n): + for _ in range(n): + s, sep = "key=value=x", "=" + p = s.partition(sep) + assert p == ("key", "=", "value=x") and p[1] is sep + r = s.rpartition(sep) + assert r == ("key=value", "=", "x") and r[1] is sep + miss = s.partition(";") + assert miss == (s, "", "") and miss[0] is s + rmiss = s.rpartition(";") + assert rmiss == ("", "", s) and rmiss[2] is s + assert "a,b".partition(",") == ("a", ",", "b") + assert ",".partition(",") == ("", ",", "") + assert "ab".partition("ab") == ("", "ab", "") + assert S("x-y").partition("-") == ("x", "-", "y") + assert type(S("x-y").partition("-")[0]) is str + text = "a\nb\r\nc\rd\x0be\x0cf\x1cg\x1dh\x1ei" + assert text.splitlines() == list("abcdefghi") + assert text.splitlines(True)[:3] == ["a\n", "b\r\n", "c\r"] + assert "x\n\ny\n".splitlines() == ["x", "", "y"] + assert "x\n\ny\n".splitlines(keepends=True) == ["x\n", "\n", "y\n"] + assert "".splitlines() == [] and "\n".splitlines() == [""] + assert "é
z\x85w".splitlines() == ["é", "z", "w"] + assert S("p\nq").splitlines() == ["p", "q"] + for text in ("a,b,,c,", ",x", "é,ü,,ß", "k," * 20 + "end"): + for m in (-1, 0, 1, 2, 30): + assert text.split(",", m) == list_split(text, m) + assert text.rsplit(",", m) == list_rsplit(text, m) + assert "aaa".rsplit("aa") == ["a", ""] and "aaa".split("aa") == ["", "a"] + + +run(2000) +for bad in ("", ): + try: + "abc".partition(bad) + except ValueError: + pass + else: + raise AssertionError("empty separator") +print("ok") diff --git a/tests/regrtest/test_str_replace_one_byte.py b/tests/regrtest/test_str_replace_one_byte.py new file mode 100644 index 000000000..7cdc14564 --- /dev/null +++ b/tests/regrtest/test_str_replace_one_byte.py @@ -0,0 +1,73 @@ +"""`str.replace` of one ASCII character by another, which copies the text +once and changes each match in place, keeps CPython's results: counts +(none, some, all, negative), no match, matches at both ends, non-ASCII +text around them, subclasses, and the other shapes beside it.""" + +import unittest + +N = 300 + + +class S(str): + pass + + +class ReplaceOneByteTests(unittest.TestCase): + def check(self, s, a, b, *count): + want = "".join(b if c == a else c for c in s) if not count or count[0] < 0 else None + for _ in range(N): + got = s.replace(a, b, *count) + self.assertIs(type(got), str) + if want is not None: + self.assertEqual(got, want) + return got + + def test_counts(self): + s = "the quick brown fox jumps over the lazy dog" + self.check(s, "o", "0") + self.check(s, "o", "0", -1) + self.assertEqual(self.check(s, "o", "0", 0), s) + self.assertEqual(self.check(s, "o", "0", 1), "the quick br0wn fox jumps over the lazy dog") + self.assertEqual(self.check(s, "o", "0", 3), "the quick br0wn f0x jumps 0ver the lazy dog") + self.assertEqual(self.check(s, "o", "0", 4), s.replace("o", "0")) + self.assertEqual(self.check(s, "o", "0", 99), s.replace("o", "0")) + self.assertEqual(s.replace("o", "0", count=2), "the quick br0wn f0x jumps over the lazy dog") + + def test_edges(self): + self.check("", "a", "b") + self.check("xyz", "a", "b") + self.check("aaaa", "a", "b") + self.check("abca", "a", "a") + self.check("a", "a", "\x7f") + self.check(" a b ", " ", "_") + self.check("a\x00b\x00", "\x00", "-") + # (Non-ASCII text around ASCII matches.) + self.check("h\xe9llo w€rld \U0001f600!o", "o", "0") + self.check("\xe9\xe9\xe9", "e", "E") + self.check("caf\xe9 au lait", " ", "-") + long = "ab" * 5000 + self.assertEqual(self.check(long, "a", "x"), "xb" * 5000) + self.assertEqual(long.replace("b", "y", 2500), "ay" * 2500 + "ab" * 2500) + + def test_result_is_fresh_and_hashes(self): + s = "hello" + r = s.replace("l", "L") + self.assertEqual(r, "heLLo") + self.assertEqual(hash(r), hash("heLLo")) + self.assertEqual({r: 1}["heLLo"], 1) + self.assertEqual(s, "hello") + self.assertIs(s.replace("z", "Z"), s) + + def test_subclass_and_other_shapes(self): + self.assertIs(type(S("abc").replace("a", "b")), str) + self.assertEqual(S("abca").replace("a", "z"), "zbcz") + self.assertEqual("abc".replace("a", "\xe9"), "\xe9bc") + self.assertEqual("\xe9bc\xe9".replace("\xe9", "e"), "ebce") + self.assertEqual("abc".replace("a", ""), "bc") + self.assertEqual("abc".replace("a", "xy"), "xybc") + self.assertEqual("abc".replace("", "-"), "-a-b-c-") + self.assertEqual("aXbXc".replace("X", "\U0001f600"), "a\U0001f600b\U0001f600c") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_str_rfind_windows.py b/tests/regrtest/test_str_rfind_windows.py new file mode 100644 index 000000000..d8a2423eb --- /dev/null +++ b/tests/regrtest/test_str_rfind_windows.py @@ -0,0 +1,81 @@ +"""`str.rfind`, `rindex`, `rpartition` and `rsplit` find the rightmost match. + +Needles of one character and longer, empty needles, needles that overlap +themselves, short and long haystacks, ASCII and non-ASCII text (character +offsets, not byte offsets), and `start`/`end` windows including negative +and out-of-range ones all agree with a plain scan from the right. +""" + +import unittest + + +def ref_rfind(s, sub, start=None, end=None): + n = len(s) + lo, hi, _ = slice(start, end).indices(n) + if start is not None and start > n: + return -1 + for i in range(hi - len(sub), lo - 1, -1): + if s[i:i + len(sub)] == sub: + return i + return -1 + + +TEXTS = ["", "a", "abcabc", "aaaa", "line 1 of text\nline 5 of text\n" * 40, + "héllo wörld héllo", "日本語の日本語", "x" * 100 + "ab" + "x" * 100, "aXbXaXbX" * 30] +NEEDLES = ["", "a", "ab", "abc", "aa", "line 5 ", "héllo", "ö", "日本", "Xb", "missing", "x" * 70] + + +class RfindTests(unittest.TestCase): + def test_against_scan(self): + for s in TEXTS: + for sub in NEEDLES: + self.assertEqual(s.rfind(sub), ref_rfind(s, sub), (s[:20], sub)) + for start, end in ((1, None), (0, 5), (-10, None), (None, -3), (3, 2), (0, 1000), (2, 2)): + want = ref_rfind(s, sub, start, end) + self.assertEqual(s.rfind(sub, start, end), want, (s[:20], sub, start, end)) + + def test_relatives(self): + s = "a,b,,c" * 20 + self.assertEqual(s.rindex(","), len(s) - 2) + with self.assertRaises(ValueError): + s.rindex("zz") + self.assertEqual(s.rpartition(",,"), (s[:s.rfind(",,")], ",,", s[s.rfind(",,") + 2:])) + self.assertEqual("a.b.c".rsplit(".", 1), ["a.b", "c"]) + self.assertEqual("x--y--z".rsplit("--", 1), ["x--y", "z"]) + self.assertEqual("ééé".rfind("é"), 2) + self.assertEqual("".rfind(""), 0) + self.assertEqual("abc".rfind("", 5), -1) + self.assertEqual("abc".rfind("", 3), 3) + + def test_window_edges(self): + # Matches placed across each boundary the search's windows could + # have, in bytes, bytearrays and text. + for size in (300, 1000, 1300, 5000, 22000, 90000, 200000): + edges = [size - e + d for e in (256, 1280, 5376, 21760) for d in range(-6, 3)] + for at in [0, 1, size // 2, size - 300, size - 8, size - 5] + edges: + if at < 0 or at + 5 > size: + continue + base = bytearray(b"." * size) + base[at:at + 5] = b"!" + base = bytes(base[:size]) + for kind in (bytes, bytearray): + hay = kind(base) + self.assertEqual(hay.rfind(b"!"), base.find(b"!"), (size, at)) + self.assertEqual(hay.rfind(b"ab"), base.find(b"ab"), (size, at)) + self.assertEqual(hay.rfind(b"zz"), -1) + text = base.decode() + self.assertEqual(text.rfind("!"), text.find("!"), (size, at)) + self.assertEqual((b"a" * 1000).rfind(b"aa"), 998) + self.assertEqual(("ab" * 500).rfind("ab"), 998) + self.assertEqual((b"xy" * 500).rfind(b"yx"), 997) + self.assertEqual((b"x" * 1000).rfind(b"xx", 0, 500), 498) + self.assertEqual((b"x" * 1000).rfind(b"xy"), -1) + + def test_many(self): + text = "".join("line %d of text\n" % i for i in range(2000)) + for _ in range(100): + self.assertEqual(text.rfind("line 5 "), text.find("line 5 ")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_str_slice_compiled.py b/tests/regrtest/test_str_slice_compiled.py new file mode 100644 index 000000000..b673c1065 --- /dev/null +++ b/tests/regrtest/test_str_slice_compiled.py @@ -0,0 +1,54 @@ +"""String slices in compiled code (`x[:8]`, `x[i:j]`, `x[-3:]`), on locals, +constants, and temporaries, run past the compile thresholds. + +ASCII and non-ASCII text, negative and out-of-range bounds, empty +results, a step, non-integer bounds, and `str` subclasses must all give +what the general subscript gives. +""" + +import unittest + + +class S(str): + def __getitem__(self, k): + return "sub" + + +class Idx: + def __index__(self): + return 2 + + +def cuts(x): + return (x[:8], x[8:12], x[-3:], x[2:-2], x[:0], x[5:2], x[100:], x[-100:3], x[:]) + + +class StrSliceCompiled(unittest.TestCase): + def test_ascii_and_wide(self): + for t in ["12345678-1234-5678", "héllo wörld, ça va", "日本語のテキストです", "", "ab"]: + bounds = [(None, 8), (8, 12), (-3, None), (2, -2), (None, 0), (5, 2), (100, None), (-100, 3), (None, None)] + want = tuple(str.__getitem__(t, slice(a, b)) for a, b in bounds) + for _ in range(3000): + self.assertEqual(cuts(t), want) + + def test_temporaries(self): + for i in range(3000): + s = "abc%05d" % i + self.assertEqual(s.upper()[:3], "ABC") + self.assertEqual(("x" + s)[-2:], s[-2:]) + self.assertEqual(f"{i:08x}"[4:], ("%08x" % i)[4:]) + + def test_other_slices(self): + t = "abcdefgh" + for i in range(3000): + self.assertEqual(t[::2], "aceg") + self.assertEqual(t[1:7:3], "be") + self.assertEqual(t[Idx():], "cdefgh") + self.assertEqual(t[None:2], "ab") + self.assertEqual(S("abc")[:2], "sub") + with self.assertRaises(TypeError): + t["a":] + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_str_subclass_payload.py b/tests/regrtest/test_str_subclass_payload.py new file mode 100644 index 000000000..d0db5c68c --- /dev/null +++ b/tests/regrtest/test_str_subclass_payload.py @@ -0,0 +1,49 @@ +"""`str(x)` of a `str` subclass's instance in compiled code. + +`email`'s `Terminal.value` is `str(self)`. An instance whose class keeps +`str`'s own `__str__` gives back its payload as an exact `str`; a class +that overrides `__str__`, directly, through a base, or after the fact, +is called, as is `Enum.__str__` of a mixed `str` enum, which comes after +`str` on its MRO (`str`'s own `__str__` doesn't stop the lookup). +Surrogates in the payload survive. Run it past the compile threshold. +""" + +import enum + + +class S(str): + pass + + +class Own(str): + def __str__(self): + return "own" + + +class FromBase(Own): + pass + + +class Later(str): + pass + + +class Mixed(str, enum.Enum): + one = "1" + + +def conv(x): + return str(x) + + +for i in range(3000): + r = conv(S("abc")) + assert r == "abc" and type(r) is str + assert conv(Own("x")) == "own" and conv(FromBase("y")) == "own" + w = conv(S("a\udcacb")) + assert w == "a\udcacb" and len(w) == 3 + assert conv(Later("l")) == ("later" if i >= 2000 else "l") + if i == 1999: + Later.__str__ = lambda self: "later" + assert str(S("q")) == "q" + assert conv(Mixed.one) == "Mixed.one" and format(Mixed.one) == "Mixed.one" diff --git a/tests/regrtest/test_str_through_repr.py b/tests/regrtest/test_str_through_repr.py new file mode 100644 index 000000000..39a2ae8f1 --- /dev/null +++ b/tests/regrtest/test_str_through_repr.py @@ -0,0 +1,93 @@ +"""`str(obj)`, `f"{obj}"`, `f"{obj!s}"` and `"%s" % obj` of an instance +whose class defines only a Python `__repr__` (keeping `object.__str__` +and `object.__format__`) call the `__repr__` directly; the text, a +non-string result's TypeError (worded as `__str__`'s), raises, a format +spec (still `object.__format__`'s TypeError), and classes that define +`__str__` or `__format__` later match the general call.""" + +import unittest + + +class Q: + def __init__(self, a): + self.a = a + self.calls = 0 + + def __repr__(self): + self.calls += 1 + return "Q(%r)" % (self.a,) + + +class Leaf: + def __repr__(self): + return "Leaf" + + +class Bad: + def __repr__(self): + return 7 + + +class Raiser: + def __repr__(self): + raise KeyError("r") + + +class Child(Q): + def __str__(self): + return "child" + + +class StrThroughRepr(unittest.TestCase): + def test_text(self): + q = Q("x") + leaf = Leaf() + for i in range(2000): + self.assertEqual(str(q), "Q('x')") + self.assertEqual(f"{q}", "Q('x')") + self.assertEqual(f"[{q!s}]", "[Q('x')]") + self.assertEqual("%s" % q, "Q('x')") + self.assertEqual(str(leaf), "Leaf") + self.assertEqual(f"{leaf}|{leaf!s}", "Leaf|Leaf") + self.assertEqual(q.calls, 8000) + + def test_bad_and_raises(self): + for i in range(300): + for make in (lambda b: str(b), lambda b: f"{b}", lambda b: f"{b!s}", lambda b: "%s" % b): + with self.assertRaises(TypeError) as cm: + make(Bad()) + self.assertEqual(str(cm.exception), "__str__ returned non-string (type int)") + with self.assertRaises(KeyError): + make(Raiser()) + + def test_spec_and_overrides(self): + q = Q(1) + for i in range(300): + with self.assertRaises(TypeError): + f"{q:>5}" + self.assertEqual(str(Child(2)), "child") + self.assertEqual(f"{Child(2)}", "child") + self.assertEqual(repr(Child(2)), "Q(2)") + + def test_replaced(self): + class C: + def __repr__(self): + return "r" + + c = C() + out = [] + for i in range(1000): + out.append(str(c) + f"{c}") + C.__str__ = lambda self: "s" + for i in range(1000): + out.append(str(c) + f"{c}") + C.__format__ = lambda self, spec: "f" + for i in range(1000): + out.append(str(c) + f"{c}") + self.assertEqual( + (out.count("rr"), out.count("ss"), out.count("sf")), (1000, 1000, 1000) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_stream_method_site.py b/tests/regrtest/test_stream_method_site.py new file mode 100644 index 000000000..5172ee4e8 --- /dev/null +++ b/tests/regrtest/test_stream_method_site.py @@ -0,0 +1,45 @@ +"""A compiled method site over native streams. + +`out.write(x)` at one site answers from the method it loaded for the +stream's kind; a site that sees text and binary streams in turn calls each +one's own method, and a stream whose own attribute shadows the method +calls that. Run it past the compile threshold. +""" + +import io + + +def emit(out, x, n): + for _ in range(n): + out.write(x) + return out + + +N = 3000 +assert emit(io.StringIO(), "ab", N).getvalue() == "ab" * N +assert emit(io.BytesIO(), b"cd", N).getvalue() == b"cd" * N +mixed = [io.StringIO(), io.BytesIO()] +for i in range(N): + emit(mixed[i % 2], "e" if i % 2 == 0 else b"f", 1) +assert mixed[0].getvalue() == "e" * (N // 2) and mixed[1].getvalue() == b"f" * (N // 2) + +seen = [] +s = io.StringIO() +s.write = seen.append +emit(s, "g", 5) +assert seen == ["g"] * 5 and s.getvalue() == "" +try: + emit(io.StringIO(), b"x", 1) +except TypeError: + pass +else: + raise AssertionError("bytes into a text stream") +closed = io.StringIO() +closed.close() +try: + emit(closed, "x", 1) +except ValueError: + pass +else: + raise AssertionError("write to a closed stream") +print("ok") diff --git a/tests/regrtest/test_stream_release_paths.py b/tests/regrtest/test_stream_release_paths.py new file mode 100644 index 000000000..22fb0787e --- /dev/null +++ b/tests/regrtest/test_stream_release_paths.py @@ -0,0 +1,90 @@ +"""Streams going away, in hot loops. + +An in-memory stream with nothing staged skips the destructor's flush and +descriptor work; a file stream still flushes what it staged and closes +its descriptor, and its `.buffer` sibling's staged bytes still reach the +file first. Weak references to either kind still clear and call back. +Names and modes still read back as given. +""" + +import gc +import io +import os +import tempfile +import unittest +import weakref + + +class StreamReleasePaths(unittest.TestCase): + def test_bytesio_loop(self): + for i in range(5000): + b = io.BytesIO() + b.write(b"abc") + b.write(bytes([i % 256])) + self.assertEqual(b.getvalue(), b"abc" + bytes([i % 256])) + b = io.BytesIO(b"seed") + self.assertEqual(b.read(), b"seed") + + def test_stringio_loop(self): + for i in range(5000): + s = io.StringIO() + s.write("x" * (i % 5)) + self.assertEqual(s.getvalue(), "x" * (i % 5)) + + def test_weakref_callbacks(self): + seen = [] + for i in range(500): + b = io.BytesIO(b"x") + s = io.StringIO("y") + r1 = weakref.ref(b, lambda _r, i=i: seen.append(("b", i))) + r2 = weakref.ref(s, lambda _r, i=i: seen.append(("s", i))) + del b, s + gc.collect() + self.assertIsNone(r1()) + self.assertIsNone(r2()) + self.assertEqual(len(seen), 1000) + + def test_unclosed_file_flushes(self): + with tempfile.TemporaryDirectory() as d: + for i in range(200): + path = os.path.join(d, f"f{i % 3}.txt") + f = open(path, "w") + f.write("line %d\n" % i) + del f + gc.collect() + with open(path) as g: + self.assertEqual(g.read(), "line %d\n" % i) + + def test_unclosed_buffer_sibling_flushes(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "sib.bin") + f = open(path, "w", encoding="ascii") + f.buffer.write(b"raw-") + f.write("text") + del f + gc.collect() + with open(path, "rb") as g: + self.assertEqual(g.read(), b"raw-text") + + def test_names_and_modes(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "n.txt") + with open(path, "w") as f: + self.assertEqual(f.name, path) + self.assertEqual(f.mode, "w") + self.assertEqual(f.buffer.name, path) + self.assertEqual(f.buffer.mode, "wb") + with open(path, "rb") as f: + self.assertEqual(f.mode, "rb") + fd = os.open(path, os.O_RDONLY) + with os.fdopen(fd, "r") as f: + self.assertEqual(f.name, fd) + self.assertEqual(f.mode, "r") + with open(os.fsencode(path), "r") as f: + self.assertEqual(f.name, os.fsencode(path)) + self.assertFalse(hasattr(io.BytesIO(), "name")) + self.assertFalse(hasattr(io.StringIO(), "mode")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_stream_states_outlive_sweeps.py b/tests/regrtest/test_stream_states_outlive_sweeps.py new file mode 100644 index 000000000..0a0b7023c --- /dev/null +++ b/tests/regrtest/test_stream_states_outlive_sweeps.py @@ -0,0 +1,71 @@ +"""Live compressors, decompressors and hashers keep their state while dead +ones are let go. + +Thousands of short-lived `zlib`, `bz2`, `lzma` and `compression.zstd` +streaming objects and hashers are made and dropped around a few that stay +alive mid-stream; the live ones still finish their streams to what one-shot +calls give, so freeing the dead ones' native state never touches theirs. +""" + +import bz2 +import hashlib +import lzma +import unittest +import zlib + +try: + from compression import zstd +except ImportError: + zstd = None + +DATA = b"stream states " * 500 + + +def roundtrips(): + makers = [ + ("zlib", zlib.compressobj, zlib.decompressobj, zlib.decompress), + ("bz2", bz2.BZ2Compressor, bz2.BZ2Decompressor, bz2.decompress), + ("lzma", lzma.LZMACompressor, lzma.LZMADecompressor, lzma.decompress), + ] + if zstd is not None: + makers.append(("zstd", zstd.ZstdCompressor, zstd.ZstdDecompressor, zstd.decompress)) + return makers + + +class SweepTests(unittest.TestCase): + def test_live_streams_finish(self): + for name, comp, decomp, one_shot in roundtrips(): + live = [comp() for _ in range(5)] + parts = [[c.compress(DATA[:100])] for c in live] + readers = [decomp() for _ in range(3)] + whole = comp() + one_shot_blob = whole.compress(DATA) + whole.flush() + got = [r.decompress(one_shot_blob[:10]) for r in readers] + count = 3000 if name in ("zlib", "zstd") else 300 + for _ in range(count): + c = comp() + c.compress(b"x") + decomp() + zlib.decompressobj() + hashlib.sha256(b"y") + for c, p in zip(live, parts): + p.append(c.compress(DATA[100:])) + p.append(c.flush()) + self.assertEqual(one_shot(b"".join(p)), DATA, name) + for r, g in zip(readers, got): + self.assertEqual(g + r.decompress(one_shot_blob[10:]), DATA, name) + + def test_live_zlib_objects(self): + d = zlib.decompressobj() + c = zlib.compressobj() + head = c.compress(DATA[:7]) + for _ in range(5000): + zlib.compressobj() + zlib.decompressobj() + blob = head + c.compress(DATA[7:]) + c.flush() + self.assertEqual(d.decompress(blob) + d.flush(), DATA) + self.assertTrue(d.eof) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_string_building_by_appending.py b/tests/regrtest/test_string_building_by_appending.py new file mode 100644 index 000000000..d892f002f --- /dev/null +++ b/tests/regrtest/test_string_building_by_appending.py @@ -0,0 +1,166 @@ +"""Building a string by appending to a local in a loop. + +`s += piece` (or `s = s + piece`) on a local whose string nothing else +holds grows the string where it is, so a loop that builds a long string +costs its length once, not once per append. Nothing else may see the +string change: a second name for it, a container that holds it, a dict +key, or a hash taken earlier all keep the value they had, and the loop +gives the same string whether it runs a few times or long enough to be +compiled. +""" + +import time +import unittest + +SHORT = 60 +LONG = 40_000 + + +def build(n, piece): + s = "" + for _ in range(n): + s += piece + return s + + +def build_plus(n, piece): + s = "" + for _ in range(n): + s = s + piece + return s + + +def build_parts(n): + s = "" + for i in range(n): + s = s + str(i & 7) + "," + return s + + +def build_with_aliases(n): + s = "start" + kept = [] + for i in range(n): + if i % 1000 == 0: + kept.append(s) + s += "x" + return s, kept + + +def build_with_second_name(n): + s = "ab" + seen = [] + for i in range(n): + t = s + s += "c" + if i % 997 == 0: + seen.append((len(t), len(s), t is s, t[-1], s[-1])) + del t + return seen, len(s) + + +def build_as_dict_keys(n): + d = {} + s = "k" + for i in range(n): + d[s] = i + s += "x" + return d + + +def build_mixed_widths(n): + s = "" + for i in range(n): + s += "é" if i & 1 else "z" + if i % 5000 == 0: + hash(s) + len(s) + return s + + +def double(n): + s = "a" + for _ in range(n): + s += s + return s + + +class AppendTests(unittest.TestCase): + def test_the_string_built(self): + for n in (SHORT, LONG): + for piece in ("ab", "", "é", "long piece of text "): + want = piece * n + self.assertEqual(build(n, piece), want) + self.assertEqual(build_plus(n, piece), want) + self.assertEqual(hash(build(n, piece)), hash(want)) + self.assertEqual(len(build(n, piece)), len(want)) + self.assertEqual(build_parts(n), "".join("%d," % (i & 7) for i in range(n))) + + def test_other_holders_keep_their_value(self): + for n in (SHORT, LONG): + s, kept = build_with_aliases(n) + self.assertEqual(s, "start" + "x" * n) + for i, k in enumerate(kept): + self.assertEqual(k, "start" + "x" * (1000 * i)) + seen, length = build_with_second_name(n) + self.assertEqual(length, n + 2) + for k, (lt, ls, same, tl, sl) in enumerate(seen): + self.assertEqual((lt, ls, same, sl), (997 * k + 2, 997 * k + 3, False, "c")) + + def test_keys_and_hashes(self): + for n in (SHORT, 5000): + d = build_as_dict_keys(n) + self.assertEqual(len(d), n) + self.assertTrue(all(len(k) == v + 1 for k, v in d.items())) + self.assertEqual(d["k" + "x" * (n - 1)], n - 1) + + def test_mixed_character_widths(self): + for n in (SHORT, LONG): + s = build_mixed_widths(n) + want = "".join("é" if i & 1 else "z" for i in range(n)) + self.assertEqual(s, want) + self.assertEqual(len(s), n) + self.assertEqual(s[n // 2], want[n // 2]) + self.assertEqual(s.encode(), want.encode()) + + def test_a_string_added_to_itself(self): + self.assertEqual(double(16), "a" * (1 << 16)) + + def test_other_types_through_the_same_statement(self): + def run(start, piece, n): + x = start + for _ in range(n): + x += piece + return x + + for n in (SHORT, LONG): + self.assertEqual(run(0, 2, n), 2 * n) + self.assertEqual(run(0.5, 1.5, n), 0.5 + 1.5 * n) + self.assertEqual(run([], [1], n), [1] * n) + self.assertEqual(run((), (1,), min(n, 3000)), (1,) * min(n, 3000)) + self.assertEqual(run(b"", b"ab", min(n, 5000)), b"ab" * min(n, 5000)) + with self.assertRaises(TypeError): + run("a", 1, LONG) + + +class CostTests(unittest.TestCase): + def per_append(self, n): + best = None + for _ in range(3): + t0 = time.perf_counter() + build(n, "ab") + dt = (time.perf_counter() - t0) / n + best = dt if best is None else min(best, dt) + return best + + def test_cost_of_an_append_does_not_grow(self): + # (A string 16 times as long cost 16 times as much an append when + # each one copied the whole string. Allow 4, far past noise.) + build(LONG, "ab") + small = self.per_append(20_000) + large = self.per_append(320_000) + self.assertLess(large, 4 * small + 1e-7, (small, large)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_stringio_small_reads.py b/tests/regrtest/test_stringio_small_reads.py new file mode 100644 index 000000000..87032a742 --- /dev/null +++ b/tests/regrtest/test_stringio_small_reads.py @@ -0,0 +1,91 @@ +"""`StringIO.read(n)` in a character-at-a-time loop (`shlex`'s lexer). + +An ASCII run with no `\\r` is copied straight out of the buffer; every +other read (non-ASCII text, carriage returns under newline translation, +surrogates, a position past the end, a closed stream) keeps the general +path's answer. +""" + +import io +import shlex +import unittest + + +def drain(stream, size=1): + out = [] + while True: + piece = stream.read(size) + if not piece: + return out + out.append(piece) + + +class StringIOReadTests(unittest.TestCase): + def test_char_loop(self): + for _ in range(300): + s = io.StringIO("ab\r\ncdéf\rgh\nxyz") + self.assertEqual( + drain(s), + ["a", "b", "\r", "\n", "c", "d", "é", "f", "\r", "g", "h", "\n", "x", "y", "z"], + ) + self.assertEqual(s.tell(), 15) + + def test_sizes(self): + for _ in range(300): + s = io.StringIO("hello world") + self.assertEqual(s.read(3), "hel") + self.assertEqual(s.read(0), "") + self.assertEqual(s.read(-5), "lo world") + self.assertEqual(s.read(2), "") + self.assertEqual(s.tell(), 11) + self.assertEqual(drain(io.StringIO("abcdefg"), 3), ["abc", "def", "g"]) + + def test_newline_translation(self): + s = io.StringIO("line1\r\nline2\rline3", newline=None) + self.assertEqual(s.read(4), "line") + self.assertEqual(s.read(), "1\nline2\nline3") + s = io.StringIO() + s.write("q\r\nw") + s.seek(0) + self.assertEqual((s.read(1), s.read(1), s.read(5)), ("q", "\r", "\nw")) + + def test_past_the_end(self): + s = io.StringIO("abc", newline="") + s.seek(10) + self.assertEqual(s.read(1), "") + self.assertEqual(s.tell(), 10) + s.write("z") + self.assertEqual(s.getvalue(), "abc" + "\0" * 7 + "z") + + def test_surrogates(self): + s = io.StringIO("ab\udcffcd") + self.assertEqual([s.read(1) for _ in range(5)], ["a", "b", "\udcff", "c", "d"]) + + def test_writes_between_reads(self): + s = io.StringIO("abc") + self.assertEqual(s.read(1), "a") + s.write("XY") + self.assertEqual(s.read(1), "") + s.seek(1) + self.assertEqual(s.read(), "XY") + + def test_closed(self): + s = io.StringIO("x") + s.close() + with self.assertRaisesRegex(ValueError, "^I/O operation on closed file$"): + s.read(1) + b = io.BytesIO(b"x") + b.close() + with self.assertRaisesRegex(ValueError, r"^I/O operation on closed file\.$"): + b.read(1) + + def test_shlex(self): + for _ in range(200): + self.assertEqual( + shlex.split("cmd --flag 'quoted arg' \"another one\" plain"), + ["cmd", "--flag", "quoted arg", "another one", "plain"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/regrtest/test_struct_reads_large_buffers_in_place.py b/tests/regrtest/test_struct_reads_large_buffers_in_place.py new file mode 100644 index 000000000..6861fc573 --- /dev/null +++ b/tests/regrtest/test_struct_reads_large_buffers_in_place.py @@ -0,0 +1,219 @@ +"""`struct.unpack_from` and `struct.pack_into` on a large buffer. + +Unpacking a few bytes at an offset of a `bytes`, `bytearray` or +`memoryview` reads those bytes where they are, and packing writes them +where they go: neither copies the buffer, so a parser that walks a large +buffer field by field costs its fields, not its fields times the buffer. +Offsets, keyword arguments, other buffer kinds and every error behave as +the documented functions do. +""" + +import array +import struct +import time +import unittest + + +class UnpackFromTests(unittest.TestCase): + def test_every_buffer_kind_and_offset(self): + data = bytes(range(256)) * 4 + buffers = { + "bytes": data, + "bytearray": bytearray(data), + "memoryview": memoryview(data), + "memoryview of bytearray": memoryview(bytearray(data)), + "sub-view": memoryview(b"\xff" * 5 + data)[5:], + "array": array.array("B", data), + } + for name, buf in buffers.items(): + for fmt in ("H", "2h3s"): + size = struct.calcsize(fmt) + for offset in (0, 1, 7, 100, len(data) - size, -size, -len(data)): + with self.subTest(buf=name, fmt=fmt, offset=offset): + start = offset if offset >= 0 else len(data) + offset + want = struct.unpack(fmt, data[start:start + size]) + self.assertEqual(struct.unpack_from(fmt, buf, offset), want) + self.assertEqual(struct.unpack_from(fmt, buffer=buf, offset=offset), want) + self.assertEqual(struct.Struct(fmt).unpack_from(buf, offset), want) + self.assertEqual(struct.unpack_from("H", (0x1234,)), + ("= 0 else 32 + offset + want = bytearray(32) + want[start:start + size] = struct.pack(fmt, *values) + self.assertEqual(bytes(buf), bytes(want)) + st = struct.Struct(fmt) + other = make() + st.pack_into(other, offset, *values) + self.assertEqual(bytes(other), bytes(want)) + + def test_a_view_writes_through(self): + buf = bytearray(16) + struct.pack_into("